diff --git a/index.html b/index.html index 11102462..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.

@@ -1440,7 +1446,7 @@

Settings

- + diff --git a/js/coin.js b/js/coin.js index b6177abc..5324f92d 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 && (['tPPC','PPC'].includes(coinjs.symbol) && 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 && (['tPPC','PPC'].includes(coinjs.symbol) && obj.version<3)) { obj.nTime = readAsInt(4); } diff --git a/js/cointoolkit.js b/js/cointoolkit.js index c08dade8..48a5c6f7 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 = ''; @@ -382,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); @@ -707,11 +717,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); + var txn = appBtc.splitTransaction(currenttransaction.serialize(),false,hasTimestamp,false); var outputsBuffer = Crypto.util.bytesToHex(appBtc.serializeTransactionOutputs(txn)); var inputs = []; @@ -729,7 +740,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]); + 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) { // we are ready @@ -748,14 +760,18 @@ $(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, transactionVersion:currenttransaction.version, sigHashType: hashType, segwit:false}; + if (timeStamp) { + params.initialTimestamp = timeStamp; + } + result = await appBtc.signP2SHTransaction(params); var success=false; console.log("signature result",result); $.each(result, function(idx,itm) { - var signature = Crypto.util.hexToBytes(itm); - if (currenttransaction.signmultisig(idx,undefined,signature.slice(-1)[0]*1,signature)) { + var signature = Crypto.util.hexToBytes(itm+hashType.toString(16)); + if (currenttransaction.signmultisig(idx,undefined,hashType*1,signature)) { success=true; } }); @@ -767,7 +783,12 @@ $(document).ready(function() { } } else { - result = await appBtc.createPaymentTransactionNew(inputs, paths, undefined, outputsBuffer, undefined, undefined, undefined, timeStamp); + 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); } } @@ -2164,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; } @@ -2349,6 +2374,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()); @@ -2466,6 +2499,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(); @@ -2526,7 +2562,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) { diff --git a/js/ledger.js b/js/ledger.js index a33a2f0a..233d2253 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1,24 +1,47 @@ -!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) : - (factory((global.NewLedger = {}))); -}(this, (function (exports) { 'use strict'; + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {})); +})(this, (function (exports) { 'use strict'; + + 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 commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - function unwrapExports (x) { + function getDefaultExportFromCjs (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; + 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_1 = createCommonjsModule(function (module) { + var runtime = {exports: {}}; + /** * Copyright (c) 2014-present, Facebook, Inc. * @@ -26,16 +49,35 @@ window.Buffer = buffer.Buffer; * 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; // More compressible than void 0. + 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; @@ -88,9 +130,9 @@ window.Buffer = buffer.Buffer; // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { + define(IteratorPrototype, iteratorSymbol, function () { return this; - }; + }); var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); @@ -104,18 +146,22 @@ window.Buffer = buffer.Buffer; var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; + 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) { - prototype[method] = function(arg) { + define(prototype, method, function(arg) { return this._invoke(method, arg); - }; + }); }); } @@ -134,9 +180,7 @@ window.Buffer = buffer.Buffer; Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } + define(genFun, toStringTagSymbol, "GeneratorFunction"); } genFun.prototype = Object.create(Gp); return genFun; @@ -150,7 +194,7 @@ window.Buffer = buffer.Buffer; return { __await: arg }; }; - function AsyncIterator(generator) { + function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { @@ -161,14 +205,14 @@ window.Buffer = buffer.Buffer; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { + return PromiseImpl.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) { + 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. @@ -186,7 +230,7 @@ window.Buffer = buffer.Buffer; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { + return new PromiseImpl(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } @@ -218,17 +262,20 @@ window.Buffer = buffer.Buffer; } defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { + 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) { + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl ); return exports.isGeneratorFunction(outerFn) @@ -322,7 +369,7 @@ window.Buffer = buffer.Buffer; // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; - if (method === undefined) { + if (method === undefined$1) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; @@ -333,7 +380,7 @@ window.Buffer = buffer.Buffer; // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; - context.arg = undefined; + context.arg = undefined$1; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { @@ -385,7 +432,7 @@ window.Buffer = buffer.Buffer; // outer generator. if (context.method !== "return") { context.method = "next"; - context.arg = undefined; + context.arg = undefined$1; } } else { @@ -403,20 +450,20 @@ window.Buffer = buffer.Buffer; // unified ._invoke helper method. defineIteratorMethods(Gp); - Gp[toStringTagSymbol] = "Generator"; + 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. - Gp[iteratorSymbol] = function() { + define(Gp, iteratorSymbol, function() { return this; - }; + }); - Gp.toString = function() { + define(Gp, "toString", function() { return "[object Generator]"; - }; + }); function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; @@ -497,7 +544,7 @@ window.Buffer = buffer.Buffer; } } - next.value = undefined; + next.value = undefined$1; next.done = true; return next; @@ -513,7 +560,7 @@ window.Buffer = buffer.Buffer; exports.values = values; function doneResult() { - return { value: undefined, done: true }; + return { value: undefined$1, done: true }; } Context.prototype = { @@ -524,12 +571,12 @@ window.Buffer = buffer.Buffer; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. - this.sent = this._sent = undefined; + this.sent = this._sent = undefined$1; this.done = false; this.delegate = null; this.method = "next"; - this.arg = undefined; + this.arg = undefined$1; this.tryEntries.forEach(resetTryEntry); @@ -539,7 +586,7 @@ window.Buffer = buffer.Buffer; if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { - this[name] = undefined; + this[name] = undefined$1; } } } @@ -572,7 +619,7 @@ window.Buffer = buffer.Buffer; // 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; + context.arg = undefined$1; } return !! caught; @@ -709,7 +756,7 @@ window.Buffer = buffer.Buffer; 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; + this.arg = undefined$1; } return ContinueSentinel; @@ -727,7 +774,7 @@ window.Buffer = buffer.Buffer; // 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 + module.exports )); try { @@ -735,5226 +782,4248 @@ window.Buffer = buffer.Buffer; } 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 + // 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. - Function("r", "regeneratorRuntime = r")(runtime); + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } } - }); + }(runtime)); - var utils = createCommonjsModule(function (module, exports) { + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); - 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 }; + 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$1[i] = code[i]; + revLookup$1[code.charCodeAt(i)] = i; + } + + revLookup$1['-'.charCodeAt(0)] = 62; + revLookup$1['_'.charCodeAt(0)] = 63; } - // 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 toByteArray$1 (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') + } - 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; - } + // 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; - // TODO use async await + // base64 is 4/3 + up to two characters of the original data + arr = new Arr$1(len * 3 / 4 - placeHolders); - function eachSeries(arr, fun) { - return arr.reduce(function (p, e) { - return p.then(function () { - return fun(e); - }); - }, Promise.resolve()); - } + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; - 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); - }); + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 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; } - return Promise.resolve().then(function () { - return iterate(0, arr, []); - }); + + if (placeHolders === 2) { + tmp = (revLookup$1[b64.charCodeAt(i)] << 2) | (revLookup$1[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + 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; + } + + return arr } - function doIf(condition, callback) { - return Promise.resolve().then(function () { - if (condition) { - return callback(); - } - }); + 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 asyncWhile(predicate, callback) { - function iterate(result) { - if (!predicate()) { - return result; - } else { - return callback().then(function (res) { - result.push(res); - return iterate(result); - }); - } + 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$1(tmp)); } - return Promise.resolve([]).then(iterate); + return output.join('') } - var isLedgerDevice = exports.isLedgerDevice = function isLedgerDevice(device) { - return device.vendorId === 0x2581 && device.productId === 0x3b7c || device.vendorId === 0x2c97; - }; + function fromByteArray$1 (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$1(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } - 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; + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + 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$1[tmp >> 10]; + output += lookup$1[(tmp >> 4) & 0x3F]; + output += lookup$1[(tmp << 2) & 0x3F]; + output += '='; + } - var require$$0 = {}; + parts.push(output); - var createHash = require$$0.createHash; + return parts.join('') + } - var Btc_1 = createCommonjsModule(function (module, exports) { + 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]; - Object.defineProperty(exports, "__esModule", { - value: true - }); + i += d; - 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; }; + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - 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; }; }(); + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - // 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 + 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) {} - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - 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"); }); }; } + buffer[offset + i - d] |= s * 128; + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var toString = {}.toString; - /** - * address format is one of legacy | p2sh | bech32 - */ - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2 + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; }; - 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 INSPECT_MAX_BYTES = 50; + /** - * Bitcoin API. + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ + * 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. - var Btc = function () { - function Btc(transport) { - var scrambleKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "BTC"; + * 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 + ? global$1.TYPED_ARRAY_SUPPORT + : true; - _classCallCheck(this, Btc); + function kMaxLength () { + return Buffer$l.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } - this.transport = transport; - transport.decorateAppAPIMethods(this, ["getWalletPublicKey", "signP2SHTransaction", "signMessageNew", "createPaymentTransactionNew"], scrambleKey); + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') } - - _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 }; - }); + if (Buffer$l.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$l.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$l(length); } + that.length = length; + } - /** - * @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"); - }); + 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$l (arg, encodingOrOffset, length) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$l)) { + return new Buffer$l(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' + ) } - }, { - 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; - } + return allocUnsafe(this, arg) + } + return from$1(this, arg, encodingOrOffset, length) + } - // 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); - } + Buffer$l.poolSize = 8192; // not used by this implementation - return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { - return _this.getTrustedInputRaw(scriptBlock); - }); - }; + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer$l._augment = function (arr) { + arr.__proto__ = Buffer$l.prototype; + return arr + }; - var processWholeScriptBlock = function processWholeScriptBlock(block) { - return _this.getTrustedInputRaw(block); - }; + function from$1 (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } - 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); - }); - }; + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } - 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); - }); - }; + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } - 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; - } + return fromObject(that, value) + } - throw new Error("getTrustedInputBIP143: missing tx"); + /** + * 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$l.from = function (value, encodingOrOffset, length) { + return from$1(null, value, encodingOrOffset, length) + }; - case 2: - isDecred = additionals.includes("decred"); + if (Buffer$l.TYPED_ARRAY_SUPPORT) { + Buffer$l.prototype.__proto__ = Uint8Array.prototype; + Buffer$l.__proto__ = Uint8Array; + } - if (!isDecred) { - _context.next = 5; - break; - } + 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$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$l.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } - throw new Error("Decred does not implement BIP143"); + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer$l.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) { + return allocUnsafe(null, size) + }; - case 5: - sha = window.createHash("sha256"); + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } - sha.update(this.serializeTransaction(transaction, true)); - hash = sha.digest(); + if (!Buffer$l.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } - sha = window.createHash("sha256"); - sha.update(hash); - hash = sha.digest(); - data = Buffer.alloc(4); + var length = byteLength$1(string, encoding) | 0; + that = createBuffer(that, length); - data.writeUInt32LE(indexLookup, 0); - outputs = transaction.outputs, locktime = transaction.locktime; + var actual = that.write(string, encoding); - if (!(!outputs || !locktime)) { - _context.next = 16; - break; - } + 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); + } - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + return that + } - case 16: - if (outputs[indexLookup]) { - _context.next = 18; - break; - } + 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 + } - throw new Error("getTrustedInputBIP143: wrong index"); + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer - case 18: - hash = Buffer.concat([hash, data, outputs[indexLookup].amount]); - _context.next = 21; - return hash.toString("hex"); + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } - case 21: - return _context.abrupt("return", _context.sent); + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } - case 22: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); + 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); + } - function getTrustedInputBIP143(_x4, _x5) { - return _ref.apply(this, arguments); - } + if (Buffer$l.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$l.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } - 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]; - } + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); - throw new Error("getVarint called with unexpected parameters"); + if (that.length === 0) { + return that } - }, { - 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]); + 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 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; - }); + return fromArrayLike(that, obj) } - /** - * 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 }; - }); - }); + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) } + } - /** - * 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 => ...); - */ + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } - }, { - 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; + 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$l.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } - 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); - } + Buffer$l.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } - var lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); + if (a === b) return 0 - var result = Buffer.concat([_this5.serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript]); + var x = a.length; + var y = b.length; - 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]); - } + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } - // 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 (x < y) return -1 + if (y < x) return 1 + return 0 + }; - if (expiryHeight) { - result = Buffer.concat([result, targetTransaction.nExpiryHeight || Buffer.alloc(0), targetTransaction.extraData || Buffer.alloc(0)]); - } + Buffer$l.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 (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]); - }); + Buffer$l.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - result = Buffer.concat([result, decredWitness]); - } + if (list.length === 0) { + return Buffer$l.alloc(0) + } - return result.toString("hex"); - }); + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; } + } - /** - * 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 => ...); - */ + var buffer = Buffer$l.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 + }; - }, { - 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 - }; + function byteLength$1 (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; + } - 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 len = string.length; + if (len === 0) return 0 - 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; + // 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$l.byteLength = byteLength$1; - /** - * 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; + function slowToString (encoding, start, end) { + var loweredCase = false; - if (isDecred) { - //Script version - offset += 2; - } + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - 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); - } + // 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 '' + } - //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; - } - } + if (end === undefined || end > this.length) { + end = this.length; + } - return { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - } + if (end <= 0) { + return '' + } - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; - }, { - key: "serializeTransactionOutputs", - value: function serializeTransactionOutputs(_ref2) { - var _this7 = this; + if (end <= start) { + return '' + } - var outputs = _ref2.outputs; + if (!encoding) encoding = 'utf8'; - 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; - } + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - /** - */ + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - }, { - 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]); - }); + case 'ascii': + return asciiSlice(this, start, end) - 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)]); - } + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - 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]); - } + case 'base64': + return base64Slice(this, start, end) - /** - */ + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - }, { - 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")); - } + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; } - }]); - - 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; + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer$l.prototype._isBuffer = true; - EventEmitter.prototype.domain = undefined; - EventEmitter.prototype._events = undefined; - EventEmitter.prototype._maxListeners = undefined; + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } - // 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; + 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') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; - 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; - } + 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') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); } + return this + }; - if (!this._events || this._events === Object.getPrototypeOf(this)._events) { - this._events = new EventHandlers(); - this._eventsCount = 0; + 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') + } + 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 + }; - this._maxListeners = this._maxListeners || undefined; + 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) }; - // 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; + 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$l.compare(this, b) === 0 }; - function $getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; - } + Buffer$l.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 '' + }; - 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); + Buffer$l.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') } - } - 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); + + if (start === undefined) { + start = 0; } - } - 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); + if (end === undefined) { + end = target ? target.length : 0; } - } - 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); + if (thisStart === undefined) { + thisStart = 0; } - } - - 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); + if (thisEnd === undefined) { + thisEnd = this.length; } - } - - 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 (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } - // 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; + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 } - handler = events[type]; + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - if (!handler) - return false; + if (this === target) return 0 - 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); - } + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - if (needDomainExit) - domain.exit(); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - return true; + 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 }; - function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; + // 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 - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); + // 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); + } - 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); + // 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 + } - // 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]; + // Normalize val + if (typeof val === 'string') { + val = Buffer$l.from(val, encoding); } - 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); - } + // 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 } - - // 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 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 && + 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) } - return target; - } - function emitWarning(e) { - typeof console.warn === 'function' ? console.warn(e) : console.log(e); + throw new TypeError('val must be string, number or Buffer') } - 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 arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; - function _onceWrap(target, type, listener) { - var fired = false; - function g() { - target.removeListener(type, g); - if (!fired) { - fired = true; - listener.apply(target, arguments); + 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; } } - 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; - }; + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - 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; - }; + 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 + } + } - // emits a 'removeListener' event iff the listener was removed - EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; + return -1 + } - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); + Buffer$l.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; - events = this._events; - if (!events) - return this; + Buffer$l.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; - list = events[type]; - if (!list) - return this; + Buffer$l.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; - 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; + 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; + } + } - for (i = list.length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - originalListener = list[i].listener; - position = i; - break; - } - } + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - if (position < 0) - return this; + 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 + } - 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); - } + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } - if (events.removeListener) - this.emit('removeListener', type, originalListener || listener); - } + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } - return this; - }; + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } - EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events; + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } - events = this._events; - if (!events) - return this; + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } - // 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); + Buffer$l.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 { - return listenerCount.call(emitter, type); + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) } - }; - EventEmitter.prototype.listenerCount = listenerCount; - function listenerCount(type) { - var events = this._events; - - if (events) { - var evlistener = events[type]; + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener) { - return evlistener.length; - } + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') } - 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; - } + if (!encoding) encoding = 'utf8'; - 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 loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - var helpers = createCommonjsModule(function (module, exports) { + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - Object.defineProperty(exports, "__esModule", { - value: true - }); + case 'ascii': + return asciiWrite(this, string, offset, length) - 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; }; + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - var errorClasses = {}; - var deserializers = {}; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - var addCustomErrorDeserializer = exports.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } }; - 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; + Buffer$l.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } }; - // 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 - } + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray$1(buf) + } else { + return fromByteArray$1(buf.slice(start, end)) + } + } - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; + 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 (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; - error = Object.create(_constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; + 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; } } - } 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); + 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; } - 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") + "]"; + res.push(codePoint); + i += bytesPerSequence; } - 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; + return decodeCodePointsArray(res) + } - try { - for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var key = _step.value; + // 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 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; - } - } + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } - 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; + // 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 to; + return res } - }); - - 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) { + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - 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"); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } - // 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"); + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - /** - * 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; + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret } - //$FlowFixMe - TransportError.prototype = new Error(); - (0, helpers.addCustomErrorDeserializer)("TransportError", function (e) { - return new TransportError(e.message, e.id); - }); + function hexSlice (buf, start, end) { + var len = buf.length; - 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 - }; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - 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"; + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex$1(buf[i]); } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; + 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 } - /** - * 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(); + Buffer$l.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - (0, helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { - return new TransportStatusError(e.statusCode); - }); + 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; + } - 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; + if (end < start) end = start; - 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 newBuf; + if (Buffer$l.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$l.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$l(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') + } - var _events3 = _interopRequireDefault(EventEmitter); + Buffer$l.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 + }; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + Buffer$l.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } - 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); } } + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } - 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"); }); }; } + return val + }; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + Buffer$l.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; - exports.TransportError = lib.TransportError; - exports.TransportStatusError = lib.TransportStatusError; - exports.StatusCodes = lib.StatusCodes; - exports.getAltStatusMessage = lib.getAltStatusMessage; + Buffer$l.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) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + Buffer$l.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$l.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - /** - * 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 - */ + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; - /** - */ + Buffer$l.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - /** - * 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; + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; - _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; - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; - throw new lib.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + Buffer$l.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - case 2: - _context.next = 4; - return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } + return val + }; - throw new lib.TransportStatusError(sw); + 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) + }; - case 8: - return _context.abrupt("return", response); + 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 + }; - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); + 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 + }; - 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; - } + Buffer$l.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - throw new lib.TransportError("Transport race condition", "RaceCondition"); + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); + Buffer$l.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); + Buffer$l.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; - case 10: - _context2.prev = 10; + Buffer$l.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); + Buffer$l.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); + Buffer$l.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; - return function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); + 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') + } - this._appAPIlock = null; + Buffer$l.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); } - /** - * Statically check if a transport is supported on the user's platform/browser. - */ - + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ + return offset + byteLength + }; + Buffer$l.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); + } - /** - * 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: () => {} - }) - */ - + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - /** - * 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 => ...) - */ + return offset + byteLength + }; + 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$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; - /** - * 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 - */ + 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$l.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) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; - /** - * 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 - */ + 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$l.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; + } + } - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ + 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$l.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$l.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) { + 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 + }; - _createClass(Transport, [{ - key: "on", + Buffer$l.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); + } - /** - * 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); + 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; + } - /** - * Stop listening to an event on an instance of transport. - */ + return offset + byteLength + }; - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; + Buffer$l.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); + 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; + } - /** - * Enable or not logs of the binary exchange - */ + return offset + byteLength + }; - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } + 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$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ + 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$l.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } + 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$l.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; - /** - * 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 - */ + 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$l.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 + }; - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; + 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$l.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 + }; - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; + 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') + } - 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]; - } + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } - var _appAPIlock; + Buffer$l.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; + Buffer$l.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; - if (!_appAPIlock) { - _context3.next = 3; - break; - } + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } - return _context3.abrupt("return", Promise.reject(new lib.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); + Buffer$l.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; - case 3: - _context3.prev = 3; + Buffer$l.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + 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; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; - case 8: - return _context3.abrupt("return", _context3.sent); + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - case 9: - _context3.prev = 9; + // 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') - _this2._appAPIlock = null; - return _context3.finish(9); + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); + var len = end - start; + var i; - return function () { - return _ref3.apply(this, arguments); - }; - }(); + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; } - }], [{ - 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; + } 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]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; + return len + }; - 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; - }); + // Usage: + // 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) { + // 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$l.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } - // $FlowFixMe - - }]); + // 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 Transport; - }(); + if (end <= start) { + return this + } - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - exports.default = Transport; + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - }); + if (!val) val = 0; - 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 i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer$l(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } - var hidFraming = createCommonjsModule(function (module, exports) { + return this + }; - Object.defineProperty(exports, "__esModule", { - value: true - }); + // 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 + } - var Tag = 0x05; + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } - function asUInt16BE(value) { - var b = Buffer.alloc(2); - b.writeUInt16BE(value, 0); - return b; + function toHex$1 (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) } - var initialAcc = { - data: Buffer.alloc(0), - dataLength: 0, - sequence: 0 - }; + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; - /** - * - */ - 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; + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); - 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"); - } + // 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 (!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); - } + // valid lead + leadSurrogate = codePoint; - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function getReducedResult(acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; + continue } - } - }; - }; - - exports.default = createHIDframing; - - }); - unwrapExports(hidFraming); + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } - var lib$1 = createCommonjsModule(function (module, exports) { + // 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); + } - Object.defineProperty(exports, "__esModule", { - value: true - }); + leadSurrogate = null; - 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; }; + // 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') + } + } - /** - * 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 - */ + return bytes + } - 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); + 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 + } - /** - * - */ - var ledgerUSBVendorId = exports.ledgerUSBVendorId = 0x2c97; + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - /** - * - */ - var getDeviceModel = exports.getDeviceModel = function getDeviceModel(id) { - var info = devices[id]; - if (!info) throw new Error("device '" + id + "' does not exist"); - return info; - }; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - /** - * - */ - 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; - }; + return byteArray + } - var bluetoothServices = []; - var serviceUuidToInfos = {}; - for (var _id in devices) { - var _deviceModel = devices[_id]; - var _bluetoothSpec = _deviceModel.bluetoothSpec; + function base64ToBytes (str) { + return toByteArray$1(base64clean(str)) + } - 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); - } + 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 getBluetoothServiceUuids = exports.getBluetoothServiceUuids = function getBluetoothServiceUuids() { - return bluetoothServices; - }; - - /** - * - */ - var getInfosForServiceUuid = exports.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { - return serviceUuidToInfos[uuid.toLowerCase()]; - }; + 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 */ - }); - - 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 - }); + 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; + }; - /** - * A Log object - */ - var id = 0; - var subscribers = []; + BIPPath.validatePathArray = function (path) { + try { + BIPPath.fromPathArray(path); + return true + } catch (e) { + return false + } + }; - /** - * 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); + BIPPath.validateString = function (text, reqRoot) { + try { + BIPPath.fromString(text, reqRoot); + return true + } catch (e) { + return false + } }; - /** - * 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(); - } - }; + BIPPath.fromPathArray = function (path) { + return new BIPPath(path) }; - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } catch (e) { - console.error(e); - } + 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') } - } - // for debug purpose - commonjsGlobal.__ledgerLogsListen = listen; + 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 index$2 = unwrapExports(lib$2); - var lib_1$2 = lib$2.log; - var lib_2$2 = lib$2.listen; + 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) + }; - var index$3 = /*#__PURE__*/Object.freeze({ - default: index$2, - __moduleExports: lib$2, - log: lib_1$2, - listen: lib_2$2 - }); + BIPPath.prototype.toPathArray = function () { + return this.path + }; - var webusb = createCommonjsModule(function (module, exports) { + 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('/') + }; - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.isSupported = exports.getFirstLedgerDevice = exports.getLedgerDevices = exports.requestLedgerDevice = undefined; + BIPPath.prototype.inspect = function () { + return 'BIPPath <' + this.toString() + '>' + }; - 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 }); + var bip32Path = BIPPath; - case 2: - device = _context.sent; - return _context.abrupt("return", device); + var inherits_browser = {exports: {}}; - case 4: - case "end": - return _context.stop(); + 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 } - } - }, _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); + } 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 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()); + var safeBuffer = {exports: {}}; - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); + var buffer = {}; - return function getFirstLedgerDevice() { - return _ref3.apply(this, arguments); - }; - }(); + var base64Js = {}; + base64Js.byteLength = byteLength; + base64Js.toByteArray = toByteArray; + base64Js.fromByteArray = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - 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 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 ledgerDevices = [{ vendorId: lib$1.ledgerUSBVendorId }]; + // 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; - var isSupported = exports.isSupported = function isSupported() { - return Promise.resolve( - // $FlowFixMe - !!navigator && !!navigator.usb && typeof navigator.usb.getDevices === "function"); - }; + function getLens (b64) { + var len = b64.length; - }); + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - unwrapExports(webusb); - var webusb_1 = webusb.isSupported; - var webusb_2 = webusb.getFirstLedgerDevice; - var webusb_3 = webusb.getLedgerDevices; - var webusb_4 = webusb.requestLedgerDevice; + // 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 TransportWebUSB_1 = createCommonjsModule(function (module, exports) { + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4); - Object.defineProperty(exports, "__esModule", { - value: true - }); + return [validLen, placeHoldersLen] + } - 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; }; }(); + // 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 _hwTransport2 = _interopRequireDefault(Transport_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 _hidFraming2 = _interopRequireDefault(hidFraming); + var i; + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = (tmp >> 16) & 0xFF; + arr[curByte++] = (tmp >> 8) & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[curByte++] = tmp & 0xFF; + } + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[curByte++] = (tmp >> 8) & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + return arr + } + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] + } + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + function fromByteArray (uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ); + } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return parts.join('') + } - 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 ieee754 = {}; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - 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; } + 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 _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; } + i += d; - var configurationValue = 1; - var interfaceNumber = 2; - var endpointNumber = 3; + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - /** - * WebUSB Transport implementation - * @example - * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; - * ... - * TransportWebUSB.create().then(transport => ...) - */ + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - var TransportWebUSB = function (_Transport) { - _inherits(TransportWebUSB, _Transport); + 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 TransportWebUSB(device) { - _classCallCheck(this, TransportWebUSB); + 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; - var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); + value = Math.abs(value); - _initialiseProps.call(_this); + 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; + } - _this.device = device; - _this.deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); - return _this; + 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; + } } - /** - * Check if WebUSB transport is supported. - */ - - - /** - * List the WebUSB devices that was previously authorized by the user. - */ + 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) {} - /** - * 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! - */ + buffer[offset + i - d] |= s * 128; + }; + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ - _createClass(TransportWebUSB, [{ - key: "close", + (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; - /** - * 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); - })); + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; - function close() { - return _ref.apply(this, arguments); - } + var K_MAX_LENGTH = 0x7fffffff; + exports.kMaxLength = K_MAX_LENGTH; - 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); - } + /** + * 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(); - return request; - }() + 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.' + ); + } - /** - * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). - */ + 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 + } + } - }, { - 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; - } + Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } + }); - return _context3.abrupt("return", null); + Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } + }); - case 5: - return _context3.abrupt("return", TransportWebUSB.open(devices[0])); + 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 + } - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); + /** + * 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 openConnected() { - return _ref3.apply(this, arguments); - } + 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) + } - return openConnected; - }() + Buffer.poolSize = 8192; // not used by this implementation - /** - * Create a Ledger transport with a USBDevice - */ + function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } - }, { - 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; - } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } - _context4.next = 5; - return device.selectConfiguration(configurationValue); + 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) + ) + } - case 5: - _context4.next = 7; - return device.reset(); + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - case 7: - _context4.prev = 7; - _context4.next = 10; - return device.claimInterface(interfaceNumber); + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - case 10: - _context4.next = 17; - break; + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } - case 12: - _context4.prev = 12; - _context4.t0 = _context4["catch"](7); - _context4.next = 16; - return device.close(); + var valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } - case 16: - throw new lib.TransportInterfaceNotAvailable(_context4.t0.message); + var b = fromObject(value); + if (b) return b - case 17: - transport = new TransportWebUSB(device); + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } - onDisconnect = function onDisconnect(e) { - if (device === e.device) { - // $FlowFixMe - navigator.usb.removeEventListener("disconnect", onDisconnect); - transport._emitDisconnect(new lib.DisconnectedDevice()); - } - }; - // $FlowFixMe + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) + }; - navigator.usb.addEventListener("disconnect", onDisconnect); - return _context4.abrupt("return", transport); + // 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); - case 21: - case "end": - return _context4.stop(); - } - } - }, _callee4, this, [[7, 12]]); - })); + 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 open(_x) { - return _ref4.apply(this, arguments); - } + 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 open; - }() - }]); + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) + }; - return TransportWebUSB; - }(_hwTransport2.default); + function allocUnsafe (size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0) + } - TransportWebUSB.isSupported = webusb.isSupported; - TransportWebUSB.list = webusb.getLedgerDevices; + /** + * 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) + }; - 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; + function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; } - return { unsubscribe: unsubscribe }; - }; - var _initialiseProps = function _initialiseProps() { - var _this2 = this; + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } - this.channel = Math.floor(Math.random() * 0xffff); - this.packetSize = 64; - this._disconnectEmitted = false; + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); - this._emitDisconnect = function (e) { - if (_this2._disconnectEmitted) return; - _this2._disconnectEmitted = true; - _this2.emit("disconnect", e); - }; + var actual = buf.write(string, encoding); - 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; + 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); + } - (0, lib$2.log)("apdu", "=> " + apdu.toString("hex")); + return buf + } - framing = (0, _hidFraming2.default)(channel, packetSize); + 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 + } - // Write... + function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) + } - blocks = framing.makeBlocks(apdu); - i = 0; + function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } - case 5: - if (!(i < blocks.length)) { - _context5.next = 12; - break; - } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } - (0, lib$2.log)("hid-frame", "=> " + blocks[i].toString("hex")); - _context5.next = 9; - return _this2.device.transferOut(endpointNumber, blocks[i]); + 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); + } - case 9: - i++; - _context5.next = 5; - break; + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype); - case 12: + return buf + } - // Read... - result = void 0; - acc = void 0; + function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); - case 14: - if (result = framing.getReducedResult(acc)) { - _context5.next = 23; - break; - } + if (buf.length === 0) { + return buf + } - _context5.next = 17; - return _this2.device.transferIn(endpointNumber, packetSize); + obj.copy(buf, 0, 0, len); + return buf + } - case 17: - r = _context5.sent; - buffer = Buffer.from(r.data.buffer); + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } - (0, lib$2.log)("hid-frame", "<= " + buffer.toString("hex")); - acc = framing.reduceResponse(acc, buffer); - _context5.next = 14; - break; + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } - case 23: + 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 + } - (0, lib$2.log)("apdu", "<= " + result.toString("hex")); - return _context5.abrupt("return", result); + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length) + } - 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; - }); - }; + Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false }; - 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 + 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' + ) + } - /** Namespace for the U2F api. - * @type {Object} - */ - var u2f = u2f || {}; + if (a === b) return 0 - var googleU2fApi = u2f; // Adaptation for u2f-api package + var x = a.length; + var y = b.length; - /** - * The U2F extension id - * @type {string} - * @const - */ - u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd'; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } - /** - * 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' + if (x < y) return -1 + if (y < x) return 1 + return 0 }; - /** - * Response status codes - * @const - * @enum {number} - */ - u2f.ErrorCodes = { - 'OK': 0, - 'OTHER_ERROR': 1, - 'BAD_REQUEST': 2, - 'CONFIGURATION_UNSUPPORTED': 3, - 'DEVICE_INELIGIBLE': 4, - 'TIMEOUT': 5 + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } }; + Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - // Low level MessagePort API support + if (list.length === 0) { + return Buffer.alloc(0) + } - /** - * Call MessagePort disconnect - */ - u2f.disconnect = function() { - if (u2f.port_ && u2f.port_.port_) { - u2f.port_.port_.disconnect(); - u2f.port_ = null; + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } } - }; - /** - * 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); + 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 { - // chrome.runtime was available, but we couldn't message - // the extension directly, use iframe - u2f.getIframePort_(callback); + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); } - }); - } 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); + } 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 }; - /** - * A wrapper for chrome.runtime.Port that is compatible with MessagePort. - * @param {Port} port - * @constructor - * @private - */ - u2f.WrappedChromeRuntimePort_ = function(port) { - this.port_ = port; - }; + 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 + ) + } - /** - * Posts a message on the underlying channel. - * @param {Object} message - */ - u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) { - this.port_.postMessage(message); - }; + var len = string.length; + var mustMatch = (arguments.length > 2 && arguments[2] === true); + if (!mustMatch && len === 0) return 0 - /** - * 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'); + // 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; - /** - * 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(); + function slowToString (encoding, start, end) { + var loweredCase = false; - iframe.addEventListener('load', function() { - // Deliver the port to the iframe and initialize - iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]); - }); + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - // 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); - }; + // 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; + } - // High-level JS API + if (end <= 0) { + return '' + } - /** - * Default extension response timeout in seconds. - * @const - */ - u2f.EXTENSION_TIMEOUT_SEC = 30; + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; - /** - * A singleton instance for a MessagePort to the extension. - * @type {MessagePort|u2f.WrappedChromeRuntimePort_} - * @private - */ - u2f.port_ = null; + if (end <= start) { + return '' + } - /** - * Callbacks waiting for a port - * @type {Array.} - * @private - */ - u2f.waitingForPort_ = []; + if (!encoding) encoding = 'utf8'; - /** - * A counter for requestIds. - * @type {number} - * @private - */ - u2f.reqCounter_ = 0; + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - /** - * A map from requestIds to client callbacks - * @type {Object.} - * @private - */ - u2f.callbackMap_ = {}; + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - /** - * 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_)); - } + case 'ascii': + return asciiSlice(this, start, end) - // Careful, here be async callbacks. Maybe. - while (u2f.waitingForPort_.length) - u2f.waitingForPort_.shift()(err, port); - }); + 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; } - 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; + // 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); } - var cb = u2f.callbackMap_[reqId]; - delete u2f.callbackMap_[reqId]; - cb(null, response['responseData']); + return this }; - /** - * 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); - }); + 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 }; - /** - * 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); - }); + 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 }; - /** - * 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); - }); + 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 u2fApi = API; + Buffer.prototype.toLocaleString = Buffer.prototype.toString; + Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + Buffer.prototype.inspect = function inspect () { + 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; + } - // 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]/ ); + 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) + ) + } - 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 (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } - if ( !isBrowser ) - return notSupported( ); + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } - 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( ); + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - var hasNativeSupport = - ( typeof window.u2f !== 'undefined' ) && - ( typeof window.u2f.sign === 'function' ); + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - if ( hasNativeSupport ) - resolve( { u2f: window.u2f, native: true } ); + if (this === target) return 0 - if ( isEDGE ) - // We don't want to check for Google's extension hack on EDGE - // as it'll cause trouble (popups, etc) - return notSupported( ); + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - if ( location.protocol === 'http:' ) - // U2F isn't supported over http, only https - return notSupported( ); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - if ( typeof MessageChannel === 'undefined' ) - // Unsupported browser, the chrome hack would throw - return notSupported( ); + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } - // Test for google extension support - googleU2fApi.isSupported( function( ok ) - { - if ( ok ) - resolve( { u2f: googleU2fApi, native: false } ); - else - notSupported( ); - } ); - } ); + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; - return _backend; - } + // 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 - 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; + // 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 getBackend( Promise ) - .then( function( backend ) - { - return !!backend.u2f; - } ); - } + // 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 _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" ); - } - } + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } - function ensureSupport( ) - { - var Promise = this; + // 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) + } - return getBackend( Promise ) - .then( _ensureSupport ); + throw new TypeError('val must be string, number or Buffer') } - 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 arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - resolve( response ); - } + 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; + } + } - if ( native ) - { - var appId = registerRequests[ 0 ].appId; + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - u2f.register( - appId, registerRequests, signRequests, cbNative, timeout ); - } - else - { - u2f.register( - registerRequests, signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; + 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 } - 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 ); - } - } + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - resolve( response ); - } + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; - if ( native ) - { - var appId = signRequests[ 0 ].appId; - var challenge = signRequests[ 0 ].challenge; + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; - u2f.sign( appId, challenge, signRequests, cbNative, timeout ); - } - else - { - u2f.sign( signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } + 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; + } + } - 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 strLen = string.length; - var args = [ ].slice.call( arguments ); - return API( commonjsGlobal.Promise )[ func ].apply( null, args ); - }; + 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 } - // 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) { + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } - Object.defineProperty(exports, "__esModule", { - value: true - }); + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } - 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; }; + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } - var errorClasses = {}; - var deserializers = {}; + 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 addCustomErrorDeserializer = exports.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; - }; + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - 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(); + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } - errorClasses[name] = C; - // $FlowFixMe we can't easily type a subset of Error for now... - return C; - }; + if (!encoding) encoding = 'utf8'; - // 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 loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) - if (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - 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); - } + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; } - 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") + "]"; + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) } - 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; - } - } + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) } + } - 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; - } + 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; - 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; + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; - var lib$3 = createCommonjsModule(function (module, exports) { + 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; + } + } + } + } - 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"); + 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; + } - // 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"); + res.push(codePoint); + i += bytesPerSequence; + } - /** - * 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 decodeCodePointsArray(res) } - //$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 - }; + // 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 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"; + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; + + // 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 } - /** - * 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); - }); + 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 + } - 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; + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - 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; }; }(); + 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 _events3 = _interopRequireDefault(EventEmitter); + 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; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } - 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 (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } - 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"); }); }; } + if (end < start) end = start; - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype); - exports.TransportError = lib$3.TransportError; - exports.TransportStatusError = lib$3.TransportStatusError; - exports.StatusCodes = lib$3.StatusCodes; - exports.getAltStatusMessage = lib$3.getAltStatusMessage; + 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 mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + return val + }; - /** - * 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 - */ + Buffer.prototype.readUintBE = + Buffer.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; + } - /** - * 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; + return val + }; - _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; - } + Buffer.prototype.readUint8 = + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; - throw new lib$3.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + 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) + }; - case 2: - _context.next = 4; - return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); + 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] + }; - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); + Buffer.prototype.readUint32LE = + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; - throw new lib$3.TransportStatusError(sw); + Buffer.prototype.readUint32BE = + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - case 8: - return _context.abrupt("return", response); + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - 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; - } + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; - throw new lib$3.TransportError("Transport race condition", "RaceCondition"); + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); + return val + }; - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; - case 10: - _context2.prev = 10; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); + return val + }; - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); + 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 function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); - - this._appAPIlock = null; - } - - /** - * Statically check if a transport is supported on the user's platform/browser. - */ + 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.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 + }; - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ + 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) + }; - /** - * 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: () => {} - }) - */ + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; - /** - * 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 => ...) - */ + 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) + }; + 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) + }; - /** - * 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 - */ + 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.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) + }; - /** - * 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 - */ + 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); + } - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + return offset + byteLength + }; - _createClass(Transport, [{ - key: "on", + 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 i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - /** - * 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); - } + return offset + byteLength + }; - /** - * Stop listening to an event on an instance of transport. - */ + 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 + }; - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; + 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 + }; - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } + 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 + }; - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); - } + 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 + }; - /** - * Enable or not logs of the binary exchange - */ + 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 + }; - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; + 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; + } - /** - * 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 - */ + return offset + byteLength + }; - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - 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; - } - } - } + 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; } - }, { - 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]; - } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } - var _appAPIlock; + return offset + byteLength + }; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; + 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 (!_appAPIlock) { - _context3.next = 3; - break; - } + 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 _context3.abrupt("return", Promise.reject(new lib$3.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); + 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 + }; - case 3: - _context3.prev = 3; + 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 + }; - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); + 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 8: - return _context3.abrupt("return", _context3.sent); + 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 9: - _context3.prev = 9; + 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 + } - _this2._appAPIlock = null; - return _context3.finish(9); + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; - return function () { - return _ref3.apply(this, arguments); - }; - }(); - } - }], [{ - key: "create", + 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 + } + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; - /** - * 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; + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; + // 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 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; - }); - } + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - // $FlowFixMe + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') - }]); + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - return Transport; - }(); + var len = end - start; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - exports.default = Transport; + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } - }); + return len + }; - 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; + // 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 TransportU2F_1 = createCommonjsModule(function (module, exports) { + // 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') + } - Object.defineProperty(exports, "__esModule", { - value: true - }); + if (end <= start) { + return this + } - 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; }; + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - 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; }; }(); + 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]; + } + } + return this + }; + // HELPER FUNCTIONS + // ================ + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - var _hwTransport2 = _interopRequireDefault(Transport_1$1); + 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 + } + // valid lead + leadSurrogate = codePoint; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + continue + } - 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"); }); }; } + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // 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 _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; } + leadSurrogate = null; - 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; } + // 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') + } + } - function wrapU2FTransportError(originalError, message, id) { - var err = new lib$3.TransportError(message, id); - // $FlowFixMe - err.originalError = originalError; - return err; + return bytes } - 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]; + 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 result; + return byteArray } - // 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 utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - 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; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - 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; - } - }); + return byteArray } - var transportInstances = []; - - function emitDisconnect() { - transportInstances.forEach(function (t) { - return t.emit("disconnect"); - }); - transportInstances = []; + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) } - function isTimeoutU2FError(u2fError) { - return u2fError.metaData.code === 5; + 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 } - /** - * 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) - */ + // 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)); + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ - /* - */ - 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 (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer$1 = buffer; + var Buffer = buffer$1.Buffer; - function open(_x) { - return _ref.apply(this, arguments); - } + // 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 open; - }() + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } - /* - */ + SafeBuffer.prototype = Object.create(Buffer.prototype); - }]); + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer); - function TransportU2F() { - _classCallCheck(this, TransportU2F); + 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 _this = _possibleConstructorReturn(this, (TransportU2F.__proto__ || Object.getPrototypeOf(TransportU2F)).call(this)); + 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 + }; - _this.unwrap = true; + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) + }; - transportInstances.push(_this); - 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)); - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ + var readableBrowser = {exports: {}}; - - _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 - }); + var _registry = {}; // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js @@ -5967,10 +5036,10 @@ window.Buffer = buffer.Buffer; } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; - if (typeof global.setTimeout === 'function') { + if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } - if (typeof global.clearTimeout === 'function') { + if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } @@ -6091,23 +5160,23 @@ window.Buffer = buffer.Buffer; }; var title = 'browser'; var platform = 'browser'; - var browser = true; + var browser$6 = true; var env = {}; var argv = []; - var version = ''; // empty string to avoid regexp issues + 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 = 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'); @@ -6119,7 +5188,7 @@ window.Buffer = buffer.Buffer; }function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global.performance || {}; + var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || @@ -6155,14 +5224,14 @@ window.Buffer = buffer.Buffer; var process = { nextTick: nextTick, title: title, - browser: browser, + browser: browser$6, env: env, argv: argv, - version: version, + version: version$1, versions: versions, on: on, addListener: addListener, - once: once, + once: once$3, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, @@ -6174,5919 +5243,37009 @@ window.Buffer = buffer.Buffer; hrtime: hrtime, platform: platform, release: release, - config: config, + config: config$1, 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 - } - }); + var events = {exports: {}}; + + 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 { - inherits = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); }; } - 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(' '); - } + function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); + } - 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; + var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; + }; + + function EventEmitter() { + EventEmitter.init.call(this); } + events.exports = EventEmitter; + events.exports.once = once$2; - // 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); - }; - } + // Backwards-compat with node 0.10.x + EventEmitter.EventEmitter = EventEmitter; - if (process.noDeprecation === true) { - return fn; - } + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._eventsCount = 0; + EventEmitter.prototype._maxListeners = undefined; - 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); - } + // 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 deprecated; + function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } } - 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() {}; + 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; } - 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); + EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; } - // 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] + this._maxListeners = this._maxListeners || undefined; }; - // 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' + // 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 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 _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; } + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; - function stylizeNoColor(str, styleType) { - return str; - } + EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; - function arrayToHash(array) { - var hash = {}; + // 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 + } - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; - } + var handler = events[type]; + if (handler === undefined) + return 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(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; + 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); } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + return true; + }; - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + checkListener(listener); - // 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); - } + 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); - // 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'); + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); } - if (isError(value)) { - return formatError(value); + + // 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 base = '', array = false, braces = ['{', '}']; + return target; + } - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + EventEmitter.prototype.on = EventEmitter.prototype.addListener; - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); + 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); } + } - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + 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 (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; - ctx.seen.push(value); + // 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 output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } + checkListener(listener); - ctx.seen.pop(); + events = this._events; + if (events === undefined) + return this; - return reduceToSingleString(output, base, braces); - } + list = events[type]; + if (list === undefined) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; - 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'); - } + 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; - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + if (list.length === 1) + events[type] = list[0]; - 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 (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + 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(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; } - 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'); + + // 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; } - } 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; - } + listeners = events[type]; + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } - 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); + return this; + }; - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } + function _listeners(target, type, unwrap) { + var events = target._events; - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } + if (events === undefined) + return []; + var evlistener = events[type]; + if (evlistener === undefined) + return []; - // 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); - } + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - function isBoolean(arg) { - return typeof arg === 'boolean'; + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } - function isNull(arg) { - return arg === null; - } + EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); + }; - function isNullOrUndefined(arg) { - return arg == null; - } + EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); + }; - function isNumber(arg) { - return typeof arg === 'number'; - } + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; - function isString(arg) { - return typeof arg === 'string'; - } + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; - function isSymbol(arg) { - return typeof arg === 'symbol'; - } + if (events !== undefined) { + var evlistener = events[type]; - function isUndefined(arg) { - return arg === void 0; - } + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; + return 0; } - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; + function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; } - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); } - function isFunction(arg) { - return typeof arg === 'function'; + 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 isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; + function once$2(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 isBuffer(maybeBuf) { - return Buffer.isBuffer(maybeBuf); + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } } - function objectToString(o) { - return Object.prototype.toString.call(o); + 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 EventEmitter$1 = events.exports; - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } + var streamBrowser = events.exports.EventEmitter; + var _nodeResolve_empty = {}; - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); - // 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(' '); - } + 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; } - // 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 _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 _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + 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 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - 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; - }; - } - }); + 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); } } - 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; - } - }); + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - 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; - } + var _require$2 = buffer, + Buffer$k = _require$2.Buffer; + + var _require2 = require$$4, + inspect$1 = _require2.inspect; - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; + var custom = inspect$1 && inspect$1.custom || 'inspect'; + + function copyBuffer(src, target, offset) { + Buffer$k.prototype.copy.call(src, target, offset); } - function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck(this, BufferList); - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') + this.head = null; + this.tail = null; + this.length = 0; } - // 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; + _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; + } - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); + 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; + } - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. - var L = 0; + }, { + 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); + } - 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; - } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. - 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; - } + }, { + 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); + } - return arr - } + break; + } - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] - } + ++c; + } - 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('') - } + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. - 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 + }, { + 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); + } - // 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))); - } + break; + } - // 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 += '='; - } + ++c; + } - parts.push(output); + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. - return parts.join('') - } + }, { + key: custom, + value: function value(_, options) { + return inspect$1(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); - 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]; + return BufferList; + }(); - i += d; + function destroy(err, cb) { + var _this = this; - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + 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); + } + } - 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) - } + 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 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 (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well - 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; + 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 { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; + nextTick(emitCloseNT, _this); } - } + }); - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + return this; + } - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } - buffer[offset + i - d] |= s * 128; + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); } - var toString = {}.toString; + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } - var isArray$1 = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; + 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; + } + } - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ + function emitErrorNT(self, err) { + self.emit('error', err); + } - var INSPECT_MAX_BYTES = 50; + 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); + } - /** - * 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. + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; - * 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; + var errorsBrowser = {}; - /* - * Export kMaxLength after typed array support is determined. - */ - var _kMaxLength = kMaxLength(); + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - function kMaxLength () { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } + var codes = {}; - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; } - 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); + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); } - that.length = length; } - return that - } + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); - /** - * 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 NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } - function Buffer$1 (arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } + return NodeError; + }(Base); - // 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' - ) + 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]); } - return allocUnsafe(this, arg) + } else { + return "of ".concat(thing, " ").concat(String(expected)); } - return from(this, arg, encodingOrOffset, length) - } + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - 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 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 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) + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; } - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) + 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; } - return fromObject(that, value) + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } } - /** - * 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) - }; + 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 (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - } + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } - 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') + 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')); } + + 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; + + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } - 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) + 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; } - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer$1.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) + var state = { + getHighWaterMark: getHighWaterMark$2 }; - 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; + var string_decoder = {}; + + /**/ + + 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; + } + }; + + 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 that + } + // 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; } - /** - * 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'; + // 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); + } - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') + 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 length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + StringDecoder$2.prototype.end = utf8End; - var actual = that.write(string, encoding); + // Returns only complete characters in a Buffer + StringDecoder$2.prototype.text = utf8Text; - 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); + // 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; + }; - return that + // 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; } - 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; + // 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 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') + // 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); + } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') + // 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; + } - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); + 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 { - array = new Uint8Array(array, byteOffset, length); + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; } + return buf.toString('base64', i, buf.length - n); + } - 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 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 fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } - if (that.length === 0) { - return that + 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]; } - obj.copy(that, 0, 0, len); - return that - } + callback.apply(this, args); + }; + } - 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) + 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 (obj.type === 'Buffer' && isArray$1(obj.data)) { - return fromArrayLike(that, obj.data) + 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); } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + 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); + }; } - 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 + 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 SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0; + 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)); + } } - return Buffer$1.alloc(+length) } - Buffer$1.isBuffer = isBuffer$1; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) + + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); } - Buffer$1.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } - if (a === b) return 0 + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } - var x = a.length; - var y = b.length; + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break + 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 (x < y) return -1 - if (y < x) return 1 - return 0 - }; + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } - 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 - } - }; + 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 - 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 lastPromise = this[kLastPromise]; + var promise; - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; + 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; - 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 - }; + // 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 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; - } + 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); + } - var len = string.length; - if (len === 0) return 0 + iterator[kError] = err; + return; + } - // 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; + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); } - } - } - Buffer$1.byteLength = byteLength; - function slowToString (encoding, start, end) { - var loweredCase = false; + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + var async_iterator = createReadableStreamAsyncIterator$1; - // 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 fromBrowser = function () { + throw new Error('Readable.from is not available in the browser') + }; - if (end === undefined || end > this.length) { - end = this.length; - } + const Registry$4 = _registry; + Registry$4.Readable = Readable$1; - if (end <= 0) { - return '' - } + Readable$1.ReadableState = ReadableState$1; + /**/ - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; + events.exports.EventEmitter; - if (end <= start) { - return '' - } + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ - 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) + var Stream$2 = streamBrowser; + /**/ - case 'ascii': - return asciiSlice(this, start, end) - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) + var Buffer$i = buffer.Buffer; - case 'base64': - return base64Slice(this, start, end) + var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$i.from(chunk); + } - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } - } + function _isUint8Array$1(obj) { + return Buffer$i.isBuffer(obj) || obj instanceof OurUint8Array$1; } + /**/ - // 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; + var debugUtil = require$$4; + + var debug$5; + + if (debugUtil && debugUtil.debuglog) { + debug$5 = debugUtil.debuglog('stream'); + } else { + debug$5 = function debug() {}; } + /**/ - 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 - }; + var BufferList$1 = buffer_list; - 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 - }; + var destroyImpl$1 = destroy_1; - 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) - }; + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; - 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 - }; + 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. - 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') - } + var StringDecoder$1; + var createReadableStreamAsyncIterator; + var from; - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } + inherits_browser.exports(Readable$1, Stream$2); - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } + 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. - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + 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 === target) return 0 + 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. - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + 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 - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + 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" - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } + 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() - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; + 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. - // 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 + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - // 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); - } + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. - // 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 - } + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - // Normalize val - if (typeof val === 'string') { - val = Buffer$1.from(val, encoding); - } + this.autoDestroy = !!options.autoDestroy; // has it been destroyed - // 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) - } + 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. - throw new TypeError('val must be string, number or Buffer') + 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 arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; + 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 - 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 isDuplex = this instanceof Registry$4.Duplex; + 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; } - function read$$1 (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) + Stream$2.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$1.destroy; + Readable$1.prototype._undestroy = destroyImpl$1.undestroy; - 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; + 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$i.from(chunk, encoding); + encoding = ''; } + + skipChunkCheck = true; } } 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 - } + skipChunkCheck = true; } - return -1 - } + return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() - 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) + Readable$1.prototype.unshift = function (chunk) { + return readableAddChunk$1(this, chunk, null, true, false); }; - Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - }; + function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug$5('readableAddChunk', chunk); + var state = stream._readableState; - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; + if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } + 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); + } - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + 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 (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 - } + 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. - 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) + return !state.ended && (state.length < state.highWaterMark || state.length === 0); } - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } + 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 base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) + maybeReadMore$1(stream, state); } - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } + function chunkInvalid$1(state, chunk) { + var er; - 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' - ) + if (!_isUint8Array$1(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; + return er; + } - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } + Readable$1.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. - if (!encoding) encoding = 'utf8'; - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + 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 - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - case 'ascii': - return asciiWrite(this, string, offset, length) + var p = this._readableState.buffer.head; + var content = ''; - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + this._readableState.buffer.clear(); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB - 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) - } - }; + var MAX_HWM$1 = 0x40000000; - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) + function computeNewHighWaterMark$1(n) { + if (n >= MAX_HWM$1) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM$1; } else { - return fromByteArray(buf.slice(start, end)) + // 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 utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. - 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; + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 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; - } - } - } - } + 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 (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 (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 decodeCodePointsArray(res) - } + return state.length; + } // you can override either this method, or the async _read(n) below. - // 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() - } + 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. - // 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 (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; } - return res - } - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret - } + 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. - 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 doRead = state.needReadable; + debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - function hexSlice (buf, start, end) { - var len = buf.length; + 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 (!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 - } + 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 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 - } + if (state.length === 0) state.needReadable = true; // call internal read method - Buffer$1.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; + this._read(state.highWaterMark); - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } + 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 (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; + if (!state.reading) n = howMuchToRead$1(nOrig, state); } - if (end < start) end = start; + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } + state.length -= n; + state.awaitDrain = 0; } - 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); + 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. - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + if (nOrig !== n && state.ended) endReadable$1(this); } - return val + if (ret !== null) this.emit('data', ret); + return ret; }; - Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } + function onEofChunk$1(stream, state) { + debug$5('onEofChunk'); + if (state.ended) return; - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } - return val - }; + state.ended = true; - Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; + 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; - Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; + 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. - 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); + function emitReadable$1(stream) { + var state = stream._readableState; + debug$5('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; + if (!state.emittedReadable) { + debug$5('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_$1, stream); + } + } - Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + 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. - 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); + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); + } + } - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + 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; } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + 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 val + + Readable$1.prototype._read = function (n) { + errorOrDestroy$1(this, new ERR_METHOD_NOT_IMPLEMENTED$2('_read()')); }; - Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + Readable$1.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + 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); - return val - }; + function onunpipe(readable, unpipeInfo) { + debug$5('onunpipe'); - 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) - }; + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } - 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 - }; + 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. - 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); + var ondrain = pipeOnDrain$1(src); + dest.on('drain', ondrain); + var cleanedUp = false; - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; + function cleanup() { + debug$5('cleanup'); // cleanup event handlers once the pipe is broken - Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + 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. - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; + src.on('data', ondata); - Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) - }; + function ondata(chunk) { + debug$5('ondata'); + var ret = dest.write(chunk); + debug$5('dest.write', ret); - Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; + 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++; + } - Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) - }; + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - 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); - } + 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. - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - return offset + byteLength - }; + prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - 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); + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + dest.once('close', onclose); + + function onfinish() { + debug$5('onfinish'); + dest.removeListener('close', onclose); + unpipe(); } - return offset + byteLength - }; + dest.once('finish', onfinish); - 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 unpipe() { + debug$5('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to - 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 - }; + dest.emit('pipe', src); // start the flow if it hasn't been started already. - 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); + if (!state.flowing) { + debug$5('pipe resume'); + src.resume(); } - return offset + 2 + + return dest; }; - 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; - } + 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); + } + }; } - 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 - }; + Readable$1.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. - 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 - }; + if (state.pipesCount === 0) return this; // just one destination. most common case. - 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); + 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. - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. - 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; + + 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 + }); } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - return offset + byteLength - }; + return this; + } // try to find the right one. - 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 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 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 - }; + Readable$1.prototype.on = function (ev, fn) { + var res = Stream$2.prototype.on.call(this, ev, fn); + var state = this._readableState; - 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 - }; + 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 - 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 - }; + 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); - 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); + if (state.length) { + emitReadable$1(this); + } else if (!state.reading) { + nextTick(nReadingNextTick$1, this); + } + } } - 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 + return res; }; - 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 - }; + Readable$1.prototype.addListener = Readable$1.prototype.on; - 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') - } + Readable$1.prototype.removeListener = function (ev, fn) { + var res = Stream$2.prototype.removeListener.call(this, ev, fn); - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); + 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(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) + return res; }; - Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - }; + Readable$1.prototype.removeAllListeners = function (ev) { + var res = Stream$2.prototype.removeAllListeners.apply(this, arguments); - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); + 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); } - 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) + return res; }; - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - }; + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; - // 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; + 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(); + } + } - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 + 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. - // 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; - } + Readable$1.prototype.resume = function () { + var state = this._readableState; - var len = end - start; - var i; + if (!state.flowing) { + debug$5('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() - 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 - ); + state.flowing = !state.readableListening; + resume$1(this, state); } - return len + state.paused = false; + return this; }; - // 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; + function resume$1(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_$1, stream, state); } + } - // 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 resume_$1(stream, state) { + debug$5('resume', state.reading); - if (end <= start) { - return this + if (!state.reading) { + stream.read(0); } - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + state.resumeScheduled = false; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); + } - if (!val) val = 0; + Readable$1.prototype.pause = function () { + debug$5('call pause flowing=%j', this._readableState.flowing); - 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]; - } + if (this._readableState.flowing !== false) { + debug$5('pause'); + this._readableState.flowing = false; + this.emit('pause'); } - return this + this._readableState.paused = true; + return this; }; - // HELPER FUNCTIONS - // ================ + function flow$1(stream) { + var state = stream._readableState; + debug$5('flow', state.flowing); - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + 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. - 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, '') - } + Readable$1.prototype.wrap = function (stream) { + var _this = this; - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug$5('wrapped end'); - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); + _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 - // 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 (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - // valid lead - leadSurrogate = codePoint; + var ret = _this.push(chunk); - continue - } + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } + 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. - // 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); + + 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(); } + }; - leadSurrogate = null; + return this; + }; - // 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') + if (typeof Symbol === 'function') { + Readable$1.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; } - } - return bytes + return createReadableStreamAsyncIterator(this); + }; } - 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(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; } - 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 + }); + 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. - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); + 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. - return byteArray + 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); - 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]; + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT$1, state, stream); } - return i } - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } + 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'); - // 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)) + 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 isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + if (typeof Symbol === 'function') { + Readable$1.from = function (iterable, opts) { + if (from === undefined) { + from = fromBrowser; + } + + return from(Readable$1, iterable, opts); + }; } - // 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)) + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; } - var buffer = /*#__PURE__*/Object.freeze({ - INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, - kMaxLength: _kMaxLength, - Buffer: Buffer$1, - SlowBuffer: SlowBuffer, - isBuffer: isBuffer$1 - }); + /** + * Module exports. + */ - var safeBuffer = createCommonjsModule(function (module, exports) { - /* eslint-disable node/no-deprecated-api */ + var browser$5 = deprecate$1; - var Buffer = buffer.Buffer; + /** + * 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 + */ - // alternative to using Object.keys for old browsers - function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key]; + 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); + } + warned = true; + } + return fn.apply(this, arguments); } + + return deprecated; } - if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer; - } else { - // Copy properties from require('buffer') - copyProps(buffer, exports); - exports.Buffer = SafeBuffer; + + /** + * 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'; } - function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) + const Registry$3 = _registry; + + Registry$3.Writable = Writable$1; + // 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); + }; } + /* */ - // 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; - }; + Writable$1.WritableState = WritableState$1; + /**/ - 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 internalUtil = { + deprecate: browser$5 }; + /**/ - 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; - }; + var Stream$1 = streamBrowser; + /**/ - 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; - } - }; + var Buffer$h = buffer.Buffer; + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } + function _uint8ArrayToBuffer(chunk) { + return Buffer$h.from(chunk); } - // 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; + function _isUint8Array(obj) { + return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; } - // 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; + var destroyImpl = destroy_1; - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } + var _require = state, + getHighWaterMark = _require.getHighWaterMark; - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); + 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; - 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 errorOrDestroy = destroyImpl.errorOrDestroy; - charStr += buffer.toString(this.encoding, 0, end); + inherits_browser.exports(Writable$1, Stream$1); - 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); - } + function nop$1() {} - // or just emit the charStr - return charStr; - }; + 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. - // 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; + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Registry$3.Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. - // 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.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() - // See http://en.wikipedia.org/wiki/UTF-8#Description + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + this.finalCalled = false; // drain event flag. - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + this.needDrain = false; // at the start of calling end() - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; + this.ending = false; // when end() has been called, and returned - StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + this.ended = false; // when 'finish' is emitted - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } + this.finished = false; // has it been destroyed - return res; - }; + 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 passThroughWrite(buffer) { - return buffer.toString(this.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. - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } + 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 base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } + this.length = 0; // a flag to see when we're in the middle of a write. - var stringDecoder = /*#__PURE__*/Object.freeze({ - StringDecoder: StringDecoder - }); + this.writing = false; // when true all writes will be buffered until .uncork() call - Readable.ReadableState = ReadableState; + 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 debug = debuglog('stream'); - inherits$1(Readable, EventEmitter); + 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 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) { + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - options = options || {}; + this.onwrite = function (er) { + onwrite$1(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - // 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; + this.writecb = null; // the amount that is being written when _write is called. - // 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; + 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 - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - // 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.prefinished = false; // True if the error was already emitted and should not be thrown again - // 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.errorEmitted = false; // Should close be emitted on destroy. Defaults to 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.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - // 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.autoDestroy = !!options.autoDestroy; // count buffered requests - // 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.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + this.corkedRequestsFree = new CorkedRequest$1(this); + } - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + WritableState$1.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; + while (current) { + out.push(current); + current = current.next; } - } - function Readable(options) { - if (!(this instanceof Readable)) return new Readable(options); + return out; + }; - this._readableState = new ReadableState(options, this); + (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. - // legacy - this.readable = true; - if (options && typeof options.read === 'function') this._read = options.read; + var realHasInstance; - EventEmitter.call(this); + 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; + }; } - // 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; + 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 - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } + 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; } - return readableAddChunk(this, state, chunk, encoding, false); - }; + Stream$1.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); + + Writable$1.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; + function writeAfterEnd$1(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - 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; - } + 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. - 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); + function validChunk$1(stream, state, chunk, cb) { + var er; - if (state.needReadable) emitReadable(stream); - } - } + 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); + } - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; + if (er) { + errorOrDestroy(stream, er); + nextTick(cb, er); + return false; } - return needMoreData(state); + return true; } - // 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$1.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - // backwards compatibility. - Readable.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; - }; + var isBuf = !state.objectMode && _isUint8Array(chunk); - // 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 (isBuf && !Buffer$h.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); } - 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; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - 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; + 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; + }; - n = howMuchToRead(n, state); + Writable$1.prototype.cork = function () { + this._writableState.corked++; + }; - // 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; - } + Writable$1.prototype.uncork = function () { + var state = this._writableState; - // 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 (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + } + }; - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); + 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; + }; - // 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); + 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(); } + }); - // 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); + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$h.from(chunk, encoding); } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + return chunk; + } - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; + 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. - 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(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(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; - } + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; - 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; + 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(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(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 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_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); + 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(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 + + finishMaybe$1(stream, 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(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); - } + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - 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; + 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); + } } - 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')); - }; + 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. - 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; + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + } // if there's something in the buffer waiting, then process it - var doEnd = (!pipeOpts || pipeOpts.end !== false); - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } + 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 onend() { - debug('onend'); - dest.end(); - } + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } - // 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); + 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 - 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); + state.pendingcb++; + state.lastBufferedRequest = null; - cleanedUp = true; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest$1(state); + } - // 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(); - } + 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 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; + 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('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount$1(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('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + Writable$1.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$1('_write()')); + }; - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } + Writable$1.prototype._writev = null; - // tell the dest that it's being piped to - dest.emit('pipe', src); + Writable$1.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('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 - 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); - } - }; - } + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + if (!state.ending) endWritable$1(this, state, cb); + 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; + 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; + } + }); - if (!dest) dest = state.pipes; + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; - // slow case. multiple pipe destinations. + if (err) { + errorOrDestroy(stream, err); + } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe$1(stream, state); + }); + } - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; + 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'); + } } + } - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) return this; + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + if (need) { + prefinish$2(stream, state); - dest.emit('unpipe', this); - - return this; - }; + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); - // 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 (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 (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); + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } } } } - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; - - function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); + return need; } - // 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 endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); } + + state.ended = true; + stream.writable = false; } - function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. - 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) {} + state.corkedRequestsFree.next = corkReq; } - // 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); + 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; } - self.push(null); - }); + 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 - 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; + this._writableState.destroyed = value; + } + }); + Writable$1.prototype.destroy = destroyImpl.destroy; + Writable$1.prototype._undestroy = destroyImpl.undestroy; - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + Writable$1.prototype._destroy = function (err, cb) { + cb(err); + }; - // 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)); - }); + var objectKeys = Object.keys || function (obj) { + var keys = []; - // 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(); - } - }; + for (var key in obj) { + keys.push(key); + } - return self; + return keys; }; + /**/ - // exposed for testing purposes only. - Readable._fromList = fromList; + const Registry$2 = _registry; - // 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; + Registry$2.Duplex = Duplex$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); - } + inherits_browser.exports(Duplex$1, Registry$2.Readable); - return ret; - } + { + // Allow the keys array to be GC'ed. + var keys$1 = objectKeys(Registry$2.Writable.prototype); - // 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); + 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]; } - 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; - } + 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; - // 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; + 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); } - ++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); + 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._writableState.highWaterMark; } - } - - 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'); + }); + 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._writableState && this._writableState.getBuffer(); } - } + }); + 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._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. - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } + nextTick(onEndNT$1, this); } - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; + function onEndNT$1(self) { + self.end(); } - // A bit simpler than readable streams. - Writable.WritableState = WritableState; - inherits$1(Writable, EventEmitter); + 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; + } - function nop() {} + 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 - 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 || {}; + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + const Registry$1 = _registry; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + Registry$1.Transform = Transform$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; + 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; - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + inherits_browser.exports(Transform$4, Registry$1.Duplex); - 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 afterTransform$1(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; - // 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 (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } - // 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'; + 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; - // 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; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } - // a flag to see when we're in the middle of a write. - this.writing = false; + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); + Registry$1.Duplex.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. - // when true all writes will be buffered until .uncork() call - this.corked = 0; + 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. - // 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._readableState.sync = false; - // 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 (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. - // 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; + this.on('prefinish', prefinish$1); + } - // the amount that is being written when _write is called. - this.writelen = 0; + function prefinish$1() { + var _this = this; - this.bufferedRequest = null; - this.lastBufferedRequest = null; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done$1(_this, er, data); + }); + } else { + done$1(this, null, null); + } + } - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + 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. + // + // 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. - // 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; + Transform$4.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; - // count buffered requests - this.bufferedRequestCount = 0; + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(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. - WritableState.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; + + 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; } - 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); + Transform$4.prototype._destroy = function (err, cb) { + Registry$1.Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; - this._writableState = new WritableState(options, this); + 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 - // legacy. - this.writable = true; + 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 (options) { - if (typeof options.write === 'function') this._write = options.write; + const Registry = _registry; + Registry.PassThrough = PassThrough$1; - if (typeof options.writev === 'function') this._writev = options.writev; - } + inherits_browser.exports(PassThrough$1, Registry.Transform); - EventEmitter.call(this); + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + Transform.call(this, options); } - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); }; - 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 eos; + + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; } - // 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; + 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; } - Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } - if (typeof encoding === 'function') { - cb = encoding; - encoding = 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')); + }; + } - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + function call(fn) { + fn(); + } - if (typeof cb !== 'function') cb = nop; + function pipe(from, to) { + return from.pipe(to); + } - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); + 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]; } - return ret; - }; + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; - Writable.prototype.cork = function () { - var state = this._writableState; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } - state.corked++; - }; + 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); + } - Writable.prototype.uncork = function () { - var state = this._writableState; + var pipeline_1 = pipeline; - if (state.corked) { - state.corked--; + (function (module, exports) { + const Registry = _registry; - 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; - } + exports = module.exports = Registry.Readable; - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); + 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)); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + var Buffer$g = safeBuffer.exports.Buffer; + var Transform$3 = readableBrowser.exports.Transform; + var inherits$i = inherits_browser.exports; - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } } - 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); + function HashBase$2 (blockSize) { + Transform$3.call(this); - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + this._block = Buffer$g.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; - if (sync) { - /**/ - nextTick(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } + this._finalized = false; } - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } + inherits$i(HashBase$2, Transform$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'); + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; } - } - - // 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; - } + callback(error); + }; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } - // 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; + callback(error); + }; - 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; - } - } + 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 (entry === null) state.lastBufferedRequest = null; + // 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++]; - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } + // 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; + } - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); + return this }; - Writable.prototype._writev = null; - - Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); + return digest }; - 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'); - } - } + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; - 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 hashBase = HashBase$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; - stream.writable = false; - } + var inherits$h = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$f = 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 ARRAY16$1 = new Array(16); - this.next = null; - this.entry = null; + function MD5$2 () { + HashBase$1.call(this, 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; - } - }; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; } - inherits$1(Duplex, Readable); + inherits$h(MD5$2, HashBase$1); - 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); + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - Readable.call(this, options); - Writable.call(this, options); + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; - if (options && options.readable === false) this.readable = 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); - if (options && options.writable === false) this.writable = 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); - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + 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); - this.once('end', onend); - } + 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); - // 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; + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; + }; - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, 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; + } + + 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 onEndNT(self) { - self.end(); + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 } - // a transform stream is a readable/writable stream where you do - inherits$1(Transform, Duplex); + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } - function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 } - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + var md5_js = MD5$2; - var cb = ts.writecb; + var Buffer$e = buffer.Buffer; + var inherits$g = inherits_browser.exports; + var HashBase = hashBase; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + var ARRAY16 = new Array(16); - ts.writechunk = null; - ts.writecb = null; + 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 (data !== null && data !== undefined) stream.push(data); + 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 + ]; - cb(er); + 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 rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } + 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; } - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); + inherits$g(RIPEMD160$3, HashBase); - this._transformState = new TransformState(this); + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - // when the writable side finishes, then flush out anything remaining. - var stream = 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; - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = 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; - // 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; + // 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]); + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; - if (typeof options.flush === 'function') this._flush = options.flush; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; } - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done(stream, er); - });else done(stream); - }); - } + // 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; + }; - 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); + 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; } - }; - // 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; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - 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; - } + // 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 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'); + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } - return stream.push(null); + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } - inherits$1(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } - Transform.call(this, options); + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } - inherits$1(Stream, EventEmitter); - Stream.Readable = Readable; - Stream.Writable = Writable; - Stream.Duplex = Duplex; - Stream.Transform = Transform; - Stream.PassThrough = PassThrough; + var ripemd160$2 = RIPEMD160$3; - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; + var sha_js = {exports: {}}; - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. + var Buffer$d = safeBuffer.exports.Buffer; - function Stream() { - EventEmitter.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; } - Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); } - source.on('data', ondata); + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; - function ondrain() { - if (source.readable && source.resume) { - source.resume(); + 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]; } - } - dest.on('drain', ondrain); + accum += remainder; + offset += remainder; - // 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 ((accum % blockSize) === 0) { + this._update(block); + } } - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } + this._len += length; + return this + }; + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + this._block[rem] = 0x80; - if (typeof dest.destroy === 'function') dest.destroy(); - } + // 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); - // 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. - } + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); } - 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); + var bits = this._len * 8; - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; - dest.removeListener('close', cleanup); + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); } - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); + this._update(this._block); + var hash = this._hash(); - dest.emit('pipe', source); + return enc ? hash.toString(enc) : hash + }; - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') }; - var Buffer$2 = safeBuffer.Buffer; - var Transform$1 = Stream.Transform; + 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. + */ - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$2.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } - } + var inherits$f = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; - function HashBase (blockSize) { - Transform$1.call(this); + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - this._block = Buffer$2.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + var W$5 = new Array(80); - this._finalized = false; + function Sha () { + this.init(); + this._w = W$5; + + Hash$6.call(this, 64, 56); } - inherits$2(HashBase, Transform$1); + inherits$f(Sha, Hash$6); - HashBase.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - callback(error); + return this }; - HashBase.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) + } - callback(error); - }; + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) + } - 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); + 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 + } - // 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++]; + Sha.prototype._update = function (M) { + var W = this._w; - // 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 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 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; }; - HashBase.prototype._update = function () { - throw new Error('_update is not implemented') - }; + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); - HashBase.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = 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); - 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 sha$4 = Sha; - return digest - }; + /* + * 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. + */ - HashBase.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; + var inherits$e = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; - var hashBase = HashBase; + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - var Buffer$3 = safeBuffer.Buffer; + var W$4 = new Array(80); - var ARRAY16 = new Array(16); + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$5.call(this, 64, 56); + } - function MD5 () { - hashBase.call(this, 64); + inherits$e(Sha1, Hash$5); - // state + 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) } - inherits$2(MD5, hashBase); + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } - MD5.prototype._update = function () { - var M = ARRAY16; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; + 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 + } - 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); + Sha1.prototype._update = function (M) { + var W = this._w; - 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 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 = 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); + 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]); - 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); + 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; - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 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; }; - 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; - } + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + 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); - // 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 + return H }; - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } + var sha1$1 = Sha1; - function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 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 + * + */ - function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } + var inherits$d = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; - function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } + 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 fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 - } + var W$3 = new Array(64); - var md5_js = MD5; + function Sha256$1 () { + this.init(); - var Buffer$4 = buffer.Buffer; + this._w = W$3; // new Array(64) + Hash$4.call(this, 64, 56); + } + inherits$d(Sha256$1, Hash$4); - 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 - ]; + 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 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 this + }; - 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 ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } - function RIPEMD160 () { - hashBase.call(this, 64); + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) } - inherits$2(RIPEMD160, hashBase); + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } - RIPEMD160.prototype._update = function () { - var words = ARRAY16$1; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } - 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; + Sha256$1.prototype._update = function (M) { + var W = this._w; - 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 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; - // 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]); - } + 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; - al = el; - el = dl; - dl = rotl$1(cl, 10); - cl = bl; - bl = tl; + 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; - ar = er; - er = dr; - dr = rotl$1(cr, 10); - cr = br; - br = tr; + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 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; + 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; }; - 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; - } + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + 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); - // 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 + return H }; - 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 - } + var sha256$2 = Sha256$1; - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 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 + * + */ - 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 inherits$c = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 - } + var W$2 = new Array(64); - var ripemd160 = RIPEMD160; + function Sha224 () { + this.init(); - var Buffer$5 = safeBuffer.Buffer; + this._w = W$2; // new Array(64) - // 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$3.call(this, 64, 56); } - 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); + inherits$c(Sha224, Sha256); - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } - - accum += remainder; - offset += remainder; - - if ((accum % blockSize) === 0) { - this._update(block); - } - } + 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; - 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); - } + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); - var bits = this._len * 8; + 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); - // 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 sha224 = Sha224; - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } + var inherits$b = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; - this._update(this._block); - var hash = this._hash(); - - return enc ? hash.toString(enc) : hash - }; + 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 + ]; - Hash.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + var W$1 = new Array(160); - var hash = Hash; + function Sha512 () { + this.init(); + this._w = W$1; - /* - * 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. - */ + 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; - var Buffer$6 = safeBuffer.Buffer; + 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 K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + return this + }; - var W = new Array(80); + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - function Sha () { - this.init(); - this._w = W; + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } - hash.call(this, 64, 56); + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) } - inherits$2(Sha, hash); + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - return this - }; + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } - function rotl5 (num) { - return (num << 5) | (num >>> 27) + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) } - function rotl30 (num) { - return (num << 30) | (num >>> 2) + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) } - 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 getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 } - Sha.prototype._update = function (M) { + Sha512.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]; + 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; - 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; + 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; - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + 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); - 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; - }; + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - Sha.prototype._hash = function () { - var H = Buffer$6.allocUnsafe(20); + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - 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 Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - return H - }; + 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 sha = Sha; + W[i] = Wih; + W[i + 1] = Wil; + } - /* - * 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. - */ + 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); - var Buffer$7 = safeBuffer.Buffer; + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - var K$1 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - var W$1 = new Array(80); + 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 Sha1 () { - this.init(); - this._w = W$1; + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - hash.call(this, 64, 56); - } + 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; + } - inherits$2(Sha1, hash); + 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; - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this + 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 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; + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - 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); + 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 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 sha512 = Sha512; - 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 inherits$a = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$7 = safeBuffer.exports.Buffer; - var W$2 = new Array(64); + var W = new Array(160); - function Sha256 () { + function Sha384 () { this.init(); + this._w = W; - this._w = W$2; // new Array(64) - - hash.call(this, 64, 56); + Hash$1.call(this, 128, 112); } - inherits$2(Sha256, hash); + inherits$a(Sha384, SHA512$2); - 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; + 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 }; - 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; + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - 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); + 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 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 sha384 = Sha384; + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); - var Buffer$9 = safeBuffer.Buffer; + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - var W$3 = new Array(64); + return new Algorithm() + }; - function Sha224 () { - this.init(); + 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; - this._w = W$3; // new Array(64) + var sha$3 = sha_js.exports; - hash.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$2(Sha224, sha256); + 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(' '); + } - 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 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; + } - var W$4 = new Array(160); + // 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 Sha512 () { - this.init(); - this._w = W$4; + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - hash.call(this, 128, 112); + return deprecated; } - inherits$2(Sha512, hash); + 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]; + } - 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; + /** + * 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._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + // 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, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } } - 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 stylizeNoColor(str, styleType) { + return str; } - 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 arrayToHash(array) { + var hash = {}; - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } + array.forEach(function(val, idx) { + hash[val] = true; + }); - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 + return hash; } - 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); + 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; } - 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]; + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - 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; + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - W[i] = Wih; - W[i + 1] = Wil; + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); } - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; + // 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); + } - var majh = maj$1(ah, bh, ch); - var majl = maj$1(al, bl, cl); + // 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 sigma0h = sigma0$1(ah, al); - var sigma0l = sigma0$1(al, ah); - var sigma1h = sigma1$1(eh, el); - var sigma1l = sigma1$1(el, eh); + var base = '', array = false, braces = ['{', '}']; - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$3[j]; - var Kil = K$3[j + 1]; + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } - 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; + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } - 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; + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); } - 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; + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - 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; - }; + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } - Sha512.prototype._hash = function () { - var H = Buffer$10.allocUnsafe(64); + ctx.seen.push(value); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + 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); + }); } - 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 - }; + ctx.seen.pop(); - var sha512 = Sha512; + return reduceToSingleString(output, base, braces); + } - var Buffer$11 = safeBuffer.Buffer; - var W$5 = new Array(160); + 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 Sha384 () { - this.init(); - this._w = W$5; - hash.call(this, 128, 112); + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; } - 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; + 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 = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; - 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(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'); + } + } - Sha384.prototype._hash = function () { - var H = Buffer$11.allocUnsafe(48); + return name + ': ' + str; + } - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 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); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[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); + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } - return H - }; - var sha384 = Sha384; + // 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); + } - var sha_js = createCommonjsModule(function (module) { - var exports = module.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + function isBoolean(arg) { + return typeof arg === 'boolean'; + } - var Algorithm = exports[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + function isNull(arg) { + return arg === null; + } - return new Algorithm() - }; + function isNumber(arg) { + return typeof arg === 'number'; + } - exports.sha = sha; - exports.sha1 = sha1; - exports.sha224 = sha224; - exports.sha256 = sha256; - exports.sha384 = sha384; - exports.sha512 = sha512; - }); + function isString(arg) { + return typeof arg === 'string'; + } - var Buffer$12 = safeBuffer.Buffer; - var Transform$2 = Stream.Transform; - var StringDecoder$1 = stringDecoder.StringDecoder; + function isUndefined(arg) { + return arg === void 0; + } + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } - 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; + function isObject(arg) { + return typeof arg === 'object' && arg !== null; } - inherits$2(CipherBase, Transform$2); - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer$12.from(data, inputEnc); - } + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } - var outData = this._update(data); - if (this.hashMode) return this + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } - if (outputEnc) { - outData = this._toString(outData, outputEnc); + 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); + } - return outData - }; + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') + 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; }; - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; }; - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') + 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; }; - 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); - } + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; }; - 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 + 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; }; - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder$1(enc); - this._encoding = enc; + 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 (this._encoding !== enc) throw new Error('can\'t switch encodings') + Readable.ReadableState = ReadableState; - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } + var debug$4 = debuglog('stream'); + inherits$9(Readable, EventEmitter$1); - return 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]]; + } + } + 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); + } + + 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 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$4('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + 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; + } + + // 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; + + // 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); + } + }; + } + + 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$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$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); + } + } + + 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; + }; + + 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); + } + } + + // 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(); + } + }; + + 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$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 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$9(Writable, events.exports.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; + } + + events.exports.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.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; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (buffer.Buffer.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.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; + + 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$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); + + 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$9(Transform$2, 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$2(options) { + if (!(this instanceof Transform$2)) return new Transform$2(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$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) { + throw new Error('Not implemented'); + }; + + 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.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$9(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); + }; + + inherits$9(Stream, EventEmitter$1); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform$2; + 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); + } + + 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$1.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 stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream, + Readable: Readable, + Writable: Writable, + Duplex: Duplex, + Transform: Transform$2, + PassThrough: PassThrough, + Stream: Stream + }); + + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + + var Buffer$6 = safeBuffer.exports.Buffer; + var Transform$1 = require$$1.Transform; + var StringDecoder = string_decoder.StringDecoder; + var inherits$7 = inherits_browser.exports; + + function CipherBase (hashMode) { + Transform$1.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$1); + + 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 + }; + + 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$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; + } + + inherits$6(Hash, Base$5); + + Hash.prototype._update = function (data) { + this._hash.update(data); + }; + + 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 + } + } + 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); + + 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 = {}; + + 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); + }; + + 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(); + } + } + 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'); + } + + // 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 = "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: {}}; + + (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$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$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 + } + + 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 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$l, 'be', 32) } + function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } + 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) + 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$l.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$l(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$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); + } + } + 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$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'); + } + } + // 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$l.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$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 { + 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$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)); + + 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$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 ( + 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$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 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$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; + } + 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$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; + } + } + // 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; + } + 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); + } + 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$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; + } + } + } + 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$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; + } + } + 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$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; + } + 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$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 + ) { + 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$l.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$l.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$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); + } + 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)); + } + 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$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; + } + } + 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; + } + + 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$l.from(hex, 'hex')); + } + 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; + } + 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; + } + 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; + } + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Buffer$l && + 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$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; + } + 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$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; + + 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(), + }; + } + 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$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; + + 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$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; + + 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$l.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$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; + + 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$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; + + 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$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; + + 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$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 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$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; + + 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$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 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$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, + }; + } + 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$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, + }; + } + 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$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, + }; + } + 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$l.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$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; + + (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$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; + } + 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$l.from(data, 'base64'); + return this.fromBuffer(buffer, opts); + } + 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; + } + 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$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, + }); + } + 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$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.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$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`, + ); + } + }; + } + 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$l.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer$l.concat([buffer, Buffer$l.from(slice)]); + } + 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); + } + 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$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; + + 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$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, + }); + } + 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$l.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$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) { + 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$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 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$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"); + } + 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$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); + } + // 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 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$l.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$l.concat([Buffer$l.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$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"); + } + 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$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; + } + 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$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])); + } + 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 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; }) || + 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$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)); + /** + * 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$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"); + } + 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; + }; + 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]; + } + 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$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; + } + 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) { + 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$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; + } + + /** + @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, + ]); + } + + 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$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 != 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$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 != 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$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*/]; + } + }); + }); + }; + 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$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$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); + 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*/]; + } + }); + }); + } + + 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$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"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + 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]); + } + 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.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, 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"); + 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(initialTimestamp, 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")]; + } + }); + }); + } + + 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 + }]; + } + }); + }); + } + + 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, 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; + 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(initialTimestamp, 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$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)); + } + + /** + * 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; + }()); + + 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$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); + } + 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$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 = 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"); + } + 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]), + Buffer$l.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$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$l.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$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 = 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$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; + } + 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; } + } + } + 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; + }()); + + 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$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; + }()); + + 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$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$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])); + 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$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 + }); + } + 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 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 = {}; + 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 cipherBase = CipherBase; + 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$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; + } + /** + * 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; + }()); - function Hash$1 (hash) { - cipherBase.call(this, 'digest'); + var hidFraming$1 = {}; - this._hash = hash; + 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$l.alloc(2); + b.writeUInt16BE(value, 0); + return b; } + var initialAcc = { + data: Buffer$l.alloc(0), + dataLength: 0, + sequence: 0 + }; + /** + * + */ + 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; - inherits$2(Hash$1, cipherBase); + }(hidFraming$1)); - Hash$1.prototype._update = function (data) { - this._hash.update(data); - }; + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); - Hash$1.prototype._final = function () { - return this._hash.digest() + 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 S Plus", + 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 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, "")] = __assign({ deviceModel: deviceModel }, spec); + } + } + } - var browser$1 = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new md5_js() - if (alg === 'rmd160' || alg === 'ripemd160') return new ripemd160() + 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 = function () { + return Promise.resolve(!!navigator && + !!navigator.usb && + typeof navigator.usb.getDevices === "function"); + }; - return new Hash$1(sha_js(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 __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("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$l.from(r.data.buffer); + acc = framing.reduceResponse(acc, buffer); + return [3 /*break*/, 4]; + case 6: + log("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; + /** + * 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)); + 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 browser$2 = /*#__PURE__*/Object.freeze({ - default: browser$1, - __moduleExports: browser$1 + var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': TransportWebUSB }); exports.Btc = Btc$1; + exports.Log = index; exports.TransportWebUSB = TransportWebUSB$1; - exports.TransportU2F = TransportU2F$1; - exports.Log = index$3; - exports.createHash = browser$2; + exports.createHash = browser$4; Object.defineProperty(exports, '__esModule', { value: true }); -}))); +})); 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;