blob: c73b511429abfc58dbfbe781de77a33aa0412e2e [file] [log] [blame]
/*
<a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
<a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
<a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
MIT
<a href="https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE">MIT License</a>
<a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
<a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
*/
(function(a,b){"object"===typeof exports?module.exports.printStackTrace=b():"function"===typeof define&&define.amd?define(b):a.printStackTrace=b()})(this,function(){function a(b){b=b||{guess:!0};var c=b.e||null,d=!!b.guess,e=b.mode||null;b=new a.implementation;c=b.run(c,e);return d?b.guessAnonymousFunctions(c):c}a.implementation=function(){};a.implementation.prototype={run:function(a,c){a=a||this.createException();c=c||this.mode(a);return"other"===c?this.other(arguments.callee):this[c](a)},createException:function(){try{this.undef()}catch(a){return a}},
mode:function(a){return"undefined"!==typeof window&&-1<window.navigator.userAgent.indexOf("PhantomJS")?"phantomjs":a.arguments&&a.stack?"chrome":a.stack&&a.sourceURL?"safari":a.stack&&a.number?"ie":a.stack&&a.fileName?"firefox":a.message&&a["opera#sourceloc"]?!a.stacktrace||-1<a.message.indexOf("\n")&&a.message.split("\n").length>a.stacktrace.split("\n").length?"opera9":"opera10a":a.message&&a.stack&&a.stacktrace?0>a.stacktrace.indexOf("called from line")?"opera10b":"opera11":a.stack&&!a.fileName?
"chrome":"other"},instrumentFunction:function(b,c,d){b=b||window;var e=b[c];b[c]=function(){d.call(this,a().slice(4));return b[c]._instrumented.apply(this,arguments)};b[c]._instrumented=e},deinstrumentFunction:function(a,c){a[c].constructor===Function&&a[c]._instrumented&&a[c]._instrumented.constructor===Function&&(a[c]=a[c]._instrumented)},chrome:function(a){return(a.stack+"\n").replace(/^[\s\S]+?\s+at\s+/," at ").replace(/^\s+(at eval )?at\s+/gm,"").replace(/^([^\(]+?)([\n$])/gm,"{anonymous}() ($1)$2").replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm,
"{anonymous}() ($1)").replace(/^(.+) \((.+)\)$/gm,"$1@$2").split("\n").slice(0,-1)},safari:function(a){return a.stack.replace(/\[native code\]\n/m,"").replace(/^(?=\w+Error\:).*$\n/m,"").replace(/^@/gm,"{anonymous}()@").split("\n")},ie:function(a){return a.stack.replace(/^\s*at\s+(.*)$/gm,"$1").replace(/^Anonymous function\s+/gm,"{anonymous}() ").replace(/^(.+)\s+\((.+)\)$/gm,"$1@$2").split("\n").slice(1)},firefox:function(a){return a.stack.replace(/(?:\n@:0)?\s+$/m,"").replace(/^(?:\((\S*)\))?@/gm,
"{anonymous}($1)@").split("\n")},opera11:function(a){var c=/^.*line (\d+), column (\d+)(?: in (.+))? in (\S+):$/;a=a.stacktrace.split("\n");for(var d=[],e=0,f=a.length;e<f;e+=2){var g=c.exec(a[e]);if(g){var h=g[4]+":"+g[1]+":"+g[2],g=g[3]||"global code",g=g.replace(/<anonymous function: (\S+)>/,"$1").replace(/<anonymous function>/,"{anonymous}");d.push(g+"@"+h+" -- "+a[e+1].replace(/^\s+/,""))}}return d},opera10b:function(a){var c=/^(.*)@(.+):(\d+)$/;a=a.stacktrace.split("\n");for(var d=[],e=0,f=
a.length;e<f;e++){var g=c.exec(a[e]);g&&d.push((g[1]?g[1]+"()":"global code")+"@"+g[2]+":"+g[3])}return d},opera10a:function(a){var c=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;a=a.stacktrace.split("\n");for(var d=[],e=0,f=a.length;e<f;e+=2){var g=c.exec(a[e]);g&&d.push((g[3]||"{anonymous}")+"()@"+g[2]+":"+g[1]+" -- "+a[e+1].replace(/^\s+/,""))}return d},opera9:function(a){var c=/Line (\d+).*script (?:in )?(\S+)/i;a=a.message.split("\n");for(var d=[],e=2,f=a.length;e<f;e+=2){var g=
c.exec(a[e]);g&&d.push("{anonymous}()@"+g[2]+":"+g[1]+" -- "+a[e+1].replace(/^\s+/,""))}return d},phantomjs:function(a){var c=/(\S+) \((\S+)\)/i;a=a.stack.split("\n");for(var d=[],e=1,f=a.length;e<f;e++){a[e]=a[e].replace(/^\s+at\s+/gm,"");var g=c.exec(a[e]);g?d.push(g[1]+"()@"+g[2]):d.push("{anonymous}()@"+a[e])}return d},other:function(a){for(var c=/function(?:\s+([\w$]+))?\s*\(/,d=[],e,f,g=Array.prototype.slice;a&&10>d.length;){e=c.test(a.toString())?RegExp.$1||"{anonymous}":"{anonymous}";try{f=
g.call(a.arguments||[])}catch(h){f=["Cannot access arguments: "+h]}d[d.length]=e+"("+this.stringifyArguments(f)+")";try{a=a.caller}catch(k){d[d.length]="Cannot access caller: "+k;break}}return d},stringifyArguments:function(a){for(var c=[],d=Array.prototype.slice,e=0;e<a.length;++e){var f=a[e];void 0===f?c[e]="undefined":null===f?c[e]="null":f.constructor&&(c[e]=f.constructor===Array?3>f.length?"["+this.stringifyArguments(f)+"]":"["+this.stringifyArguments(d.call(f,0,1))+"..."+this.stringifyArguments(d.call(f,
-1))+"]":f.constructor===Object?"#object":f.constructor===Function?"#function":f.constructor===String?'"'+f+'"':f.constructor===Number?f:"?")}return c.join(",")},sourceCache:{},ajax:function(a){var c=this.createXMLHTTPObject();if(c)try{return c.open("GET",a,!1),c.send(null),c.responseText}catch(d){}return""},createXMLHTTPObject:function(){for(var a,c=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},
function(){return new ActiveXObject("Microsoft.XMLHTTP")}],d=0;d<c.length;d++)try{return a=c[d](),this.createXMLHTTPObject=c[d],a}catch(e){}},isSameDomain:function(a){return"undefined"!==typeof location&&-1!==a.indexOf(location.hostname)},getSource:function(a){a in this.sourceCache||(this.sourceCache[a]=this.ajax(a).split("\n"));return this.sourceCache[a]},guessAnonymousFunctions:function(a){for(var c=0;c<a.length;++c){var d=/^(.*?)(?::(\d+))(?::(\d+))?(?: -- .+)?$/,e=a[c],f=/\{anonymous\}\(.*\)@(.*)/.exec(e);
if(f){var g=d.exec(f[1]);g&&(d=g[1],f=g[2],g=g[3]||0,d&&this.isSameDomain(d)&&f&&(d=this.guessAnonymousFunction(d,f,g),a[c]=e.replace("{anonymous}",d)))}}return a},guessAnonymousFunction:function(a,c,d){var e;try{e=this.findFunctionName(this.getSource(a),c)}catch(f){e="getSource failed with url: "+a+", exception: "+f.toString()}return e},findFunctionName:function(a,c){for(var d=/function\s+([^(]*?)\s*\(([^)]*)\)/,e=/['"]?([$_A-Za-z][$_A-Za-z0-9]*)['"]?\s*[:=]\s*function\b/,f=/['"]?([$_A-Za-z][$_A-Za-z0-9]*)['"]?\s*[:=]\s*(?:eval|new Function)\b/,
g="",h,k=Math.min(c,20),l,m=0;m<k;++m)if(h=a[c-m-1],l=h.indexOf("//"),0<=l&&(h=h.substr(0,l)),h)if(g=h+g,(h=e.exec(g))&&h[1]||(h=d.exec(g))&&h[1]||(h=f.exec(g))&&h[1])return h[1];return"(?)"}};return a});var ndn=ndn||{},exports=ndn,module={};function require(){return ndn}exports.printStackTrace=printStackTrace;
function DetectSubtleCrypto(){var a=!1;if("undefined"!==typeof crypto&&crypto&&crypto.subtle){var b={name:"RSASSA-PKCS1-v1_5",modulusLength:2048,hash:{name:"SHA-256"},publicExponent:new Uint8Array([1,0,1])},c;crypto.subtle.generateKey(b,!0,["sign","verify"]).then(function(a){c=a;return crypto.subtle.sign(b,a.privateKey,new Uint8Array([1,2,3,4,5]))}).then(function(a){return crypto.subtle.verify(b,c.publicKey,a,new Uint8Array([1,2,3,4,5]))}).then(function(a){return crypto.subtle.exportKey("pkcs8",c.privateKey)}).then(function(a){return crypto.subtle.importKey("pkcs8",
a,b,!0,["sign"])}).then(function(a){return crypto.subtle.exportKey("spki",c.publicKey)}).then(function(a){return crypto.subtle.importKey("spki",a,b,!0,["verify"])}).then(function(a){a=new Uint8Array([1,2,3,4,5]);return crypto.subtle.digest({name:"SHA-256"},a.buffer)}).then(function(b){a=!0},function(a){console.log("DetectSubtleCrypto encountered error, not using crypto.subtle: ",a)})}return function(){return a}}var UseSubtleCrypto=DetectSubtleCrypto();exports.UseSubtleCrypto=UseSubtleCrypto;
var CryptoJS=CryptoJS||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;b&&c.mixIn(b);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},
clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=b?c:4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes;a=a.sigBytes;this.clamp();if(d%4)for(var e=0;e<a;e++)b[d+e>>>2]|=(c[e>>>2]>>>24-e%4*8&255)<<24-(d+e)%4*8;else for(e=0;e<a;e+=4)b[d+e>>>2]=c[e>>>2];this.sigBytes+=a;return this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>
2]&=4294967295<<32-c%4*8;b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);a.words=this.words.slice(0);return a},random:function(b){for(var c=[],d=0;d<b;d+=4)c.push(4294967296*a.random()|0);return new f.init(c,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){var b=a.words;a=a.sigBytes;for(var c=[],d=0;d<a;d++){var e=b[d>>>2]>>>24-d%4*8&255;c.push((e>>>4).toString(16));c.push((e&15).toString(16))}return c.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d+=2)c[d>>>3]|=parseInt(a.substr(d,
2),16)<<24-d%8*4;return new f.init(c,b/2)}},k=g.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var c=[],d=0;d<a;d++)c.push(String.fromCharCode(b[d>>>2]>>>24-d%4*8&255));return c.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d++)c[d>>>2]|=(a.charCodeAt(d)&255)<<24-d%4*8;return new f.init(c,b)}},l=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}},
m=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=l.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=e/(4*g),h=b?a.ceil(h):a.max((h|0)-this._minBufferSize,0);b=h*g;e=a.min(4*b,e);if(b){for(var k=0;k<b;k+=g)this._doProcessBlock(d,k);k=d.splice(0,b);c.sigBytes-=e}return new f.init(k,e)},clone:function(){var a=e.clone.call(this);
a._data=this._data.clone();return a},_minBufferSize:0});d.Hasher=m.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){m.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(b,c){return(new a.init(c)).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return(new q.HMAC.init(a,
c)).finalize(b)}}});var q=c.algo={};return c}(Math);exports.CryptoJS=CryptoJS;module.exports=exports;var C=require("./core.js").CryptoJS;
(function(a){var b=C.lib,c=b.WordArray,d=b.Hasher,b=C.algo,e=[],f=[];(function(){function b(c){for(var d=a.sqrt(c),e=2;e<=d;e++)if(!(c%e))return!1;return!0}function c(a){return 4294967296*(a-(a|0))|0}for(var d=2,g=0;64>g;)b(d)&&(8>g&&(e[g]=c(a.pow(d,0.5))),f[g]=c(a.pow(d,1/3)),g++),d++})();var g=[],b=b.SHA256=d.extend({_doReset:function(){this._hash=new c.init(e.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],p=c[2],s=c[3],w=c[4],M=c[5],O=c[6],K=c[7],x=0;64>x;x++){if(16>
x)g[x]=a[b+x]|0;else{var A=g[x-15],I=g[x-2];g[x]=((A<<25|A>>>7)^(A<<14|A>>>18)^A>>>3)+g[x-7]+((I<<15|I>>>17)^(I<<13|I>>>19)^I>>>10)+g[x-16]}A=K+((w<<26|w>>>6)^(w<<21|w>>>11)^(w<<7|w>>>25))+(w&M^~w&O)+f[x]+g[x];I=((d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22))+(d&e^d&p^e&p);K=O;O=M;M=w;w=s+A|0;s=p;p=e;e=d;d=A+I|0}c[0]=c[0]+d|0;c[1]=c[1]+e|0;c[2]=c[2]+p|0;c[3]=c[3]+s|0;c[4]=c[4]+w|0;c[5]=c[5]+M|0;c[6]=c[6]+O|0;c[7]=c[7]+K|0},_doFinalize:function(){var b=this._data,c=b.words,d=8*this._nDataBytes,e=8*b.sigBytes;
c[e>>>5]|=128<<24-e%32;c[(e+64>>>9<<4)+14]=a.floor(d/4294967296);c[(e+64>>>9<<4)+15]=d;b.sigBytes=4*c.length;this._process();return this._hash},clone:function(){var a=d.clone.call(this);a._hash=this._hash.clone();return a}});C.SHA256=d._createHelper(b);C.HmacSHA256=d._createHmacHelper(b)})(Math);exports.CryptoJS=C;module.exports=exports;
(function(){var a=CryptoJS,b=a.enc.Utf8;a.algo.HMAC=a.lib.Base.extend({init:function(a,d){a=this._hasher=new a.init;"string"==typeof d&&(d=b.parse(d));var e=a.blockSize,f=4*e;d.sigBytes>f&&(d=a.finalize(d));d.clamp();for(var g=this._oKey=d.clone(),h=this._iKey=d.clone(),k=g.words,l=h.words,m=0;m<e;m++)k[m]^=1549556828,l[m]^=909522486;g.sigBytes=h.sigBytes=f;this.reset()},reset:function(){var a=this._hasher;a.reset();a.update(this._iKey)},update:function(a){this._hasher.update(a);return this},finalize:function(a){var b=
this._hasher;a=b.finalize(a);b.reset();return b.finalize(this._oKey.clone().concat(a))}})})();var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64pad="=";
function hex2b64(a){var b,c,d="";for(b=0;b+3<=a.length;b+=3)c=parseInt(a.substring(b,b+3),16),d+=b64map.charAt(c>>6)+b64map.charAt(c&63);b+1==a.length?(c=parseInt(a.substring(b,b+1),16),d+=b64map.charAt(c<<2)):b+2==a.length&&(c=parseInt(a.substring(b,b+2),16),d+=b64map.charAt(c>>2)+b64map.charAt((c&3)<<4));if(b64pad)for(;0<(d.length&3);)d+=b64pad;return d}
function b64tohex(a){var b="",c,d=0,e,f;for(c=0;c<a.length&&a.charAt(c)!=b64pad;++c)f=b64map.indexOf(a.charAt(c)),0>f||(0==d?(b+=int2char(f>>2),e=f&3,d=1):1==d?(b+=int2char(e<<2|f>>4),e=f&15,d=2):2==d?(b+=int2char(e),b+=int2char(f>>2),e=f&3,d=3):(b+=int2char(e<<2|f>>4),b+=int2char(f&15),d=0));1==d&&(b+=int2char(e<<2));return b}function b64toBA(a){a=b64tohex(a);var b,c=[];for(b=0;2*b<a.length;++b)c[b]=parseInt(a.substring(2*b,2*b+2),16);return c}exports.b64tohex=b64tohex;exports.b64toBA=b64toBA;
exports.hex2b64=hex2b64;module.exports=exports;function Arcfour(){this.j=this.i=0;this.S=[]}function ARC4init(a){var b,c,d;for(b=0;256>b;++b)this.S[b]=b;for(b=c=0;256>b;++b)c=c+this.S[b]+a[b%a.length]&255,d=this.S[b],this.S[b]=this.S[c],this.S[c]=d;this.j=this.i=0}function ARC4next(){var a;this.i=this.i+1&255;this.j=this.j+this.S[this.i]&255;a=this.S[this.i];this.S[this.i]=this.S[this.j];this.S[this.j]=a;return this.S[a+this.S[this.i]&255]}Arcfour.prototype.init=ARC4init;Arcfour.prototype.next=ARC4next;
function prng_newstate(){return new Arcfour}var rng_psize=256,rng_state,rng_pool,rng_pptr;function rng_seed_int(a){rng_pool[rng_pptr++]^=a&255;rng_pool[rng_pptr++]^=a>>8&255;rng_pool[rng_pptr++]^=a>>16&255;rng_pool[rng_pptr++]^=a>>24&255;rng_pptr>=rng_psize&&(rng_pptr-=rng_psize)}function rng_seed_time(){rng_seed_int((new Date).getTime())}
if(null==rng_pool){rng_pool=[];rng_pptr=0;var t;if("Netscape"==navigator.appName&&"5">navigator.appVersion&&window.crypto){var z=window.crypto.random(32);for(t=0;t<z.length;++t)rng_pool[rng_pptr++]=z.charCodeAt(t)&255}for(;rng_pptr<rng_psize;)t=Math.floor(65536*Math.random()),rng_pool[rng_pptr++]=t>>>8,rng_pool[rng_pptr++]=t&255;rng_pptr=0;rng_seed_time()}
function rng_get_byte(){if(null==rng_state){rng_seed_time();rng_state=prng_newstate();rng_state.init(rng_pool);for(rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr)rng_pool[rng_pptr]=0;rng_pptr=0}return rng_state.next()}function rng_get_bytes(a){var b;for(b=0;b<a.length;++b)a[b]=rng_get_byte()}function SecureRandom(){}SecureRandom.prototype.nextBytes=rng_get_bytes;var intShim=require("jsbn");function parseBigInt(a,b){return new BigInteger(a,b)}
function linebrk(a,b){for(var c="",d=0;d+b<a.length;)c+=a.substring(d,d+b)+"\n",d+=b;return c+a.substring(d,a.length)}function byte2Hex(a){return 16>a?"0"+a.toString(16):a.toString(16)}
function pkcs1pad2(a,b){if(b<a.length+11)return alert("Message too long for RSA"),null;for(var c=[],d=a.length-1;0<=d&&0<b;){var e=a.charCodeAt(d--);128>e?c[--b]=e:127<e&&2048>e?(c[--b]=e&63|128,c[--b]=e>>6|192):(c[--b]=e&63|128,c[--b]=e>>6&63|128,c[--b]=e>>12|224)}c[--b]=0;d=new SecureRandom;for(e=[];2<b;){for(e[0]=0;0==e[0];)d.nextBytes(e);c[--b]=e[0]}c[--b]=2;c[--b]=0;return new BigInteger(c)}
function oaep_mgf1_arr(a,b,c){for(var d="",e=0;d.length<b;)d+=c(String.fromCharCode.apply(String,a.concat([(e&4278190080)>>24,(e&16711680)>>16,(e&65280)>>8,e&255]))),e+=1;return d}var SHA1_SIZE=20;
function oaep_pad(a,b,c){if(a.length+2*SHA1_SIZE+2>b)throw"Message too long for RSA";var d="",e;for(e=0;e<b-a.length-2*SHA1_SIZE-2;e+=1)d+="\x00";b=rstr_sha1("")+d+"\u0001"+a;a=Array(SHA1_SIZE);(new SecureRandom).nextBytes(a);d=oaep_mgf1_arr(a,b.length,c||rstr_sha1);c=[];for(e=0;e<b.length;e+=1)c[e]=b.charCodeAt(e)^d.charCodeAt(e);b=oaep_mgf1_arr(c,a.length,rstr_sha1);d=[0];for(e=0;e<a.length;e+=1)d[e+1]=a[e]^b.charCodeAt(e);return new BigInteger(d.concat(c))}
function RSAKey(){this.n=null;this.e=0;this.coeff=this.dmq1=this.dmp1=this.q=this.p=this.d=null}function RSASetPublic(a,b){this.isPublic=!0;"string"!==typeof a?(this.n=a,this.e=b):null!=a&&null!=b&&0<a.length&&0<b.length?(this.n=parseBigInt(a,16),this.e=parseInt(b,16)):alert("Invalid RSA public key")}function RSADoPublic(a){return a.modPowInt(this.e,this.n)}
function RSAEncrypt(a){a=pkcs1pad2(a,this.n.bitLength()+7>>3);if(null==a)return null;a=this.doPublic(a);if(null==a)return null;a=a.toString(16);return 0==(a.length&1)?a:"0"+a}function RSAEncryptOAEP(a,b){var c=oaep_pad(a,this.n.bitLength()+7>>3,b);if(null==c)return null;c=this.doPublic(c);if(null==c)return null;c=c.toString(16);return 0==(c.length&1)?c:"0"+c}RSAKey.prototype.doPublic=RSADoPublic;RSAKey.prototype.setPublic=RSASetPublic;RSAKey.prototype.encrypt=RSAEncrypt;
RSAKey.prototype.encryptOAEP=RSAEncryptOAEP;RSAKey.prototype.type="RSA";exports.RSAKey=RSAKey;module.exports=exports;var intShim=require("jsbn"),BigInteger=intShim.BigInteger?intShim.BigInteger:intShim,RSAKey=require("./rsa.js").RSAKey;
function pkcs1unpad2(a,b){for(var c=a.toByteArray(),d=0;d<c.length&&0==c[d];)++d;if(c.length-d!=b-1||2!=c[d])return null;for(++d;0!=c[d];)if(++d>=c.length)return null;for(var e="";++d<c.length;){var f=c[d]&255;128>f?e+=String.fromCharCode(f):191<f&&224>f?(e+=String.fromCharCode((f&31)<<6|c[d+1]&63),++d):(e+=String.fromCharCode((f&15)<<12|(c[d+1]&63)<<6|c[d+2]&63),d+=2)}return e}
function oaep_mgf1_str(a,b,c){for(var d="",e=0;d.length<b;)d+=c(a+String.fromCharCode.apply(String,[(e&4278190080)>>24,(e&16711680)>>16,(e&65280)>>8,e&255])),e+=1;return d}SHA1_SIZE=20;
function oaep_unpad(a,b,c){a=a.toByteArray();var d;for(d=0;d<a.length;d+=1)a[d]&=255;for(;a.length<b;)a.unshift(0);a=String.fromCharCode.apply(String,a);if(a.length<2*SHA1_SIZE+2)throw"Cipher too short";var e=a.substr(1,SHA1_SIZE);b=a.substr(SHA1_SIZE+1);c=oaep_mgf1_str(b,SHA1_SIZE,c||rstr_sha1);var f=[];for(d=0;d<e.length;d+=1)f[d]=e.charCodeAt(d)^c.charCodeAt(d);e=oaep_mgf1_str(String.fromCharCode.apply(String,f),a.length-SHA1_SIZE,rstr_sha1);a=[];for(d=0;d<b.length;d+=1)a[d]=b.charCodeAt(d)^e.charCodeAt(d);
a=String.fromCharCode.apply(String,a);if(a.substr(0,SHA1_SIZE)!==rstr_sha1(""))throw"Hash mismatch";a=a.substr(SHA1_SIZE);d=a.indexOf("\u0001");if((-1!=d?a.substr(0,d).lastIndexOf("\x00"):-1)+1!=d)throw"Malformed data";return a.substr(d+1)}function RSASetPrivate(a,b,c){this.isPrivate=!0;"string"!==typeof a?(this.n=a,this.e=b,this.d=c):null!=a&&null!=b&&0<a.length&&0<b.length?(this.n=parseBigInt(a,16),this.e=parseInt(b,16),this.d=parseBigInt(c,16)):alert("Invalid RSA private key")}
function RSASetPrivateEx(a,b,c,d,e,f,g,h){this.isPrivate=!0;if(null==a)throw"RSASetPrivateEx N == null";if(null==b)throw"RSASetPrivateEx E == null";if(0==a.length)throw"RSASetPrivateEx N.length == 0";if(0==b.length)throw"RSASetPrivateEx E.length == 0";null!=a&&null!=b&&0<a.length&&0<b.length?(this.n=parseBigInt(a,16),this.e=parseInt(b,16),this.d=parseBigInt(c,16),this.p=parseBigInt(d,16),this.q=parseBigInt(e,16),this.dmp1=parseBigInt(f,16),this.dmq1=parseBigInt(g,16),this.coeff=parseBigInt(h,16)):
alert("Invalid RSA private key in RSASetPrivateEx")}
function RSAGenerate(a,b){var c=new SecureRandom,d=a>>1;this.e=parseInt(b,16);for(var e=new BigInteger(b,16);;){for(;this.p=new BigInteger(a-d,1,c),0!=this.p.subtract(BigInteger.ONE).gcd(e).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(d,1,c),0!=this.q.subtract(BigInteger.ONE).gcd(e).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(0>=this.p.compareTo(this.q)){var f=this.p;this.p=this.q;this.q=f}var f=this.p.subtract(BigInteger.ONE),g=this.q.subtract(BigInteger.ONE),
h=f.multiply(g);if(0==h.gcd(e).compareTo(BigInteger.ONE)){this.n=this.p.multiply(this.q);this.d=e.modInverse(h);this.dmp1=this.d.mod(f);this.dmq1=this.d.mod(g);this.coeff=this.q.modInverse(this.p);break}}this.isPrivate=!0}
function RSADoPrivate(a){if(null==this.p||null==this.q)return a.modPow(this.d,this.n);var b=a.mod(this.p).modPow(this.dmp1,this.p);for(a=a.mod(this.q).modPow(this.dmq1,this.q);0>b.compareTo(a);)b=b.add(this.p);return b.subtract(a).multiply(this.coeff).mod(this.p).multiply(this.q).add(a)}function RSADecrypt(a){a=parseBigInt(a,16);a=this.doPrivate(a);return null==a?null:pkcs1unpad2(a,this.n.bitLength()+7>>3)}
function RSADecryptOAEP(a,b){var c=parseBigInt(a,16),c=this.doPrivate(c);return null==c?null:oaep_unpad(c,this.n.bitLength()+7>>3,b)}RSAKey.prototype.doPrivate=RSADoPrivate;RSAKey.prototype.setPrivate=RSASetPrivate;RSAKey.prototype.setPrivateEx=RSASetPrivateEx;RSAKey.prototype.generate=RSAGenerate;RSAKey.prototype.decrypt=RSADecrypt;RSAKey.prototype.decryptOAEP=RSADecryptOAEP;exports.RSAKey=RSAKey;module.exports=exports;CryptoJS=require("./sha256.js").CryptoJS;intShim=require("jsbn");
"undefined"!=typeof KJUR&&KJUR||(KJUR={});"undefined"!=typeof KJUR.crypto&&KJUR.crypto||(KJUR.crypto={});
KJUR.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"};this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",
sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",
SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa"};this.CRYPTOJSMESSAGEDIGESTNAME=
{md5:"CryptoJS.algo.MD5",sha1:"CryptoJS.algo.SHA1",sha224:"CryptoJS.algo.SHA224",sha256:"CryptoJS.algo.SHA256",sha384:"CryptoJS.algo.SHA384",sha512:"CryptoJS.algo.SHA512",ripemd160:"CryptoJS.algo.RIPEMD160"};this.getDigestInfoHex=function(a,b){if("undefined"==typeof this.DIGESTINFOHEAD[b])throw"alg not supported in Util.DIGESTINFOHEAD: "+b;return this.DIGESTINFOHEAD[b]+a};this.getPaddedDigestInfoHex=function(a,b,c){var d=this.getDigestInfoHex(a,b);a=c/4;if(d.length+22>a)throw"key is too short for SigAlg: keylen="+
c+","+b;b="00"+d;c="";a=a-4-b.length;for(d=0;d<a;d+=2)c+="ff";return"0001"+c+b};this.hashString=function(a,b){return(new KJUR.crypto.MessageDigest({alg:b})).digestString(a)};this.hashHex=function(a,b){return(new KJUR.crypto.MessageDigest({alg:b})).digestHex(a)};this.sha1=function(a){return(new KJUR.crypto.MessageDigest({alg:"sha1",prov:"cryptojs"})).digestString(a)};this.sha256=function(a){return(new KJUR.crypto.MessageDigest({alg:"sha256",prov:"cryptojs"})).digestString(a)};this.sha256Hex=function(a){return(new KJUR.crypto.MessageDigest({alg:"sha256",
prov:"cryptojs"})).digestHex(a)};this.sha512=function(a){return(new KJUR.crypto.MessageDigest({alg:"sha512",prov:"cryptojs"})).digestString(a)};this.sha512Hex=function(a){return(new KJUR.crypto.MessageDigest({alg:"sha512",prov:"cryptojs"})).digestHex(a)};this.md5=function(a){return(new KJUR.crypto.MessageDigest({alg:"md5",prov:"cryptojs"})).digestString(a)};this.ripemd160=function(a){return(new KJUR.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"})).digestString(a)};this.getCryptoJSMDByName=
function(a){}};
KJUR.crypto.MessageDigest=function(a){this.setAlgAndProvider=function(a,c){null!=a&&void 0===c&&(c=KJUR.crypto.Util.DEFAULTPROVIDER[a]);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(a)&&"cryptojs"==c){try{this.md=eval(KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[a]).create()}catch(d){throw"setAlgAndProvider hash alg set fail alg="+a+"/"+d;}this.updateString=function(a){this.md.update(a)};this.updateHex=function(a){a=CryptoJS.enc.Hex.parse(a);this.md.update(a)};this.digest=function(){return this.md.finalize().toString(CryptoJS.enc.Hex)};
this.digestString=function(a){this.updateString(a);return this.digest()};this.digestHex=function(a){this.updateHex(a);return this.digest()}}if(-1!=":sha256:".indexOf(a)&&"sjcl"==c){try{this.md=new sjcl.hash.sha256}catch(e){throw"setAlgAndProvider hash alg set fail alg="+a+"/"+e;}this.updateString=function(a){this.md.update(a)};this.updateHex=function(a){a=sjcl.codec.hex.toBits(a);this.md.update(a)};this.digest=function(){var a=this.md.finalize();return sjcl.codec.hex.fromBits(a)};this.digestString=
function(a){this.updateString(a);return this.digest()};this.digestHex=function(a){this.updateHex(a);return this.digest()}}};this.updateString=function(a){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName;};this.updateHex=function(a){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName;};this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName;};this.digestString=function(a){throw"digestString(str) not supported for this alg/prov: "+
this.algName+"/"+this.provName;};this.digestHex=function(a){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName;};void 0!==a&&void 0!==a.alg&&(this.algName=a.alg,void 0===a.prov&&(this.provName=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))};
KJUR.crypto.Mac=function(a){this.setAlgAndProvider=function(a,c){a=a.toLowerCase();null==a&&(a="hmacsha1");a=a.toLowerCase();if("hmac"!=a.substr(0,4))throw"setAlgAndProvider unsupported HMAC alg: "+a;void 0===c&&(c=KJUR.crypto.Util.DEFAULTPROVIDER[a]);this.algProv=a+"/"+c;var d=a.substr(4);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(d)&&"cryptojs"==c){try{var e=eval(KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[d]);this.mac=CryptoJS.algo.HMAC.create(e,this.pass)}catch(f){throw"setAlgAndProvider hash alg set fail hashAlg="+
d+"/"+f;}this.updateString=function(a){this.mac.update(a)};this.updateHex=function(a){a=CryptoJS.enc.Hex.parse(a);this.mac.update(a)};this.doFinal=function(){return this.mac.finalize().toString(CryptoJS.enc.Hex)};this.doFinalString=function(a){this.updateString(a);return this.doFinal()};this.doFinalHex=function(a){this.updateHex(a);return this.doFinal()}}};this.updateString=function(a){throw"updateString(str) not supported for this alg/prov: "+this.algProv;};this.updateHex=function(a){throw"updateHex(hex) not supported for this alg/prov: "+
this.algProv;};this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv;};this.doFinalString=function(a){throw"digestString(str) not supported for this alg/prov: "+this.algProv;};this.doFinalHex=function(a){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv;};this.setPassword=function(a){if("string"==typeof a){var c=a;1!=a.length%2&&a.match(/^[0-9A-Fa-f]+$/)||(c=rstrtohex(a))}else{if("object"!=typeof a)throw"KJUR.crypto.Mac unsupported password type: "+
a;c=null;if(void 0!==a.hex){if(0!=a.hex.length%2||!a.hex.match(/^[0-9A-Fa-f]+$/))throw"Mac: wrong hex password: "+a.hex;c=a.hex}void 0!==a.utf8&&(c=utf8tohex(a.utf8));void 0!==a.rstr&&(c=rstrtohex(a.rstr));void 0!==a.b64&&(c=b64tohex(a.b64));void 0!==a.b64u&&(c=b64utohex(a.b64u));if(null==c)throw"KJUR.crypto.Mac unsupported password type: "+a;}this.pass=CryptoJS.enc.Hex.parse(c)};void 0!==a&&(void 0!==a.pass&&this.setPassword(a.pass),void 0!==a.alg&&(this.algName=a.alg,void 0===a.prov&&(this.provName=
KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))};
KJUR.crypto.Signature=function(a){var b=null;this._setAlgNames=function(){this.algName.match(/^(.+)with(.+)$/)&&(this.mdAlgName=RegExp.$1.toLowerCase(),this.pubkeyAlgName=RegExp.$2.toLowerCase())};this._zeroPaddingOfSignature=function(a,b){for(var c="",g=b/4-a.length,h=0;h<g;h++)c+="0";return c+a};this.setAlgAndProvider=function(a,b){this._setAlgNames();if("cryptojs/jsrsa"!=b)throw"provider not supported: "+b;if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)){try{this.md=
new KJUR.crypto.MessageDigest({alg:this.mdAlgName})}catch(c){throw"setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+c;}this.init=function(a,b){var c=null;try{c=void 0===b?KEYUTIL.getKey(a):KEYUTIL.getKey(a,b)}catch(d){throw"init failed:"+d;}if(!0===c.isPrivate)this.prvKey=c,this.state="SIGN";else if(!0===c.isPublic)this.pubKey=c,this.state="VERIFY";else throw"init failed.:"+c;};this.initSign=function(a){"string"==typeof a.ecprvhex&&"string"==typeof a.eccurvename?(this.ecprvhex=a.ecprvhex,
this.eccurvename=a.eccurvename):this.prvKey=a;this.state="SIGN"};this.initVerifyByPublicKey=function(a){"string"==typeof a.ecpubhex&&"string"==typeof a.eccurvename?(this.ecpubhex=a.ecpubhex,this.eccurvename=a.eccurvename):a instanceof KJUR.crypto.ECDSA?this.pubKey=a:a instanceof RSAKey&&(this.pubKey=a);this.state="VERIFY"};this.initVerifyByCertificatePEM=function(a){var b=new X509;b.readCertPEM(a);this.pubKey=b.subjectPublicKeyRSA;this.state="VERIFY"};this.updateString=function(a){this.md.updateString(a)};
this.updateHex=function(a){this.md.updateHex(a)};this.sign=function(){this.sHashHex=this.md.digest();if("undefined"!=typeof this.ecprvhex&&"undefined"!=typeof this.eccurvename)this.hSign=(new KJUR.crypto.ECDSA({curve:this.eccurvename})).signHex(this.sHashHex,this.ecprvhex);else if(this.prvKey instanceof RSAKey&&"rsaandmgf1"==this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof RSAKey&&"rsa"==this.pubkeyAlgName)this.hSign=
this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof KJUR.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else if(this.prvKey instanceof KJUR.crypto.DSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else throw"Signature: unsupported public key alg: "+this.pubkeyAlgName;return this.hSign};this.signString=function(a){this.updateString(a);return this.sign()};this.signHex=function(a){this.updateHex(a);return this.sign()};this.verify=
function(a){this.sHashHex=this.md.digest();if("undefined"!=typeof this.ecpubhex&&"undefined"!=typeof this.eccurvename)return(new KJUR.crypto.ECDSA({curve:this.eccurvename})).verifyHex(this.sHashHex,a,this.ecpubhex);if(this.pubKey instanceof RSAKey&&"rsaandmgf1"==this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,a,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof RSAKey&&"rsa"==this.pubkeyAlgName||this.pubKey instanceof KJUR.crypto.ECDSA||this.pubKey instanceof KJUR.crypto.DSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,
a);throw"Signature: unsupported public key alg: "+this.pubkeyAlgName;}}};this.init=function(a,b){throw"init(key, pass) not supported for this alg:prov="+this.algProvName;};this.initVerifyByPublicKey=function(a){throw"initVerifyByPublicKey(rsaPubKeyy) not supported for this alg:prov="+this.algProvName;};this.initVerifyByCertificatePEM=function(a){throw"initVerifyByCertificatePEM(certPEM) not supported for this alg:prov="+this.algProvName;};this.initSign=function(a){throw"initSign(prvKey) not supported for this alg:prov="+
this.algProvName;};this.updateString=function(a){throw"updateString(str) not supported for this alg:prov="+this.algProvName;};this.updateHex=function(a){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName;};this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName;};this.signString=function(a){throw"digestString(str) not supported for this alg:prov="+this.algProvName;};this.signHex=function(a){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName;
};this.verify=function(a){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName;};this.initParams=a;if(void 0!==a&&(void 0!==a.alg&&(this.algName=a.alg,this.provName=void 0===a.prov?KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]:a.prov,this.algProvName=this.algName+":"+this.provName,this.setAlgAndProvider(this.algName,this.provName),this._setAlgNames()),void 0!==a.psssaltlen&&(this.pssSaltLen=a.psssaltlen),void 0!==a.prvkeypem)){if(void 0!==a.prvkeypas)throw"both prvkeypem and prvkeypas parameters not supported";
try{b=new RSAKey,b.readPrivateKeyFromPEMString(a.prvkeypem),this.initSign(b)}catch(c){throw"fatal error to load pem private key: "+c;}}};
KJUR.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040023":"secp521r1","2b81040022":"secp384r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA"}};exports.KJUR=KJUR;module.exports=exports;
var ASN1HEX=require("./asn1hex-1.1.js").ASN1HEX,b64tohex=require("./base64.js").b64tohex,RSAKey=require("./rsa2.js").RSAKey;function _rsapem_pemToBase64(a){a=a.replace("-----BEGIN RSA PRIVATE KEY-----","");a=a.replace("-----END RSA PRIVATE KEY-----","");return a=a.replace(/[ \n]+/g,"")}
function _rsapem_getPosArrayOfChildrenFromHex(a){var b=[],c=ASN1HEX.getStartPosOfV_AtObj(a,0),d=ASN1HEX.getPosOfNextSibling_AtObj(a,c),e=ASN1HEX.getPosOfNextSibling_AtObj(a,d),f=ASN1HEX.getPosOfNextSibling_AtObj(a,e),g=ASN1HEX.getPosOfNextSibling_AtObj(a,f),h=ASN1HEX.getPosOfNextSibling_AtObj(a,g),k=ASN1HEX.getPosOfNextSibling_AtObj(a,h),l=ASN1HEX.getPosOfNextSibling_AtObj(a,k);a=ASN1HEX.getPosOfNextSibling_AtObj(a,l);b.push(c,d,e,f,g,h,k,l,a);return b}
function _rsapem_getHexValueArrayOfChildrenFromHex(a){var b=_rsapem_getPosArrayOfChildrenFromHex(a),c=ASN1HEX.getHexOfV_AtObj(a,b[0]),d=ASN1HEX.getHexOfV_AtObj(a,b[1]),e=ASN1HEX.getHexOfV_AtObj(a,b[2]),f=ASN1HEX.getHexOfV_AtObj(a,b[3]),g=ASN1HEX.getHexOfV_AtObj(a,b[4]),h=ASN1HEX.getHexOfV_AtObj(a,b[5]),k=ASN1HEX.getHexOfV_AtObj(a,b[6]),l=ASN1HEX.getHexOfV_AtObj(a,b[7]);a=ASN1HEX.getHexOfV_AtObj(a,b[8]);b=[];b.push(c,d,e,f,g,h,k,l,a);return b}
function _rsapem_readPrivateKeyFromASN1HexString(a){a=_rsapem_getHexValueArrayOfChildrenFromHex(a);this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8])}function _rsapem_readPrivateKeyFromPEMString(a){a=_rsapem_pemToBase64(a);a=b64tohex(a);a=_rsapem_getHexValueArrayOfChildrenFromHex(a);this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8])}RSAKey.prototype.readPrivateKeyFromPEMString=_rsapem_readPrivateKeyFromPEMString;RSAKey.prototype.readPrivateKeyFromASN1HexString=_rsapem_readPrivateKeyFromASN1HexString;
exports.RSAKey=RSAKey;module.exports=exports;var intShim=require("jsbn"),BigInteger=intShim.BigInteger?intShim.BigInteger:intShim,RSAKey=require("./rsapem-1.1.js").RSAKey,_RE_HEXDECONLY=RegExp("");_RE_HEXDECONLY.compile("[^0-9a-f]","gi");function _rsasign_getHexPaddedDigestInfoForString(a,b,c){a=KJUR.crypto.Util.hashString(a,c);return KJUR.crypto.Util.getPaddedDigestInfoHex(a,c,b)}function _zeroPaddingOfSignature(a,b){for(var c="",d=b/4-a.length,e=0;e<d;e++)c+="0";return c+a}
function _rsasign_signString(a,b){var c=KJUR.crypto.Util.hashString(a,b);return this.signWithMessageHash(c,b)}function _rsasign_signWithMessageHash(a,b){var c=KJUR.crypto.Util.getPaddedDigestInfoHex(a,b,this.n.bitLength()),c=parseBigInt(c,16),c=this.doPrivate(c).toString(16);return _zeroPaddingOfSignature(c,this.n.bitLength())}function _rsasign_signStringWithSHA1(a){return _rsasign_signString.call(this,a,"sha1")}
function _rsasign_signStringWithSHA256(a){return _rsasign_signString.call(this,a,"sha256")}function pss_mgf1_str(a,b,c){for(var d="",e=0;d.length<b;)d+=hextorstr(c(rstrtohex(a+String.fromCharCode.apply(String,[(e&4278190080)>>24,(e&16711680)>>16,(e&65280)>>8,e&255])))),e+=1;return d}function _rsasign_signStringPSS(a,b,c){a=rstrtohex(a);a=KJUR.crypto.Util.hashHex(a,b);void 0===c&&(c=-1);return this.signWithMessageHashPSS(a,b,c)}
function _rsasign_signWithMessageHashPSS(a,b,c){var d=hextorstr(a);a=d.length;var e=this.n.bitLength()-1,f=Math.ceil(e/8),g=function(a){return KJUR.crypto.Util.hashHex(a,b)};if(-1===c||void 0===c)c=a;else if(-2===c)c=f-a-2;else if(-2>c)throw"invalid salt length";if(f<a+c+2)throw"data too long";var h="";0<c&&(h=Array(c),(new SecureRandom).nextBytes(h),h=String.fromCharCode.apply(String,h));for(var k=hextorstr(g(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+d+h))),l=[],d=0;d<f-c-a-2;d+=1)l[d]=0;c=String.fromCharCode.apply(String,
l)+"\u0001"+h;g=pss_mgf1_str(k,c.length,g);h=[];for(d=0;d<c.length;d+=1)h[d]=c.charCodeAt(d)^g.charCodeAt(d);h[0]&=~(65280>>8*f-e&255);for(d=0;d<a;d++)h.push(k.charCodeAt(d));h.push(188);return _zeroPaddingOfSignature(this.doPrivate(new BigInteger(h)).toString(16),this.n.bitLength())}function _rsasign_getDecryptSignatureBI(a,b,c){var d=new RSAKey;d.setPublic(b,c);return d.doPublic(a)}
function _rsasign_getHexDigestInfoFromSig(a,b,c){return _rsasign_getDecryptSignatureBI(a,b,c).toString(16).replace(/^1f+00/,"")}function _rsasign_getAlgNameAndHashFromHexDisgestInfo(a){for(var b in KJUR.crypto.Util.DIGESTINFOHEAD){var c=KJUR.crypto.Util.DIGESTINFOHEAD[b],d=c.length;if(a.substring(0,d)==c)return[b,a.substring(d)]}return[]}
function _rsasign_verifySignatureWithArgs(a,b,c,d){b=_rsasign_getHexDigestInfoFromSig(b,c,d);c=_rsasign_getAlgNameAndHashFromHexDisgestInfo(b);if(0==c.length)return!1;b=c[1];a=KJUR.crypto.Util.hashString(a,c[0]);return b==a}function _rsasign_verifyHexSignatureForMessage(a,b){var c=parseBigInt(a,16);return _rsasign_verifySignatureWithArgs(b,c,this.n.toString(16),this.e.toString(16))}
function _rsasign_verifyString(a,b){b=b.replace(_RE_HEXDECONLY,"");b=b.replace(/[ \n]+/g,"");var c=parseBigInt(b,16);if(c.bitLength()>this.n.bitLength())return 0;var c=this.doPublic(c).toString(16).replace(/^1f+00/,""),d=_rsasign_getAlgNameAndHashFromHexDisgestInfo(c);if(0==d.length)return!1;c=d[1];d=KJUR.crypto.Util.hashString(a,d[0]);return c==d}
function _rsasign_verifyWithMessageHash(a,b){b=b.replace(_RE_HEXDECONLY,"");b=b.replace(/[ \n]+/g,"");var c=parseBigInt(b,16);if(c.bitLength()>this.n.bitLength())return 0;c=this.doPublic(c).toString(16).replace(/^1f+00/,"");c=_rsasign_getAlgNameAndHashFromHexDisgestInfo(c);return 0==c.length?!1:c[1]==a}function _rsasign_verifyStringPSS(a,b,c,d){a=rstrtohex(a);a=KJUR.crypto.Util.hashHex(a,c);void 0===d&&(d=-1);return this.verifyWithMessageHashPSS(a,b,c,d)}
function _rsasign_verifyWithMessageHashPSS(a,b,c,d){var e=new BigInteger(b,16);if(e.bitLength()>this.n.bitLength())return!1;b=function(a){return KJUR.crypto.Util.hashHex(a,c)};a=hextorstr(a);var f=a.length,g=this.n.bitLength()-1,h=Math.ceil(g/8);if(-1===d||void 0===d)d=f;else if(-2===d)d=h-f-2;else if(-2>d)throw"invalid salt length";if(h<f+d+2)throw"data too long";for(var k=this.doPublic(e).toByteArray(),e=0;e<k.length;e+=1)k[e]&=255;for(;k.length<h;)k.unshift(0);if(188!==k[h-1])throw"encoded message does not end in 0xbc";
var k=String.fromCharCode.apply(String,k),l=k.substr(0,h-f-1),k=k.substr(l.length,f),m=65280>>8*h-g&255;if(0!==(l.charCodeAt(0)&m))throw"bits beyond keysize not zero";for(var q=pss_mgf1_str(k,l.length,b),g=[],e=0;e<l.length;e+=1)g[e]=l.charCodeAt(e)^q.charCodeAt(e);g[0]&=~m;f=h-f-d-2;for(e=0;e<f;e+=1)if(0!==g[e])throw"leftmost octets not zero";if(1!==g[f])throw"0x01 marker not found";return k===hextorstr(b(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+a+String.fromCharCode.apply(String,g.slice(-d)))))}
RSAKey.prototype.signWithMessageHash=_rsasign_signWithMessageHash;RSAKey.prototype.signString=_rsasign_signString;RSAKey.prototype.signStringWithSHA1=_rsasign_signStringWithSHA1;RSAKey.prototype.signStringWithSHA256=_rsasign_signStringWithSHA256;RSAKey.prototype.sign=_rsasign_signString;RSAKey.prototype.signWithSHA1=_rsasign_signStringWithSHA1;RSAKey.prototype.signWithSHA256=_rsasign_signStringWithSHA256;RSAKey.prototype.signWithMessageHashPSS=_rsasign_signWithMessageHashPSS;
RSAKey.prototype.signStringPSS=_rsasign_signStringPSS;RSAKey.prototype.signPSS=_rsasign_signStringPSS;RSAKey.SALT_LEN_HLEN=-1;RSAKey.SALT_LEN_MAX=-2;RSAKey.prototype.verifyWithMessageHash=_rsasign_verifyWithMessageHash;RSAKey.prototype.verifyString=_rsasign_verifyString;RSAKey.prototype.verifyHexSignatureForMessage=_rsasign_verifyHexSignatureForMessage;RSAKey.prototype.verify=_rsasign_verifyString;RSAKey.prototype.verifyHexSignatureForByteArrayMessage=_rsasign_verifyHexSignatureForMessage;
RSAKey.prototype.verifyWithMessageHashPSS=_rsasign_verifyWithMessageHashPSS;RSAKey.prototype.verifyStringPSS=_rsasign_verifyStringPSS;RSAKey.prototype.verifyPSS=_rsasign_verifyStringPSS;RSAKey.SALT_LEN_RECOVER=-2;exports.RSAKey=RSAKey;module.exports=exports;"undefined"!=typeof KJUR&&KJUR||(KJUR={});"undefined"!=typeof KJUR.crypto&&KJUR.crypto||(KJUR.crypto={});
KJUR.crypto.ECDSA=function(a){var b=new SecureRandom;this.type="EC";this.getBigRandom=function(a){return(new BigInteger(a.bitLength(),b)).mod(a.subtract(BigInteger.ONE)).add(BigInteger.ONE)};this.setNamedCurve=function(a){this.ecparams=KJUR.crypto.ECParameterDB.getByName(a);this.pubKeyHex=this.prvKeyHex=null;this.curveName=a};this.setPrivateKeyHex=function(a){this.isPrivate=!0;this.prvKeyHex=a};this.setPublicKeyHex=function(a){this.isPublic=!0;this.pubKeyHex=a};this.generateKeyPairHex=function(){var a=
this.getBigRandom(this.ecparams.n),b=this.ecparams.G.multiply(a),e=b.getX().toBigInteger(),b=b.getY().toBigInteger(),f=this.ecparams.keylen/4,a=("0000000000"+a.toString(16)).slice(-f),e=("0000000000"+e.toString(16)).slice(-f),b=("0000000000"+b.toString(16)).slice(-f),e="04"+e+b;this.setPrivateKeyHex(a);this.setPublicKeyHex(e);return{ecprvhex:a,ecpubhex:e}};this.signWithMessageHash=function(a){return this.signHex(a,this.prvKeyHex)};this.signHex=function(a,b){var e=new BigInteger(b,16),f=this.ecparams.n,
g=new BigInteger(a,16);do var h=this.getBigRandom(f),k=this.ecparams.G.multiply(h).getX().toBigInteger().mod(f);while(0>=k.compareTo(BigInteger.ZERO));e=h.modInverse(f).multiply(g.add(e.multiply(k))).mod(f);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(k,e)};this.sign=function(a,b){var e=this.ecparams.n,f=BigInteger.fromByteArrayUnsigned(a);do var g=this.getBigRandom(e),h=this.ecparams.G.multiply(g).getX().toBigInteger().mod(e);while(0>=h.compareTo(BigInteger.ZERO));e=g.modInverse(e).multiply(f.add(b.multiply(h))).mod(e);
return this.serializeSig(h,e)};this.verifyWithMessageHash=function(a,b){return this.verifyHex(a,b,this.pubKeyHex)};this.verifyHex=function(a,b,e){var f;f=KJUR.crypto.ECDSA.parseSigHex(b);b=f.r;f=f.s;e=ECPointFp.decodeFromHex(this.ecparams.curve,e);a=new BigInteger(a,16);return this.verifyRaw(a,b,f,e)};this.verify=function(a,b,e){var f;if(Bitcoin.Util.isArray(b))b=this.parseSig(b),f=b.r,b=b.s;else if("object"===typeof b&&b.r&&b.s)f=b.r,b=b.s;else throw"Invalid value for signature";if(!(e instanceof
ECPointFp))if(Bitcoin.Util.isArray(e))e=ECPointFp.decodeFrom(this.ecparams.curve,e);else throw"Invalid format for pubkey value, must be byte array or ECPointFp";a=BigInteger.fromByteArrayUnsigned(a);return this.verifyRaw(a,f,b,e)};this.verifyRaw=function(a,b,e,f){var g=this.ecparams.n,h=this.ecparams.G;if(0>b.compareTo(BigInteger.ONE)||0<=b.compareTo(g)||0>e.compareTo(BigInteger.ONE)||0<=e.compareTo(g))return!1;e=e.modInverse(g);a=a.multiply(e).mod(g);e=b.multiply(e).mod(g);return h.multiply(a).add(f.multiply(e)).getX().toBigInteger().mod(g).equals(b)};
this.serializeSig=function(a,b){var e=a.toByteArraySigned(),f=b.toByteArraySigned(),g=[];g.push(2);g.push(e.length);g=g.concat(e);g.push(2);g.push(f.length);g=g.concat(f);g.unshift(g.length);g.unshift(48);return g};this.parseSig=function(a){var b;if(48!=a[0])throw Error("Signature not a valid DERSequence");b=2;if(2!=a[b])throw Error("First element in signature must be a DERInteger");var e=a.slice(b+2,b+2+a[b+1]);b+=2+a[b+1];if(2!=a[b])throw Error("Second element in signature must be a DERInteger");
a=a.slice(b+2,b+2+a[b+1]);e=BigInteger.fromByteArrayUnsigned(e);a=BigInteger.fromByteArrayUnsigned(a);return{r:e,s:a}};this.parseSigCompact=function(a){if(65!==a.length)throw"Signature has the wrong length";var b=a[0]-27;if(0>b||7<b)throw"Invalid signature type";var e=this.ecparams.n,f=BigInteger.fromByteArrayUnsigned(a.slice(1,33)).mod(e);a=BigInteger.fromByteArrayUnsigned(a.slice(33,65)).mod(e);return{r:f,s:a,i:b}};void 0!==a&&void 0!==a.curve&&(this.curveName=a.curve);void 0===this.curveName&&
(this.curveName="secp256r1");this.setNamedCurve(this.curveName);void 0!==a&&(void 0!==a.prv&&this.setPrivateKeyHex(a.prv),void 0!==a.pub&&this.setPublicKeyHex(a.pub))};KJUR.crypto.ECDSA.parseSigHex=function(a){var b=KJUR.crypto.ECDSA.parseSigHexInHexRS(a);a=new BigInteger(b.r,16);b=new BigInteger(b.s,16);return{r:a,s:b}};
KJUR.crypto.ECDSA.parseSigHexInHexRS=function(a){if("30"!=a.substr(0,2))throw"signature is not a ASN.1 sequence";var b=ASN1HEX.getPosArrayOfChildren_AtObj(a,0);if(2!=b.length)throw"number of signature ASN.1 sequence elements seem wrong";var c=b[0],b=b[1];if("02"!=a.substr(c,2))throw"1st item of sequene of signature is not ASN.1 integer";if("02"!=a.substr(b,2))throw"2nd item of sequene of signature is not ASN.1 integer";c=ASN1HEX.getHexOfV_AtObj(a,c);a=ASN1HEX.getHexOfV_AtObj(a,b);return{r:c,s:a}};
KJUR.crypto.ECDSA.asn1SigToConcatSig=function(a){var b=KJUR.crypto.ECDSA.parseSigHexInHexRS(a);a=b.r;b=b.s;"00"==a.substr(0,2)&&8==a.length/2*8%128&&(a=a.substr(2));"00"==b.substr(0,2)&&8==b.length/2*8%128&&(b=b.substr(2));if(0!=a.length/2*8%128)throw"unknown ECDSA sig r length error";if(0!=b.length/2*8%128)throw"unknown ECDSA sig s length error";return a+b};
KJUR.crypto.ECDSA.concatSigToASN1Sig=function(a){if(0!=a.length/2*8%128)throw"unknown ECDSA concatinated r-s sig length error";var b=a.substr(0,a.length/2);a=a.substr(a.length/2);return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(b,a)};KJUR.crypto.ECDSA.hexRSSigToASN1Sig=function(a,b){var c=new BigInteger(a,16),d=new BigInteger(b,16);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(c,d)};
KJUR.crypto.ECDSA.biRSSigToASN1Sig=function(a,b){var c=new KJUR.asn1.DERInteger({bigint:a}),d=new KJUR.asn1.DERInteger({bigint:b});return(new KJUR.asn1.DERSequence({array:[c,d]})).getEncodedHex()};intShim=require("jsbn");
ASN1HEX=new function(){this.getByteLengthOfL_AtObj=function(a,b){if("8"!=a.substring(b+2,b+3))return 1;var c=parseInt(a.substring(b+3,b+4));return 0==c?-1:0<c&&10>c?c+1:-2};this.getHexOfL_AtObj=function(a,b){var c=this.getByteLengthOfL_AtObj(a,b);return 1>c?"":a.substring(b+2,b+2+2*c)};this.getIntOfL_AtObj=function(a,b){var c=this.getHexOfL_AtObj(a,b);return""==c?-1:(8>parseInt(c.substring(0,1))?new BigInteger(c,16):new BigInteger(c.substring(2),16)).intValue()};this.getStartPosOfV_AtObj=function(a,
b){var c=this.getByteLengthOfL_AtObj(a,b);return 0>c?c:b+2*(c+1)};this.getHexOfV_AtObj=function(a,b){var c=this.getStartPosOfV_AtObj(a,b),d=this.getIntOfL_AtObj(a,b);return a.substring(c,c+2*d)};this.getHexOfTLV_AtObj=function(a,b){var c=a.substr(b,2),d=this.getHexOfL_AtObj(a,b),e=this.getHexOfV_AtObj(a,b);return c+d+e};this.getPosOfNextSibling_AtObj=function(a,b){var c=this.getStartPosOfV_AtObj(a,b),d=this.getIntOfL_AtObj(a,b);return c+2*d};this.getPosArrayOfChildren_AtObj=function(a,b){var c=[],
d=this.getStartPosOfV_AtObj(a,b);c.push(d);for(var e=this.getIntOfL_AtObj(a,b),f=d,g=0;;){f=this.getPosOfNextSibling_AtObj(a,f);if(null==f||f-d>=2*e)break;if(200<=g)break;c.push(f);g++}return c};this.getNthChildIndex_AtObj=function(a,b,c){return this.getPosArrayOfChildren_AtObj(a,b)[c]};this.getDecendantIndexByNthList=function(a,b,c){if(0==c.length)return b;var d=c.shift();b=this.getPosArrayOfChildren_AtObj(a,b);return this.getDecendantIndexByNthList(a,b[d],c)};this.getDecendantHexTLVByNthList=function(a,
b,c){b=this.getDecendantIndexByNthList(a,b,c);return this.getHexOfTLV_AtObj(a,b)};this.getDecendantHexVByNthList=function(a,b,c){b=this.getDecendantIndexByNthList(a,b,c);return this.getHexOfV_AtObj(a,b)}};ASN1HEX.getVbyList=function(a,b,c,d){b=this.getDecendantIndexByNthList(a,b,c);if(void 0===b)throw"can't find nthList object";if(void 0!==d&&a.substr(b,2)!=d)throw"checking tag doesn't match: "+a.substr(b,2)+"!="+d;return this.getHexOfV_AtObj(a,b)};
ASN1HEX.hextooidstr=function(a){var b=function(a,b){return a.length>=b?a:Array(b-a.length+1).join("0")+a},c=[],d=a.substr(0,2),d=parseInt(d,16);c[0]=new String(Math.floor(d/40));c[1]=new String(d%40);var e=a.substr(2);a=[];for(d=0;d<e.length/2;d++)a.push(parseInt(e.substr(2*d,2),16));for(var e=[],f="",d=0;d<a.length;d++)a[d]&128?f+=b((a[d]&127).toString(2),7):(f+=b((a[d]&127).toString(2),7),e.push(new String(parseInt(f,2))),f="");b=c.join(".");0<e.length&&(b=b+"."+e.join("."));return b};
ASN1HEX.dump=function(a,b,c,d){var e=function(a,b){return a.length<=2*b?a:a.substr(0,b)+"..(total "+a.length/2+"bytes).."+a.substr(a.length-b,b)};void 0===b&&(b={ommit_long_octet:32});void 0===c&&(c=0);void 0===d&&(d="");var f=b.ommit_long_octet;if("01"==a.substr(c,2))return a=ASN1HEX.getHexOfV_AtObj(a,c),"00"==a?d+"BOOLEAN FALSE\n":d+"BOOLEAN TRUE\n";if("02"==a.substr(c,2))return a=ASN1HEX.getHexOfV_AtObj(a,c),d+"INTEGER "+e(a,f)+"\n";if("03"==a.substr(c,2))return a=ASN1HEX.getHexOfV_AtObj(a,c),
d+"BITSTRING "+e(a,f)+"\n";if("04"==a.substr(c,2))return a=ASN1HEX.getHexOfV_AtObj(a,c),ASN1HEX.isASN1HEX(a)?e=d+"OCTETSTRING, encapsulates\n"+ASN1HEX.dump(a,b,0,d+" "):d+"OCTETSTRING "+e(a,f)+"\n";if("05"==a.substr(c,2))return d+"NULL\n";if("06"==a.substr(c,2)){a=ASN1HEX.getHexOfV_AtObj(a,c);var g=KJUR.asn1.ASN1Util.oidHexToInt(a),f=KJUR.asn1.x509.OID.oid2name(g);a=g.replace(/\./g," ");return""!=f?d+"ObjectIdentifier "+f+" ("+a+")\n":d+"ObjectIdentifier ("+a+")\n"}if("0c"==a.substr(c,2))return d+
"UTF8String '"+hextoutf8(ASN1HEX.getHexOfV_AtObj(a,c))+"'\n";if("13"==a.substr(c,2))return d+"PrintableString '"+hextoutf8(ASN1HEX.getHexOfV_AtObj(a,c))+"'\n";if("14"==a.substr(c,2))return d+"TeletexString '"+hextoutf8(ASN1HEX.getHexOfV_AtObj(a,c))+"'\n";if("16"==a.substr(c,2))return d+"IA5String '"+hextoutf8(ASN1HEX.getHexOfV_AtObj(a,c))+"'\n";if("17"==a.substr(c,2))return d+"UTCTime "+hextoutf8(ASN1HEX.getHexOfV_AtObj(a,c))+"\n";if("18"==a.substr(c,2))return d+"GeneralizedTime "+hextoutf8(ASN1HEX.getHexOfV_AtObj(a,
c))+"\n";if("30"==a.substr(c,2)){if("3000"==a.substr(c,4))return d+"SEQUENCE {}\n";e=d+"SEQUENCE\n";c=ASN1HEX.getPosArrayOfChildren_AtObj(a,c);f=b;2!=c.length&&3!=c.length||"06"!=a.substr(c[0],2)||"04"!=a.substr(c[c.length-1],2)||(f=ASN1HEX.getHexOfV_AtObj(a,c[0]),g=KJUR.asn1.ASN1Util.oidHexToInt(f),f=KJUR.asn1.x509.OID.oid2name(g),b=JSON.parse(JSON.stringify(b)),b.x509ExtName=f,f=b);for(g=0;g<c.length;g++)e+=ASN1HEX.dump(a,f,c[g],d+" ");return e}if("31"==a.substr(c,2)){e=d+"SET\n";c=ASN1HEX.getPosArrayOfChildren_AtObj(a,
c);for(g=0;g<c.length;g++)e+=ASN1HEX.dump(a,b,c[g],d+" ");return e}f=parseInt(a.substr(c,2),16);if(0!=(f&128)){e=f&31;if(0!=(f&32))for(e=d+"["+e+"]\n",c=ASN1HEX.getPosArrayOfChildren_AtObj(a,c),g=0;g<c.length;g++)e+=ASN1HEX.dump(a,b,c[g],d+" ");else a=ASN1HEX.getHexOfV_AtObj(a,c),"68747470"==a.substr(0,8)&&(a=hextoutf8(a)),"subjectAltName"===b.x509ExtName&&2==e&&(a=hextoutf8(a)),e=d+"["+e+"] "+a+"\n";return e}return d+"UNKNOWN("+a.substr(c,2)+") "+ASN1HEX.getHexOfV_AtObj(a,c)+"\n"};
ASN1HEX.isASN1HEX=function(a){if(1==a.length%2)return!1;var b=ASN1HEX.getIntOfL_AtObj(a,0),c=a.substr(0,2),d=ASN1HEX.getHexOfL_AtObj(a,0);return a.length-c.length-d.length==2*b?!0:!1};exports.ASN1HEX=ASN1HEX;module.exports=exports;b64tohex=require("./base64.js").b64tohex;RSAKey=require("./rsa.js").RSAKey;ASN1HEX=require("./asn1hex-1.1.js").ASN1HEX;
function X509(){this.hex=this.subjectPublicKeyRSA_hE=this.subjectPublicKeyRSA_hN=this.subjectPublicKeyRSA=null;this.getSerialNumberHex=function(){return ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,1])};this.getIssuerHex=function(){return ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,3])};this.getIssuerString=function(){return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,3]))};this.getSubjectHex=function(){return ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,5])};this.getSubjectString=
function(){return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,5]))};this.getNotBefore=function(){var a=ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,4,0]),a=a.replace(/(..)/g,"%$1");return a=decodeURIComponent(a)};this.getNotAfter=function(){var a=ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,4,1]),a=a.replace(/(..)/g,"%$1");return a=decodeURIComponent(a)};this.readCertPEM=function(a){a=X509.pemToHex(a);var b=X509.getPublicKeyHexArrayFromCertHex(a),c=new RSAKey;c.setPublic(b[0],
b[1]);this.subjectPublicKeyRSA=c;this.subjectPublicKeyRSA_hN=b[0];this.subjectPublicKeyRSA_hE=b[1];this.hex=a};this.readCertPEMWithoutRSAInit=function(a){a=X509.pemToHex(a);var b=X509.getPublicKeyHexArrayFromCertHex(a);this.subjectPublicKeyRSA.setPublic(b[0],b[1]);this.subjectPublicKeyRSA_hN=b[0];this.subjectPublicKeyRSA_hE=b[1];this.hex=a}}X509.pemToBase64=function(a){a=a.replace("-----BEGIN CERTIFICATE-----","");a=a.replace("-----END CERTIFICATE-----","");return a=a.replace(/[ \n]+/g,"")};
X509.pemToHex=function(a){a=X509.pemToBase64(a);return b64tohex(a)};X509.getSubjectPublicKeyPosFromCertHex=function(a){var b=X509.getSubjectPublicKeyInfoPosFromCertHex(a);if(-1==b)return-1;b=ASN1HEX.getPosArrayOfChildren_AtObj(a,b);if(2!=b.length)return-1;b=b[1];if("03"!=a.substring(b,b+2))return-1;b=ASN1HEX.getStartPosOfV_AtObj(a,b);return"00"!=a.substring(b,b+2)?-1:b+2};
X509.getSubjectPublicKeyInfoPosFromCertHex=function(a){var b=ASN1HEX.getStartPosOfV_AtObj(a,0),b=ASN1HEX.getPosArrayOfChildren_AtObj(a,b);return 1>b.length?-1:"a003020102"==a.substring(b[0],b[0]+10)?6>b.length?-1:b[6]:5>b.length?-1:b[5]};X509.getPublicKeyHexArrayFromCertHex=function(a){var b=X509.getSubjectPublicKeyPosFromCertHex(a),c=ASN1HEX.getPosArrayOfChildren_AtObj(a,b);if(2!=c.length)return[];b=ASN1HEX.getHexOfV_AtObj(a,c[0]);a=ASN1HEX.getHexOfV_AtObj(a,c[1]);return null!=b&&null!=a?[b,a]:[]};
X509.getHexTbsCertificateFromCert=function(a){return ASN1HEX.getStartPosOfV_AtObj(a,0)};X509.getPublicKeyHexArrayFromCertPEM=function(a){a=X509.pemToHex(a);return X509.getPublicKeyHexArrayFromCertHex(a)};X509.hex2dn=function(a){for(var b="",c=ASN1HEX.getPosArrayOfChildren_AtObj(a,0),d=0;d<c.length;d++)var e=ASN1HEX.getHexOfTLV_AtObj(a,c[d]),b=b+"/"+X509.hex2rdn(e);return b};
X509.hex2rdn=function(a){var b=ASN1HEX.getDecendantHexTLVByNthList(a,0,[0,0]),c=ASN1HEX.getDecendantHexVByNthList(a,0,[0,1]);a="";try{a=X509.DN_ATTRHEX[b]}catch(d){a=b}c=c.replace(/(..)/g,"%$1");b=decodeURIComponent(c);return a+"="+b};X509.DN_ATTRHEX={"0603550406":"C","060355040a":"O","060355040b":"OU","0603550403":"CN","0603550405":"SN","0603550408":"ST","0603550407":"L"};
X509.getPublicKeyFromCertPEM=function(a){var b=X509.getPublicKeyInfoPropOfCertPEM(a);if("2a864886f70d010101"==b.algoid){var c=KEYUTIL.parsePublicRawRSAKeyHex(b.keyhex);a=new RSAKey;a.setPublic(c.n,c.e);return a}if("2a8648ce3d0201"==b.algoid)return a=new KJUR.crypto.ECDSA({curve:KJUR.crypto.OID.oidhex2name[b.algparam],info:b.keyhex}),a.setPublicKeyHex(b.keyhex),a;if("2a8648ce380401"==b.algoid){var c=ASN1HEX.getVbyList(b.algparam,0,[0],"02"),d=ASN1HEX.getVbyList(b.algparam,0,[1],"02"),e=ASN1HEX.getVbyList(b.algparam,
0,[2],"02"),b=ASN1HEX.getHexOfV_AtObj(b.keyhex,0),b=b.substr(2);a=new KJUR.crypto.DSA;a.setPublic(new BigInteger(c,16),new BigInteger(d,16),new BigInteger(e,16),new BigInteger(b,16));return a}throw"unsupported key";};
X509.getPublicKeyInfoPropOfCertPEM=function(a){var b={algparam:null};a=X509.pemToHex(a);var c=ASN1HEX.getPosArrayOfChildren_AtObj(a,0);if(3!=c.length)throw"malformed X.509 certificate PEM (code:001)";if("30"!=a.substr(c[0],2))throw"malformed X.509 certificate PEM (code:002)";c=ASN1HEX.getPosArrayOfChildren_AtObj(a,c[0]);if(7>c.length)throw"malformed X.509 certificate PEM (code:003)";c=ASN1HEX.getPosArrayOfChildren_AtObj(a,c[6]);if(2!=c.length)throw"malformed X.509 certificate PEM (code:004)";var d=
ASN1HEX.getPosArrayOfChildren_AtObj(a,c[0]);if(2!=d.length)throw"malformed X.509 certificate PEM (code:005)";b.algoid=ASN1HEX.getHexOfV_AtObj(a,d[0]);"06"==a.substr(d[1],2)?b.algparam=ASN1HEX.getHexOfV_AtObj(a,d[1]):"30"==a.substr(d[1],2)&&(b.algparam=ASN1HEX.getHexOfTLV_AtObj(a,d[1]));if("03"!=a.substr(c[1],2))throw"malformed X.509 certificate PEM (code:006)";a=ASN1HEX.getHexOfV_AtObj(a,c[1]);b.keyhex=a.substr(2);return b};
X509.getPublicKeyInfoPosOfCertHEX=function(a){var b=ASN1HEX.getPosArrayOfChildren_AtObj(a,0);if(3!=b.length)throw"malformed X.509 certificate PEM (code:001)";if("30"!=a.substr(b[0],2))throw"malformed X.509 certificate PEM (code:002)";a=ASN1HEX.getPosArrayOfChildren_AtObj(a,b[0]);if(7>a.length)throw"malformed X.509 certificate PEM (code:003)";return a[6]};
X509.getV3ExtInfoListOfCertHex=function(a){var b=ASN1HEX.getPosArrayOfChildren_AtObj(a,0);if(3!=b.length)throw"malformed X.509 certificate PEM (code:001)";if("30"!=a.substr(b[0],2))throw"malformed X.509 certificate PEM (code:002)";b=ASN1HEX.getPosArrayOfChildren_AtObj(a,b[0]);if(8>b.length)throw"malformed X.509 certificate PEM (code:003)";if("a3"!=a.substr(b[7],2))throw"malformed X.509 certificate PEM (code:004)";b=ASN1HEX.getPosArrayOfChildren_AtObj(a,b[7]);if(1!=b.length)throw"malformed X.509 certificate PEM (code:005)";
if("30"!=a.substr(b[0],2))throw"malformed X.509 certificate PEM (code:006)";for(var b=ASN1HEX.getPosArrayOfChildren_AtObj(a,b[0]),c=b.length,d=Array(c),e=0;e<c;e++)d[e]=X509.getV3ExtItemInfo_AtObj(a,b[e]);return d};
X509.getV3ExtItemInfo_AtObj=function(a,b){var c={};c.posTLV=b;var d=ASN1HEX.getPosArrayOfChildren_AtObj(a,b);if(2!=d.length&&3!=d.length)throw"malformed X.509v3 Ext (code:001)";if("06"!=a.substr(d[0],2))throw"malformed X.509v3 Ext (code:002)";var e=ASN1HEX.getHexOfV_AtObj(a,d[0]);c.oid=ASN1HEX.hextooidstr(e);c.critical=!1;3==d.length&&(c.critical=!0);d=d[d.length-1];if("04"!=a.substr(d,2))throw"malformed X.509v3 Ext (code:003)";c.posV=ASN1HEX.getStartPosOfV_AtObj(a,d);return c};
X509.getHexOfTLV_V3ExtValue=function(a,b){var c=X509.getPosOfTLV_V3ExtValue(a,b);return-1==c?"":ASN1HEX.getHexOfTLV_AtObj(a,c)};X509.getHexOfV_V3ExtValue=function(a,b){var c=X509.getPosOfTLV_V3ExtValue(a,b);return-1==c?"":ASN1HEX.getHexOfV_AtObj(a,c)};X509.getPosOfTLV_V3ExtValue=function(a,b){var c=b;b.match(/^[0-9.]+$/)||(c=KJUR.asn1.x509.OID.name2oid(b));if(""==c)return-1;for(var d=X509.getV3ExtInfoListOfCertHex(a),e=0;e<d.length;e++){var f=d[e];if(f.oid==c)return f.posV}return-1};
X509.KEYUSAGE_NAME="digitalSignature nonRepudiation keyEncipherment dataEncipherment keyAgreement keyCertSign cRLSign encipherOnly decipherOnly".split(" ");X509.getExtKeyUsageBin=function(a){var b=X509.getHexOfV_V3ExtValue(a,"keyUsage");if(""==b)return"";if(0!=b.length%2||2>=b.length)throw"malformed key usage value";a=parseInt(b.substr(0,2));b=parseInt(b.substr(2),16).toString(2);return b.substr(0,b.length-a)};
X509.getExtKeyUsageString=function(a){a=X509.getExtKeyUsageBin(a);for(var b=[],c=0;c<a.length;c++)"1"==a.substr(c,1)&&b.push(X509.KEYUSAGE_NAME[c]);return b.join(",")};
X509.getExtAIAInfo=function(a){var b={ocsp:[],caissuer:[]},c=X509.getPosOfTLV_V3ExtValue(a,"authorityInfoAccess");if(-1==c)return null;if("30"!=a.substr(c,2))throw"malformed AIA Extn Value";for(var c=ASN1HEX.getPosArrayOfChildren_AtObj(a,c),d=0;d<c.length;d++){var e=ASN1HEX.getPosArrayOfChildren_AtObj(a,c[d]);if(2!=e.length)throw"malformed AccessDescription of AIA Extn";var f=e[0],e=e[1];"2b06010505073001"==ASN1HEX.getHexOfV_AtObj(a,f)&&"86"==a.substr(e,2)&&b.ocsp.push(hextoutf8(ASN1HEX.getHexOfV_AtObj(a,
e)));"2b06010505073002"==ASN1HEX.getHexOfV_AtObj(a,f)&&"86"==a.substr(e,2)&&b.caissuer.push(hextoutf8(ASN1HEX.getHexOfV_AtObj(a,e)))}return b};exports.X509=X509;module.exports=exports;var dbits,canary=0xdeadbeefcafe,j_lm=15715070==(canary&16777215),BigInteger=function(a,b,c){null!=a&&("number"==typeof a?this.fromNumber(a,b,c):null==b&&"string"!=typeof a?this.fromString(a,256):this.fromString(a,b))};function nbi(){return new BigInteger(null)}
function am1(a,b,c,d,e,f){for(;0<=--f;){var g=b*this[a++]+c[d]+e;e=Math.floor(g/67108864);c[d++]=g&67108863}return e}function am2(a,b,c,d,e,f){var g=b&32767;for(b>>=15;0<=--f;){var h=this[a]&32767,k=this[a++]>>15,l=b*h+k*g,h=g*h+((l&32767)<<15)+c[d]+(e&1073741823);e=(h>>>30)+(l>>>15)+b*k+(e>>>30);c[d++]=h&1073741823}return e}
function am3(a,b,c,d,e,f){var g=b&16383;for(b>>=14;0<=--f;){var h=this[a]&16383,k=this[a++]>>14,l=b*h+k*g,h=g*h+((l&16383)<<14)+c[d]+e;e=(h>>28)+(l>>14)+b*k;c[d++]=h&268435455}return e}j_lm&&"Microsoft Internet Explorer"==navigator.appName?(BigInteger.prototype.am=am2,dbits=30):j_lm&&"Netscape"!=navigator.appName?(BigInteger.prototype.am=am1,dbits=26):(BigInteger.prototype.am=am3,dbits=28);BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<<dbits)-1;BigInteger.prototype.DV=1<<dbits;
var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RM="0123456789abcdefghijklmnopqrstuvwxyz",BI_RC=[],rr,vv;rr=48;for(vv=0;9>=vv;++vv)BI_RC[rr++]=vv;rr=97;for(vv=10;36>vv;++vv)BI_RC[rr++]=vv;rr=65;for(vv=10;36>vv;++vv)BI_RC[rr++]=vv;function int2char(a){return BI_RM.charAt(a)}function intAt(a,b){var c=BI_RC[a.charCodeAt(b)];return null==c?-1:c}
function bnpCopyTo(a){for(var b=this.t-1;0<=b;--b)a[b]=this[b];a.t=this.t;a.s=this.s}function bnpFromInt(a){this.t=1;this.s=0>a?-1:0;0<a?this[0]=a:-1>a?this[0]=a+this.DV:this.t=0}function nbv(a){var b=nbi();b.fromInt(a);return b}
function bnpFromString(a,b){var c;if(16==b)c=4;else if(8==b)c=3;else if(256==b)c=8;else if(2==b)c=1;else if(32==b)c=5;else if(4==b)c=2;else{this.fromRadix(a,b);return}this.s=this.t=0;for(var d=a.length,e=!1,f=0;0<=--d;){var g=8==c?a[d]&255:intAt(a,d);0>g?"-"==a.charAt(d)&&(e=!0):(e=!1,0==f?this[this.t++]=g:f+c>this.DB?(this[this.t-1]|=(g&(1<<this.DB-f)-1)<<f,this[this.t++]=g>>this.DB-f):this[this.t-1]|=g<<f,f+=c,f>=this.DB&&(f-=this.DB))}8==c&&0!=(a[0]&128)&&(this.s=-1,0<f&&(this[this.t-1]|=(1<<this.DB-
f)-1<<f));this.clamp();e&&BigInteger.ZERO.subTo(this,this)}function bnpClamp(){for(var a=this.s&this.DM;0<this.t&&this[this.t-1]==a;)--this.t}
function bnToString(a){if(0>this.s)return"-"+this.negate().toString(a);if(16==a)a=4;else if(8==a)a=3;else if(2==a)a=1;else if(32==a)a=5;else if(4==a)a=2;else return this.toRadix(a);var b=(1<<a)-1,c,d=!1,e="",f=this.t,g=this.DB-f*this.DB%a;if(0<f--)for(g<this.DB&&0<(c=this[f]>>g)&&(d=!0,e=int2char(c));0<=f;)g<a?(c=(this[f]&(1<<g)-1)<<a-g,c|=this[--f]>>(g+=this.DB-a)):(c=this[f]>>(g-=a)&b,0>=g&&(g+=this.DB,--f)),0<c&&(d=!0),d&&(e+=int2char(c));return d?e:"0"}
function bnNegate(){var a=nbi();BigInteger.ZERO.subTo(this,a);return a}function bnAbs(){return 0>this.s?this.negate():this}function bnCompareTo(a){var b=this.s-a.s;if(0!=b)return b;var c=this.t,b=c-a.t;if(0!=b)return 0>this.s?-b:b;for(;0<=--c;)if(0!=(b=this[c]-a[c]))return b;return 0}function nbits(a){var b=1,c;0!=(c=a>>>16)&&(a=c,b+=16);0!=(c=a>>8)&&(a=c,b+=8);0!=(c=a>>4)&&(a=c,b+=4);0!=(c=a>>2)&&(a=c,b+=2);0!=a>>1&&(b+=1);return b}
function bnBitLength(){return 0>=this.t?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(a,b){var c;for(c=this.t-1;0<=c;--c)b[c+a]=this[c];for(c=a-1;0<=c;--c)b[c]=0;b.t=this.t+a;b.s=this.s}function bnpDRShiftTo(a,b){for(var c=a;c<this.t;++c)b[c-a]=this[c];b.t=Math.max(this.t-a,0);b.s=this.s}
function bnpLShiftTo(a,b){var c=a%this.DB,d=this.DB-c,e=(1<<d)-1,f=Math.floor(a/this.DB),g=this.s<<c&this.DM,h;for(h=this.t-1;0<=h;--h)b[h+f+1]=this[h]>>d|g,g=(this[h]&e)<<c;for(h=f-1;0<=h;--h)b[h]=0;b[f]=g;b.t=this.t+f+1;b.s=this.s;b.clamp()}
function bnpRShiftTo(a,b){b.s=this.s;var c=Math.floor(a/this.DB);if(c>=this.t)b.t=0;else{var d=a%this.DB,e=this.DB-d,f=(1<<d)-1;b[0]=this[c]>>d;for(var g=c+1;g<this.t;++g)b[g-c-1]|=(this[g]&f)<<e,b[g-c]=this[g]>>d;0<d&&(b[this.t-c-1]|=(this.s&f)<<e);b.t=this.t-c;b.clamp()}}
function bnpSubTo(a,b){for(var c=0,d=0,e=Math.min(a.t,this.t);c<e;)d+=this[c]-a[c],b[c++]=d&this.DM,d>>=this.DB;if(a.t<this.t){for(d-=a.s;c<this.t;)d+=this[c],b[c++]=d&this.DM,d>>=this.DB;d+=this.s}else{for(d+=this.s;c<a.t;)d-=a[c],b[c++]=d&this.DM,d>>=this.DB;d-=a.s}b.s=0>d?-1:0;-1>d?b[c++]=this.DV+d:0<d&&(b[c++]=d);b.t=c;b.clamp()}
function bnpMultiplyTo(a,b){var c=this.abs(),d=a.abs(),e=c.t;for(b.t=e+d.t;0<=--e;)b[e]=0;for(e=0;e<d.t;++e)b[e+c.t]=c.am(0,d[e],b,e,0,c.t);b.s=0;b.clamp();this.s!=a.s&&BigInteger.ZERO.subTo(b,b)}function bnpSquareTo(a){for(var b=this.abs(),c=a.t=2*b.t;0<=--c;)a[c]=0;for(c=0;c<b.t-1;++c){var d=b.am(c,b[c],a,2*c,0,1);(a[c+b.t]+=b.am(c+1,2*b[c],a,2*c+1,d,b.t-c-1))>=b.DV&&(a[c+b.t]-=b.DV,a[c+b.t+1]=1)}0<a.t&&(a[a.t-1]+=b.am(c,b[c],a,2*c,0,1));a.s=0;a.clamp()}
function bnpDivRemTo(a,b,c){var d=a.abs();if(!(0>=d.t)){var e=this.abs();if(e.t<d.t)null!=b&&b.fromInt(0),null!=c&&this.copyTo(c);else{null==c&&(c=nbi());var f=nbi(),g=this.s;a=a.s;var h=this.DB-nbits(d[d.t-1]);0<h?(d.lShiftTo(h,f),e.lShiftTo(h,c)):(d.copyTo(f),e.copyTo(c));d=f.t;e=f[d-1];if(0!=e){var k=e*(1<<this.F1)+(1<d?f[d-2]>>this.F2:0),l=this.FV/k,k=(1<<this.F1)/k,m=1<<this.F2,q=c.t,p=q-d,s=null==b?nbi():b;f.dlShiftTo(p,s);0<=c.compareTo(s)&&(c[c.t++]=1,c.subTo(s,c));BigInteger.ONE.dlShiftTo(d,
s);for(s.subTo(f,f);f.t<d;)f[f.t++]=0;for(;0<=--p;){var w=c[--q]==e?this.DM:Math.floor(c[q]*l+(c[q-1]+m)*k);if((c[q]+=f.am(0,w,c,p,0,d))<w)for(f.dlShiftTo(p,s),c.subTo(s,c);c[q]<--w;)c.subTo(s,c)}null!=b&&(c.drShiftTo(d,b),g!=a&&BigInteger.ZERO.subTo(b,b));c.t=d;c.clamp();0<h&&c.rShiftTo(h,c);0>g&&BigInteger.ZERO.subTo(c,c)}}}}function bnMod(a){var b=nbi();this.abs().divRemTo(a,null,b);0>this.s&&0<b.compareTo(BigInteger.ZERO)&&a.subTo(b,b);return b}function Classic(a){this.m=a}
function cConvert(a){return 0>a.s||0<=a.compareTo(this.m)?a.mod(this.m):a}function cRevert(a){return a}function cReduce(a){a.divRemTo(this.m,null,a)}function cMulTo(a,b,c){a.multiplyTo(b,c);this.reduce(c)}function cSqrTo(a,b){a.squareTo(b);this.reduce(b)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;
function bnpInvDigit(){if(1>this.t)return 0;var a=this[0];if(0==(a&1))return 0;var b=a&3,b=b*(2-(a&15)*b)&15,b=b*(2-(a&255)*b)&255,b=b*(2-((a&65535)*b&65535))&65535,b=b*(2-a*b%this.DV)%this.DV;return 0<b?this.DV-b:-b}function Montgomery(a){this.m=a;this.mp=a.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<a.DB-15)-1;this.mt2=2*a.t}
function montConvert(a){var b=nbi();a.abs().dlShiftTo(this.m.t,b);b.divRemTo(this.m,null,b);0>a.s&&0<b.compareTo(BigInteger.ZERO)&&this.m.subTo(b,b);return b}function montRevert(a){var b=nbi();a.copyTo(b);this.reduce(b);return b}
function montReduce(a){for(;a.t<=this.mt2;)a[a.t++]=0;for(var b=0;b<this.m.t;++b){var c=a[b]&32767,d=c*this.mpl+((c*this.mph+(a[b]>>15)*this.mpl&this.um)<<15)&a.DM,c=b+this.m.t;for(a[c]+=this.m.am(0,d,a,b,0,this.m.t);a[c]>=a.DV;)a[c]-=a.DV,a[++c]++}a.clamp();a.drShiftTo(this.m.t,a);0<=a.compareTo(this.m)&&a.subTo(this.m,a)}function montSqrTo(a,b){a.squareTo(b);this.reduce(b)}function montMulTo(a,b,c){a.multiplyTo(b,c);this.reduce(c)}Montgomery.prototype.convert=montConvert;
Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return 0==(0<this.t?this[0]&1:this.s)}function bnpExp(a,b){if(4294967295<a||1>a)return BigInteger.ONE;var c=nbi(),d=nbi(),e=b.convert(this),f=nbits(a)-1;for(e.copyTo(c);0<=--f;)if(b.sqrTo(c,d),0<(a&1<<f))b.mulTo(d,e,c);else var g=c,c=d,d=g;return b.revert(c)}
function bnModPowInt(a,b){var c;c=256>a||b.isEven()?new Classic(b):new Montgomery(b);return this.exp(a,c)}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;
BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;
BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);function bnClone(){var a=nbi();this.copyTo(a);return a}function bnIntValue(){if(0>this.s){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]}function bnByteValue(){return 0==this.t?this.s:this[0]<<24>>24}function bnShortValue(){return 0==this.t?this.s:this[0]<<16>>16}function bnpChunkSize(a){return Math.floor(Math.LN2*this.DB/Math.log(a))}
function bnSigNum(){return 0>this.s?-1:0>=this.t||1==this.t&&0>=this[0]?0:1}function bnpToRadix(a){null==a&&(a=10);if(0==this.signum()||2>a||36<a)return"0";var b=this.chunkSize(a),b=Math.pow(a,b),c=nbv(b),d=nbi(),e=nbi(),f="";for(this.divRemTo(c,d,e);0<d.signum();)f=(b+e.intValue()).toString(a).substr(1)+f,d.divRemTo(c,d,e);return e.intValue().toString(a)+f}
function bnpFromRadix(a,b){this.fromInt(0);null==b&&(b=10);for(var c=this.chunkSize(b),d=Math.pow(b,c),e=!1,f=0,g=0,h=0;h<a.length;++h){var k=intAt(a,h);0>k?"-"==a.charAt(h)&&0==this.signum()&&(e=!0):(g=b*g+k,++f>=c&&(this.dMultiply(d),this.dAddOffset(g,0),g=f=0))}0<f&&(this.dMultiply(Math.pow(b,f)),this.dAddOffset(g,0));e&&BigInteger.ZERO.subTo(this,this)}
function bnpFromNumber(a,b,c){if("number"==typeof b)if(2>a)this.fromInt(1);else for(this.fromNumber(a,c),this.testBit(a-1)||this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(b);)this.dAddOffset(2,0),this.bitLength()>a&&this.subTo(BigInteger.ONE.shiftLeft(a-1),this);else{c=[];var d=a&7;c.length=(a>>3)+1;b.nextBytes(c);c[0]=0<d?c[0]&(1<<d)-1:0;this.fromString(c,256)}}
function bnToByteArray(){var a=this.t,b=[];b[0]=this.s;var c=this.DB-a*this.DB%8,d,e=0;if(0<a--)for(c<this.DB&&(d=this[a]>>c)!=(this.s&this.DM)>>c&&(b[e++]=d|this.s<<this.DB-c);0<=a;)if(8>c?(d=(this[a]&(1<<c)-1)<<8-c,d|=this[--a]>>(c+=this.DB-8)):(d=this[a]>>(c-=8)&255,0>=c&&(c+=this.DB,--a)),0!=(d&128)&&(d|=-256),0==e&&(this.s&128)!=(d&128)&&++e,0<e||d!=this.s)b[e++]=d;return b}function bnEquals(a){return 0==this.compareTo(a)}function bnMin(a){return 0>this.compareTo(a)?this:a}
function bnMax(a){return 0<this.compareTo(a)?this:a}function bnpBitwiseTo(a,b,c){var d,e,f=Math.min(a.t,this.t);for(d=0;d<f;++d)c[d]=b(this[d],a[d]);if(a.t<this.t){e=a.s&this.DM;for(d=f;d<this.t;++d)c[d]=b(this[d],e);c.t=this.t}else{e=this.s&this.DM;for(d=f;d<a.t;++d)c[d]=b(e,a[d]);c.t=a.t}c.s=b(this.s,a.s);c.clamp()}function op_and(a,b){return a&b}function bnAnd(a){var b=nbi();this.bitwiseTo(a,op_and,b);return b}function op_or(a,b){return a|b}
function bnOr(a){var b=nbi();this.bitwiseTo(a,op_or,b);return b}function op_xor(a,b){return a^b}function bnXor(a){var b=nbi();this.bitwiseTo(a,op_xor,b);return b}function op_andnot(a,b){return a&~b}function bnAndNot(a){var b=nbi();this.bitwiseTo(a,op_andnot,b);return b}function bnNot(){for(var a=nbi(),b=0;b<this.t;++b)a[b]=this.DM&~this[b];a.t=this.t;a.s=~this.s;return a}function bnShiftLeft(a){var b=nbi();0>a?this.rShiftTo(-a,b):this.lShiftTo(a,b);return b}
function bnShiftRight(a){var b=nbi();0>a?this.lShiftTo(-a,b):this.rShiftTo(a,b);return b}function lbit(a){if(0==a)return-1;var b=0;0==(a&65535)&&(a>>=16,b+=16);0==(a&255)&&(a>>=8,b+=8);0==(a&15)&&(a>>=4,b+=4);0==(a&3)&&(a>>=2,b+=2);0==(a&1)&&++b;return b}function bnGetLowestSetBit(){for(var a=0;a<this.t;++a)if(0!=this[a])return a*this.DB+lbit(this[a]);return 0>this.s?this.t*this.DB:-1}function cbit(a){for(var b=0;0!=a;)a&=a-1,++b;return b}
function bnBitCount(){for(var a=0,b=this.s&this.DM,c=0;c<this.t;++c)a+=cbit(this[c]^b);return a}function bnTestBit(a){var b=Math.floor(a/this.DB);return b>=this.t?0!=this.s:0!=(this[b]&1<<a%this.DB)}function bnpChangeBit(a,b){var c=BigInteger.ONE.shiftLeft(a);this.bitwiseTo(c,b,c);return c}function bnSetBit(a){return this.changeBit(a,op_or)}function bnClearBit(a){return this.changeBit(a,op_andnot)}function bnFlipBit(a){return this.changeBit(a,op_xor)}
function bnpAddTo(a,b){for(var c=0,d=0,e=Math.min(a.t,this.t);c<e;)d+=this[c]+a[c],b[c++]=d&this.DM,d>>=this.DB;if(a.t<this.t){for(d+=a.s;c<this.t;)d+=this[c],b[c++]=d&this.DM,d>>=this.DB;d+=this.s}else{for(d+=this.s;c<a.t;)d+=a[c],b[c++]=d&this.DM,d>>=this.DB;d+=a.s}b.s=0>d?-1:0;0<d?b[c++]=d:-1>d&&(b[c++]=this.DV+d);b.t=c;b.clamp()}function bnAdd(a){var b=nbi();this.addTo(a,b);return b}function bnSubtract(a){var b=nbi();this.subTo(a,b);return b}
function bnMultiply(a){var b=nbi();this.multiplyTo(a,b);return b}function bnSquare(){var a=nbi();this.squareTo(a);return a}function bnDivide(a){var b=nbi();this.divRemTo(a,b,null);return b}function bnRemainder(a){var b=nbi();this.divRemTo(a,null,b);return b}function bnDivideAndRemainder(a){var b=nbi(),c=nbi();this.divRemTo(a,b,c);return[b,c]}function bnpDMultiply(a){this[this.t]=this.am(0,a-1,this,0,0,this.t);++this.t;this.clamp()}
function bnpDAddOffset(a,b){if(0!=a){for(;this.t<=b;)this[this.t++]=0;for(this[b]+=a;this[b]>=this.DV;)this[b]-=this.DV,++b>=this.t&&(this[this.t++]=0),++this[b]}}function NullExp(){}function nNop(a){return a}function nMulTo(a,b,c){a.multiplyTo(b,c)}function nSqrTo(a,b){a.squareTo(b)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(a){return this.exp(a,new NullExp)}
function bnpMultiplyLowerTo(a,b,c){var d=Math.min(this.t+a.t,b);c.s=0;for(c.t=d;0<d;)c[--d]=0;var e;for(e=c.t-this.t;d<e;++d)c[d+this.t]=this.am(0,a[d],c,d,0,this.t);for(e=Math.min(a.t,b);d<e;++d)this.am(0,a[d],c,d,0,b-d);c.clamp()}function bnpMultiplyUpperTo(a,b,c){--b;var d=c.t=this.t+a.t-b;for(c.s=0;0<=--d;)c[d]=0;for(d=Math.max(b-this.t,0);d<a.t;++d)c[this.t+d-b]=this.am(b-d,a[d],c,0,0,this.t+d-b);c.clamp();c.drShiftTo(1,c)}
function Barrett(a){this.r2=nbi();this.q3=nbi();BigInteger.ONE.dlShiftTo(2*a.t,this.r2);this.mu=this.r2.divide(a);this.m=a}function barrettConvert(a){if(0>a.s||a.t>2*this.m.t)return a.mod(this.m);if(0>a.compareTo(this.m))return a;var b=nbi();a.copyTo(b);this.reduce(b);return b}function barrettRevert(a){return a}
function barrettReduce(a){a.drShiftTo(this.m.t-1,this.r2);a.t>this.m.t+1&&(a.t=this.m.t+1,a.clamp());this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);for(this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);0>a.compareTo(this.r2);)a.dAddOffset(1,this.m.t+1);for(a.subTo(this.r2,a);0<=a.compareTo(this.m);)a.subTo(this.m,a)}function barrettSqrTo(a,b){a.squareTo(b);this.reduce(b)}function barrettMulTo(a,b,c){a.multiplyTo(b,c);this.reduce(c)}Barrett.prototype.convert=barrettConvert;
Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;
function bnModPow(a,b){var c=a.bitLength(),d,e=nbv(1),f;if(0>=c)return e;d=18>c?1:48>c?3:144>c?4:768>c?5:6;f=8>c?new Classic(b):b.isEven()?new Barrett(b):new Montgomery(b);var g=[],h=3,k=d-1,l=(1<<d)-1;g[1]=f.convert(this);if(1<d)for(c=nbi(),f.sqrTo(g[1],c);h<=l;)g[h]=nbi(),f.mulTo(c,g[h-2],g[h]),h+=2;for(var m=a.t-1,q,p=!0,s=nbi(),c=nbits(a[m])-1;0<=m;){c>=k?q=a[m]>>c-k&l:(q=(a[m]&(1<<c+1)-1)<<k-c,0<m&&(q|=a[m-1]>>this.DB+c-k));for(h=d;0==(q&1);)q>>=1,--h;0>(c-=h)&&(c+=this.DB,--m);if(p)g[q].copyTo(e),
p=!1;else{for(;1<h;)f.sqrTo(e,s),f.sqrTo(s,e),h-=2;0<h?f.sqrTo(e,s):(h=e,e=s,s=h);f.mulTo(s,g[q],e)}for(;0<=m&&0==(a[m]&1<<c);)f.sqrTo(e,s),h=e,e=s,s=h,0>--c&&(c=this.DB-1,--m)}return f.revert(e)}
function bnGCD(a){var b=0>this.s?this.negate():this.clone();a=0>a.s?a.negate():a.clone();if(0>b.compareTo(a)){var c=b,b=a;a=c}var c=b.getLowestSetBit(),d=a.getLowestSetBit();if(0>d)return b;c<d&&(d=c);0<d&&(b.rShiftTo(d,b),a.rShiftTo(d,a));for(;0<b.signum();)0<(c=b.getLowestSetBit())&&b.rShiftTo(c,b),0<(c=a.getLowestSetBit())&&a.rShiftTo(c,a),0<=b.compareTo(a)?(b.subTo(a,b),b.rShiftTo(1,b)):(a.subTo(b,a),a.rShiftTo(1,a));0<d&&a.lShiftTo(d,a);return a}
function bnpModInt(a){if(0>=a)return 0;var b=this.DV%a,c=0>this.s?a-1:0;if(0<this.t)if(0==b)c=this[0]%a;else for(var d=this.t-1;0<=d;--d)c=(b*c+this[d])%a;return c}
function bnModInverse(a){var b=a.isEven();if(this.isEven()&&b||0==a.signum())return BigInteger.ZERO;for(var c=a.clone(),d=this.clone(),e=nbv(1),f=nbv(0),g=nbv(0),h=nbv(1);0!=c.signum();){for(;c.isEven();)c.rShiftTo(1,c),b?(e.isEven()&&f.isEven()||(e.addTo(this,e),f.subTo(a,f)),e.rShiftTo(1,e)):f.isEven()||f.subTo(a,f),f.rShiftTo(1,f);for(;d.isEven();)d.rShiftTo(1,d),b?(g.isEven()&&h.isEven()||(g.addTo(this,g),h.subTo(a,h)),g.rShiftTo(1,g)):h.isEven()||h.subTo(a,h),h.rShiftTo(1,h);0<=c.compareTo(d)?
(c.subTo(d,c),b&&e.subTo(g,e),f.subTo(h,f)):(d.subTo(c,d),b&&g.subTo(e,g),h.subTo(f,h))}if(0!=d.compareTo(BigInteger.ONE))return BigInteger.ZERO;if(0<=h.compareTo(a))return h.subtract(a);if(0>h.signum())h.addTo(a,h);else return h;return 0>h.signum()?h.add(a):h}
var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,
733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],lplim=67108864/lowprimes[lowprimes.length-1];
function bnIsProbablePrime(a){var b,c=this.abs();if(1==c.t&&c[0]<=lowprimes[lowprimes.length-1]){for(b=0;b<lowprimes.length;++b)if(c[0]==lowprimes[b])return!0;return!1}if(c.isEven())return!1;for(b=1;b<lowprimes.length;){for(var d=lowprimes[b],e=b+1;e<lowprimes.length&&d<lplim;)d*=lowprimes[e++];for(d=c.modInt(d);b<e;)if(0==d%lowprimes[b++])return!1}return c.millerRabin(a)}
function bnpMillerRabin(a){var b=this.subtract(BigInteger.ONE),c=b.getLowestSetBit();if(0>=c)return!1;var d=b.shiftRight(c);a=a+1>>1;a>lowprimes.length&&(a=lowprimes.length);for(var e=nbi(),f=0;f<a;++f){e.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);var g=e.modPow(d,this);if(0!=g.compareTo(BigInteger.ONE)&&0!=g.compareTo(b)){for(var h=1;h++<c&&0!=g.compareTo(b);)if(g=g.modPowInt(2,this),0==g.compareTo(BigInteger.ONE))return!1;if(0!=g.compareTo(b))return!1}}return!0}
BigInteger.prototype.chunkSize=bnpChunkSize;BigInteger.prototype.toRadix=bnpToRadix;BigInteger.prototype.fromRadix=bnpFromRadix;BigInteger.prototype.fromNumber=bnpFromNumber;BigInteger.prototype.bitwiseTo=bnpBitwiseTo;BigInteger.prototype.changeBit=bnpChangeBit;BigInteger.prototype.addTo=bnpAddTo;BigInteger.prototype.dMultiply=bnpDMultiply;BigInteger.prototype.dAddOffset=bnpDAddOffset;BigInteger.prototype.multiplyLowerTo=bnpMultiplyLowerTo;BigInteger.prototype.multiplyUpperTo=bnpMultiplyUpperTo;
BigInteger.prototype.modInt=bnpModInt;BigInteger.prototype.millerRabin=bnpMillerRabin;BigInteger.prototype.clone=bnClone;BigInteger.prototype.intValue=bnIntValue;BigInteger.prototype.byteValue=bnByteValue;BigInteger.prototype.shortValue=bnShortValue;BigInteger.prototype.signum=bnSigNum;BigInteger.prototype.toByteArray=bnToByteArray;BigInteger.prototype.equals=bnEquals;BigInteger.prototype.min=bnMin;BigInteger.prototype.max=bnMax;BigInteger.prototype.and=bnAnd;BigInteger.prototype.or=bnOr;
BigInteger.prototype.xor=bnXor;BigInteger.prototype.andNot=bnAndNot;BigInteger.prototype.not=bnNot;BigInteger.prototype.shiftLeft=bnShiftLeft;BigInteger.prototype.shiftRight=bnShiftRight;BigInteger.prototype.getLowestSetBit=bnGetLowestSetBit;BigInteger.prototype.bitCount=bnBitCount;BigInteger.prototype.testBit=bnTestBit;BigInteger.prototype.setBit=bnSetBit;BigInteger.prototype.clearBit=bnClearBit;BigInteger.prototype.flipBit=bnFlipBit;BigInteger.prototype.add=bnAdd;BigInteger.prototype.subtract=bnSubtract;
BigInteger.prototype.multiply=bnMultiply;BigInteger.prototype.divide=bnDivide;BigInteger.prototype.remainder=bnRemainder;BigInteger.prototype.divideAndRemainder=bnDivideAndRemainder;BigInteger.prototype.modPow=bnModPow;BigInteger.prototype.modInverse=bnModInverse;BigInteger.prototype.pow=bnPow;BigInteger.prototype.gcd=bnGCD;BigInteger.prototype.isProbablePrime=bnIsProbablePrime;BigInteger.prototype.square=bnSquare;exports.BigInteger=BigInteger;module.exports=exports;
var ASN1HEX=require("../contrib/securityLib/asn1hex-1.1.js").ASN1HEX,KJUR=require("../contrib/securityLib/crypto-1.0.js").KJUR,RSAKey=require("../contrib/securityLib/rsasign-1.2.js").RSAKey,b64tohex=require("../contrib/securityLib/base64.js").b64tohex,exports=ndn=ndn||{};
exports.createHash=function(a){if("sha256"!=a)throw Error("createHash: unsupported algorithm.");a={};a.md=new KJUR.crypto.MessageDigest({alg:"sha256",prov:"cryptojs"});a.update=function(a){this.md.updateHex(a.toString("hex"))};a.digest=function(a){var c=this.md.digest();return"hex"==a?c:"base64"==a?(new Buffer(c,"hex")).toString("base64"):new Buffer(c,"hex")};return a};
exports.createHmac=function(a,b){if("sha256"!==a)throw Error("createHmac: unsupported algorithm.");var c={};c.md=new KJUR.crypto.Mac({alg:"HmacSHA256",pass:{hex:b.toString("hex")}});c.update=function(a){this.md.updateHex(a.toString("hex"))};c.digest=function(a){var b=this.md.doFinal();return"hex"==a?b:"base64"==a?(new Buffer(b,"hex")).toString("base64"):new Buffer(b,"hex")};return c};
exports.createSign=function(a){if("RSA-SHA256"!=a)throw Error("createSign: unsupported algorithm.");return{arr:[],update:function(a){this.arr.push(a)},sign:function(a){var c=new RSAKey;c.readPrivateKeyFromPEMString(a);a=new KJUR.crypto.Signature({alg:"SHA256withRSA",prov:"cryptojs/jsrsa"});a.initSign(c);for(c=0;c<this.arr.length;++c)a.updateHex(this.arr[c].toString("hex"));return new Buffer(a.sign(),"hex")}}};
exports.createVerify=function(a){if("RSA-SHA256"!=a)throw Error("createSign: unsupported algorithm.");return{arr:[],update:function(a){this.arr.push(a)},verify:function(a,c){for(var d=a.split("\n"),e="",f=1;f<d.length-1;f++)e+=d[f];d=(new Buffer(e,"base64")).toString("hex");e=ASN1HEX.getPosArrayOfChildren_AtObj(d,0);2!=e.length?e=-1:(e=e[1],"03"!=d.substring(e,e+2)?e=-1:(e=ASN1HEX.getStartPosOfV_AtObj(d,e),e="00"!=d.substring(e,e+2)?-1:e+2));f=ASN1HEX.getPosArrayOfChildren_AtObj(d,e);2!=f.length?
e=null:(e=ASN1HEX.getHexOfV_AtObj(d,f[0]),d=ASN1HEX.getHexOfV_AtObj(d,f[1]),f=new RSAKey,f.setPublic(e,d),e=f);d=new KJUR.crypto.Signature({alg:"SHA256withRSA",prov:"cryptojs/jsrsa"});d.initVerifyByPublicKey(e);for(e=0;e<this.arr.length;e++)d.updateHex(this.arr[e].toString("hex"));e=c.toString("hex");return d.verify(e)}}};exports.randomBytes=function(a){for(var b=new Buffer(a),c=0;c<a;++c)b[c]=Math.floor(256*Math.random());return b};
exports.toByteArray=function(a){var b=[];b64tohex(a).replace(/(..)/g,function(a){b.push(parseInt(a,16))});return b};module.exports=exports;var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",base64js={};
(function(a){function b(a){a=a.charCodeAt(0);if(a===d)return 62;if(a===e)return 63;if(a<f)return-1;if(a<f+10)return a-f+52;if(a<h+26)return a-h;if(a<g+26)return a-g+26}var c="undefined"!==typeof Uint8Array?Uint8Array:Array,d=43,e=47,f=48,g=97,h=65;a.toByteArray=function(a){function d(a){w[M++]=a}var e,f,g,h,w;if(0<a.length%4)throw Error("Invalid string. Length must be a multiple of 4");e=a.length;h="="===a.charAt(e-2)?2:"="===a.charAt(e-1)?1:0;w=new c(3*a.length/4-h);f=0<h?a.length-4:a.length;var M=
0;for(e=0;e<f;e+=4)g=b(a.charAt(e))<<18|b(a.charAt(e+1))<<12|b(a.charAt(e+2))<<6|b(a.charAt(e+3)),d((g&16711680)>>16),d((g&65280)>>8),d(g&255);2===h?(g=b(a.charAt(e))<<2|b(a.charAt(e+1))>>4,d(g&255)):1===h&&(g=b(a.charAt(e))<<10|b(a.charAt(e+1))<<4|b(a.charAt(e+2))>>2,d(g>>8&255),d(g&255));return w};a.fromByteArray=function(a){var b,c=a.length%3,d="",e,f;b=0;for(f=a.length-c;b<f;b+=3)e=(a[b]<<16)+(a[b+1]<<8)+a[b+2],e=lookup.charAt(e>>18&63)+lookup.charAt(e>>12&63)+lookup.charAt(e>>6&63)+lookup.charAt(e&
63),d+=e;switch(c){case 1:e=a[a.length-1];d+=lookup.charAt(e>>2);d+=lookup.charAt(e<<4&63);d+="==";break;case 2:e=(a[a.length-2]<<8)+a[a.length-1],d+=lookup.charAt(e>>10),d+=lookup.charAt(e>>4&63),d+=lookup.charAt(e<<2&63),d+="="}return d}})(base64js);
var ieee={read:function(a,b,c,d,e){var f;f=8*e-d-1;var g=(1<<f)-1,h=g>>1,k=-7;e=c?e-1:0;var l=c?-1:1,m=a[b+e];e+=l;c=m&(1<<-k)-1;m>>=-k;for(k+=f;0<k;c=256*c+a[b+e],e+=l,k-=8);f=c&(1<<-k)-1;c>>=-k;for(k+=d;0<k;f=256*f+a[b+e],e+=l,k-=8);if(0===c)c=1-h;else{if(c===g)return f?NaN:Infinity*(m?-1:1);f+=Math.pow(2,d);c-=h}return(m?-1:1)*f*Math.pow(2,c-d)},write:function(a,b,c,d,e,f){var g,h=8*f-e-1,k=(1<<h)-1,l=k>>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0;f=d?0:f-1;var q=d?1:-1,p=0>b||0===b&&0>1/b?1:
0;b=Math.abs(b);isNaN(b)||Infinity===b?(b=isNaN(b)?1:0,d=k):(d=Math.floor(Math.log(b)/Math.LN2),1>b*(g=Math.pow(2,-d))&&(d--,g*=2),b=1<=d+l?b+m/g:b+m*Math.pow(2,1-l),2<=b*g&&(d++,g/=2),d+l>=k?(b=0,d=k):1<=d+l?(b=(b*g-1)*Math.pow(2,e),d+=l):(b=b*Math.pow(2,l-1)*Math.pow(2,e),d=0));for(;8<=e;a[c+f]=b&255,f+=q,b/=256,e-=8);d=d<<e|b;for(h+=e;0<h;a[c+f]=d&255,f+=q,d/=256,h-=8);a[c+f-q]|=128*p}};exports.ieee=ieee;var base64=base64js,ieee754=require("./ieee754.js").ieee;exports.Buffer=Buffer;
exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;Buffer._useTypedArrays=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray}catch(c){return!1}}();
function Buffer(a,b,c){if(!(this instanceof Buffer))return new Buffer(a,b,c);var d=typeof a;if("base64"===b&&"string"===d)for(a=Buffer.stringtrim(a);0!==a.length%4;)a+="=";var e;if("number"===d)e=Buffer.coerce(a);else if("string"===d)e=Buffer.byteLength(a,b);else if("object"===d)e=Buffer.coerce(a.length);else throw Error("First argument needs to be a number, array or string.");var f;Buffer._useTypedArrays?f=Buffer._augment(new Uint8Array(e)):(f=this,f.length=e,f._isBuffer=!0);if(Buffer._useTypedArrays&&
"number"===typeof a.byteLength)f._set(a);else if(Buffer.isArrayish(a))if(Buffer.isBuffer(a))for(b=0;b<e;b++)f[b]=a.readUInt8(b);else for(b=0;b<e;b++)f[b]=(a[b]%256+256)%256;else if("string"===d)f.write(a,0,b);else if("number"===d&&!Buffer._useTypedArrays&&!c)for(b=0;b<e;b++)f[b]=0;return f}
Buffer.isEncoding=function(a){switch(String(a).toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "raw":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return!0;default:return!1}};Buffer.isBuffer=function(a){return!(null===a||void 0===a||!a._isBuffer)};
Buffer.byteLength=function(a,b){var c;a=a.toString();switch(b||"utf8"){case "hex":c=a.length/2;break;case "utf8":case "utf-8":c=Buffer.utf8ToBytes(a).length;break;case "ascii":case "binary":case "raw":c=a.length;break;case "base64":c=Buffer.base64ToBytes(a).length;break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":c=2*a.length;break;default:throw Error("Unknown encoding");}return c};
Buffer.concat=function(a,b){Buffer.assert(Buffer.isArray(a),"Usage: Buffer.concat(list[, length])");if(0===a.length)return new Buffer(0);if(1===a.length)return a[0];var c;if(void 0===b)for(c=b=0;c<a.length;c++)b+=a[c].length;var d=new Buffer(b),e=0;for(c=0;c<a.length;c++){var f=a[c];f.copy(d,e);e+=f.length}return d};
Buffer.compare=function(a,b){Buffer.assert(Buffer.isBuffer(a)&&Buffer.isBuffer(b),"Arguments must be Buffers");for(var c=a.length,d=b.length,e=0,f=Math.min(c,d);e<f&&a[e]===b[e];e++);e!==f&&(c=a[e],d=b[e]);return c<d?-1:d<c?1:0};
Buffer.hexWrite=function(a,b,c,d){c=Number(c)||0;var e=a.length-c;d?(d=Number(d),d>e&&(d=e)):d=e;e=b.length;Buffer.assert(0===e%2,"Invalid hex string");d>e/2&&(d=e/2);for(e=0;e<d;e++){var f=parseInt(b.substr(2*e,2),16);Buffer.assert(!isNaN(f),"Invalid hex string");a[c+e]=f}return e};Buffer.utf8Write=function(a,b,c,d){return Buffer.blitBuffer(Buffer.utf8ToBytes(b),a,c,d)};Buffer.asciiWrite=function(a,b,c,d){return Buffer.blitBuffer(Buffer.asciiToBytes(b),a,c,d)};
Buffer.binaryWrite=function(a,b,c,d){return Buffer.asciiWrite(a,b,c,d)};Buffer.base64Write=function(a,b,c,d){return Buffer.blitBuffer(Buffer.base64ToBytes(b),a,c,d)};Buffer.utf16leWrite=function(a,b,c,d){return Buffer.blitBuffer(Buffer.utf16leToBytes(b),a,c,d)};
Buffer.prototype.write=function(a,b,c,d){if(isFinite(b))isFinite(c)||(d=c,c=void 0);else{var e=d;d=b;b=c;c=e}b=Number(b)||0;e=this.length-b;c?(c=Number(c),c>e&&(c=e)):c=e;d=String(d||"utf8").toLowerCase();switch(d){case "hex":a=Buffer.hexWrite(this,a,b,c);break;case "utf8":case "utf-8":a=Buffer.utf8Write(this,a,b,c);break;case "ascii":a=Buffer.asciiWrite(this,a,b,c);break;case "binary":a=Buffer.binaryWrite(this,a,b,c);break;case "base64":a=Buffer.base64Write(this,a,b,c);break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":a=
Buffer.utf16leWrite(this,a,b,c);break;default:throw Error("Unknown encoding");}return a};
Buffer.prototype.toString=function(a,b,c){a=String(a||"utf8").toLowerCase();b=Number(b)||0;c=void 0===c?this.length:Number(c);if(c===b)return"";switch(a){case "hex":a=Buffer.hexSlice(this,b,c);break;case "utf8":case "utf-8":a=Buffer.utf8Slice(this,b,c);break;case "ascii":a=Buffer.asciiSlice(this,b,c);break;case "binary":a=Buffer.binarySlice(this,b,c);break;case "base64":a=Buffer.base64Slice(this,b,c);break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":a=utf16leSlice(this,b,c);break;default:throw Error("Unknown encoding");
}return a};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.equals=function(a){Buffer.assert(Buffer.isBuffer(a),"Argument must be a Buffer");return 0===Buffer.compare(this,a)};Buffer.prototype.compare=function(a){Buffer.assert(Buffer.isBuffer(a),"Argument must be a Buffer");return Buffer.compare(this,a)};
Buffer.prototype.copy=function(a,b,c,d){c||(c=0);d||0===d||(d=this.length);b||(b=0);if(d!==c&&0!==a.length&&0!==this.length)if(Buffer.assert(d>=c,"sourceEnd < sourceStart"),Buffer.assert(0<=b&&b<a.length,"targetStart out of bounds"),Buffer.assert(0<=c&&c<this.length,"sourceStart out of bounds"),Buffer.assert(0<=d&&d<=this.length,"sourceEnd out of bounds"),d>this.length&&(d=this.length),a.length-b<d-c&&(d=a.length-b+c),d-=c,100>d||!Buffer._useTypedArrays)for(var e=0;e<d;e++)a[e+b]=this[e+c];else a._set(this.subarray(c,
c+d),b)};Buffer.base64Slice=function(a,b,c){return 0===b&&c===a.length?base64.fromByteArray(a):base64.fromByteArray(a.slice(b,c))};Buffer.utf8Slice=function(a,b,c){var d="",e="";for(c=Math.min(a.length,c);b<c;b++)127>=a[b]?(d+=Buffer.decodeUtf8Char(e)+String.fromCharCode(a[b]),e=""):e+="%"+a[b].toString(16);return d+Buffer.decodeUtf8Char(e)};Buffer.asciiSlice=function(a,b,c){var d="";for(c=Math.min(a.length,c);b<c;b++)d+=String.fromCharCode(a[b]);return d};
Buffer.binarySlice=function(a,b,c){return Buffer.asciiSlice(a,b,c)};Buffer.hexSlice=function(a,b,c){var d=a.length;if(!b||0>b)b=0;if(!c||0>c||c>d)c=d;for(d="";b<c;b++)d+=Buffer.toHex(a[b]);return d};function utf16leSlice(a,b,c){a=a.slice(b,c);b="";for(c=0;c<a.length;c+=2)b+=String.fromCharCode(a[c]+256*a[c+1]);return b}
Buffer.prototype.slice=function(a,b){var c=this.length;a=Buffer.clamp(a,c,0);b=Buffer.clamp(b,c,c);if(Buffer._useTypedArrays)return Buffer._augment(this.subarray(a,b));for(var c=b-a,d=new Buffer(c,void 0,!0),e=0;e<c;e++)d[e]=this[e+a];return d};Buffer.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(a)};
Buffer.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};Buffer.prototype.readUInt8=function(a,b){b||(Buffer.assert(void 0!==a&&null!==a,"missing offset"),Buffer.assert(a<this.length,"Trying to read beyond buffer length"));if(!(a>=this.length))return this[a]};
Buffer.readUInt16=function(a,b,c,d){d||(Buffer.assert("boolean"===typeof c,"missing or invalid endian"),Buffer.assert(void 0!==b&&null!==b,"missing offset"),Buffer.assert(b+1<a.length,"Trying to read beyond buffer length"));d=a.length;if(!(b>=d))return c?(c=a[b],b+1<d&&(c|=a[b+1]<<8)):(c=a[b]<<8,b+1<d&&(c|=a[b+1])),c};Buffer.prototype.readUInt16LE=function(a,b){return Buffer.readUInt16(this,a,!0,b)};Buffer.prototype.readUInt16BE=function(a,b){return Buffer.readUInt16(this,a,!1,b)};
Buffer.readUInt32=function(a,b,c,d){d||(Buffer.assert("boolean"===typeof c,"missing or invalid endian"),Buffer.assert(void 0!==b&&null!==b,"missing offset"),Buffer.assert(b+3<a.length,"Trying to read beyond buffer length"));d=a.length;if(!(b>=d)){var e;c?(b+2<d&&(e=a[b+2]<<16),b+1<d&&(e|=a[b+1]<<8),e|=a[b],b+3<d&&(e+=a[b+3]<<24>>>0)):(b+1<d&&(e=a[b+1]<<16),b+2<d&&(e|=a[b+2]<<8),b+3<d&&(e|=a[b+3]),e+=a[b]<<24>>>0);return e}};
Buffer.prototype.readUInt32LE=function(a,b){return Buffer.readUInt32(this,a,!0,b)};Buffer.prototype.readUInt32BE=function(a,b){return Buffer.readUInt32(this,a,!1,b)};Buffer.prototype.readInt8=function(a,b){b||(Buffer.assert(void 0!==a&&null!==a,"missing offset"),Buffer.assert(a<this.length,"Trying to read beyond buffer length"));if(!(a>=this.length))return this[a]&128?-1*(255-this[a]+1):this[a]};
Buffer.readInt16=function(a,b,c,d){d||(Buffer.assert("boolean"===typeof c,"missing or invalid endian"),Buffer.assert(void 0!==b&&null!==b,"missing offset"),Buffer.assert(b+1<a.length,"Trying to read beyond buffer length"));if(!(b>=a.length))return a=Buffer.readUInt16(a,b,c,!0),a&32768?-1*(65535-a+1):a};Buffer.prototype.readInt16LE=function(a,b){return Buffer.readInt16(this,a,!0,b)};Buffer.prototype.readInt16BE=function(a,b){return Buffer.readInt16(this,a,!1,b)};
Buffer.readInt32=function(a,b,c,d){d||(Buffer.assert("boolean"===typeof c,"missing or invalid endian"),Buffer.assert(void 0!==b&&null!==b,"missing offset"),Buffer.assert(b+3<a.length,"Trying to read beyond buffer length"));if(!(b>=a.length))return a=Buffer.readUInt32(a,b,c,!0),a&2147483648?-1*(4294967295-a+1):a};Buffer.prototype.readInt32LE=function(a,b){return Buffer.readInt32(this,a,!0,b)};Buffer.prototype.readInt32BE=function(a,b){return Buffer.readInt32(this,a,!1,b)};
Buffer.readFloat=function(a,b,c,d){d||(Buffer.assert("boolean"===typeof c,"missing or invalid endian"),Buffer.assert(b+3<a.length,"Trying to read beyond buffer length"));return ieee754.read(a,b,c,23,4)};Buffer.prototype.readFloatLE=function(a,b){return Buffer.readFloat(this,a,!0,b)};Buffer.prototype.readFloatBE=function(a,b){return Buffer.readFloat(this,a,!1,b)};
Buffer.readDouble=function(a,b,c,d){d||(Buffer.assert("boolean"===typeof c,"missing or invalid endian"),Buffer.assert(b+7<a.length,"Trying to read beyond buffer length"));return ieee754.read(a,b,c,52,8)};Buffer.prototype.readDoubleLE=function(a,b){return Buffer.readDouble(this,a,!0,b)};Buffer.prototype.readDoubleBE=function(a,b){return Buffer.readDouble(this,a,!1,b)};
Buffer.prototype.writeUInt8=function(a,b,c){c||(Buffer.assert(void 0!==a&&null!==a,"missing value"),Buffer.assert(void 0!==b&&null!==b,"missing offset"),Buffer.assert(b<this.length,"trying to write beyond buffer length"),Buffer.verifuint(a,255));if(!(b>=this.length))return this[b]=a,b+1};
Buffer.writeUInt16=function(a,b,c,d,e){e||(Buffer.assert(void 0!==b&&null!==b,"missing value"),Buffer.assert("boolean"===typeof d,"missing or invalid endian"),Buffer.assert(void 0!==c&&null!==c,"missing offset"),Buffer.assert(c+1<a.length,"trying to write beyond buffer length"),Buffer.verifuint(b,65535));var f=a.length;if(!(c>=f)){e=0;for(f=Math.min(f-c,2);e<f;e++)a[c+e]=(b&255<<8*(d?e:1-e))>>>8*(d?e:1-e);return c+2}};
Buffer.prototype.writeUInt16LE=function(a,b,c){return Buffer.writeUInt16(this,a,b,!0,c)};Buffer.prototype.writeUInt16BE=function(a,b,c){return Buffer.writeUInt16(this,a,b,!1,c)};
Buffer.writeUInt32=function(a,b,c,d,e){e||(Buffer.assert(void 0!==b&&null!==b,"missing value"),Buffer.assert("boolean"===typeof d,"missing or invalid endian"),Buffer.assert(void 0!==c&&null!==c,"missing offset"),Buffer.assert(c+3<a.length,"trying to write beyond buffer length"),Buffer.verifuint(b,4294967295));var f=a.length;if(!(c>=f)){e=0;for(f=Math.min(f-c,4);e<f;e++)a[c+e]=b>>>8*(d?e:3-e)&255;return c+4}};Buffer.prototype.writeUInt32LE=function(a,b,c){return Buffer.writeUInt32(this,a,b,!0,c)};
Buffer.prototype.writeUInt32BE=function(a,b,c){return Buffer.writeUInt32(this,a,b,!1,c)};Buffer.prototype.writeInt8=function(a,b,c){c||(Buffer.assert(void 0!==a&&null!==a,"missing value"),Buffer.assert(void 0!==b&&null!==b,"missing offset"),Buffer.assert(b<this.length,"Trying to write beyond buffer length"),Buffer.verifsint(a,127,-128));if(!(b>=this.length))return 0<=a?this.writeUInt8(a,b,c):this.writeUInt8(255+a+1,b,c),b+1};
Buffer.writeInt16=function(a,b,c,d,e){e||(Buffer.assert(void 0!==b&&null!==b,"missing value"),Buffer.assert("boolean"===typeof d,"missing or invalid endian"),Buffer.assert(void 0!==c&&null!==c,"missing offset"),Buffer.assert(c+1<a.length,"Trying to write beyond buffer length"),Buffer.verifsint(b,32767,-32768));if(!(c>=a.length))return 0<=b?Buffer.writeUInt16(a,b,c,d,e):Buffer.writeUInt16(a,65535+b+1,c,d,e),c+2};Buffer.prototype.writeInt16LE=function(a,b,c){return Buffer.writeInt16(this,a,b,!0,c)};
Buffer.prototype.writeInt16BE=function(a,b,c){return Buffer.writeInt16(this,a,b,!1,c)};
Buffer.writeInt32=function(a,b,c,d,e){e||(Buffer.assert(void 0!==b&&null!==b,"missing value"),Buffer.assert("boolean"===typeof d,"missing or invalid endian"),Buffer.assert(void 0!==c&&null!==c,"missing offset"),Buffer.assert(c+3<a.length,"Trying to write beyond buffer length"),Buffer.verifsint(b,2147483647,-2147483648));if(!(c>=a.length))return 0<=b?Buffer.writeUInt32(a,b,c,d,e):Buffer.writeUInt32(a,4294967295+b+1,c,d,e),c+4};
Buffer.prototype.writeInt32LE=function(a,b,c){return Buffer.writeInt32(this,a,b,!0,c)};Buffer.prototype.writeInt32BE=function(a,b,c){return Buffer.writeInt32(this,a,b,!1,c)};
Buffer.writeFloat=function(a,b,c,d,e){e||(Buffer.assert(void 0!==b&&null!==b,"missing value"),Buffer.assert("boolean"===typeof d,"missing or invalid endian"),Buffer.assert(void 0!==c&&null!==c,"missing offset"),Buffer.assert(c+3<a.length,"Trying to write beyond buffer length"),Buffer.verifIEEE754(b,3.4028234663852886E38,-3.4028234663852886E38));if(!(c>=a.length))return ieee754.write(a,b,c,d,23,4),c+4};Buffer.prototype.writeFloatLE=function(a,b,c){return Buffer.writeFloat(this,a,b,!0,c)};
Buffer.prototype.writeFloatBE=function(a,b,c){return Buffer.writeFloat(this,a,b,!1,c)};Buffer.writeDouble=function(a,b,c,d,e){e||(Buffer.assert(void 0!==b&&null!==b,"missing value"),Buffer.assert("boolean"===typeof d,"missing or invalid endian"),Buffer.assert(void 0!==c&&null!==c,"missing offset"),Buffer.assert(c+7<a.length,"Trying to write beyond buffer length"),Buffer.verifIEEE754(b,1.7976931348623157E308,-1.7976931348623157E308));if(!(c>=a.length))return ieee754.write(a,b,c,d,52,8),c+8};
Buffer.prototype.writeDoubleLE=function(a,b,c){return Buffer.writeDouble(this,a,b,!0,c)};Buffer.prototype.writeDoubleBE=function(a,b,c){return Buffer.writeDouble(this,a,b,!1,c)};
Buffer.prototype.fill=function(a,b,c){a||(a=0);b||(b=0);c||(c=this.length);Buffer.assert(c>=b,"end < start");if(c!==b&&0!==this.length){Buffer.assert(0<=b&&b<this.length,"start out of bounds");Buffer.assert(0<=c&&c<=this.length,"end out of bounds");if("number"===typeof a)for(;b<c;b++)this[b]=a;else{a=Buffer.utf8ToBytes(a.toString());for(var d=a.length;b<c;b++)this[b]=a[b%d]}return this}};
Buffer.prototype.inspect=function(){for(var a=[],b=this.length,c=0;c<b;c++)if(a[c]=Buffer.toHex(this[c]),c===exports.INSPECT_MAX_BYTES){a[c+1]="...";break}return"<Buffer "+a.join(" ")+">"};Buffer.prototype.toArrayBuffer=function(){if("undefined"!==typeof Uint8Array){if(Buffer._useTypedArrays)return(new Buffer(this)).buffer;for(var a=new Uint8Array(this.length),b=0,c=a.length;b<c;b+=1)a[b]=this[b];return a.buffer}throw Error("Buffer.toArrayBuffer not supported in this browser");};var BP=Buffer.prototype;
Buffer._augment=function(a){a._isBuffer=!0;a._get=a.get;a._set=a.set;a.get=BP.get;a.set=BP.set;a.write=BP.write;a.toString=BP.toString;a.toLocaleString=BP.toString;a.toJSON=BP.toJSON;a.equals=BP.equals;a.compare=BP.compare;a.copy=BP.copy;a.slice=BP.slice;a.readUInt8=BP.readUInt8;a.readUInt16LE=BP.readUInt16LE;a.readUInt16BE=BP.readUInt16BE;a.readUInt32LE=BP.readUInt32LE;a.readUInt32BE=BP.readUInt32BE;a.readInt8=BP.readInt8;a.readInt16LE=BP.readInt16LE;a.readInt16BE=BP.readInt16BE;a.readInt32LE=BP.readInt32LE;
a.readInt32BE=BP.readInt32BE;a.readFloatLE=BP.readFloatLE;a.readFloatBE=BP.readFloatBE;a.readDoubleLE=BP.readDoubleLE;a.readDoubleBE=BP.readDoubleBE;a.writeUInt8=BP.writeUInt8;a.writeUInt16LE=BP.writeUInt16LE;a.writeUInt16BE=BP.writeUInt16BE;a.writeUInt32LE=BP.writeUInt32LE;a.writeUInt32BE=BP.writeUInt32BE;a.writeInt8=BP.writeInt8;a.writeInt16LE=BP.writeInt16LE;a.writeInt16BE=BP.writeInt16BE;a.writeInt32LE=BP.writeInt32LE;a.writeInt32BE=BP.writeInt32BE;a.writeFloatLE=BP.writeFloatLE;a.writeFloatBE=
BP.writeFloatBE;a.writeDoubleLE=BP.writeDoubleLE;a.writeDoubleBE=BP.writeDoubleBE;a.fill=BP.fill;a.inspect=BP.inspect;a.toArrayBuffer=BP.toArrayBuffer;return a};Buffer.stringtrim=function(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")};Buffer.clamp=function(a,b,c){if("number"!==typeof a)return c;a=~~a;if(a>=b)return b;if(0<=a)return a;a+=b;return 0<=a?a:0};Buffer.coerce=function(a){a=~~Math.ceil(+a);return 0>a?0:a};
Buffer.isArray=function(a){return(Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)})(a)};Buffer.isArrayish=function(a){return Buffer.isArray(a)||Buffer.isBuffer(a)||a&&"object"===typeof a&&"number"===typeof a.length};Buffer.toHex=function(a){return 16>a?"0"+a.toString(16):a.toString(16)};
Buffer.utf8ToBytes=function(a){for(var b=[],c=0;c<a.length;c++){var d=a.charCodeAt(c);if(127>=d)b.push(d);else{var e=c;55296<=d&&57343>=d&&c++;d=encodeURIComponent(a.slice(e,c+1)).substr(1).split("%");for(e=0;e<d.length;e++)b.push(parseInt(d[e],16))}}return b};Buffer.asciiToBytes=function(a){for(var b=[],c=0;c<a.length;c++)b.push(a.charCodeAt(c)&255);return b};Buffer.utf16leToBytes=function(a){for(var b,c,d=[],e=0;e<a.length;e++)b=a.charCodeAt(e),c=b>>8,b%=256,d.push(b),d.push(c);return d};
Buffer.base64ToBytes=function(a){return base64.toByteArray(a)};Buffer.blitBuffer=function(a,b,c,d){for(var e=0;e<d&&!(e+c>=b.length||e>=a.length);e++)b[e+c]=a[e];return e};Buffer.decodeUtf8Char=function(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}};
Buffer.verifuint=function(a,b){Buffer.assert("number"===typeof a,"cannot write a non-number as a number");Buffer.assert(0<=a,"specified a negative value for writing an unsigned value");Buffer.assert(a<=b,"value is larger than maximum value for type");Buffer.assert(Math.floor(a)===a,"value has a fractional component")};
Buffer.verifsint=function(a,b,c){Buffer.assert("number"===typeof a,"cannot write a non-number as a number");Buffer.assert(a<=b,"value larger than maximum allowed value");Buffer.assert(a>=c,"value smaller than minimum allowed value");Buffer.assert(Math.floor(a)===a,"value has a fractional component")};Buffer.verifIEEE754=function(a,b,c){Buffer.assert("number"===typeof a,"cannot write a non-number as a number");Buffer.assert(a<=b,"value larger than maximum allowed value");Buffer.assert(a>=c,"value smaller than minimum allowed value")};
Buffer.assert=function(a,b){if(!a)throw Error(b||"Failed assertion");};var Log=function(){};exports.Log=Log;Log.LOG=0;var printStackTrace=require("../../contrib/stacktrace/stacktrace.js").printStackTrace,NdnCommon={};exports.NdnCommon=NdnCommon;NdnCommon.MAX_NDN_PACKET_SIZE=8800;NdnCommon.getErrorWithStackTrace=function(a){return a+"\n"+printStackTrace({e:a}).join("\n")};
NdnCommon.checkIndexedDb=function(a){try{var b=new Dexie("test-Dexie-support");b.version(1).stores({});b.open();setTimeout(function(){try{a(b.isOpen())}catch(c){a(!1)}},200)}catch(c){a(!1)}};var NdnCommon=require("./ndn-common.js").NdnCommon,ExponentialReExpress=function(a,b,c,d){d=d||{};this.face=a;this.callerOnData=b;this.callerOnTimeout=c;this.maxInterestLifetime=d.maxInterestLifetime||16E3};exports.ExponentialReExpress=ExponentialReExpress;
ExponentialReExpress.makeOnTimeout=function(a,b,c,d){var e=new ExponentialReExpress(a,b,c,d);return function(a){e.onTimeout(a)}};
ExponentialReExpress.prototype.onTimeout=function(a){var b=a.getInterestLifetimeMilliseconds();if(null==b){if(this.callerOnTimeout)try{this.callerOnTimeout(a)}catch(c){console.log("Error in onTimeout: "+NdnCommon.getErrorWithStackTrace(c))}}else if(b*=2,b>this.maxInterestLifetime){if(this.callerOnTimeout)try{this.callerOnTimeout(a)}catch(d){console.log("Error in onTimeout: "+NdnCommon.getErrorWithStackTrace(d))}}else{a=a.clone();a.setInterestLifetimeMilliseconds(b);var e=this;this.face.expressInterest(a,
this.callerOnData,function(a){e.onTimeout(a)})}};var Blob=function Blob(b,c){null==c&&(c=!0);null==b?this.buffer=null:"object"===typeof b&&b instanceof Blob?this.buffer=b.buffer:"string"===typeof b?this.buffer=new Buffer(b,"utf8"):c?this.buffer=new Buffer(b):Buffer.isBuffer(b)?this.buffer=b:this.buffer=new Buffer(b);this.length=null!=this.buffer?this.buffer.length:0};exports.Blob=Blob;Blob.prototype.size=function(){return null!=this.buffer?this.buffer.length:0};Blob.prototype.buf=function(){return this.buffer};
Blob.prototype.isNull=function(){return null==this.buffer};Blob.prototype.toHex=function(){return null==this.buffer?"":this.buffer.toString("hex")};Blob.prototype.toString=function(){return null==this.buffer?"":this.buffer.toString("utf8")};Blob.prototype.equals=function(a){if(this.isNull())return a.isNull();if(a.isNull()||this.buffer.length!=a.buffer.length)return!1;for(var b=0;b<this.buffer.length;++b)if(this.buffer[b]!=a.buffer[b])return!1;return!0};
var Blob=require("./blob.js").Blob,SignedBlob=function SignedBlob(b,c,d){Blob.call(this,b);null==this.buffer?this.signedPortionEndOffset=this.signedPortionBeginOffset=0:"object"===typeof b&&b instanceof SignedBlob?(this.signedPortionBeginOffset=null==c?b.signedPortionBeginOffset:c,this.signedPortionEndOffset=null==d?b.signedPortionEndOffset:d):(this.signedPortionBeginOffset=c||0,this.signedPortionEndOffset=d||0);this.signedBuffer=null==this.buffer?null:this.buffer.slice(this.signedPortionBeginOffset,
this.signedPortionEndOffset)};SignedBlob.prototype=new Blob;SignedBlob.prototype.name="SignedBlob";exports.SignedBlob=SignedBlob;SignedBlob.prototype.signedSize=function(){return null!=this.signedBuffer?this.signedBuffer.length:0};SignedBlob.prototype.signedBuf=function(){return this.signedBuffer};SignedBlob.prototype.getSignedPortionBeginOffset=function(){return this.signedPortionBeginOffset};SignedBlob.prototype.getSignedPortionEndOffset=function(){return this.signedPortionEndOffset};
var DynamicBuffer=function(a){a||(a=16);this.array=new Buffer(a)};exports.DynamicBuffer=DynamicBuffer;DynamicBuffer.prototype.ensureLength=function(a){if(!(this.array.length>=a)){var b=2*this.array.length;a>b&&(b=a);a=new Buffer(b);this.array.copy(a);this.array=a}};DynamicBuffer.prototype.copy=function(a,b){this.ensureLength(a.length+b);Buffer.isBuffer(a)?a.copy(this.array,b):(new Buffer(a)).copy(this.array,b);return b+a.length};
DynamicBuffer.prototype.ensureLengthFromBack=function(a){if(!(this.array.length>=a)){var b=2*this.array.length;a>b&&(b=a);a=new Buffer(b);this.array.copy(a,a.length-this.array.length);this.array=a}};DynamicBuffer.prototype.copyFromBack=function(a,b){this.ensureLengthFromBack(b);Buffer.isBuffer(a)?a.copy(this.array,this.array.length-b):(new Buffer(a)).copy(this.array,this.array.length-b)};DynamicBuffer.prototype.slice=function(a,b){return void 0==b?this.array.slice(a):this.array.slice(a,b)};
var ChangeCounter=function(a){this.target=a;this.changeCount=null==a?0:a.getChangeCount()};exports.ChangeCounter=ChangeCounter;ChangeCounter.prototype.get=function(){return this.target};ChangeCounter.prototype.set=function(a){this.target=a;this.changeCount=null==a?0:a.getChangeCount()};ChangeCounter.prototype.checkChanged=function(){if(null==this.target)return!1;var a=this.target.getChangeCount();return this.changeCount!=a?(this.changeCount=a,!0):!1};
var NdnCommon=require("./ndn-common.js").NdnCommon,SyncPromise=function(a,b){this.value=a;this.isRejected=b};exports.SyncPromise=SyncPromise;SyncPromise.prototype.then=function(a,b){if(this.isRejected)if(b)try{return b(this.value)}catch(c){return new SyncPromise(c,!0)}else return this;else if(a)try{return a(this.value)}catch(d){return new SyncPromise(d,!0)}else return this};SyncPromise.prototype["catch"]=function(a){return this.then(void 0,a)};
SyncPromise.resolve=function(a){return new SyncPromise(a,!1)};SyncPromise.reject=function(a){return new SyncPromise(a,!0)};SyncPromise.getValue=function(a){if(a instanceof SyncPromise){if(a.isRejected)throw a.value;return a.value}throw Error("Cannot return immediately because promise is not a SyncPromise");};
SyncPromise.complete=function(a,b,c){var d;c?d=b:(c=b,d=null);if(a)c.then(function(b){try{a(b)}catch(c){console.log("Error in onComplete: "+NdnCommon.getErrorWithStackTrace(c))}},function(a){if(d)try{d(a)}catch(b){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(b))}else{if(c instanceof SyncPromise)throw a;console.log("Uncaught exception from a Promise: "+NdnCommon.getErrorWithStackTrace(a))}});else return SyncPromise.getValue(c)};var DataUtils={};exports.DataUtils=DataUtils;
DataUtils.keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";DataUtils.stringtoBase64=function(a){var b="",c,d,e="",f,g,h="",k=0;do c=a.charCodeAt(k++),d=a.charCodeAt(k++),e=a.charCodeAt(k++),f=c>>2,c=(c&3)<<4|d>>4,g=(d&15)<<2|e>>6,h=e&63,isNaN(d)?g=h=64:isNaN(e)&&(h=64),b=b+DataUtils.keyStr.charAt(f)+DataUtils.keyStr.charAt(c)+DataUtils.keyStr.charAt(g)+DataUtils.keyStr.charAt(h);while(k<a.length);return b};
DataUtils.base64toString=function(a){var b="",c,d,e="",f,g="",h=0;/[^A-Za-z0-9\+\/\=]/g.exec(a)&&alert("There were invalid base64 characters in the input text.\nValid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\nExpect errors in decoding.");a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");do c=DataUtils.keyStr.indexOf(a.charAt(h++)),d=DataUtils.keyStr.indexOf(a.charAt(h++)),f=DataUtils.keyStr.indexOf(a.charAt(h++)),g=DataUtils.keyStr.indexOf(a.charAt(h++)),c=c<<2|d>>4,d=(d&15)<<4|f>>2,e=(f&3)<<6|g,
b+=String.fromCharCode(c),64!=f&&(b+=String.fromCharCode(d)),64!=g&&(b+=String.fromCharCode(e));while(h<a.length);return b};DataUtils.toHex=function(a){return a.toString("hex")};DataUtils.stringToHex=function(a){for(var b="",c=0;c<a.length;++c)var d=a.charCodeAt(c),b=b+((16>d?"0":"")+d.toString(16));return b};DataUtils.toString=function(a){return a.toString("binary")};DataUtils.toNumbers=function(a){return new Buffer(a,"hex")};
DataUtils.hexToRawString=function(a){if("string"==typeof a){var b="";a.replace(/(..)/g,function(a){b+=String.fromCharCode(parseInt(a,16))});return b}};DataUtils.toNumbersFromString=function(a){return new Buffer(a,"binary")};DataUtils.toNumbersIfString=function(a){return"string"===typeof a?new Buffer(a,"binary"):a};DataUtils.stringToUtf8Array=function(a){return new Buffer(a,"utf8")};DataUtils.concatArrays=function(a){return Buffer.concat(a)};
DataUtils.decodeUtf8=function(a){for(var b="",c=0,d=0,e=0;c<a.length;)if(d=a.charCodeAt(c),128>d)b+=String.fromCharCode(d),c++;else if(191<d&&224>d)e=a.charCodeAt(c+1),b+=String.fromCharCode((d&31)<<6|e&63),c+=2;else var e=a.charCodeAt(c+1),f=a.charCodeAt(c+2),b=b+String.fromCharCode((d&15)<<12|(e&63)<<6|f&63),c=c+3;return b};
DataUtils.arraysEqual=function(a,b){if(!a.slice)throw Error("DataUtils.arraysEqual: a1 is not an array");if(!b.slice)throw Error("DataUtils.arraysEqual: a2 is not an array");if(a.length!=b.length)return!1;for(var c=0;c<a.length;++c)if(a[c]!=b[c])return!1;return!0};DataUtils.bigEndianToUnsignedInt=function(a){for(var b=0,c=0;c<a.length;++c)b*=256,b+=a[c];return b};
DataUtils.nonNegativeIntToBigEndian=function(a){a=Math.round(a);if(0>=a)return new Buffer(0);for(var b=new Buffer(8),c=0;0!=a;)++c,b[8-c]=a&255,a=Math.floor(a/256);return b.slice(8-c,8)};DataUtils.shuffle=function(a){for(var b=a.length-1;1<=b;--b){var c=Math.floor(Math.random()*(b+1)),d=a[b];a[b]=a[c];a[c]=d}};DataUtils.privateKeyPemToDer=function(a){a=a.split("\n");for(var b="",c=1;c<a.length-1;c++)b+=a[c];return new Buffer(b,"base64")};
function DecodingException(a){if(a)return a.__proto__=DecodingException.prototype,a}DecodingException.prototype=Error();DecodingException.prototype.name="DecodingException";exports.DecodingException=DecodingException;var Tlv=function(){};exports.Tlv=Tlv;Tlv.Interest=5;Tlv.Data=6;Tlv.Name=7;Tlv.ImplicitSha256DigestComponent=1;Tlv.NameComponent=8;Tlv.Selectors=9;Tlv.Nonce=10;Tlv.InterestLifetime=12;Tlv.MinSuffixComponents=13;Tlv.MaxSuffixComponents=14;Tlv.PublisherPublicKeyLocator=15;Tlv.Exclude=16;
Tlv.ChildSelector=17;Tlv.MustBeFresh=18;Tlv.Any=19;Tlv.MetaInfo=20;Tlv.Content=21;Tlv.SignatureInfo=22;Tlv.SignatureValue=23;Tlv.ContentType=24;Tlv.FreshnessPeriod=25;Tlv.FinalBlockId=26;Tlv.SignatureType=27;Tlv.KeyLocator=28;Tlv.KeyLocatorDigest=29;Tlv.SelectedDelegation=32;Tlv.FaceInstance=128;Tlv.ForwardingEntry=129;Tlv.StatusResponse=130;Tlv.Action=131;Tlv.FaceID=132;Tlv.IPProto=133;Tlv.Host=134;Tlv.Port=135;Tlv.MulticastInterface=136;Tlv.MulticastTTL=137;Tlv.ForwardingFlags=138;
Tlv.StatusCode=139;Tlv.StatusText=140;Tlv.SignatureType_DigestSha256=0;Tlv.SignatureType_SignatureSha256WithRsa=1;Tlv.SignatureType_SignatureSha256WithEcdsa=3;Tlv.SignatureType_SignatureHmacWithSha256=4;Tlv.ContentType_Default=0;Tlv.ContentType_Link=1;Tlv.ContentType_Key=2;Tlv.NfdCommand_ControlResponse=101;Tlv.NfdCommand_StatusCode=102;Tlv.NfdCommand_StatusText=103;Tlv.ControlParameters_ControlParameters=104;Tlv.ControlParameters_FaceId=105;Tlv.ControlParameters_Uri=114;
Tlv.ControlParameters_LocalControlFeature=110;Tlv.ControlParameters_Origin=111;Tlv.ControlParameters_Cost=106;Tlv.ControlParameters_Flags=108;Tlv.ControlParameters_Strategy=107;Tlv.ControlParameters_ExpirationPeriod=109;Tlv.LpPacket_LpPacket=100;Tlv.LpPacket_Fragment=80;Tlv.LpPacket_Sequence=81;Tlv.LpPacket_FragIndex=82;Tlv.LpPacket_FragCount=83;Tlv.LpPacket_Nack=800;Tlv.LpPacket_NackReason=801;Tlv.LpPacket_NextHopFaceId=816;Tlv.LpPacket_IncomingFaceId=817;Tlv.LpPacket_CachePolicy=820;
Tlv.LpPacket_CachePolicyType=821;Tlv.LpPacket_IGNORE_MIN=800;Tlv.LpPacket_IGNORE_MAX=959;Tlv.Link_Preference=30;Tlv.Link_Delegation=31;Tlv.Encrypt_EncryptedContent=130;Tlv.Encrypt_EncryptionAlgorithm=131;Tlv.Encrypt_EncryptedPayload=132;Tlv.Encrypt_InitialVector=133;Tlv.Encrypt_StartDate=134;Tlv.Encrypt_EndDate=135;Tlv.Encrypt_IntervalStartHour=136;Tlv.Encrypt_IntervalEndHour=137;Tlv.Encrypt_NRepeats=138;Tlv.Encrypt_RepeatUnit=139;Tlv.Encrypt_RepetitiveInterval=140;Tlv.Encrypt_WhiteIntervalList=141;
Tlv.Encrypt_BlackIntervalList=142;Tlv.Encrypt_Schedule=143;Tlv.getHighBytes=function(a){return(a-a%4294967296)/4294967296};var DynamicBuffer=require("../../util/dynamic-buffer.js").DynamicBuffer,Tlv=require("./tlv.js").Tlv,TlvEncoder=function(a){this.output=new DynamicBuffer(a||16);this.length=0};exports.TlvEncoder=TlvEncoder;TlvEncoder.prototype.getLength=function(){return this.length};
TlvEncoder.prototype.writeVarNumber=function(a){if(253>a)this.length+=1,this.output.ensureLengthFromBack(this.length),this.output.array[this.output.array.length-this.length]=a&255;else if(65535>=a){this.length+=3;this.output.ensureLengthFromBack(this.length);var b=this.output.array.length-this.length;this.output.array[b]=253;this.output.array[b+1]=a>>8&255;this.output.array[b+2]=a&255}else if(4294967295>=a)this.length+=5,this.output.ensureLengthFromBack(this.length),b=this.output.array.length-this.length,
this.output.array[b]=254,this.output.array[b+1]=a>>24&255,this.output.array[b+2]=a>>16&255,this.output.array[b+3]=a>>8&255,this.output.array[b+4]=a&255;else{this.length+=9;this.output.ensureLengthFromBack(this.length);b=this.output.array.length-this.length;this.output.array[b]=255;var c=Tlv.getHighBytes(a);this.output.array[b+1]=c>>24&255;this.output.array[b+2]=c>>16&255;this.output.array[b+3]=c>>8&255;this.output.array[b+4]=c&255;this.output.array[b+5]=a>>24&255;this.output.array[b+6]=a>>16&255;
this.output.array[b+7]=a>>8&255;this.output.array[b+8]=a&255}};TlvEncoder.prototype.writeTypeAndLength=function(a,b){this.writeVarNumber(b);this.writeVarNumber(a)};
TlvEncoder.prototype.writeNonNegativeInteger=function(a){if(0>a)throw Error("TLV integer value may not be negative");a=Math.round(a);if(255>=a)this.length+=1,this.output.ensureLengthFromBack(this.length),this.output.array[this.output.array.length-this.length]=a&255;else if(65535>=a){this.length+=2;this.output.ensureLengthFromBack(this.length);var b=this.output.array.length-this.length;this.output.array[b]=a>>8&255;this.output.array[b+1]=a&255}else if(4294967295>=a)this.length+=4,this.output.ensureLengthFromBack(this.length),
b=this.output.array.length-this.length,this.output.array[b]=a>>24&255,this.output.array[b+1]=a>>16&255,this.output.array[b+2]=a>>8&255,this.output.array[b+3]=a&255;else{this.length+=8;this.output.ensureLengthFromBack(this.length);var b=this.output.array.length-this.length,c=Tlv.getHighBytes(a);this.output.array[b]=c>>24&255;this.output.array[b+1]=c>>16&255;this.output.array[b+2]=c>>8&255;this.output.array[b+3]=c&255;this.output.array[b+4]=a>>24&255;this.output.array[b+5]=a>>16&255;this.output.array[b+
6]=a>>8&255;this.output.array[b+7]=a&255}};TlvEncoder.prototype.writeNonNegativeIntegerTlv=function(a,b){var c=this.length;this.writeNonNegativeInteger(b);this.writeTypeAndLength(a,this.length-c)};TlvEncoder.prototype.writeOptionalNonNegativeIntegerTlv=function(a,b){null!=b&&0<=b&&this.writeNonNegativeIntegerTlv(a,b)};TlvEncoder.prototype.writeBuffer=function(a){null!=a&&(this.length+=a.length,this.output.copyFromBack(a,this.length))};
TlvEncoder.prototype.writeBlobTlv=function(a,b){null==b?this.writeTypeAndLength(a,0):(this.writeBuffer(b),this.writeTypeAndLength(a,b.length))};TlvEncoder.prototype.writeOptionalBlobTlv=function(a,b){null!=b&&0<b.length&&this.writeBlobTlv(a,b)};TlvEncoder.prototype.getOutput=function(){return this.output.array.slice(this.output.array.length-this.length)};var DecodingException=require("../decoding-exception.js").DecodingException,TlvDecoder=function(a){this.input=a;this.offset=0};
exports.TlvDecoder=TlvDecoder;TlvDecoder.prototype.readVarNumber=function(){var a=this.input[this.offset];this.offset+=1;return 253>a?a:this.readExtendedVarNumber(a)};
TlvDecoder.prototype.readExtendedVarNumber=function(a){253==a?(a=(this.input[this.offset]<<8)+this.input[this.offset+1],this.offset+=2):254==a?(a=Math.abs(this.input[this.offset]<<24)+(this.input[this.offset+1]<<16)+(this.input[this.offset+2]<<8)+this.input[this.offset+3],this.offset+=4):(a=4294967296*(Math.abs(this.input[this.offset]<<24)+(this.input[this.offset+1]<<16)+(this.input[this.offset+2]<<8)+this.input[this.offset+3])+(this.input[this.offset+4]<<24)+(this.input[this.offset+5]<<16)+(this.input[this.offset+
6]<<8)+this.input[this.offset+7],this.offset+=8);return a};TlvDecoder.prototype.readTypeAndLength=function(a){if(this.readVarNumber()!=a)throw new DecodingException(Error("Did not get the expected TLV type"));a=this.readVarNumber();if(this.offset+a>this.input.length)throw new DecodingException(Error("TLV length exceeds the buffer length"));return a};TlvDecoder.prototype.readNestedTlvsStart=function(a){return this.readTypeAndLength(a)+this.offset};
TlvDecoder.prototype.finishNestedTlvs=function(a){if(this.offset!=a){for(;this.offset<a;){this.readVarNumber();var b=this.readVarNumber();this.offset+=b;if(this.offset>this.input.length)throw new DecodingException(Error("TLV length exceeds the buffer length"));}if(this.offset!=a)throw new DecodingException(Error("TLV length does not equal the total length of the nested TLVs"));}};
TlvDecoder.prototype.peekType=function(a,b){if(this.offset>=b)return!1;var c=this.offset,d=this.readVarNumber();this.offset=c;return d==a};
TlvDecoder.prototype.readNonNegativeInteger=function(a){var b;if(1==a)b=this.input[this.offset];else if(2==a)b=(this.input[this.offset]<<8)+this.input[this.offset+1];else if(4==a)b=Math.abs(this.input[this.offset]<<24)+(this.input[this.offset+1]<<16)+(this.input[this.offset+2]<<8)+this.input[this.offset+3];else if(8==a)b=4294967296*(Math.abs(this.input[this.offset]<<24)+(this.input[this.offset+1]<<16)+(this.input[this.offset+2]<<8)+this.input[this.offset+3])+Math.abs(this.input[this.offset+4]<<24)+
(this.input[this.offset+5]<<16)+(this.input[this.offset+6]<<8)+this.input[this.offset+7];else throw new DecodingException(Error("Invalid length for a TLV nonNegativeInteger"));this.offset+=a;return b};TlvDecoder.prototype.readNonNegativeIntegerTlv=function(a){a=this.readTypeAndLength(a);return this.readNonNegativeInteger(a)};TlvDecoder.prototype.readOptionalNonNegativeIntegerTlv=function(a,b){return this.peekType(a,b)?this.readNonNegativeIntegerTlv(a):null};
TlvDecoder.prototype.readBlobTlv=function(a){a=this.readTypeAndLength(a);var b=this.input.slice(this.offset,this.offset+a);this.offset+=a;return b};TlvDecoder.prototype.readOptionalBlobTlv=function(a,b){return this.peekType(a,b)?this.readBlobTlv(a):null};TlvDecoder.prototype.readBooleanTlv=function(a,b){if(this.peekType(a,b)){var c=this.readTypeAndLength(a);this.offset+=c;return!0}return!1};TlvDecoder.prototype.getOffset=function(){return this.offset};
TlvDecoder.prototype.seek=function(a){this.offset=a};TlvDecoder.prototype.getSlice=function(a,b){return this.input.slice(a,b)};var TlvDecoder=require("./tlv-decoder.js").TlvDecoder,TlvStructureDecoder=function TlvStructureDecoder(){this.gotElementEnd_=!1;this.offset_=0;this.state_=TlvStructureDecoder.READ_TYPE;this.headerLength_=0;this.useHeaderBuffer_=!1;this.headerBuffer_=new Buffer(8);this.nBytesToRead_=0};exports.TlvStructureDecoder=TlvStructureDecoder;TlvStructureDecoder.READ_TYPE=0;
TlvStructureDecoder.READ_TYPE_BYTES=1;TlvStructureDecoder.READ_LENGTH=2;TlvStructureDecoder.READ_LENGTH_BYTES=3;TlvStructureDecoder.READ_VALUE_BYTES=4;
TlvStructureDecoder.prototype.findElementEnd=function(a){if(this.gotElementEnd_)return!0;for(var b=new TlvDecoder(a);;){if(this.offset_>=a.length)return!1;if(this.state_==TlvStructureDecoder.READ_TYPE){var c=a[this.offset_];this.offset_+=1;253>c?this.state_=TlvStructureDecoder.READ_LENGTH:(this.nBytesToRead_=253==c?2:254==c?4:8,this.state_=TlvStructureDecoder.READ_TYPE_BYTES)}else if(this.state_==TlvStructureDecoder.READ_TYPE_BYTES){c=a.length-this.offset_;if(c<this.nBytesToRead_)return this.offset_+=
c,this.nBytesToRead_-=c,!1;this.offset_+=this.nBytesToRead_;this.state_=TlvStructureDecoder.READ_LENGTH}else if(this.state_==TlvStructureDecoder.READ_LENGTH)if(c=a[this.offset_],this.offset_+=1,253>c){this.nBytesToRead_=c;if(0==this.nBytesToRead_)return this.gotElementEnd_=!0;this.state_=TlvStructureDecoder.READ_VALUE_BYTES}else this.nBytesToRead_=253==c?2:254==c?4:8,this.firstOctet_=c,this.state_=TlvStructureDecoder.READ_LENGTH_BYTES;else if(this.state_==TlvStructureDecoder.READ_LENGTH_BYTES){c=
a.length-this.offset_;if(!this.useHeaderBuffer_&&c>=this.nBytesToRead_)b.seek(this.offset_),this.nBytesToRead_=b.readExtendedVarNumber(this.firstOctet_),this.offset_=b.getOffset();else{this.useHeaderBuffer_=!0;var d=this.nBytesToRead_-this.headerLength_;if(d>c){if(this.headerLength_+c>this.headerBuffer_.length)throw Error("Cannot store more header bytes than the size of headerBuffer");a.slice(this.offset_,this.offset_+c).copy(this.headerBuffer_,this.headerLength_);this.offset_+=c;this.headerLength_+=
c;return!1}if(this.headerLength_+d>this.headerBuffer_.length)throw Error("Cannot store more header bytes than the size of headerBuffer");a.slice(this.offset_,this.offset_+d).copy(this.headerBuffer_,this.headerLength_);this.offset_+=d;this.nBytesToRead_=(new TlvDecoder(this.headerBuffer_)).readExtendedVarNumber(this.firstOctet_)}if(0==this.nBytesToRead_)return this.gotElementEnd_=!0;this.state_=TlvStructureDecoder.READ_VALUE_BYTES}else{if(this.state_==TlvStructureDecoder.READ_VALUE_BYTES){c=a.length-
this.offset_;if(c<this.nBytesToRead_)return this.offset_+=c,this.nBytesToRead_-=c,!1;this.offset_+=this.nBytesToRead_;return this.gotElementEnd_=!0}throw Error("findElementEnd: unrecognized state");}}};TlvStructureDecoder.prototype.getOffset=function(){return this.offset_};TlvStructureDecoder.prototype.seek=function(a){this.offset_=a};
var TlvEncoder=require("./tlv/tlv-encoder.js").TlvEncoder,TlvDecoder=require("./tlv/tlv-decoder.js").TlvDecoder,Blob=require("../util/blob.js").Blob,Name=require("../name.js").Name,ProtobufTlv=function(){};exports.ProtobufTlv=ProtobufTlv;ProtobufTlv._Field=null;ProtobufTlv.establishField=function(){if(null===ProtobufTlv._Field)try{ProtobufTlv._Field=dcodeIO.ProtoBuf.Reflect.Message.Field}catch(a){ProtobufTlv._Field=require("protobufjs").Reflect.Message.Field}};
ProtobufTlv.encode=function(a,b){ProtobufTlv.establishField();a.encodeAB();var c=new TlvEncoder;ProtobufTlv._encodeMessageValue(a,b,c);return new Blob(c.getOutput(),!1)};ProtobufTlv.decode=function(a,b,c){ProtobufTlv.establishField();c="object"===typeof c&&c instanceof Blob?c.buf():c;var d=new TlvDecoder(c);ProtobufTlv._decodeMessageValue(a,b,d,c.length)};
ProtobufTlv._encodeMessageValue=function(a,b,c){b=b.getChildren(ProtobufTlv._Field);for(var d=b.length-1;0<=d;--d){var e=b[d],f=e.id,g;if(e.repeated)g=a[e.name];else if(null!=a[e.name])g=[a[e.name]];else continue;for(var h=g.length-1;0<=h;--h){var k=g[h];if("message"==e.type.name){var l=c.getLength();ProtobufTlv._encodeMessageValue(k,e.resolvedType,c);c.writeTypeAndLength(f,c.getLength()-l)}else if("uint32"==e.type.name||"uint64"==e.type.name)c.writeNonNegativeIntegerTlv(f,k);else if("enum"==e.type.name){if(0>
k)throw Error("ProtobufTlv::encode: ENUM value may not be negative");c.writeNonNegativeIntegerTlv(f,k)}else if("bytes"==e.type.name)l=k.toBuffer(),void 0==l.length&&(l=new Uint8Array(k.toArrayBuffer())),c.writeBlobTlv(f,l);else if("string"==e.type.name)c.writeBlobTlv(f,(new Blob(k,!1)).buf());else if("bool"==e.type.name)k&&c.writeTypeAndLength(f,0);else if("double"==e.type.name)l=new Buffer(8),l.writeDoubleLE(k,0),c.writeBlobTlv(f,l);else throw Error("ProtobufTlv::encode: Unknown field type");}}};
ProtobufTlv._decodeMessageValue=function(a,b,c,d){b=b.getChildren(ProtobufTlv._Field);for(var e=0;e<b.length;++e){var f=b[e],g=f.id;if(f.required||c.peekType(g,d))if(f.repeated)for(;c.peekType(g,d);)if("message"==f.type.name){var h=c.readNestedTlvsStart(g),k=new (f.resolvedType.build());a.add(f.name,k);ProtobufTlv._decodeMessageValue(k,f.resolvedType,c,h);c.finishNestedTlvs(h)}else a.add(f.name,ProtobufTlv._decodeFieldValue(f,g,c,d));else"message"==f.type.name?(h=c.readNestedTlvsStart(g),k=new (f.resolvedType.build()),
a.set(f.name,k),ProtobufTlv._decodeMessageValue(k,f.resolvedType,c,h),c.finishNestedTlvs(h)):a.set(f.name,ProtobufTlv._decodeFieldValue(f,g,c,d))}};
ProtobufTlv._decodeFieldValue=function(a,b,c,d){if("uint32"==a.type.name||"uint64"==a.type.name||"enum"==a.type.name)return c.readNonNegativeIntegerTlv(b);if("bytes"==a.type.name)return c.readBlobTlv(b);if("string"==a.type.name)return c.readBlobTlv(b).toString();if("bool"==a.type.name)return c.readBooleanTlv(b,d);if("double"==a.type.name)return c.readBlobTlv(b).readDoubleLE(0);throw Error("ProtobufTlv.decode: Unknown field type");};
ProtobufTlv.toName=function(a){for(var b=new Name,c=0;c<a.length;++c)b.append(new Blob(new Buffer(a[c].toBinary(),"binary")),!1);return b};var OID=function(a){if("string"===typeof a){a=a.split(".");this.oid=[];for(var b=0;b<a.length;++b)this.oid.push(parseInt(a[b]))}else this.oid=a.slice(0,a.length)};exports.OID=OID;OID.prototype.getIntegerList=function(){return this.oid};OID.prototype.setIntegerList=function(a){this.oid=a.slice(0,a.length)};
OID.prototype.toString=function(){for(var a="",b=0;b<this.oid.length;++b)0!==b&&(a+="."),a+=this.oid[b];return a};OID.prototype.equals=function(a){if(!(a instanceof OID)||this.oid.length!==a.oid.length)return!1;for(var b=0;b<this.oid.length;++b)if(this.oid[b]!=a.oid[b])return!1;return!0};var WireFormat=function(){};exports.WireFormat=WireFormat;WireFormat.prototype.encodeName=function(a){throw Error("encodeName is unimplemented in the base WireFormat class. You should use a derived class.");};
WireFormat.prototype.decodeName=function(a,b,c){throw Error("decodeName is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.encodeInterest=function(a){throw Error("encodeInterest is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.decodeInterest=function(a,b,c){throw Error("decodeInterest is unimplemented in the base WireFormat class. You should use a derived class.");};
WireFormat.prototype.encodeData=function(a){throw Error("encodeData is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.decodeData=function(a,b,c){throw Error("decodeData is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.encodeControlParameters=function(a){throw Error("encodeControlParameters is unimplemented in the base WireFormat class. You should use a derived class.");};
WireFormat.prototype.decodeControlParameters=function(a,b,c){throw Error("decodeControlParameters is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.encodeControlResponse=function(a){throw Error("encodeControlResponse is unimplemented in the base WireFormat class. You should use a derived class.");};
WireFormat.prototype.decodeControlResponse=function(a,b,c){throw Error("decodeControlResponse is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.encodeSignatureInfo=function(a){throw Error("encodeSignatureInfo is unimplemented in the base WireFormat class. You should use a derived class.");};
WireFormat.prototype.decodeSignatureInfoAndValue=function(a,b,c){throw Error("decodeSignatureInfoAndValue is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.encodeSignatureValue=function(a){throw Error("encodeSignatureValue is unimplemented in the base WireFormat class. You should use a derived class.");};
WireFormat.prototype.decodeLpPacket=function(a,b,c){throw Error("decodeLpPacket is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.encodeDelegationSet=function(a){throw Error("encodeDelegationSet is unimplemented in the base WireFormat class. You should use a derived class.");};
WireFormat.prototype.decodeDelegationSet=function(a,b,c){throw Error("decodeDelegationSet is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.prototype.encodeEncryptedContent=function(a){throw Error("encodeEncryptedContent is unimplemented in the base WireFormat class. You should use a derived class.");};
WireFormat.prototype.decodeEncryptedContent=function(a,b,c){throw Error("decodeEncryptedContent is unimplemented in the base WireFormat class. You should use a derived class.");};WireFormat.setDefaultWireFormat=function(a){WireFormat.defaultWireFormat=a};WireFormat.getDefaultWireFormat=function(){return WireFormat.defaultWireFormat};
var TlvWireFormat=require("./tlv-wire-format.js").TlvWireFormat,DataUtils=require("./data-utils.js").DataUtils,Tlv=require("./tlv/tlv.js").Tlv,TlvStructureDecoder=require("./tlv/tlv-structure-decoder.js").TlvStructureDecoder,DecodingException=require("./decoding-exception.js").DecodingException,NdnCommon=require("../util/ndn-common.js").NdnCommon,LOG=require("../log.js").Log.LOG,ElementReader=function(a){this.elementListener_=a;this.dataParts_=[];this.tlvStructureDecoder_=new TlvStructureDecoder};
exports.ElementReader=ElementReader;
ElementReader.prototype.onReceivedData=function(a){for(;;){var b,c;try{if(0===this.dataParts_.length&&0>=a.length)break;this.tlvStructureDecoder_.seek(0);b=this.tlvStructureDecoder_.findElementEnd(a);c=this.tlvStructureDecoder_.getOffset()}catch(d){throw this.dataParts_=[],this.tlvStructureDecoder_=new TlvStructureDecoder,d;}if(b){var e;0===this.dataParts_.length?e=a.slice(0,c):(this.dataParts_.push(a.slice(0,c)),e=DataUtils.concatArrays(this.dataParts_),this.dataParts_=[]);a=a.slice(c,a.length);
this.tlvStructureDecoder_=new TlvStructureDecoder;this.elementListener_.onReceivedElement(e);if(0==a.length)break}else{b=a.length;for(c=0;c<this.dataParts_.length;++c)b+=this.dataParts_[c].length;if(b>NdnCommon.MAX_NDN_PACKET_SIZE)throw this.dataParts_=[],this.tlvStructureDecoder_=new TlvStructureDecoder,new DecodingException(Error("The incoming packet exceeds the maximum limit Face.getMaxNdnPacketSize()"));this.dataParts_.push(new Buffer(a));3<LOG&&console.log("Incomplete packet received. Length "+
a.length+". Wait for more input.");break}}};function DerDecodingException(a){if(a)return a.__proto__=DerDecodingException.prototype,a}DerDecodingException.prototype=Error();DerDecodingException.prototype.name="DerDecodingException";exports.DerDecodingException=DerDecodingException;function DerEncodingException(a){if(a)return a.__proto__=DerEncodingException.prototype,a}DerEncodingException.prototype=Error();DerEncodingException.prototype.name="DerEncodingException";exports.DerEncodingException=DerEncodingException;
var DerNodeType=function(){};exports.DerNodeType=DerNodeType;DerNodeType.Eoc=0;DerNodeType.Boolean=1;DerNodeType.Integer=2;DerNodeType.BitString=3;DerNodeType.OctetString=4;DerNodeType.Null=5;DerNodeType.ObjectIdentifier=6;DerNodeType.ObjectDescriptor=7;DerNodeType.External=40;DerNodeType.Real=9;DerNodeType.Enumerated=10;DerNodeType.EmbeddedPdv=43;DerNodeType.Utf8String=12;DerNodeType.RelativeOid=13;DerNodeType.Sequence=48;DerNodeType.Set=49;DerNodeType.NumericString=18;
DerNodeType.PrintableString=19;DerNodeType.T61String=20;DerNodeType.VideoTexString=21;DerNodeType.Ia5String=22;DerNodeType.UtcTime=23;DerNodeType.GeneralizedTime=24;DerNodeType.GraphicString=25;DerNodeType.VisibleString=26;DerNodeType.GeneralString=27;DerNodeType.UniversalString=28;DerNodeType.CharacterString=29;DerNodeType.BmpString=30;
var DynamicBuffer=require("../../util/dynamic-buffer.js").DynamicBuffer,Blob=require("../../util/blob.js").Blob,DerDecodingException=require("./der-decoding-exception.js").DerDecodingException,DerEncodingException=require("./der-encoding-exception.js").DerEncodingException,DerNodeType=require("./der-node-type.js").DerNodeType,DerNode=function(a){this.nodeType_=a;this.parent_=null;this.header_=new Buffer(0);this.payload_=new DynamicBuffer(0);this.payloadPosition_=0};exports.DerNode=DerNode;
DerNode.prototype.getSize=function(){return this.header_.length+this.payloadPosition_};
DerNode.prototype.encodeHeader=function(a){var b=new DynamicBuffer(10),c=0;b.array[c++]=this.nodeType_;if(0>a)throw Error("encodeHeader: DER object has negative length");if(127>=a)b.array[c++]=a&255;else{var d=new DynamicBuffer(10),e=a;for(a=0;0!=e;)++a,d.ensureLengthFromBack(a),d.array[d.array.length-a]=e&255,e>>=8;e=a+1;d.ensureLengthFromBack(e);d.array[d.array.length-e]=(128|a)&255;b.copy(d.slice(d.array.length-e),c);c+=e}this.header_=b.slice(0,c)};
DerNode.prototype.decodeHeader=function(a,b){var c=b,d=a[c]&255,c=c+1;this.nodeType_=d;var e=a[c]&255,c=c+1,f=new DynamicBuffer(10),g=0;f.array[g++]=d;d=f.array[g++]=e;if(0!=(e&128))for(e&=127,d=0;0<e;){var h=a[c],c=c+1;f.ensureLength(g+1);f.array[g++]=h;d=256*d+(h&255);e-=1}this.header_=f.slice(0,g);return d};DerNode.prototype.encode=function(){var a=new Buffer(this.getSize());this.header_.copy(a);this.payload_.slice(0,this.payloadPosition_).copy(a,this.header_.length);return new Blob(a,!1)};
DerNode.prototype.decode=function(a,b){var c=b,d=this.decodeHeader(a,c),e=this.header_.length;0<d&&(c+=e,this.payloadAppend(a.slice(c,c+d)))};DerNode.prototype.payloadAppend=function(a){this.payloadPosition_=this.payload_.copy(a,this.payloadPosition_)};
DerNode.parse=function(a,b){void 0==b&&(b=0);var c=a[b]&255;if(c===DerNodeType.Boolean)c=new DerNode.DerBoolean;else if(c===DerNodeType.Integer)c=new DerNode.DerInteger;else if(c===DerNodeType.BitString)c=new DerNode.DerBitString;else if(c===DerNodeType.OctetString)c=new DerNode.DerOctetString;else if(c===DerNodeType.Null)c=new DerNode.DerNull;else if(c===DerNodeType.ObjectIdentifier)c=new DerNode.DerOid;else if(c===DerNodeType.Sequence)c=new DerNode.DerSequence;else if(c===DerNodeType.PrintableString)c=
new DerNode.DerPrintableString;else if(c===DerNodeType.GeneralizedTime)c=new DerNode.DerGeneralizedTime;else throw new DerDecodingException(Error("Unimplemented DER type "+c));c.decode(a,b);return c};DerNode.prototype.toVal=function(){return this.encode()};DerNode.prototype.getPayload=function(){return new Blob(this.payload_.slice(0,this.payloadPosition_),!0)};DerNode.prototype.getChildren=function(){throw new DerDecodingException(Error("getChildren: This DerNode is not DerSequence"));};
DerNode.getSequence=function(a,b){if(0>b||b>=a.length)throw new DerDecodingException(Error("getSequence: Child index is out of bounds"));if(!(a[b]instanceof DerNode.DerSequence))throw new DerDecodingException(Error("getSequence: Child DerNode is not a DerSequence"));return a[b]};DerNode.DerStructure=function(a){DerNode.call(this,a);this.childChanged_=!1;this.nodeList_=[];this.size_=0};DerNode.DerStructure.prototype=new DerNode;DerNode.DerStructure.prototype.name="DerStructure";
DerNode.DerStructure.prototype.getSize=function(){this.childChanged_&&(this.updateSize(),this.childChanged_=!1);this.encodeHeader(this.size_);return this.size_+this.header_.length};DerNode.DerStructure.prototype.getChildren=function(){return this.nodeList_};DerNode.DerStructure.prototype.updateSize=function(){for(var a=0,b=0;b<this.nodeList_.length;++b)a+=this.nodeList_[b].getSize();this.size_=a;this.childChanged_=!1};
DerNode.DerStructure.prototype.addChild=function(a,b){a.parent_=this;this.nodeList_.push(a);b&&null!=this.parent_&&this.parent_.setChildChanged();this.childChanged_=!0};DerNode.DerStructure.prototype.setChildChanged=function(){null!=this.parent_&&this.parent_.setChildChanged();this.childChanged_=!0};
DerNode.DerStructure.prototype.encode=function(){var a=new DynamicBuffer(10),b=0;this.updateSize();this.encodeHeader(this.size_);for(var b=a.copy(this.header_,b),c=0;c<this.nodeList_.length;++c)var d=this.nodeList_[c].encode(),b=a.copy(d.buf(),b);return new Blob(a.slice(0,b),!1)};DerNode.DerStructure.prototype.decode=function(a,b){var c=b;this.size_=this.decodeHeader(a,c);for(var c=c+this.header_.length,d=0;d<this.size_;){var e=DerNode.parse(a,c),f=e.getSize(),c=c+f,d=d+f;this.addChild(e,!1)}};
DerNode.DerByteString=function(a,b){DerNode.call(this,b);null!=a&&(this.payloadAppend(a),this.encodeHeader(a.length))};DerNode.DerByteString.prototype=new DerNode;DerNode.DerByteString.prototype.name="DerByteString";DerNode.DerByteString.prototype.toVal=function(){return this.getPayload()};DerNode.DerBoolean=function(a){DerNode.call(this,DerNodeType.Boolean);void 0!=a&&(a=a?255:0,this.payload_.ensureLength(this.payloadPosition_+1),this.payload_.array[this.payloadPosition_++]=a,this.encodeHeader(1))};
DerNode.DerBoolean.prototype=new DerNode;DerNode.DerBoolean.prototype.name="DerBoolean";DerNode.DerBoolean.prototype.toVal=function(){return 0!=this.payload_.array[0]};
DerNode.DerInteger=function(a){DerNode.call(this,DerNodeType.Integer);if(void 0!=a){if(Buffer.isBuffer(a)){if(0<a.length&&128<=a[0])throw new DerEncodingException(Error("DerInteger: Negative integers are not currently supported"));0==a.length?this.payloadAppend(new Buffer([0])):this.payloadAppend(a)}else{a=Math.round(a);if(0>a)throw new DerEncodingException(Error("DerInteger: Negative integers are not currently supported"));for(var b=new DynamicBuffer(10),c=0;!(++c,b.ensureLengthFromBack(c),b.array[b.array.length-
c]=a&255,a>>=8,0>=a););128<=b.array[b.array.length-c]&&(++c,b.ensureLengthFromBack(c),b.array[b.array.length-c]=0);this.payloadAppend(b.slice(b.array.length-c))}this.encodeHeader(this.payloadPosition_)}};DerNode.DerInteger.prototype=new DerNode;DerNode.DerInteger.prototype.name="DerInteger";
DerNode.DerInteger.prototype.toVal=function(){if(0<this.payloadPosition_&&128<=this.payload_.array[0])throw new DerDecodingException(Error("DerInteger: Negative integers are not currently supported"));for(var a=0,b=0;b<this.payloadPosition_;++b)a<<=8,a+=this.payload_.array[b];return a};DerNode.DerBitString=function(a,b){DerNode.call(this,DerNodeType.BitString);void 0!=a&&(this.payload_.ensureLength(this.payloadPosition_+1),this.payload_.array[this.payloadPosition_++]=b&255,this.payloadAppend(a),this.encodeHeader(this.payloadPosition_))};
DerNode.DerBitString.prototype=new DerNode;DerNode.DerBitString.prototype.name="DerBitString";DerNode.DerOctetString=function(a){DerNode.DerByteString.call(this,a,DerNodeType.OctetString)};DerNode.DerOctetString.prototype=new DerNode.DerByteString;DerNode.DerOctetString.prototype.name="DerOctetString";DerNode.DerNull=function(){DerNode.call(this,DerNodeType.Null);this.encodeHeader(0)};DerNode.DerNull.prototype=new DerNode;DerNode.DerNull.prototype.name="DerNull";
DerNode.DerOid=function(a){DerNode.call(this,DerNodeType.ObjectIdentifier);if(void 0!=a)if("string"===typeof a){a=a.split(".");for(var b=[],c=0;c<a.length;++c)b.push(parseInt(a[c]));this.prepareEncoding(b)}else this.prepareEncoding(a.getIntegerList())};DerNode.DerOid.prototype=new DerNode;DerNode.DerOid.prototype.name="DerOid";
DerNode.DerOid.prototype.prepareEncoding=function(a){var b;if(0==a.length)throw new DerEncodingException(Error("No integer in OID"));if(0<=a[0]&&2>=a[0])b=40*a[0];else throw new DerEncodingException(Error("First integer in OID is out of range"));if(2<=a.length)if(0<=a[1]&&39>=a[1])b+=a[1];else throw new DerEncodingException(Error("Second integer in OID is out of range"));var c=new DynamicBuffer(10),d=0,d=c.copy(DerNode.DerOid.encode128(b),d);if(2<a.length)for(b=2;b<a.length;++b)d=c.copy(DerNode.DerOid.encode128(a[b]),
d);this.encodeHeader(d);this.payloadAppend(c.slice(0,d))};DerNode.DerOid.encode128=function(a){var b=new DynamicBuffer(10),c=0;if(128>a)++c,b.array[b.array.length-c]=a&127;else for(++c,b.array[b.array.length-c]=a&127,a>>=7;0!=a;)++c,b.ensureLengthFromBack(c),b.array[b.array.length-c]=a&127|128,a>>=7;return b.slice(b.array.length-c)};
DerNode.DerOid.prototype.decode128=function(a,b){for(var c=0,d=a;0!=(this.payload_.array[a]&128);)c=128*c+(this.payload_.array[a]&255)-128,a+=1;c=128*c+(this.payload_.array[a]&255);b[0]=a-d+1;return c};DerNode.DerOid.prototype.toVal=function(){for(var a=0,b=[];a<this.payloadPosition_;){var c=[0],d=this.decode128(a,c),a=a+c[0];b.push(d)}a=b[0];a=Math.floor(a/40)+"."+a%40;for(c=1;c<b.length;++c)a+="."+b[c];return a};DerNode.DerSequence=function(){DerNode.DerStructure.call(this,DerNodeType.Sequence)};
DerNode.DerSequence.prototype=new DerNode.DerStructure;DerNode.DerSequence.prototype.name="DerSequence";DerNode.DerPrintableString=function(a){DerNode.DerByteString.call(this,a,DerNodeType.PrintableString)};DerNode.DerPrintableString.prototype=new DerNode.DerByteString;DerNode.DerPrintableString.prototype.name="DerPrintableString";
DerNode.DerGeneralizedTime=function(a){DerNode.call(this,DerNodeType.GeneralizedTime);void 0!=a&&(a=DerNode.DerGeneralizedTime.toDerTimeString(a),this.payloadAppend((new Blob(a)).buf()),this.encodeHeader(this.payloadPosition_))};DerNode.DerGeneralizedTime.prototype=new DerNode;DerNode.DerGeneralizedTime.prototype.name="DerGeneralizedTime";
DerNode.DerGeneralizedTime.toDerTimeString=function(a){a=new Date(Math.round(a));return a.getUTCFullYear()+DerNode.DerGeneralizedTime.to2DigitString(a.getUTCMonth()+1)+DerNode.DerGeneralizedTime.to2DigitString(a.getUTCDate())+DerNode.DerGeneralizedTime.to2DigitString(a.getUTCHours())+DerNode.DerGeneralizedTime.to2DigitString(a.getUTCMinutes())+DerNode.DerGeneralizedTime.to2DigitString(a.getUTCSeconds())+"Z"};
DerNode.DerGeneralizedTime.to2DigitString=function(a){a=a.toString();return 1===a.length?"0"+a:a};DerNode.DerGeneralizedTime.prototype.toVal=function(){var a=this.payload_.slice(0,this.payloadPosition_).toString();return Date.UTC(parseInt(a.substr(0,4)),parseInt(a.substr(4,2)-1),parseInt(a.substr(6,2)),parseInt(a.substr(8,2)),parseInt(a.substr(10,2)),parseInt(a.substr(12,2)))};var fs=require("fs"),BoostInfoTree=function(a,b){this.subtrees=[];this.value=a;this.parent=b;this.lastChild=null};
BoostInfoTree.prototype.addSubtree=function(a,b){var c=this.find(a);null!==c?c.push(b):this.subtrees.push({key:a,value:[b]});b.parent=this;this.lastChild=b};BoostInfoTree.prototype.createSubtree=function(a,b){var c=new BoostInfoTree(b,this);this.addSubtree(a,c);return c};
BoostInfoTree.prototype.get=function(a){a=a.replace(/^\/+/,"");if(0===a.length)return[this];var b=a.split("/");a=this.find(b[0]);if(null===a)return[];if(1==b.length)return a.slice(0);for(var b=b.slice(1).join("/"),c=[],d=0;d<a.length;++d)var e=a[d].get(b),c=c.concat(e);return c};BoostInfoTree.prototype.getFirstValue=function(a){a=this.get(a);return 1<=a.length?a[0].value:null};BoostInfoTree.prototype.getValue=function(){return this.value};BoostInfoTree.prototype.getParent=function(){return this.parent};
BoostInfoTree.prototype.getLastChild=function(){return this.lastChild};
BoostInfoTree.prototype.prettyPrint=function(a){a=a||1;var b=Array(a+1).join(" "),c="";null!=this.parent&&(this.value&&0<this.value.length&&(c+='"'+this.value+'"'),c+="\n");if(0<this.subtrees.length){this.parent&&(c+=b+"{\n");for(var d=Array(a+2+1).join(" "),e=0;e<this.subtrees.length;++e)for(var f=0;f<this.subtrees[e].value.length;++f)c+=d+this.subtrees[e].key+" "+this.subtrees[e].value[f].prettyPrint(a+2);this.parent&&(c+=b+"}\n")}return c};BoostInfoTree.prototype.toString=function(){return this.prettyPrint()};
BoostInfoTree.prototype.find=function(a){for(var b=0;b<this.subtrees.length;++b)if(this.subtrees[b].key==a)return this.subtrees[b].value;return null};var BoostInfoParser=function(){this.root=new BoostInfoTree};exports.BoostInfoParser=BoostInfoParser;exports.BoostInfoTree=BoostInfoTree;BoostInfoParser.prototype.read=function(a,b){var c;"string"==typeof b?c=a:(b=a,c=fs.readFileSync(a).toString());var d=this.root,e=this;c.split(/\r?\n/).forEach(function(a){d=e.parseLine(a.trim(),d)})};
BoostInfoParser.prototype.write=function(a){fs.writeFileSync(a,""+this.root)};BoostInfoParser.prototype.getRoot=function(){return this.root};
BoostInfoParser.shlex_split=function(a){var b=[];if(""==a)return b;for(var c=0;;){for(;0<=" \t\n\r".indexOf(a[c]);)if(c+=1,c>=a.length)return b;for(var d=c,e=!1,f="";;){if("\\"==a[d]){if(f+=a.substring(c,d),d=c=d+1,d>=a.length)break}else if(e)'"'==a[d]&&(f+=a.substring(c,d),c=d+1,e=!1);else if('"'==a[d])f+=a.substring(c,d),c=d+1,e=!0;else if(0<=" \t\n\r".indexOf(a[d]))break;d+=1;if(d>=a.length)break}f+=a.substring(c,d);b.push(f);if(d>=a.length)return b;c=d}};
BoostInfoParser.prototype.parseLine=function(a,b){var c=a.indexOf(";");0<=c&&(a=a.substring(0,c).trim());if(0==a.length)return b;for(var c=BoostInfoParser.shlex_split(a),d=!1,e=!1,f=0;f<c.length;++f)d=d||"{"==c[f],e=e||"}"==c[f];if(!d&&!e){var d=c[0],g;1<c.length&&(g=c[1]);b.createSubtree(d,g);return b}c=a.indexOf("{");if(0<c)return g=a.substring(0,c),c=a.substring(c),g=this.parseLine(g,b),this.parseLine(c,g);if("{"==a[0])return b=b.getLastChild();if("}"==a[0])return b=b.getParent();throw runtime_error("BoostInfoParser: input line is malformed");
};
var Name=require("../name.js").Name,InterestFilter=require("../interest-filter.js").InterestFilter,ForwardingFlags=require("../forwarding-flags.js").ForwardingFlags,WireFormat=require("../encoding/wire-format.js").WireFormat,LOG=require("../log.js").Log.LOG,MemoryContentCache=function(a,b){b=b||1E3;this.face=a;this.cleanupIntervalMilliseconds=b;this.nextCleanupTime=(new Date).getTime()+b;this.onDataNotFoundForPrefix={};this.interestFilterIdList=[];this.registeredPrefixIdList=[];this.noStaleTimeCache=[];
this.staleTimeCache=[];this.emptyComponent=new Name.Component;this.pendingInterestTable=[];var c=this;this.storePendingInterestCallback=function(a,b,f,g,h){c.storePendingInterest(b,f)}};exports.MemoryContentCache=MemoryContentCache;
MemoryContentCache.prototype.registerPrefix=function(a,b,c,d,e,f){var g=c,h=d,k=e;c="object"===typeof g&&1===g.length&&"function"===typeof g[0]?g[0]:null;d="function"===typeof g?g:"function"===typeof h?h:null;e=g instanceof ForwardingFlags?g:h instanceof ForwardingFlags?h:k instanceof ForwardingFlags?k:new ForwardingFlags;f=g instanceof WireFormat?g:h instanceof WireFormat?h:k instanceof WireFormat?k:f instanceof WireFormat?f:WireFormat.getDefaultWireFormat();d&&(this.onDataNotFoundForPrefix[a.toUri()]=
d);a=this.face.registerPrefix(a,this.onInterest.bind(this),b,c,e,f);this.registeredPrefixIdList.push(a)};MemoryContentCache.prototype.setInterestFilter=function(a,b){if(b){var c;c="object"===typeof a&&a instanceof InterestFilter?a.getPrefix():a;this.onDataNotFoundForPrefix[c.toUri()]=b}c=this.face.setInterestFilter(a,this.onInterest.bind(this));this.interestFilterIdList.push(c)};
MemoryContentCache.prototype.unregisterAll=function(){for(var a=0;a<this.interestFilterIdList.length;++a)this.face.unsetInterestFilter(this.interestFilterIdList[a]);this.interestFilterIdList=[];for(a=0;a<this.registeredPrefixIdList.length;++a)this.face.removeRegisteredPrefix(this.registeredPrefixIdList[a]);this.registeredPrefixIdList=[];this.onDataNotFoundForPrefix={}};
MemoryContentCache.prototype.add=function(a){this.doCleanup();if(null!=a.getMetaInfo().getFreshnessPeriod()&&0<=a.getMetaInfo().getFreshnessPeriod()){for(var b=new MemoryContentCache.StaleTimeContent(a),c=this.staleTimeCache.length-1;0<=c&&!(this.staleTimeCache[c].staleTimeMilliseconds<=b.staleTimeMilliseconds);)--c;this.staleTimeCache.splice(c+1,0,b)}else this.noStaleTimeCache.push(new MemoryContentCache.Content(a));b=(new Date).getTime();for(c=this.pendingInterestTable.length-1;0<=c;--c)if(this.pendingInterestTable[c].isTimedOut(b))this.pendingInterestTable.splice(c,
1);else if(this.pendingInterestTable[c].getInterest().matchesName(a.getName())){try{this.pendingInterestTable[c].getFace().send(a.wireEncode().buf())}catch(d){0<LOG&&console.log(""+d);break}this.pendingInterestTable.splice(c,1)}};MemoryContentCache.prototype.storePendingInterest=function(a,b){this.pendingInterestTable.push(new MemoryContentCache.PendingInterest(a,b))};MemoryContentCache.prototype.getStorePendingInterest=function(){return this.storePendingInterestCallback};
MemoryContentCache.prototype.onInterest=function(a,b,c,d,e){this.doCleanup();for(var f=0,g=null,h=this.staleTimeCache.length+this.noStaleTimeCache.length,k=0;k<h;++k){var l;l=k<this.staleTimeCache.length?this.staleTimeCache[k]:this.noStaleTimeCache[k-this.staleTimeCache.length];if(b.matchesName(l.getName())){if(0>b.getChildSelector()){c.send(l.getDataEncoding());return}var m;m=l.getName().size()>b.getName().size()?l.getName().get(b.getName().size()):this.emptyComponent;var q=!1;null===g?q=!0:0==b.getChildSelector()?
0>m.compare(f)&&(q=!0):0<m.compare(f)&&(q=!0);q&&(f=m,g=l.getDataEncoding())}}null!==g?c.send(g):(f=this.onDataNotFoundForPrefix[a.toUri()])&&f(a,b,c,d,e)};MemoryContentCache.prototype.doCleanup=function(){var a=(new Date).getTime();if(a>=this.nextCleanupTime){for(;0<this.staleTimeCache.length&&this.staleTimeCache[0].isStale(a);)this.staleTimeCache.shift();this.nextCleanupTime=a+this.cleanupIntervalMilliseconds}};
MemoryContentCache.Content=function(a){a&&(this.name=new Name(a.getName()),this.dataEncoding=a.wireEncode().buf())};MemoryContentCache.Content.prototype.getName=function(){return this.name};MemoryContentCache.Content.prototype.getDataEncoding=function(){return this.dataEncoding};MemoryContentCache.StaleTimeContent=function(a){MemoryContentCache.Content.call(this,a);this.staleTimeMilliseconds=(new Date).getTime()+a.getMetaInfo().getFreshnessPeriod()};MemoryContentCache.StaleTimeContent.prototype=new MemoryContentCache.Content;
MemoryContentCache.StaleTimeContent.prototype.name="StaleTimeContent";MemoryContentCache.StaleTimeContent.prototype.isStale=function(a){return this.staleTimeMilliseconds<=a};MemoryContentCache.PendingInterest=function(a,b){this.interest=a;this.face=b;0<=this.interest.getInterestLifetimeMilliseconds()?this.timeoutMilliseconds=(new Date).getTime()+this.interest.getInterestLifetimeMilliseconds():this.timeoutMilliseconds=-1};MemoryContentCache.PendingInterest.prototype.getInterest=function(){return this.interest};
MemoryContentCache.PendingInterest.prototype.getFace=function(){return this.face};MemoryContentCache.PendingInterest.prototype.isTimedOut=function(a){return 0<=this.timeoutTimeMilliseconds&&a>=this.timeoutTimeMilliseconds};var Name=require("../name.js").Name,NdnRegexMatcher=function(){};exports.NdnRegexMatcher=NdnRegexMatcher;NdnRegexMatcher.match=function(a,b){var c=b.toUri();a=NdnRegexMatcher.sanitizeSets(a);a=a.replace(/<>/g,"(?:<.+?>)");a=a.replace(/>/g,"");a=a.replace(/<(?!!)/g,"/");return c.match(new RegExp(a))};
NdnRegexMatcher.sanitizeSets=function(a){for(var b=a,c=/\[(\^?)(.*?)\]/g,d;null!==(d=c.exec(a));){var e=c.lastIndex-1-d[2].length,f=e+d[2].length;0!==e-f&&(d=d[2].replace(/></g,">|<"),b=b.substr(0,e)+d+b.substr(f))}0<=b.indexOf("[^")?(b=b.replace(/\[\^/g,"(?:(?!"),b=b.replace(/\]/g,")(?:/.*)*)")):(b=b.replace(/\[/g,"("),b=b.replace(/\]/g,")"));return b};
var Interest=require("../interest.js").Interest,Blob=require("./blob.js").Blob,KeyChain=require("../security/key-chain.js").KeyChain,NdnCommon=require("./ndn-common.js").NdnCommon,SegmentFetcher=function(a,b,c,d,e){this.face=a;this.validatorKeyChain=b;this.verifySegment=c;this.onComplete=d;this.onError=e;this.contentParts=[]};exports.SegmentFetcher=SegmentFetcher;SegmentFetcher.ErrorCode={INTEREST_TIMEOUT:1,DATA_HAS_NO_SEGMENT:2,SEGMENT_VERIFICATION_FAILED:3};SegmentFetcher.DontVerifySegment=function(a){return!0};
SegmentFetcher.fetch=function(a,b,c,d,e){null==c||c instanceof KeyChain?(new SegmentFetcher(a,c,SegmentFetcher.DontVerifySegment,d,e)).fetchFirstSegment(b):(new SegmentFetcher(a,null,c,d,e)).fetchFirstSegment(b)};SegmentFetcher.prototype.fetchFirstSegment=function(a){a=new Interest(a);a.setChildSelector(1);a.setMustBeFresh(!0);var b=this;this.face.expressInterest(a,function(a,d){b.onData(a,d)},function(a){b.onTimeout(a)})};
SegmentFetcher.prototype.fetchNextSegment=function(a,b,c){a=new Interest(a);a.setChildSelector(0);a.setMustBeFresh(!1);a.setName(b.getPrefix(-1).appendSegment(c));var d=this;this.face.expressInterest(a,function(a,b){d.onData(a,b)},function(a){d.onTimeout(a)})};
SegmentFetcher.prototype.onData=function(a,b){if(null!=this.validatorKeyChain)try{var c=this;this.validatorKeyChain.verifyData(b,function(b){c.onVerified(b,a)},this.onValidationFailed.bind(this))}catch(d){console.log("Error in KeyChain.verifyData: "+d)}else if(this.verifySegment(b))this.onVerified(b,a);else try{this.onError(SegmentFetcher.ErrorCode.SEGMENT_VERIFICATION_FAILED,"Segment verification failed")}catch(e){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(e))}};
SegmentFetcher.prototype.onVerified=function(a,b){if(SegmentFetcher.endsWithSegmentNumber(a.getName())){var c=0;try{c=a.getName().get(-1).toSegment()}catch(d){try{this.onError(SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,"Error decoding the name segment number "+a.getName().get(-1).toEscapedString()+": "+d)}catch(e){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(e))}return}var f=this.contentParts.length;if(c!=f)this.fetchNextSegment(b,a.getName(),f);else{this.contentParts.push(a.getContent().buf());
if(0<a.getMetaInfo().getFinalBlockId().getValue().size()){var g=0;try{g=a.getMetaInfo().getFinalBlockId().toSegment()}catch(h){try{this.onError(SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,"Error decoding the FinalBlockId segment number "+a.getMetaInfo().getFinalBlockId().toEscapedString()+": "+h)}catch(k){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(k))}return}if(c==g){c=Buffer.concat(this.contentParts);try{this.onComplete(new Blob(c,!1))}catch(l){console.log("Error in onComplete: "+
NdnCommon.getErrorWithStackTrace(l))}return}}this.fetchNextSegment(b,a.getName(),f+1)}}else try{this.onError(SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,"Got an unexpected packet without a segment number: "+a.getName().toUri())}catch(m){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(m))}};
SegmentFetcher.prototype.onValidationFailed=function(a,b){try{this.onError(SegmentFetcher.ErrorCode.SEGMENT_VERIFICATION_FAILED,"Segment verification failed for "+a.getName().toUri()+" . Reason: "+b)}catch(c){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(c))}};SegmentFetcher.prototype.onTimeout=function(a){try{this.onError(SegmentFetcher.ErrorCode.INTEREST_TIMEOUT,"Time out for interest "+a.getName().toUri())}catch(b){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(b))}};
SegmentFetcher.endsWithSegmentNumber=function(a){return 1<=a.size()&&a.get(-1).isSegment()};var Transport=function(){};exports.Transport=Transport;Transport.ConnectionInfo=function(){};Transport.prototype.isLocal=function(a,b,c){c("Transport.isLocal is not implemented")};
var MicroForwarderTransport=function(){Transport.call(this);this.onReceivedObject=this.connectionInfo=this.elementReader=null;var a=this;window.addEventListener("message",function(b){if(b.source==window&&b.data.type&&"FromMicroForwarderStub"==b.data.type)if(b=b.data.object,b.type&&"Buffer"==b.type){if(null!=a.elementReader)a.elementReader.onReceivedData(new Buffer(b.data))}else if(a.onReceivedObject)a.onReceivedObject(b)},!1)};MicroForwarderTransport.prototype=new Transport;
MicroForwarderTransport.prototype.name="MicroForwarderTransport";MicroForwarderTransport.ConnectionInfo=function(){Transport.ConnectionInfo.call(this)};MicroForwarderTransport.ConnectionInfo.prototype=new Transport.ConnectionInfo;MicroForwarderTransport.ConnectionInfo.prototype.name="MicroForwarderTransport.ConnectionInfo";MicroForwarderTransport.ConnectionInfo.prototype.equals=function(a){return null==a?!1:!0};MicroForwarderTransport.ConnectionInfo.prototype.toString=function(){return"{}"};
MicroForwarderTransport.prototype.setOnReceivedObject=function(a){this.onReceivedObject=a};MicroForwarderTransport.prototype.isLocal=function(a,b,c){b(!0)};MicroForwarderTransport.prototype.connect=function(a,b,c,d){this.elementReader=new ElementReader(b);this.connectionInfo=a;c()};MicroForwarderTransport.prototype.sendObject=function(a){window.postMessage({type:"FromMicroForwarderTransport",object:a},"*")};
MicroForwarderTransport.prototype.send=function(a){null==this.connectionInfo?console.log("MicroForwarderTransport connection is not established."):this.sendObject(a.toJSON())};var RuntimePortTransport=function(a){Transport.call(this);this.connectionInfo=this.elementReader=null;this.onReceivedObject=a;this.port=null};RuntimePortTransport.prototype=new Transport;RuntimePortTransport.prototype.name="RuntimePortTransport";
RuntimePortTransport.ConnectionInfo=function(a){Transport.ConnectionInfo.call(this);this.port=a};RuntimePortTransport.ConnectionInfo.prototype=new Transport.ConnectionInfo;RuntimePortTransport.ConnectionInfo.prototype.name="RuntimePortTransport.ConnectionInfo";RuntimePortTransport.ConnectionInfo.prototype.equals=function(a){return null==a||void 0==a.port?!1:this.port==a.port};RuntimePortTransport.ConnectionInfo.prototype.toString=function(){return"{}"};
RuntimePortTransport.prototype.setOnReceivedObject=function(a){this.onReceivedObject=a};RuntimePortTransport.prototype.isLocal=function(a,b,c){b(!0)};
RuntimePortTransport.prototype.connect=function(a,b,c,d){this.elementReader=new ElementReader(b);this.connectionInfo=a;this.port=this.connectionInfo.port;var e=this;this.port.onMessage.addListener(function(a){if("Buffer"==a.type)e.elementReader.onReceivedData(Buffer.isBuffer(a.data)?a.data:new Buffer(a.data));else if(null!=e.onReceivedObject)e.onReceivedObject(a)});this.port.onDisconnect.addListener(function(){e.port=null;null!=d&&d()});c()};
RuntimePortTransport.prototype.sendObject=function(a){null==this.port?console.log("RuntimePortTransport connection is not established."):this.port.postMessage(a)};RuntimePortTransport.prototype.send=function(a){this.sendObject(a.toJSON())};
var ElementReader=require("../encoding/element-reader.js").ElementReader,LOG=require("../log.js").Log.LOG,Transport=require("./transport.js").Transport,Face,WebSocketTransport=function WebSocketTransport(){Transport.call(this);if(!WebSocket)throw Error("WebSocket support is not available on this platform.");this.elementReader=this.connectionInfo=this.ws=null;this.defaultGetConnectionInfo=Face.makeShuffledHostGetConnectionInfo("A.ws.ndn.ucla.edu B.ws.ndn.ucla.edu C.ws.ndn.ucla.edu D.ws.ndn.ucla.edu E.ws.ndn.ucla.edu F.ws.ndn.ucla.edu G.ws.ndn.ucla.edu H.ws.ndn.ucla.edu I.ws.ndn.ucla.edu J.ws.ndn.ucla.edu K.ws.ndn.ucla.edu L.ws.ndn.ucla.edu M.ws.ndn.ucla.edu N.ws.ndn.ucla.edu".split(" "),
9696,function(b,c){return new WebSocketTransport.ConnectionInfo(b,c)})};WebSocketTransport.prototype=new Transport;WebSocketTransport.prototype.name="WebSocketTransport";WebSocketTransport.importFace=function(a){Face=a};exports.WebSocketTransport=WebSocketTransport;WebSocketTransport.ConnectionInfo=function(a,b){Transport.ConnectionInfo.call(this);this.host=a;this.port=void 0!==b?b:9696};WebSocketTransport.ConnectionInfo.prototype=new Transport.ConnectionInfo;
WebSocketTransport.ConnectionInfo.prototype.name="WebSocketTransport.ConnectionInfo";WebSocketTransport.ConnectionInfo.prototype.equals=function(a){return null==a||void 0==a.host||void 0==a.port?!1:this.host==a.host&&this.port==a.port};WebSocketTransport.ConnectionInfo.prototype.toString=function(){return this.hostIsUri()?"{ uri: "+this.host+" }":"{ host: "+this.host+", port: "+this.port+" }"};
WebSocketTransport.ConnectionInfo.prototype.hostIsUri=function(){return"ws:"==this.host.substr(0,3)||"wss:"==this.host.substr(0,4)};WebSocketTransport.prototype.isLocal=function(a,b,c){b(!1)};
WebSocketTransport.prototype.connect=function(a,b,c,d){this.close();var e=a.hostIsUri()?a.host:"ws://"+a.host+":"+a.port;this.ws=new WebSocket(e);0<LOG&&console.log("ws connection created.");this.connectionInfo=a;this.ws.binaryType="arraybuffer";this.elementReader=new ElementReader(b);var f=this;this.ws.onmessage=function(a){a=a.data;if(null==a||void 0==a||""==a)console.log("INVALID ANSWER");else if(a instanceof ArrayBuffer){a=new Buffer(new Uint8Array(a));3<LOG&&console.log("BINARY RESPONSE IS "+
a.toString("hex"));try{f.elementReader.onReceivedData(a)}catch(b){console.log("NDN.ws.onmessage exception: "+b)}}};this.ws.onopen=function(a){3<LOG&&console.log(a);3<LOG&&console.log("ws.onopen: WebSocket connection opened.");3<LOG&&console.log("ws.onopen: ReadyState: "+this.readyState);c()};this.ws.onerror=function(a){console.log("ws.onerror: ReadyState: "+this.readyState);console.log(a);console.log("ws.onerror: WebSocket error: "+a.data)};this.ws.onclose=function(a){console.log("ws.onclose: WebSocket connection closed.");
f.ws=null;null!=d&&d()}};WebSocketTransport.prototype.connectByFace=function(a,b){this.connect(a.connectionInfo,a,b,function(){a.closeByTransport()})};WebSocketTransport.prototype.send=function(a){if(null!=this.ws){var b=new Uint8Array(a.length);b.set(a);this.ws.send(b.buffer);3<LOG&&console.log("ws.send() returned.")}else console.log("WebSocket connection is not established.")};WebSocketTransport.prototype.close=function(){null!=this.ws&&delete this.ws};exports.TcpTransport=require("./transport/web-socket-transport").WebSocketTransport;
Blob=require("./util/blob.js").Blob;DataUtils=require("./encoding/data-utils.js").DataUtils;LOG=require("./log.js").Log.LOG;DecodingException=require("./encoding/decoding-exception.js").DecodingException;
Name=function Name(b){if("string"==typeof b)3<LOG&&console.log("Content Name String "+b),this.components=Name.createNameArray(b);else if("object"===typeof b)if(this.components=[],b instanceof Name)this.append(b);else for(var c=0;c<b.length;++c)this.append(b[c]);else null==b?this.components=[]:1<LOG&&console.log("NO CONTENT NAME GIVEN");this.changeCount=0};exports.Name=Name;
Name.Component=function(a){"object"===typeof a&&a instanceof Name.Component?(this.value_=a.value_,this.type_=a.type_):(this.value_=a?"object"===typeof a&&"undefined"!==typeof ArrayBuffer&&a instanceof ArrayBuffer?new Blob(new Buffer(new Uint8Array(a)),!1):"object"===typeof a&&a instanceof Blob?a:new Blob(a):new Blob([]),this.type_=Name.Component.ComponentType.GENERIC)};Name.Component.ComponentType={IMPLICIT_SHA256_DIGEST:1,GENERIC:8};Name.Component.prototype.getValue=function(){return this.value_};
Name.Component.prototype.getValueAsBuffer=function(){return this.value_.buf()};Object.defineProperty(Name.Component.prototype,"value",{get:function(){return this.getValueAsBuffer()}});Name.Component.prototype.toEscapedString=function(){return this.type_===Name.Component.ComponentType.IMPLICIT_SHA256_DIGEST?"sha256digest="+this.value_.toHex():Name.toEscapedString(this.value_.buf())};Name.Component.prototype.isSegment=function(){return 1<=this.value_.size()&&0==this.value_.buf()[0]&&this.isGeneric()};
Name.Component.prototype.isSegmentOffset=function(){return 1<=this.value_.size()&&251==this.value_.buf()[0]&&this.isGeneric()};Name.Component.prototype.isVersion=function(){return 1<=this.value_.size()&&253==this.value_.buf()[0]&&this.isGeneric()};Name.Component.prototype.isTimestamp=function(){return 1<=this.value_.size()&&252==this.value_.buf()[0]&&this.isGeneric()};Name.Component.prototype.isSequenceNumber=function(){return 1<=this.value_.size()&&254==this.value_.buf()[0]&&this.isGeneric()};
Name.Component.prototype.isGeneric=function(){return this.type_===Name.Component.ComponentType.GENERIC};Name.Component.prototype.isImplicitSha256Digest=function(){return this.type_===Name.Component.ComponentType.IMPLICIT_SHA256_DIGEST};Name.Component.prototype.toNumber=function(){return DataUtils.bigEndianToUnsignedInt(this.value_.buf())};
Name.Component.prototype.toNumberWithMarker=function(a){if(0==this.value_.size()||this.value_.buf()[0]!=a)throw Error("Name component does not begin with the expected marker");return DataUtils.bigEndianToUnsignedInt(this.value_.buf().slice(1))};Name.Component.prototype.toSegment=function(){return this.toNumberWithMarker(0)};Name.Component.prototype.toSegmentOffset=function(){return this.toNumberWithMarker(251)};Name.Component.prototype.toVersion=function(){return this.toNumberWithMarker(253)};
Name.Component.prototype.toTimestamp=function(){return this.toNumberWithMarker(252)};Name.Component.prototype.toSequenceNumber=function(){return this.toNumberWithMarker(254)};Name.Component.fromNumber=function(a){var b=new TlvEncoder(8);b.writeNonNegativeInteger(a);return new Name.Component(new Blob(b.getOutput(),!1))};
Name.Component.fromNumberWithMarker=function(a,b){var c=new TlvEncoder(9);c.writeNonNegativeInteger(a);c.writeNonNegativeInteger(b);return new Name.Component(new Blob(c.getOutput(),!1))};Name.Component.fromSegment=function(a){return Name.Component.fromNumberWithMarker(a,0)};Name.Component.fromSegmentOffset=function(a){return Name.Component.fromNumberWithMarker(a,251)};Name.Component.fromVersion=function(a){return Name.Component.fromNumberWithMarker(a,253)};
Name.Component.fromTimestamp=function(a){return Name.Component.fromNumberWithMarker(a,252)};Name.Component.fromSequenceNumber=function(a){return Name.Component.fromNumberWithMarker(a,254)};
Name.Component.fromImplicitSha256Digest=function(a){digestBlob="object"===typeof a&&a instanceof Blob?a:new Blob(a,!0);if(32!==digestBlob.size())throw new DecodingException("Name.Component.fromImplicitSha256Digest: The digest length must be 32 bytes");a=new Name.Component(digestBlob);a.type_=Name.Component.ComponentType.IMPLICIT_SHA256_DIGEST;return a};
Name.Component.prototype.getSuccessor=function(){for(var a=new Buffer(this.value_.size()+1),b=!0,c=this.value_.size()-1;0<=c;--c)b?(a[c]=this.value_.buf()[c]+1&255,b=0===a[c]):a[c]=this.value_.buf()[c];b?a[a.length-1]=0:a=a.slice(0,this.value_.size());return new Name.Component(new Blob(a,!1))};Name.Component.prototype.equals=function(a){return"object"===typeof a&&a instanceof Name.Component&&this.value_.equals(a.value_)&&this.type_===a.type_};
Name.Component.prototype.compare=function(a){return this.type_<a.type_?-1:this.type_>a.type_?1:Name.Component.compareBuffers(this.value_.buf(),a.value_.buf())};Name.Component.compareBuffers=function(a,b){if(a.length<b.length)return-1;if(a.length>b.length)return 1;for(var c=0;c<a.length;++c){if(a[c]<b[c])return-1;if(a[c]>b[c])return 1}return 0};Name.prototype.getName=function(){return this.toUri()};
Name.createNameArray=function(a){a=a.trim();if(0>=a.length)return[];var b=a.indexOf(":");if(0<=b){var c=a.indexOf("/");if(0>c||b<c)a=a.substr(b+1,a.length-b-1).trim()}if("/"==a[0])if(2<=a.length&&"/"==a[1]){b=a.indexOf("/",2);if(0>b)return[];a=a.substr(b+1,a.length-b-1).trim()}else a=a.substr(1,a.length-1).trim();a=a.split("/");for(b=0;b<a.length;++b)"sha256digest="==a[b].substr(0,13)?(c=a[b].substr(13).trim(),c=Name.Component.fromImplicitSha256Digest(new Blob(new Buffer(c,"hex")),!1)):c=new Name.Component(Name.fromEscapedString(a[b])),
c.getValue().isNull()?(a.splice(b,1),--b):a[b]=c;return a};Name.prototype.set=function(a){this.components=Name.createNameArray(a);++this.changeCount};
Name.prototype.append=function(a){if("object"==typeof a&&a instanceof Name){a=a==this?this.components.slice(0,this.components.length):a.components;for(var b=0;b<a.length;++b)this.components.push(new Name.Component(a[b]))}else"object"===typeof a&&a instanceof Name.Component?this.components.push(a):this.components.push(new Name.Component(a));++this.changeCount;return this};Name.prototype.add=function(a){return this.append(a)};Name.prototype.clear=function(){this.components=[];++this.changeCount};
Name.prototype.toUri=function(a){if(0==this.size())return a?"ndn:/":"/";a=a?"ndn:":"";for(var b=0;b<this.size();++b)a+="/"+this.components[b].toEscapedString();return a};Name.prototype.to_uri=function(){return this.toUri()};Name.prototype.toString=function(){return this.toUri()};Name.prototype.appendSegment=function(a){return this.append(Name.Component.fromSegment(a))};Name.prototype.appendSegmentOffset=function(a){return this.append(Name.Component.fromSegmentOffset(a))};
Name.prototype.appendVersion=function(a){return this.append(Name.Component.fromVersion(a))};Name.prototype.appendTimestamp=function(a){return this.append(Name.Component.fromTimestamp(a))};Name.prototype.appendSequenceNumber=function(a){return this.append(Name.Component.fromSequenceNumber(a))};Name.prototype.appendImplicitSha256Digest=function(a){return this.append(Name.Component.fromImplicitSha256Digest(a))};Name.prototype.addSegment=function(a){return this.appendSegment(a)};
Name.prototype.getSubName=function(a,b){0>a&&(a=this.components.length- -a);void 0==b&&(b=this.components.length-a);for(var c=new Name,d=a+b,e=a;e<d&&e<this.components.length;++e)c.components.push(this.components[e]);return c};Name.prototype.getPrefix=function(a){return 0>a?this.getSubName(0,this.components.length+a):this.getSubName(0,a)};Name.prototype.cut=function(a){return new Name(this.components.slice(0,this.components.length-a))};Name.prototype.size=function(){return this.components.length};
Name.prototype.get=function(a){if(0<=a){if(a>=this.components.length)throw Error("Name.get: Index is out of bounds");return this.components[a]}if(a<-this.components.length)throw Error("Name.get: Index is out of bounds");return this.components[this.components.length- -a]};Name.prototype.getComponentCount=function(){return this.components.length};Name.prototype.getComponent=function(a){return new Buffer(this.components[a].getValue().buf())};
Name.prototype.indexOfFileName=function(){for(var a=this.size()-1;0<=a;--a){var b=this.components[a].getValue().buf();if(!(0>=b.length||0==b[0]||192==b[0]||193==b[0]||245<=b[0]&&255>=b[0]))return a}return-1};Name.prototype.wireEncode=function(a){a=a||WireFormat.getDefaultWireFormat();return a.encodeName(this)};Name.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();"object"===typeof a&&a instanceof Blob?b.decodeName(this,a.buf(),!1):b.decodeName(this,a,!0)};
Name.prototype.compare=function(a,b,c,d,e){a instanceof Name&&(c=a,a=0,b=this.size());void 0==d&&(d=0);void 0==e&&(e=c.size());0>a&&(a=this.size()- -a);0>d&&(d=c.size()- -d);b=Math.min(b,this.size()-a);e=Math.min(e,c.size()-d);for(var f=Math.min(b,e),g=0;g<f;++g){var h=this.components[a+g].compare(c.components[d+g]);if(0!=h)return h}return b<e?-1:b>e?1:0};
Name.prototype.equals=function(a){if(this.components.length!=a.components.length)return!1;for(var b=this.components.length-1;0<=b;--b)if(!this.components[b].equals(a.components[b]))return!1;return!0};Name.prototype.equalsName=function(a){return this.equals(a)};Name.prototype.getContentDigestValue=function(){for(var a=this.size()-1;0<=a;--a){var b=Name.getComponentContentDigestValue(this.components[a]);if(null!=b)return b}return null};
Name.getComponentContentDigestValue=function(a){"object"==typeof a&&a instanceof Name.Component&&(a=a.getValue().buf());return a.length==Name.ContentDigestPrefix.length+32+Name.ContentDigestSuffix.length&&DataUtils.arraysEqual(a.slice(0,Name.ContentDigestPrefix.length),Name.ContentDigestPrefix)&&DataUtils.arraysEqual(a.slice(a.length-Name.ContentDigestSuffix.length,a.length),Name.ContentDigestSuffix)?a.slice(Name.ContentDigestPrefix.length,Name.ContentDigestPrefix.length+32):null};
Name.ContentDigestPrefix=new Buffer([193,46,77,46,71,193,1,170,2,133]);Name.ContentDigestSuffix=new Buffer([0]);
Name.toEscapedString=function(a){"object"==typeof a&&a instanceof Name.Component?a=a.getValue().buf():"object"===typeof a&&a instanceof Blob&&(a=a.buf());for(var b="",c=!1,d=0;d<a.length;++d)if(46!=a[d]){c=!0;break}if(c)for(d=0;d<a.length;++d)c=a[d],b=48<=c&&57>=c||65<=c&&90>=c||97<=c&&122>=c||43==c||45==c||46==c||95==c?b+String.fromCharCode(c):b+("%"+(16>c?"0":"")+c.toString(16).toUpperCase());else for(b="...",d=0;d<a.length;++d)b+=".";return b};
Name.fromEscapedString=function(a){a=unescape(a.trim());return null==a.match(/[^.]/)?2>=a.length?new Blob:new Blob(DataUtils.toNumbersFromString(a.substr(3,a.length-3)),!1):new Blob(DataUtils.toNumbersFromString(a),!1)};Name.fromEscapedStringAsBuffer=function(a){return Name.fromEscapedString(a).buf()};Name.prototype.getSuccessor=function(){if(0==this.size()){var a=new Name;a.append(new Blob(new Buffer([0]),!1));return a}return this.getPrefix(-1).append(this.get(-1).getSuccessor())};
Name.prototype.match=function(a){var b=this.components;a=a.components;if(b.length>a.length)return!1;for(var c=b.length-1;0<=c;--c)if(!b[c].equals(a[c]))return!1;return!0};Name.prototype.isPrefixOf=function(a){return this.match(a)};Name.prototype.getChangeCount=function(){return this.changeCount};
var TlvEncoder=require("./encoding/tlv/tlv-encoder.js").TlvEncoder,WireFormat=require("./encoding/wire-format.js").WireFormat,Blob=require("./util/blob.js").Blob,ChangeCounter=require("./util/change-counter.js").ChangeCounter,Name=require("./name.js").Name,KeyLocatorType={KEYNAME:1,KEY_LOCATOR_DIGEST:2};exports.KeyLocatorType=KeyLocatorType;
var KeyLocator=function KeyLocator(b,c){"object"===typeof b&&b instanceof KeyLocator?(this.type_=b.type_,this.keyName_=new ChangeCounter(new Name(b.getKeyName())),this.keyData_=b.keyData_):(this.type_=c,this.keyName_=new ChangeCounter(new Name),this.keyData_=new Blob,c==KeyLocatorType.KEYNAME?this.keyName_.set("object"===typeof b&&b instanceof Name?new Name(b):new Name):c==KeyLocatorType.KEY_LOCATOR_DIGEST&&(this.keyData_=new Blob(b)));this.changeCount_=0};exports.KeyLocator=KeyLocator;
KeyLocator.prototype.getType=function(){return this.type_};KeyLocator.prototype.getKeyName=function(){return this.keyName_.get()};KeyLocator.prototype.getKeyData=function(){return this.keyData_};KeyLocator.prototype.getKeyDataAsBuffer=function(){return this.getKeyData().buf()};KeyLocator.prototype.setType=function(a){this.type_=a;++this.changeCount_};KeyLocator.prototype.setKeyName=function(a){this.keyName_.set("object"===typeof a&&a instanceof Name?new Name(a):new Name);++this.changeCount_};
KeyLocator.prototype.setKeyData=function(a){this.keyData_="object"===typeof a&&a instanceof Blob?a:new Blob(a);++this.changeCount_};KeyLocator.prototype.clear=function(){this.type_=null;this.keyName_.set(new Name);this.keyData_=new Blob;++this.changeCount_};
KeyLocator.prototype.equals=function(a){if(this.type_!=a.type_)return!1;if(this.type_==KeyLocatorType.KEYNAME){if(!this.getKeyName().equals(a.getKeyName()))return!1}else if(this.type_==KeyLocatorType.KEY_LOCATOR_DIGEST&&!this.getKeyData().equals(a.getKeyData()))return!1;return!0};KeyLocator.canGetFromSignature=function(a){return a instanceof Sha256WithRsaSignature||a instanceof Sha256WithEcdsaSignature||a instanceof HmacWithSha256Signature};
KeyLocator.getFromSignature=function(a){if(a instanceof Sha256WithRsaSignature||a instanceof Sha256WithEcdsaSignature||a instanceof HmacWithSha256Signature)return a.getKeyLocator();throw Error("KeyLocator.getFromSignature: Signature type does not have a KeyLocator");};KeyLocator.prototype.getChangeCount=function(){this.keyName_.checkChanged()&&++this.changeCount_;return this.changeCount_};Object.defineProperty(KeyLocator.prototype,"type",{get:function(){return this.getType()},set:function(a){this.setType(a)}});
Object.defineProperty(KeyLocator.prototype,"keyData",{get:function(){return this.getKeyDataAsBuffer()},set:function(a){this.setKeyData(a)}});var Sha256WithRsaSignature=require("./sha256-with-rsa-signature.js").Sha256WithRsaSignature,Sha256WithEcdsaSignature=require("./sha256-with-ecdsa-signature.js").Sha256WithEcdsaSignature,HmacWithSha256Signature=require("./hmac-with-sha256-signature.js").HmacWithSha256Signature,Name=require("./name.js").Name,ContentType={BLOB:0,LINK:1,KEY:2,NACK:3,OTHER_CODE:32767};
exports.ContentType=ContentType;
var MetaInfo=function MetaInfo(b,c,d,e,f,g){if(c)throw Error("MetaInfo constructor: timestamp support has been removed.");if(e)throw Error("MetaInfo constructor: locator support has been removed.");if("object"===typeof b&&b instanceof MetaInfo)this.publisher_=b.publisher_,this.type_=b.type_,this.otherTypeCode_=b.otherTypeCode_,this.freshnessPeriod_=b.freshnessPeriod_,this.finalBlockId_=b.finalBlockId_;else{if(b)throw Error("MetaInfo constructor: publisher support has been removed.");this.type=null==
d||0>d?ContentType.BLOB:d;this.otherTypeCode_=-1;this.freshnessSeconds=f;this.finalBlockID=g}this.changeCount_=0};exports.MetaInfo=MetaInfo;MetaInfo.prototype.getType=function(){return this.type_};MetaInfo.prototype.getOtherTypeCode=function(){return this.otherTypeCode_};MetaInfo.prototype.getFreshnessPeriod=function(){return this.freshnessPeriod_};MetaInfo.prototype.getFinalBlockId=function(){return this.finalBlockId_};MetaInfo.prototype.getFinalBlockID=function(){return this.getFinalBlockId()};
MetaInfo.prototype.getFinalBlockIDAsBuffer=function(){return this.finalBlockId_.getValue().buf()};MetaInfo.prototype.setType=function(a){this.type_=null==a||0>a?ContentType.BLOB:a;++this.changeCount_};MetaInfo.prototype.setOtherTypeCode=function(a){if(0>a)throw Error("MetaInfo other type code must be non-negative");this.otherTypeCode_=a;++this.changeCount_};MetaInfo.prototype.setFreshnessPeriod=function(a){this.freshnessPeriod_=null==a||0>a?null:a;++this.changeCount_};
MetaInfo.prototype.setFinalBlockId=function(a){this.finalBlockId_="object"===typeof a&&a instanceof Name.Component?a:new Name.Component(a);++this.changeCount_};MetaInfo.prototype.setFinalBlockID=function(a){this.setFinalBlockId(a)};MetaInfo.prototype.getChangeCount=function(){return this.changeCount_};Object.defineProperty(MetaInfo.prototype,"type",{get:function(){return this.getType()},set:function(a){this.setType(a)}});
Object.defineProperty(MetaInfo.prototype,"freshnessSeconds",{get:function(){return null==this.freshnessPeriod_||0>this.freshnessPeriod_?null:this.freshnessPeriod_/1E3},set:function(a){this.freshnessPeriod_=null==a||0>a?null:1E3*a;++this.changeCount_}});Object.defineProperty(MetaInfo.prototype,"finalBlockID",{get:function(){return this.getFinalBlockIDAsBuffer()},set:function(a){this.setFinalBlockId(a)}});Blob=require("./util/blob.js").Blob;ChangeCounter=require("./util/change-counter.js").ChangeCounter;
KeyLocator=require("./key-locator.js").KeyLocator;Sha256WithEcdsaSignature=function Sha256WithEcdsaSignature(b){"object"===typeof b&&b instanceof Sha256WithEcdsaSignature?(this.keyLocator_=new ChangeCounter(new KeyLocator(b.getKeyLocator())),this.signature_=b.signature_):(this.keyLocator_=new ChangeCounter(new KeyLocator),this.signature_=new Blob);this.changeCount_=0};exports.Sha256WithEcdsaSignature=Sha256WithEcdsaSignature;Sha256WithEcdsaSignature.prototype.clone=function(){return new Sha256WithEcdsaSignature(this)};
Sha256WithEcdsaSignature.prototype.getKeyLocator=function(){return this.keyLocator_.get()};Sha256WithEcdsaSignature.prototype.getSignature=function(){return this.signature_};Sha256WithEcdsaSignature.prototype.setKeyLocator=function(a){this.keyLocator_.set("object"===typeof a&&a instanceof KeyLocator?new KeyLocator(a):new KeyLocator);++this.changeCount_};Sha256WithEcdsaSignature.prototype.setSignature=function(a){this.signature_="object"===typeof a&&a instanceof Blob?a:new Blob(a);++this.changeCount_};
Sha256WithEcdsaSignature.prototype.getChangeCount=function(){this.keyLocator_.checkChanged()&&++this.changeCount_;return this.changeCount_};Blob=require("./util/blob.js").Blob;ChangeCounter=require("./util/change-counter.js").ChangeCounter;KeyLocator=require("./key-locator.js").KeyLocator;
Sha256WithRsaSignature=function Sha256WithRsaSignature(b){"object"===typeof b&&b instanceof Sha256WithRsaSignature?(this.keyLocator_=new ChangeCounter(new KeyLocator(b.getKeyLocator())),this.signature_=b.signature_):(this.keyLocator_=new ChangeCounter(new KeyLocator),this.signature_=new Blob);this.changeCount_=0};exports.Sha256WithRsaSignature=Sha256WithRsaSignature;Sha256WithRsaSignature.prototype.clone=function(){return new Sha256WithRsaSignature(this)};
Sha256WithRsaSignature.prototype.getKeyLocator=function(){return this.keyLocator_.get()};Sha256WithRsaSignature.prototype.getSignature=function(){return this.signature_};Sha256WithRsaSignature.prototype.getSignatureAsBuffer=function(){return this.signature_.buf()};Sha256WithRsaSignature.prototype.setKeyLocator=function(a){this.keyLocator_.set("object"===typeof a&&a instanceof KeyLocator?new KeyLocator(a):new KeyLocator);++this.changeCount_};
Sha256WithRsaSignature.prototype.setSignature=function(a){this.signature_="object"===typeof a&&a instanceof Blob?a:new Blob(a);++this.changeCount_};Sha256WithRsaSignature.prototype.getChangeCount=function(){this.keyLocator_.checkChanged()&&++this.changeCount_;return this.changeCount_};Object.defineProperty(Sha256WithRsaSignature.prototype,"keyLocator",{get:function(){return this.getKeyLocator()},set:function(a){this.setKeyLocator(a)}});
Object.defineProperty(Sha256WithRsaSignature.prototype,"signature",{get:function(){return this.getSignatureAsBuffer()},set:function(a){this.setSignature(a)}});
var Blob=require("./util/blob.js").Blob,GenericSignature=function GenericSignature(b){"object"===typeof b&&b instanceof GenericSignature?(this.signature_=b.signature_,this.signatureInfoEncoding_=b.signatureInfoEncoding_,this.typeCode_=b.typeCode_):(this.signature_=new Blob,this.signatureInfoEncoding_=new Blob,this.typeCode_=null);this.changeCount_=0};exports.GenericSignature=GenericSignature;GenericSignature.prototype.clone=function(){return new GenericSignature(this)};
GenericSignature.prototype.getSignature=function(){return this.signature_};GenericSignature.prototype.getSignatureAsBuffer=function(){return this.signature_.buf()};GenericSignature.prototype.getSignatureInfoEncoding=function(){return this.signatureInfoEncoding_};GenericSignature.prototype.getTypeCode=function(){return this.typeCode_};GenericSignature.prototype.setSignature=function(a){this.signature_="object"===typeof a&&a instanceof Blob?a:new Blob(a);++this.changeCount_};
GenericSignature.prototype.setSignatureInfoEncoding=function(a,b){this.signatureInfoEncoding_="object"===typeof a&&a instanceof Blob?a:new Blob(a);this.typeCode_=b;++this.changeCount_};GenericSignature.prototype.getChangeCount=function(){return this.changeCount_};Object.defineProperty(GenericSignature.prototype,"signature",{get:function(){return this.getSignatureAsBuffer()},set:function(a){this.setSignature(a)}});Blob=require("./util/blob.js").Blob;ChangeCounter=require("./util/change-counter.js").ChangeCounter;
KeyLocator=require("./key-locator.js").KeyLocator;HmacWithSha256Signature=function HmacWithSha256Signature(b){"object"===typeof b&&b instanceof HmacWithSha256Signature?(this.keyLocator_=new ChangeCounter(new KeyLocator(b.getKeyLocator())),this.signature_=b.signature_):(this.keyLocator_=new ChangeCounter(new KeyLocator),this.signature_=new Blob);this.changeCount_=0};exports.HmacWithSha256Signature=HmacWithSha256Signature;HmacWithSha256Signature.prototype.clone=function(){return new HmacWithSha256Signature(this)};
HmacWithSha256Signature.prototype.getKeyLocator=function(){return this.keyLocator_.get()};HmacWithSha256Signature.prototype.getSignature=function(){return this.signature_};HmacWithSha256Signature.prototype.getSignatureAsBuffer=function(){return this.signature_.buf()};HmacWithSha256Signature.prototype.setKeyLocator=function(a){this.keyLocator_.set("object"===typeof a&&a instanceof KeyLocator?new KeyLocator(a):new KeyLocator);++this.changeCount_};
HmacWithSha256Signature.prototype.setSignature=function(a){this.signature_="object"===typeof a&&a instanceof Blob?a:new Blob(a);++this.changeCount_};HmacWithSha256Signature.prototype.getChangeCount=function(){this.keyLocator_.checkChanged()&&++this.changeCount_;return this.changeCount_};Object.defineProperty(HmacWithSha256Signature.prototype,"keyLocator",{get:function(){return this.getKeyLocator()},set:function(a){this.setKeyLocator(a)}});
Object.defineProperty(HmacWithSha256Signature.prototype,"signature",{get:function(){return this.getSignatureAsBuffer()},set:function(a){this.setSignature(a)}});var Blob=require("./util/blob.js").Blob,DigestSha256Signature=function DigestSha256Signature(b){this.signature_="object"===typeof b&&b instanceof DigestSha256Signature?b.signature_:new Blob;this.changeCount_=0};exports.DigestSha256Signature=DigestSha256Signature;DigestSha256Signature.prototype.clone=function(){return new DigestSha256Signature(this)};
DigestSha256Signature.prototype.getSignature=function(){return this.signature_};DigestSha256Signature.prototype.setSignature=function(a){this.signature_="object"===typeof a&&a instanceof Blob?a:new Blob(a);++this.changeCount_};DigestSha256Signature.prototype.getChangeCount=function(){return this.changeCount_};Object.defineProperty(DigestSha256Signature.prototype,"signature",{get:function(){return this.getSignature()},set:function(a){this.setSignature(a)}});
var Blob=require("./util/blob.js").Blob,SignedBlob=require("./util/signed-blob.js").SignedBlob,ChangeCounter=require("./util/change-counter.js").ChangeCounter,Name=require("./name.js").Name,Sha256WithRsaSignature=require("./sha256-with-rsa-signature.js").Sha256WithRsaSignature,MetaInfo=require("./meta-info.js").MetaInfo,IncomingFaceId=require("./lp/incoming-face-id.js").IncomingFaceId,WireFormat=require("./encoding/wire-format.js").WireFormat,Crypto=require("./crypto.js"),Data=function Data(b,c,d){b instanceof
Data?(this.name_=new ChangeCounter(new Name(b.getName())),this.metaInfo_=new ChangeCounter(new MetaInfo(b.getMetaInfo())),this.signature_=new ChangeCounter(b.getSignature().clone()),this.content_=b.content_,this.defaultWireEncoding_=b.getDefaultWireEncoding(),this.defaultFullName_=b.defaultFullName_,this.defaultWireEncodingFormat_=b.defaultWireEncodingFormat_):(this.name_="string"===typeof b?new ChangeCounter(new Name(b)):new ChangeCounter("object"===typeof b&&b instanceof Name?new Name(b):new Name),
"object"===typeof c&&c instanceof MetaInfo?(b=c,c=d):b=null,this.metaInfo_=new ChangeCounter("object"===typeof b&&b instanceof MetaInfo?new MetaInfo(b):new MetaInfo),this.content_="object"===typeof c&&c instanceof Blob?c:new Blob(c,!0),this.signature_=new ChangeCounter(new Sha256WithRsaSignature),this.defaultWireEncoding_=new SignedBlob,this.defaultFullName_=new Name,this.defaultWireEncodingFormat_=null);this.changeCount_=this.getDefaultWireEncodingChangeCount_=0;this.lpPacket_=null};
exports.Data=Data;Data.prototype.getName=function(){return this.name_.get()};Data.prototype.getMetaInfo=function(){return this.metaInfo_.get()};Data.prototype.getSignature=function(){return this.signature_.get()};Data.prototype.getContent=function(){return this.content_};Data.prototype.getContentAsBuffer=function(){return this.content_.buf()};
Data.prototype.getDefaultWireEncoding=function(){this.getDefaultWireEncodingChangeCount_!=this.getChangeCount()&&(this.defaultWireEncoding_=new SignedBlob,this.defaultWireEncodingFormat_=null,this.getDefaultWireEncodingChangeCount_=this.getChangeCount());return this.defaultWireEncoding_};Data.prototype.getDefaultWireEncodingFormat=function(){return this.defaultWireEncodingFormat_};
Data.prototype.getIncomingFaceId=function(){var a=null===this.lpPacket_?null:IncomingFaceId.getFirstHeader(this.lpPacket_);return null===a?null:a.getFaceId()};
Data.prototype.getFullName=function(a){a=a||WireFormat.getDefaultWireFormat();if(!this.getDefaultWireEncoding().isNull()&&0<this.defaultFullName_.size()&&this.getDefaultWireEncodingFormat()==a)return this.defaultFullName_;var b=new Name(this.getName()),c=Crypto.createHash("sha256");c.update(this.wireEncode(a).buf());b.appendImplicitSha256Digest(new Blob(c.digest(),!1));a==WireFormat.getDefaultWireFormat()&&(this.defaultFullName_=b);return b};
Data.prototype.setName=function(a){this.name_.set("object"===typeof a&&a instanceof Name?new Name(a):new Name);++this.changeCount_;return this};Data.prototype.setMetaInfo=function(a){this.metaInfo_.set("object"===typeof a&&a instanceof MetaInfo?new MetaInfo(a):new MetaInfo);++this.changeCount_;return this};Data.prototype.setSignature=function(a){this.signature_.set(null==a?new Sha256WithRsaSignature:a.clone());++this.changeCount_;return this};
Data.prototype.setContent=function(a){this.content_="object"===typeof a&&a instanceof Blob?a:new Blob(a,!0);++this.changeCount_;return this};
Data.prototype.wireEncode=function(a){a=a||WireFormat.getDefaultWireFormat();if(!this.getDefaultWireEncoding().isNull()&&this.getDefaultWireEncodingFormat()==a)return this.getDefaultWireEncoding();var b=a.encodeData(this),b=new SignedBlob(b.encoding,b.signedPortionBeginOffset,b.signedPortionEndOffset);a==WireFormat.getDefaultWireFormat()&&this.setDefaultWireEncoding(b,WireFormat.getDefaultWireFormat());return b};
Data.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();var c;c="object"===typeof a&&a instanceof Blob?b.decodeData(this,a.buf(),!1):b.decodeData(this,a,!0);b==WireFormat.getDefaultWireFormat()?this.setDefaultWireEncoding(new SignedBlob(new Blob(a,!0),c.signedPortionBeginOffset,c.signedPortionEndOffset),WireFormat.getDefaultWireFormat()):this.setDefaultWireEncoding(new SignedBlob,null)};Data.prototype.setLpPacket=function(a){this.lpPacket_=a;return this};
Data.prototype.getChangeCount=function(){var a=this.name_.checkChanged(),a=this.metaInfo_.checkChanged()||a;(a=this.signature_.checkChanged()||a)&&++this.changeCount_;return this.changeCount_};Data.prototype.setDefaultWireEncoding=function(a,b){this.defaultWireEncoding_=a;this.defaultWireEncodingFormat_=b;this.getDefaultWireEncodingChangeCount_=this.getChangeCount()};Object.defineProperty(Data.prototype,"name",{get:function(){return this.getName()},set:function(a){this.setName(a)}});
Object.defineProperty(Data.prototype,"metaInfo",{get:function(){return this.getMetaInfo()},set:function(a){this.setMetaInfo(a)}});Object.defineProperty(Data.prototype,"signature",{get:function(){return this.getSignature()},set:function(a){this.setSignature(a)}});Object.defineProperty(Data.prototype,"content",{get:function(){return this.getContentAsBuffer()},set:function(a){this.setContent(a)}});function SecurityException(a){if(a)return a.__proto__=SecurityException.prototype,a}
SecurityException.prototype=Error();SecurityException.prototype.name="SecurityException";exports.SecurityException=SecurityException;function UnrecognizedKeyFormatException(a){SecurityException.call(this,a)}UnrecognizedKeyFormatException.prototype=new SecurityException;UnrecognizedKeyFormatException.prototype.name="UnrecognizedKeyFormatException";exports.UnrecognizedKeyFormatException=UnrecognizedKeyFormatException;function UnrecognizedDigestAlgorithmException(a){SecurityException.call(this,a)}
UnrecognizedDigestAlgorithmException.prototype=new SecurityException;UnrecognizedDigestAlgorithmException.prototype.name="UnrecognizedDigestAlgorithmException";exports.UnrecognizedDigestAlgorithmException=UnrecognizedDigestAlgorithmException;var KeyType=function(){};exports.KeyType=KeyType;KeyType.RSA=0;KeyType.ECDSA=1;KeyType.AES=128;var KeyClass=function(){};exports.KeyClass=KeyClass;KeyClass.PUBLIC=1;KeyClass.PRIVATE=2;KeyClass.SYMMETRIC=3;var DigestAlgorithm=function(){};
exports.DigestAlgorithm=DigestAlgorithm;DigestAlgorithm.SHA256=1;var KeyType=require("./security-types.js").KeyType,KeyParams=function(a){this.keyType=a};exports.KeyParams=KeyParams;KeyParams.prototype.getKeyType=function(){return this.keyType};var RsaKeyParams=function RsaKeyParams(b){KeyParams.call(this,RsaKeyParams.getType());null==b&&(b=RsaKeyParams.getDefaultSize());this.size=b};RsaKeyParams.prototype=new KeyParams;RsaKeyParams.prototype.name="RsaKeyParams";exports.RsaKeyParams=RsaKeyParams;
RsaKeyParams.prototype.getKeySize=function(){return this.size};RsaKeyParams.getDefaultSize=function(){return 2048};RsaKeyParams.getType=function(){return KeyType.RSA};var EcdsaKeyParams=function EcdsaKeyParams(b){KeyParams.call(this,EcdsaKeyParams.getType());null==b&&(b=EcdsaKeyParams.getDefaultSize());this.size=b};EcdsaKeyParams.prototype=new KeyParams;EcdsaKeyParams.prototype.name="EcdsaKeyParams";exports.EcdsaKeyParams=EcdsaKeyParams;EcdsaKeyParams.prototype.getKeySize=function(){return this.size};
EcdsaKeyParams.getDefaultSize=function(){return 256};EcdsaKeyParams.getType=function(){return KeyType.ECDSA};var AesKeyParams=function AesKeyParams(b){KeyParams.call(this,AesKeyParams.getType());null==b&&(b=AesKeyParams.getDefaultSize());this.size=b};AesKeyParams.prototype=new KeyParams;AesKeyParams.prototype.name="AesKeyParams";exports.AesKeyParams=AesKeyParams;AesKeyParams.prototype.getKeySize=function(){return this.size};AesKeyParams.getDefaultSize=function(){return 64};AesKeyParams.getType=function(){return KeyType.AES};
var Crypto=require("../../crypto.js"),Blob=require("../../util/blob.js").Blob,DerDecodingException=require("../../encoding/der/der-decoding-exception.js").DerDecodingException,DerNode=require("../../encoding/der/der-node.js").DerNode,SecurityException=require("../security-exception.js").SecurityException,UnrecognizedKeyFormatException=require("../security-exception.js").UnrecognizedKeyFormatException,KeyType=require("../security-types.js").KeyType,DigestAlgorithm=require("../security-types.js").DigestAlgorithm,
PublicKey=function PublicKey(b){if(b){this.keyDer=b;var c=null;try{var d=DerNode.parse(b.buf(),0).getChildren(),c=DerNode.getSequence(d,0).getChildren()[0].toVal()}catch(e){throw new UnrecognizedKeyFormatException(Error("PublicKey.decodeKeyType: Error decoding the public key: "+e.message));}c==PublicKey.RSA_ENCRYPTION_OID?this.keyType=KeyType.RSA:c==PublicKey.EC_ENCRYPTION_OID&&(this.keyType=KeyType.ECDSA)}else this.keyDer=new Blob,this.keyType=null};exports.PublicKey=PublicKey;
PublicKey.prototype.toDer=function(){return DerNode.parse(this.keyDer.buf())};PublicKey.prototype.getKeyType=function(){return this.keyType};PublicKey.prototype.getDigest=function(a){void 0==a&&(a=DigestAlgorithm.SHA256);if(a==DigestAlgorithm.SHA256)return a=Crypto.createHash("sha256"),a.update(this.keyDer.buf()),new Blob(a.digest(),!1);throw new SecurityException(Error("Wrong format!"));};PublicKey.prototype.getKeyDer=function(){return this.keyDer};PublicKey.RSA_ENCRYPTION_OID="1.2.840.113549.1.1.1";
PublicKey.EC_ENCRYPTION_OID="1.2.840.10045.2.1";var DerNode=require("../../encoding/der/der-node.js").DerNode,OID=require("../../encoding/oid.js").OID,CertificateExtension=function(a,b,c){this.extensionId="string"===typeof a?new OID(a):a;this.isCritical=b;this.extensionValue=c};exports.CertificateExtension=CertificateExtension;
CertificateExtension.prototype.toDer=function(){var a=new DerNode.DerSequence,b=new DerNode.DerOid(this.extensionId),c=new DerNode.DerBoolean(this.isCritical),d=new DerNode.DerOctetString(this.extensionValue.buf());a.addChild(b);a.addChild(c);a.addChild(d);a.getSize();return a};CertificateExtension.prototype.toDerBlob=function(){return this.toDer().encode()};CertificateExtension.prototype.getOid=function(){return this.extensionId};CertificateExtension.prototype.getIsCritical=function(){return this.isCritical};
CertificateExtension.prototype.getValue=function(){return this.extensionValue};var Blob=require("../../util/blob.js").Blob,OID=require("../../encoding/oid.js").OID,DerNode=require("../../encoding/der/der-node.js").DerNode,CertificateSubjectDescription=function(a,b){this.oid="string"===typeof a?new OID(a):a;this.value=b};exports.CertificateSubjectDescription=CertificateSubjectDescription;
CertificateSubjectDescription.prototype.toDer=function(){var a=new DerNode.DerSequence,b=new DerNode.DerOid(this.oid),c=new DerNode.DerPrintableString((new Blob(this.value)).buf());a.addChild(b);a.addChild(c);return a};CertificateSubjectDescription.prototype.getOidString=function(){return this.oid.toString()};CertificateSubjectDescription.prototype.getValue=function(){return this.value};
var Data=require("../../data.js").Data,ContentType=require("../../meta-info.js").ContentType,WireFormat=require("../../encoding/wire-format.js").WireFormat,DerNode=require("../../encoding/der/der-node.js").DerNode,KeyType=require("../../security/security-types.js").KeyType,PublicKey=require("./public-key.js").PublicKey,CertificateSubjectDescription=require("./certificate-subject-description.js").CertificateSubjectDescription,CertificateExtension=require("./certificate-extension.js").CertificateExtension,
Certificate=function(a){void 0!=a?Data.call(this,a):Data.call(this);this.subjectDescriptionList=[];this.extensionList=[];this.notBefore=Number.MAX_VALUE;this.notAfter=-Number.MAX_VALUE;this.key=new PublicKey;void 0!=a&&this.decode()};Certificate.prototype=new Data;Certificate.prototype.name="Certificate";exports.Certificate=Certificate;Certificate.prototype.encode=function(){var a=this.toDer();this.setContent(a.encode());this.getMetaInfo().setType(ContentType.KEY)};
Certificate.prototype.addSubjectDescription=function(a){this.subjectDescriptionList.push(a)};Certificate.prototype.getSubjectDescriptionList=function(){return this.subjectDescriptionList};Certificate.prototype.addExtension=function(a){this.extensionList.push(a)};Certificate.prototype.getExtensionList=function(){return this.extensionList};Certificate.prototype.setNotBefore=function(a){this.notBefore=a};Certificate.prototype.getNotBefore=function(){return this.notBefore};
Certificate.prototype.setNotAfter=function(a){this.notAfter=a};Certificate.prototype.getNotAfter=function(){return this.notAfter};Certificate.prototype.setPublicKeyInfo=function(a){this.key=a};Certificate.prototype.getPublicKeyInfo=function(){return this.key};Certificate.prototype.isTooEarly=function(){return(new Date).getTime()<this.notBefore};Certificate.prototype.isTooLate=function(){return(new Date).getTime()>this.notAfter};
Certificate.prototype.toDer=function(){var a=new DerNode.DerSequence,b=new DerNode.DerSequence,c=new DerNode.DerGeneralizedTime(this.notBefore),d=new DerNode.DerGeneralizedTime(this.notAfter);b.addChild(c);b.addChild(d);a.addChild(b);c=new DerNode.DerSequence;for(b=0;b<this.subjectDescriptionList.length;++b)c.addChild(this.subjectDescriptionList[b].toDer());a.addChild(c);a.addChild(this.key.toDer());if(0<this.extensionList.length){c=new DerNode.DerSequence;for(b=0;b<this.extensionList.length;++b)c.addChild(this.extensionList[b].toDer());
a.addChild(c)}return a};
Certificate.prototype.decode=function(){var a=DerNode.parse(this.getContent().buf()).getChildren(),b=DerNode.getSequence(a,0).getChildren();this.notBefore=b[0].toVal();this.notAfter=b[1].toVal();for(var c=DerNode.getSequence(a,1).getChildren(),b=0;b<c.length;++b){var d=DerNode.getSequence(c,b).getChildren(),e=d[0].toVal(),d=d[1].toVal().buf().toString("binary");this.addSubjectDescription(new CertificateSubjectDescription(e,d))}b=a[2].encode();this.key=new PublicKey(b);if(3<a.length)for(a=DerNode.getSequence(a,
3).getChildren(),b=0;b<a.length;++b)d=DerNode.getSequence(a,b).getChildren(),e=d[0].toVal(),c=d[1].toVal(),d=d[2].toVal(),this.addExtension(new CertificateExtension(e,c,d))};Certificate.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();Data.prototype.wireDecode.call(this,a,b);this.decode()};
Certificate.prototype.toString=function(){var a;a="Certificate name:\n"+(" "+this.getName().toUri()+"\n");a+="Validity:\n";var b=Certificate.toIsoString(Math.round(this.notBefore)),c=Certificate.toIsoString(Math.round(this.notAfter));a=a+(" NotBefore: "+b+"\n")+(" NotAfter: "+c+"\n");for(b=0;b<this.subjectDescriptionList.length;++b)c=this.subjectDescriptionList[b],a+="Subject Description:\n",a+=" "+c.getOidString()+": "+c.getValue()+"\n";a+="Public key bits:\n";c=this.key.getKeyDer().buf().toString("base64");
for(b=0;b<c.length;b+=64)a+=c.substring(b,Math.min(b+64,c.length))+"\n";if(0<this.extensionList.length)for(a+="Extensions:\n",b=0;b<this.extensionList.length;++b)c=this.extensionList[b],a+=" OID: "+c.getOid()+"\n",a+=" Is critical: "+(c.getIsCritical()?"Y":"N")+"\n",a+=" Value: "+c.getValue().toHex()+"\n";return a};
Certificate.toIsoString=function(a){a=new Date(Math.round(a));return a.getUTCFullYear()+Certificate.to2DigitString(a.getUTCMonth()+1)+Certificate.to2DigitString(a.getUTCDate())+"T"+Certificate.to2DigitString(a.getUTCHours())+Certificate.to2DigitString(a.getUTCMinutes())+Certificate.to2DigitString(a.getUTCSeconds())};Certificate.to2DigitString=function(a){a=a.toString();return 1===a.length?"0"+a:a};
var Data=require("../../data.js").Data,Name=require("../../name.js").Name,SecurityException=require("../../security//security-exception.js").SecurityException,Certificate=require("./certificate.js").Certificate,WireFormat=require("../../encoding/wire-format.js").WireFormat,IdentityCertificate=function IdentityCertificate(b){void 0!=b?Certificate.call(this,b):Certificate.call(this);this.publicKeyName=new Name;if(b instanceof IdentityCertificate)this.publicKeyName=new Name(b.publicKeyName);else if(b instanceof
Data){if(!IdentityCertificate.isCorrectName(b.getName()))throw new SecurityException(Error("Wrong Identity Certificate Name!"));this.setPublicKeyName()}};IdentityCertificate.prototype=new Certificate;IdentityCertificate.prototype.name="IdentityCertificate";exports.IdentityCertificate=IdentityCertificate;
IdentityCertificate.prototype.setName=function(a){if(!IdentityCertificate.isCorrectName(a))throw new SecurityException(Error("Wrong Identity Certificate Name!"));Certificate.prototype.setName.call(this,a);this.setPublicKeyName();return this};IdentityCertificate.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();Certificate.prototype.wireDecode.call(this,a,b);this.setPublicKeyName()};IdentityCertificate.prototype.getPublicKeyName=function(){return this.publicKeyName};
IdentityCertificate.isIdentityCertificate=function(a){return IdentityCertificate.isCorrectName(a.getName())};
IdentityCertificate.certificateNameToPublicKeyName=function(a){for(var b=!1,c=a.size()-1;0<c+1;--c)if("ID-CERT"==a.get(c).toEscapedString()){b=!0;break}if(!b)throw Error("Incorrect identity certificate name "+a.toUri());for(var b=a.getSubName(0,c),c=!1,d=0;d<b.size();d++)if("KEY"==b.get(d).toEscapedString()){c=!0;break}if(!c)throw Error("Incorrect identity certificate name "+a.toUri());return b.getSubName(0,d).append(b.getSubName(d+1,b.size()-d-1))};
IdentityCertificate.isCorrectName=function(a){for(var b=a.size()-1;0<=b&&"ID-CERT"!=a.get(b).toEscapedString();b--);if(0>b)return!1;for(b=0;b<a.size()&&"KEY"!=a.get(b).toEscapedString();b++);return b>=a.size()?!1:!0};IdentityCertificate.prototype.setPublicKeyName=function(){this.publicKeyName=IdentityCertificate.certificateNameToPublicKeyName(this.getName())};
var Name=require("../../name.js").Name,SecurityException=require("../security-exception.js").SecurityException,SyncPromise=require("../../util/sync-promise.js").SyncPromise,IdentityStorage=function(){};exports.IdentityStorage=IdentityStorage;IdentityStorage.prototype.doesIdentityExistPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.doesIdentityExistPromise is not implemented"))};
IdentityStorage.prototype.doesIdentityExist=function(a){return SyncPromise.getValue(this.doesIdentityExistPromise(a,!0))};IdentityStorage.prototype.addIdentityPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.addIdentityPromise is not implemented"))};IdentityStorage.prototype.addIdentity=function(a){return SyncPromise.getValue(this.addIdentityPromise(a,!0))};IdentityStorage.prototype.revokeIdentity=function(){return SyncPromise.reject(Error("IdentityStorage.revokeIdentity is not implemented"))};
IdentityStorage.prototype.getNewKeyNamePromise=function(a,b,c){for(var d=Math.floor((new Date).getTime()/1E3);d<=IdentityStorage.lastTimestamp;)d+=1;IdentityStorage.lastTimestamp=d;d=""+d;b=b?"ksk-"+d:"dsk-"+d;var e=(new Name(a)).append(b);return this.doesKeyExistPromise(e,c).then(function(a){if(a)throw new SecurityException(Error("Key name already exists"));return SyncPromise.resolve(e)})};
IdentityStorage.prototype.getNewKeyName=function(a,b){return SyncPromise.getValue(this.getNewKeyNamePromise(a,b,!0))};IdentityStorage.prototype.doesKeyExistPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.doesKeyExistPromise is not implemented"))};IdentityStorage.prototype.doesKeyExist=function(a){return SyncPromise.getValue(this.doesKeyExistPromise(a,!0))};IdentityStorage.prototype.addKeyPromise=function(a,b,c,d){return SyncPromise.reject(Error("IdentityStorage.addKeyPromise is not implemented"))};
IdentityStorage.prototype.addKey=function(a,b,c){return SyncPromise.getValue(this.addKeyPromise(a,b,c,!0))};IdentityStorage.prototype.getKeyPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.getKeyPromise is not implemented"))};IdentityStorage.prototype.getKey=function(a){return SyncPromise.getValue(this.getKeyPromise(a,!0))};IdentityStorage.prototype.activateKey=function(a){throw Error("IdentityStorage.activateKey is not implemented");};
IdentityStorage.prototype.deactivateKey=function(a){throw Error("IdentityStorage.deactivateKey is not implemented");};IdentityStorage.prototype.doesCertificateExistPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.doesCertificateExistPromise is not implemented"))};IdentityStorage.prototype.doesCertificateExist=function(a){return SyncPromise.getValue(this.doesCertificateExistPromise(a,!0))};IdentityStorage.prototype.addCertificatePromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.addCertificatePromise is not implemented"))};
IdentityStorage.prototype.addCertificate=function(a){return SyncPromise.getValue(this.addCertificatePromise(a,!0))};IdentityStorage.prototype.getCertificatePromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.getCertificatePromise is not implemented"))};IdentityStorage.prototype.getCertificate=function(a){return SyncPromise.getValue(this.getValuePromise(a,!0))};IdentityStorage.prototype.getTpmLocatorPromise=function(a){return SyncPromise.reject(Error("IdentityStorage.getTpmLocatorPromise is not implemented"))};
IdentityStorage.prototype.getTpmLocator=function(){return SyncPromise.getValue(this.getTpmLocatorPromise(!0))};IdentityStorage.prototype.getDefaultIdentityPromise=function(a){return SyncPromise.reject(Error("IdentityStorage.getDefaultIdentityPromise is not implemented"))};IdentityStorage.prototype.getDefaultIdentity=function(){return SyncPromise.getValue(this.getDefaultIdentityPromise(!0))};IdentityStorage.prototype.getDefaultKeyNameForIdentityPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.getDefaultKeyNameForIdentityPromise is not implemented"))};
IdentityStorage.prototype.getDefaultKeyNameForIdentity=function(a){return SyncPromise.getValue(this.getDefaultKeyNameForIdentityPromise(a,!0))};IdentityStorage.prototype.getDefaultCertificateNameForIdentityPromise=function(a,b){var c=this;return this.getDefaultKeyNameForIdentityPromise(a).then(function(a){return c.getDefaultCertificateNameForKeyPromise(a)})};
IdentityStorage.prototype.getDefaultCertificateNameForIdentity=function(a){return SyncPromise.getValue(this.getDefaultCertificateNameForIdentityPromise(a,!0))};IdentityStorage.prototype.getDefaultCertificateNameForKeyPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.getDefaultCertificateNameForKeyPromise is not implemented"))};IdentityStorage.prototype.getDefaultCertificateNameForKey=function(a){return SyncPromise.getValue(this.getDefaultCertificateNameForKeyPromise(a,!0))};
IdentityStorage.prototype.getAllIdentitiesPromise=function(a,b,c){return SyncPromise.reject(Error("IdentityStorage.getAllIdentitiesPromise is not implemented"))};IdentityStorage.prototype.getAllKeyNamesOfIdentityPromise=function(a,b,c,d){return SyncPromise.reject(Error("IdentityStorage.getAllKeyNamesOfIdentityPromise is not implemented"))};IdentityStorage.prototype.getAllCertificateNamesOfKeyPromise=function(a,b,c,d){return SyncPromise.reject(Error("IdentityStorage.getAllCertificateNamesOfKeyPromise is not implemented"))};
IdentityStorage.prototype.getAllKeyNamesOfIdentity=function(a,b,c){return SyncPromise.getValue(this.getAllKeyNamesOfIdentityPromise(a,b,c,!0))};IdentityStorage.prototype.setDefaultIdentityPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.setDefaultIdentityPromise is not implemented"))};IdentityStorage.prototype.setDefaultIdentity=function(a){return SyncPromise.getValue(this.setDefaultIdentityPromise(a,!0))};
IdentityStorage.prototype.setDefaultKeyNameForIdentityPromise=function(a,b,c){return SyncPromise.reject(Error("IdentityStorage.setDefaultKeyNameForIdentityPromise is not implemented"))};IdentityStorage.prototype.setDefaultKeyNameForIdentity=function(a,b){return SyncPromise.getValue(this.setDefaultKeyNameForIdentityPromise(a,b,!0))};IdentityStorage.prototype.setDefaultCertificateNameForKeyPromise=function(a,b,c){return SyncPromise.reject(Error("IdentityStorage.setDefaultCertificateNameForKeyPromise is not implemented"))};
IdentityStorage.prototype.setDefaultCertificateNameForKey=function(a,b){return SyncPromise.getValue(this.setDefaultCertificateNameForKeyPromise(a,b,!0))};IdentityStorage.prototype.getDefaultCertificatePromise=function(a){var b=this;return this.getDefaultIdentityPromise(a).then(function(c){return b.getDefaultCertificateNameForIdentityPromise(c,a)},function(a){return SyncPromise.resolve(null)}).then(function(c){return null==c?SyncPromise.resolve(null):b.getCertificatePromise(c,a)})};
IdentityStorage.prototype.getDefaultCertificate=function(){return SyncPromise.getValue(this.getDefaultCertificatePromise(!0))};IdentityStorage.prototype.deleteCertificateInfoPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.deleteCertificateInfoPromise is not implemented"))};IdentityStorage.prototype.deleteCertificateInfo=function(a){return SyncPromise.getValue(this.deleteCertificateInfoPromise(a,!0))};IdentityStorage.prototype.deletePublicKeyInfoPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.deletePublicKeyInfoPromise is not implemented"))};
IdentityStorage.prototype.deletePublicKeyInfo=function(a){return SyncPromise.getValue(this.deletePublicKeyInfoPromise(a,!0))};IdentityStorage.prototype.deleteIdentityInfoPromise=function(a,b){return SyncPromise.reject(Error("IdentityStorage.deleteIdentityInfoPromise is not implemented"))};IdentityStorage.prototype.deleteIdentityInfo=function(a){return SyncPromise.getValue(this.deleteIdentityInfoPromise(a,!0))};IdentityStorage.lastTimestamp=Math.floor((new Date).getTime()/1E3);
var IndexedDbIdentityStorage=function(){IdentityStorage.call(this);this.database=new Dexie("ndnsec-public-info");this.database.version(1).stores({globals:"key",identity:"identityNameUri",publicKey:"keyNameUri",certificate:"certificateNameUri"});this.database.open()};IndexedDbIdentityStorage.prototype=new IdentityStorage;IndexedDbIdentityStorage.prototype.name="IndexedDbIdentityStorage";
IndexedDbIdentityStorage.prototype.doesIdentityExistPromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.doesIdentityExistPromise is only supported for async"))):this.database.identity.where("identityNameUri").equals(a.toUri()).count().then(function(a){return Promise.resolve(0<a)})};
IndexedDbIdentityStorage.prototype.addIdentityPromise=function(a,b){if(b)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.addIdentityPromise is only supported for async")));var c=this;return this.doesIdentityExistPromise(a).then(function(b){return b?Promise.resolve():c.database.identity.put({identityNameUri:a.toUri(),defaultKeyUri:null})})};
IndexedDbIdentityStorage.prototype.doesKeyExistPromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.doesKeyExistPromise is only supported for async"))):this.database.publicKey.where("keyNameUri").equals(a.toUri()).count().then(function(a){return Promise.resolve(0<a)})};
IndexedDbIdentityStorage.prototype.addKeyPromise=function(a,b,c,d){if(d)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.addKeyPromise is only supported for async")));if(0===a.size())return Promise.resolve();var e=this;return this.doesKeyExistPromise(a).then(function(d){if(d)return Promise.resolve();d=a.getPrefix(-1);return e.addIdentityPromise(d).then(function(){return e.database.publicKey.put({keyNameUri:a.toUri(),keyType:b,keyDer:(new Blob(c,!0)).buf(),defaultCertificate:null})})})};
IndexedDbIdentityStorage.prototype.getKeyPromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.getKeyPromise is only supported for async"))):0===a.size()?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage::getKeyPromise: Empty keyName"))):this.database.publicKey.get(a.toUri()).then(function(a){return a?Promise.resolve(new Blob(a.keyDer)):Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage::getKeyPromise: The key does not exist")))})};
IndexedDbIdentityStorage.prototype.doesCertificateExistPromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.doesCertificateExistPromise is only supported for async"))):this.database.certificate.where("certificateNameUri").equals(a.toUri()).count().then(function(a){return Promise.resolve(0<a)})};
IndexedDbIdentityStorage.prototype.addCertificatePromise=function(a,b){if(b)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.addCertificatePromise is only supported for async")));var c=a.getName(),d=a.getPublicKeyName(),e=this;return this.addKeyPromise(d,a.getPublicKeyInfo().getKeyType(),a.getPublicKeyInfo().getKeyDer(),b).then(function(){return e.doesCertificateExistPromise(c)}).then(function(b){return b?Promise.resolve():e.database.certificate.put({certificateNameUri:c.toUri(),
encoding:a.wireEncode().buf()})})};IndexedDbIdentityStorage.prototype.getCertificatePromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.getCertificatePromise is only supported for async"))):this.database.certificate.get(a.toUri()).then(function(a){if(a){var b=new IdentityCertificate;try{b.wireDecode(a.encoding)}catch(e){return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage::getCertificatePromise: The certificate cannot be decoded")))}return Promise.resolve(b)}return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage::getCertificatePromise: The certificate does not exist")))})};
IndexedDbIdentityStorage.prototype.getDefaultIdentityPromise=function(a){return this.database.globals.get("defaultIdentityUri").then(function(a){if(a)return Promise.resolve(new Name(a.value));throw new SecurityException(Error("IndexedDbIdentityStorage.getDefaultIdentity: The default identity is not defined"));})};
IndexedDbIdentityStorage.prototype.getDefaultKeyNameForIdentityPromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.getDefaultKeyNameForIdentityPromise is only supported for async"))):this.database.identity.get(a.toUri()).then(function(a){if(a){if(null!=a.defaultKeyUri)return Promise.resolve(new Name(a.defaultKeyUri));throw new SecurityException(Error("No default key set."));}throw new SecurityException(Error("Identity not found."));})};
IndexedDbIdentityStorage.prototype.getDefaultCertificateNameForKeyPromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.getDefaultCertificateNameForKeyPromise is only supported for async"))):this.database.publicKey.get(a.toUri()).then(function(a){if(a){if(null!=a.defaultCertificateUri)return Promise.resolve(new Name(a.defaultCertificateUri));throw new SecurityException(Error("No default certificate set."));}throw new SecurityException(Error("Key not found."));
})};
IndexedDbIdentityStorage.prototype.getAllIdentitiesPromise=function(a,b,c){if(c)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.getAllIdentitiesPromise is only supported for async")));var d=null,e=this;return this.getDefaultIdentityPromise().then(function(a){d=a;return SyncPromise.resolve()},function(a){return SyncPromise.resolve()}).then(function(){return e.database.identity.each(function(c){c=new Name(c.identityNameUri);var e=null!==d&&c.equals(d);b&&e?a.push(c):b||e||
a.push(c)})})};
IndexedDbIdentityStorage.prototype.getAllKeyNamesOfIdentityPromise=function(a,b,c,d){if(d)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.getAllKeyNamesOfIdentityPromise is only supported for async")));var e=null,f=this;return this.getDefaultKeyNameForIdentityPromise(a).then(function(a){e=a;return SyncPromise.resolve()},function(a){return SyncPromise.resolve()}).then(function(){return f.database.publicKey.each(function(d){d=new Name(d.keyNameUri);if(d.getPrefix(-1).equals(a)){var f=null!==
e&&d.equals(e);c&&f?b.push(d):c||f||b.push(d)}})})};
IndexedDbIdentityStorage.prototype.getAllCertificateNamesOfKeyPromise=function(a,b,c,d){if(d)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.getAllCertificateNamesOfKeyPromise is only supported for async")));var e=null,f=this;return this.getDefaultCertificateNameForKeyPromise(a).then(function(a){e=a;return SyncPromise.resolve()},function(a){return SyncPromise.resolve()}).then(function(){return f.database.certificate.each(function(d){d=new Name(d.certificateNameUri);if(IdentityCertificate.certificateNameToPublicKeyName(d).equals(a)){var f=
null!==e&&d.equals(e);c&&f?b.push(d):c||f||b.push(d)}})})};IndexedDbIdentityStorage.prototype.setDefaultIdentityPromise=function(a,b){if(b)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.setDefaultIdentityPromise is only supported for async")));var c=this;return this.doesIdentityExistPromise(a).then(function(b){return b?c.database.globals.put({key:"defaultIdentityUri",value:a.toUri()}):c.database.globals["delete"]("defaultIdentityUri")})};
IndexedDbIdentityStorage.prototype.setDefaultKeyNameForIdentityPromise=function(a,b,c){c="boolean"===typeof b?b:c;b=b instanceof Name?b:null;if(c)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.setDefaultKeyNameForIdentityPromise is only supported for async")));c=a.getPrefix(-1);return null!=b&&0<b.size()&&!b.equals(c)?Promise.reject(new SecurityException(Error("The specified identity name does not match the key name"))):this.database.identity.update(c.toUri(),{defaultKeyUri:a.toUri()})};
IndexedDbIdentityStorage.prototype.setDefaultCertificateNameForKeyPromise=function(a,b,c){return c?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.setDefaultCertificateNameForKeyPromise is only supported for async"))):this.database.publicKey.update(a.toUri(),{defaultCertificateUri:b.toUri()})};
IndexedDbIdentityStorage.prototype.deleteCertificateInfoPromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.deleteCertificateInfoPromise is only supported for async"))):0===a.size()?Promise.resolve():this.database.certificate["delete"](a.toUri())};
IndexedDbIdentityStorage.prototype.deletePublicKeyInfoPromise=function(a,b){if(b)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.deletePublicKeyInfoPromise is only supported for async")));if(0===a.size())return Promise.resolve();var c=this;return this.database.publicKey["delete"](a.toUri()).then(function(){return c.database.certificate.each(function(b){IdentityCertificate.certificateNameToPublicKeyName(new Name(b.certificateNameUri)).equals(a)&&c.database.certificate["delete"](b.certificateNameUri)})})};
IndexedDbIdentityStorage.prototype.deleteIdentityInfoPromise=function(a,b){if(b)return Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.deleteIdentityInfoPromise is only supported for async")));var c=this;return this.database.identity["delete"](a.toUri()).then(function(){return c.database.publicKey.each(function(b){(new Name(b.keyNameUri)).getPrefix(-1).equals(a)&&c.database.publicKey["delete"](b.keyNameUri)})}).then(function(){return c.database.certificate.each(function(b){IdentityCertificate.certificateNameToPublicKeyName(new Name(b.certificateNameUri)).getPrefix(-1).equals(a)&&
c.database.certificate["delete"](b.certificateNameUri)})})};
var Name=require("../../name.js").Name,Blob=require("../../util/blob.js").Blob,SecurityException=require("../security-exception.js").SecurityException,IdentityCertificate=require("../certificate/identity-certificate.js").IdentityCertificate,SyncPromise=require("../../util/sync-promise.js").SyncPromise,IdentityStorage=require("./identity-storage.js").IdentityStorage,MemoryIdentityStorage=function(){IdentityStorage.call(this);this.identityStore={};this.defaultIdentity="";this.keyStore={};this.certificateStore=
{}};MemoryIdentityStorage.prototype=new IdentityStorage;MemoryIdentityStorage.prototype.name="MemoryIdentityStorage";exports.MemoryIdentityStorage=MemoryIdentityStorage;MemoryIdentityStorage.prototype.doesIdentityExistPromise=function(a){return SyncPromise.resolve(void 0!==this.identityStore[a.toUri()])};MemoryIdentityStorage.prototype.addIdentityPromise=function(a){a=a.toUri();void 0===this.identityStore[a]&&(this.identityStore[a]={defaultKey:null});return SyncPromise.resolve()};
MemoryIdentityStorage.prototype.doesKeyExistPromise=function(a){return SyncPromise.resolve(void 0!==this.keyStore[a.toUri()])};MemoryIdentityStorage.prototype.addKeyPromise=function(a,b,c){if(0===a.size()||this.doesKeyExist(a))return SyncPromise.resolve();var d=a.getSubName(0,a.size()-1);this.addIdentity(d);this.keyStore[a.toUri()]={keyType:b,keyDer:new Blob(c),defaultCertificate:null};return SyncPromise.resolve()};
MemoryIdentityStorage.prototype.getKeyPromise=function(a){if(0===a.size())return SyncPromise.reject(new SecurityException(Error("MemoryIdentityStorage::getKeyPromise: Empty keyName")));a=a.toUri();a=this.keyStore[a];return void 0===a?SyncPromise.reject(new SecurityException(Error("MemoryIdentityStorage::getKeyPromise: The key does not exist"))):SyncPromise.resolve(a.keyDer)};MemoryIdentityStorage.prototype.doesCertificateExistPromise=function(a){return SyncPromise.resolve(void 0!==this.certificateStore[a.toUri()])};
MemoryIdentityStorage.prototype.addCertificatePromise=function(a){var b=a.getName(),c=a.getPublicKeyName();this.addKey(c,a.getPublicKeyInfo().getKeyType(),a.getPublicKeyInfo().getKeyDer());if(this.doesCertificateExist(b))return SyncPromise.resolve();this.certificateStore[b.toUri()]=a.wireEncode();return SyncPromise.resolve()};
MemoryIdentityStorage.prototype.getCertificatePromise=function(a){a=a.toUri();if(void 0===this.certificateStore[a])return SyncPromise.reject(new SecurityException(Error("MemoryIdentityStorage::getCertificatePromise: The certificate does not exist")));var b=new IdentityCertificate;try{b.wireDecode(this.certificateStore[a])}catch(c){return SyncPromise.reject(new SecurityException(Error("MemoryIdentityStorage::getCertificatePromise: The certificate cannot be decoded")))}return SyncPromise.resolve(b)};
IdentityStorage.prototype.getTpmLocatorPromise=function(a){return SyncPromise.resolve("tpm-memory:")};MemoryIdentityStorage.prototype.getDefaultIdentityPromise=function(){return 0===this.defaultIdentity.length?SyncPromise.reject(new SecurityException(Error("MemoryIdentityStorage.getDefaultIdentity: The default identity is not defined"))):SyncPromise.resolve(new Name(this.defaultIdentity))};
MemoryIdentityStorage.prototype.getDefaultKeyNameForIdentityPromise=function(a){a=a.toUri();return void 0!==this.identityStore[a]?null!=this.identityStore[a].defaultKey?SyncPromise.resolve(this.identityStore[a].defaultKey):SyncPromise.reject(new SecurityException(Error("No default key set."))):SyncPromise.reject(new SecurityException(Error("Identity not found.")))};
MemoryIdentityStorage.prototype.getDefaultCertificateNameForKeyPromise=function(a){a=a.toUri();return void 0!==this.keyStore[a]?null!=this.keyStore[a].defaultCertificate?SyncPromise.resolve(this.keyStore[a].defaultCertificate):SyncPromise.reject(new SecurityException(Error("No default certificate set."))):SyncPromise.reject(new SecurityException(Error("Key not found.")))};
MemoryIdentityStorage.prototype.setDefaultIdentityPromise=function(a){a=a.toUri();this.defaultIdentity=void 0!==this.identityStore[a]?a:"";return SyncPromise.resolve()};
MemoryIdentityStorage.prototype.setDefaultKeyNameForIdentityPromise=function(a,b){b=b instanceof Name?b:null;var c=a.getPrefix(-1);if(null!=b&&0<b.size()&&!b.equals(c))return SyncPromise.reject(new SecurityException(Error("The specified identity name does not match the key name")));c=c.toUri();void 0!==this.identityStore[c]&&(this.identityStore[c].defaultKey=new Name(a));return SyncPromise.resolve()};
MemoryIdentityStorage.prototype.setDefaultCertificateNameForKeyPromise=function(a,b){var c=a.toUri();void 0!==this.keyStore[c]&&(this.keyStore[c].defaultCertificate=new Name(b));return SyncPromise.resolve()};MemoryIdentityStorage.prototype.deleteCertificateInfoPromise=function(a){return SyncPromise.reject(Error("MemoryIdentityStorage.deleteCertificateInfoPromise is not implemented"))};MemoryIdentityStorage.prototype.deletePublicKeyInfoPromise=function(a){return SyncPromise.reject(Error("MemoryIdentityStorage.deletePublicKeyInfoPromise is not implemented"))};
MemoryIdentityStorage.prototype.deleteIdentityInfoPromise=function(a){return SyncPromise.reject(Error("MemoryIdentityStorage.deleteIdentityInfoPromise is not implemented"))};var SyncPromise=require("../../util/sync-promise.js").SyncPromise,DerNode=require("../../encoding/der/der-node.js").DerNode,PrivateKeyStorage=function(){};exports.PrivateKeyStorage=PrivateKeyStorage;PrivateKeyStorage.prototype.generateKeyPairPromise=function(a,b,c){return SyncPromise.reject(Error("PrivateKeyStorage.generateKeyPairPromise is not implemented"))};
PrivateKeyStorage.prototype.generateKeyPair=function(a,b){SyncPromise.getValue(this.generateKeyPairPromise(a,b,!0))};PrivateKeyStorage.prototype.deleteKeyPairPromise=function(a,b){return SyncPromise.reject(Error("PrivateKeyStorage.deleteKeyPairPromise is not implemented"))};PrivateKeyStorage.prototype.deleteKeyPair=function(a){SyncPromise.getValue(this.deleteKeyPairPromise(a,!0))};PrivateKeyStorage.prototype.getPublicKeyPromise=function(a,b){return SyncPromise.reject(Error("PrivateKeyStorage.getPublicKeyPromise is not implemented"))};
PrivateKeyStorage.prototype.getPublicKey=function(a){return SyncPromise.getValue(this.getPublicKeyPromise(a,!0))};PrivateKeyStorage.prototype.signPromise=function(a,b,c,d){return SyncPromise.reject(Error("PrivateKeyStorage.sign is not implemented"))};PrivateKeyStorage.prototype.sign=function(a,b,c){return SyncPromise.getValue(this.signPromise(a,b,c,!0))};PrivateKeyStorage.prototype.decrypt=function(a,b,c){throw Error("PrivateKeyStorage.decrypt is not implemented");};
PrivateKeyStorage.prototype.encrypt=function(a,b,c){throw Error("PrivateKeyStorage.encrypt is not implemented");};PrivateKeyStorage.prototype.generateKey=function(a,b){throw Error("PrivateKeyStorage.generateKey is not implemented");};PrivateKeyStorage.prototype.doesKeyExistPromise=function(a,b,c){return SyncPromise.reject(Error("PrivateKeyStorage.doesKeyExist is not implemented"))};PrivateKeyStorage.prototype.doesKeyExist=function(a,b){return SyncPromise.getValue(this.doesKeyExistPromise(a,b,!0))};
PrivateKeyStorage.encodePkcs8PrivateKey=function(a,b,c){var d=new DerNode.DerSequence;d.addChild(new DerNode.DerOid(b));d.addChild(c);b=new DerNode.DerSequence;b.addChild(new DerNode.DerInteger(0));b.addChild(d);b.addChild(new DerNode.DerOctetString(a));return b.encode()};
PrivateKeyStorage.encodePkcs1PrivateKeyFromRSAKey=function(a){var b=new DerNode.DerSequence;b.addChild(new DerNode.DerInteger(0));b.addChild(new DerNode.DerInteger(PrivateKeyStorage.bigIntegerToBuffer(a.n)));b.addChild(new DerNode.DerInteger(a.e));b.addChild(new DerNode.DerInteger(PrivateKeyStorage.bigIntegerToBuffer(a.d)));b.addChild(new DerNode.DerInteger(PrivateKeyStorage.bigIntegerToBuffer(a.p)));b.addChild(new DerNode.DerInteger(PrivateKeyStorage.bigIntegerToBuffer(a.q)));b.addChild(new DerNode.DerInteger(PrivateKeyStorage.bigIntegerToBuffer(a.dmp1)));
b.addChild(new DerNode.DerInteger(PrivateKeyStorage.bigIntegerToBuffer(a.dmq1)));b.addChild(new DerNode.DerInteger(PrivateKeyStorage.bigIntegerToBuffer(a.coeff)));return b.encode()};
PrivateKeyStorage.encodePublicKeyFromRSAKey=function(a){var b=new DerNode.DerSequence;b.addChild(new DerNode.DerInteger(PrivateKeyStorage.bigIntegerToBuffer(a.n)));b.addChild(new DerNode.DerInteger(a.e));a=new DerNode.DerSequence;a.addChild(new DerNode.DerOid(new OID(PrivateKeyStorage.RSA_ENCRYPTION_OID)));a.addChild(new DerNode.DerNull);var c=new DerNode.DerSequence;c.addChild(a);c.addChild(new DerNode.DerBitString(b.encode().buf(),0));return c.encode()};
PrivateKeyStorage.bigIntegerToBuffer=function(a){a=a.toString(16);if("-"==a.substr(0,1))throw Error("PrivateKeyStorage.bigIntegerToBuffer: Negative integers are not currently supported");1==a.length%2?a="0"+a:a.match(/^[0-7]/)||(a="00"+a);return new Buffer(a,"hex")};PrivateKeyStorage.RSA_ENCRYPTION_OID="1.2.840.113549.1.1.1";PrivateKeyStorage.EC_ENCRYPTION_OID="1.2.840.10045.2.1";
var Crypto=require("../../crypto.js"),Blob=require("../../util/blob.js").Blob,SecurityException=require("../security-exception.js").SecurityException,PublicKey=require("../certificate/public-key.js").PublicKey,KeyClass=require("../security-types.js").KeyClass,KeyType=require("../security-types").KeyType,DigestAlgorithm=require("../security-types.js").DigestAlgorithm,DataUtils=require("../../encoding/data-utils.js").DataUtils,PrivateKeyStorage=require("./private-key-storage.js").PrivateKeyStorage,
DerNode=require("../../encoding/der/der-node.js").DerNode,OID=require("../../encoding/oid.js").OID,SyncPromise=require("../../util/sync-promise.js").SyncPromise,UseSubtleCrypto=require("../../use-subtle-crypto-node.js").UseSubtleCrypto,rsaKeygen=null;try{rsaKeygen=require("rsa-keygen")}catch(e$$44){}var MemoryPrivateKeyStorage=function(){PrivateKeyStorage.call(this);this.publicKeyStore={};this.privateKeyStore={}};MemoryPrivateKeyStorage.prototype=new PrivateKeyStorage;
MemoryPrivateKeyStorage.prototype.name="MemoryPrivateKeyStorage";exports.MemoryPrivateKeyStorage=MemoryPrivateKeyStorage;MemoryPrivateKeyStorage.prototype.setPublicKeyForKeyName=function(a,b,c){this.publicKeyStore[a.toUri()]=new PublicKey(new Blob(c,!0))};
MemoryPrivateKeyStorage.prototype.setPrivateKeyForKeyName=function(a,b,c){c=c.toString("base64");var d;if(b===KeyType.RSA){d="-----BEGIN RSA PRIVATE KEY-----\n";for(var e=0;e<c.length;e+=64)d+=c.substr(e,64)+"\n";d+="-----END RSA PRIVATE KEY-----"}else if(b===KeyType.ECDSA){d="-----BEGIN EC PRIVATE KEY-----\n";for(e=0;e<c.length;e+=64)d+=c.substr(e,64)+"\n";d+="-----END EC PRIVATE KEY-----"}else throw new SecurityException(Error("MemoryPrivateKeyStorage: KeyType is not supported"));this.privateKeyStore[a.toUri()]=
{keyType:b,privateKey:d}};MemoryPrivateKeyStorage.prototype.setKeyPairForKeyName=function(a,b,c,d){this.setPublicKeyForKeyName(a,b,c);this.setPrivateKeyForKeyName(a,b,d)};
MemoryPrivateKeyStorage.prototype.generateKeyPairPromise=function(a,b,c){if(this.doesKeyExist(a,KeyClass.PUBLIC))return SyncPromise.reject(new SecurityException(Error("Public key already exists")));if(this.doesKeyExist(a,KeyClass.PRIVATE))return SyncPromise.reject(new SecurityException(Error("Private key already exists")));var d=this;if(UseSubtleCrypto()&&!c){if(b.getKeyType()===KeyType.RSA){var e=null,f=null;return crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:b.getKeySize(),
publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){e=a.privateKey;return crypto.subtle.exportKey("spki",a.publicKey)}).then(function(a){f=(new Blob(new Uint8Array(a),!1)).buf();return crypto.subtle.exportKey("pkcs8",e)}).then(function(c){c=DerNode.parse((new Blob(new Uint8Array(c),!1)).buf()).getChildren()[2].toVal();d.setKeyPairForKeyName(a,b.getKeyType(),f,c.buf());d.privateKeyStore[a.toUri()].subtleKey=e;return Promise.resolve()})}return SyncPromise.reject(new SecurityException(Error("Only RSA key generation currently supported")))}return SyncPromise.resolve().then(function(){if("undefined"!==
typeof RSAKey)if(b.getKeyType()===KeyType.RSA){var c=new RSAKey;c.generate(b.getKeySize(),"010001");d.setKeyPairForKeyName(a,b.getKeyType(),PrivateKeyStorage.encodePublicKeyFromRSAKey(c).buf(),PrivateKeyStorage.encodePkcs1PrivateKeyFromRSAKey(c).buf())}else return SyncPromise.reject(new SecurityException(Error("Only RSA key generation currently supported")));else{var e;if(b.getKeyType()===KeyType.RSA){if(!rsaKeygen)return SyncPromise.reject(new SecurityException(Error("Need to install rsa-keygen: sudo npm install rsa-keygen")));
e=rsaKeygen.generate(b.getKeySize());c=e.public_key.toString().replace("-----BEGIN PUBLIC KEY-----","").replace("-----END PUBLIC KEY-----","");c=new Buffer(c,"base64");e=e.private_key.toString()}else return SyncPromise.reject(new SecurityException(Error("Only RSA key generation currently supported")));d.setPublicKeyForKeyName(a,b.getKeyType(),c);d.privateKeyStore[a.toUri()]={keyType:b.getKeyType(),privateKey:e}}return SyncPromise.resolve()})};
MemoryPrivateKeyStorage.prototype.deleteKeyPairPromise=function(a){a=a.toUri();delete this.publicKeyStore[a];delete this.privateKeyStore[a];return SyncPromise.resolve()};MemoryPrivateKeyStorage.prototype.getPublicKeyPromise=function(a){var b=a.toUri(),b=this.publicKeyStore[b];return void 0===b?SyncPromise.reject(new SecurityException(Error("MemoryPrivateKeyStorage: Cannot find public key "+a.toUri()))):SyncPromise.resolve(b)};
MemoryPrivateKeyStorage.prototype.signPromise=function(a,b,c,d){d="boolean"===typeof c?c:d;c="boolean"!==typeof c&&c?c:DigestAlgorithm.SHA256;if(c!=DigestAlgorithm.SHA256)return SyncPromise.reject(new SecurityException(Error("MemoryPrivateKeyStorage.sign: Unsupported digest algorithm")));b=b.toUri();var e=this.privateKeyStore[b];if(void 0===e)return SyncPromise.reject(new SecurityException(Error("MemoryPrivateKeyStorage: Cannot find private key "+b)));if(UseSubtleCrypto()&&!d){var f={name:"RSASSA-PKCS1-v1_5",
hash:{name:"SHA-256"}};e.subtleKey?d=crypto.subtle.sign(f,e.subtleKey,a):(d=DataUtils.privateKeyPemToDer(e.privateKey),d=PrivateKeyStorage.encodePkcs8PrivateKey(d,new OID(PrivateKeyStorage.RSA_ENCRYPTION_OID),new DerNode.DerNull).buf(),d=crypto.subtle.importKey("pkcs8",d.buffer,f,!0,["sign"]).then(function(b){e.subtleKey=b;return crypto.subtle.sign(f,b,a)}));return d.then(function(a){a=new Blob(new Uint8Array(a),!0);return Promise.resolve(a)})}if(e.keyType===KeyType.RSA)d=Crypto.createSign("RSA-SHA256");
else if(e.keyType===KeyType.ECDSA)d=Crypto.createSign("sha256");else return SyncPromise.reject(new SecurityException(Error("MemoryPrivateKeyStorage.sign: Unrecognized private key type")));d.update(a);d=new Buffer(DataUtils.toNumbersIfString(d.sign(e.privateKey)));d=new Blob(d,!1);return SyncPromise.resolve(d)};
MemoryPrivateKeyStorage.prototype.doesKeyExistPromise=function(a,b){var c=a.toUri(),d=!1;b==KeyClass.PUBLIC?d=void 0!==this.publicKeyStore[c]:b==KeyClass.PRIVATE&&(d=void 0!==this.privateKeyStore[c]);return SyncPromise.resolve(d)};var Crypto=require("../../crypto.js"),IndexedDbPrivateKeyStorage=function(){PrivateKeyStorage.call(this);this.database=new Dexie("ndnsec-tpm");this.database.version(1).stores({publicKey:"nameHash",privateKey:"nameHash"});this.database.open()};
IndexedDbPrivateKeyStorage.prototype=new PrivateKeyStorage;IndexedDbPrivateKeyStorage.prototype.name="IndexedDbPrivateKeyStorage";
IndexedDbPrivateKeyStorage.prototype.generateKeyPairPromise=function(a,b,c){if(c)return Promise.reject(new SecurityException(Error("IndexedDbPrivateKeyStorage.generateKeyPairPromise is only supported for async")));var d=this;return d.doesKeyExistPromise(a,KeyClass.PUBLIC).then(function(b){if(b)throw Error("Public key already exists");return d.doesKeyExistPromise(a,KeyClass.PRIVATE)}).then(function(c){if(c)throw Error("Private key already exists");if(b.getKeyType()===KeyType.RSA){var f=null,g=null;
return crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:b.getKeySize(),publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){f=a.privateKey;return crypto.subtle.exportKey("spki",a.publicKey)}).then(function(a){g=new Uint8Array(a);return crypto.subtle.exportKey("pkcs8",f)}).then(function(b){return d.database.transaction("rw",d.database.privateKey,d.database.publicKey,function(){d.database.publicKey.put({nameHash:IndexedDbPrivateKeyStorage.transformName(a),
encoding:g});d.database.privateKey.put({nameHash:IndexedDbPrivateKeyStorage.transformName(a),encoding:new Uint8Array(b)})})})}throw Error("Only RSA key generation currently supported");})};IndexedDbPrivateKeyStorage.prototype.deleteKeyPairPromise=function(a,b){if(b)return Promise.reject(new SecurityException(Error("IndexedDbPrivateKeyStorage.deleteKeyPairPromise is only supported for async")));var c=this;return this.database.publicKey["delete"](IndexedDbPrivateKeyStorage.transformName(a)).then(function(){return c.database.privateKey["delete"](IndexedDbPrivateKeyStorage.transformName(a))})};
IndexedDbPrivateKeyStorage.prototype.getPublicKeyPromise=function(a,b){return b?Promise.reject(new SecurityException(Error("IndexedDbPrivateKeyStorage.getPublicKeyPromise is only supported for async"))):this.database.publicKey.get(IndexedDbPrivateKeyStorage.transformName(a)).then(function(a){return Promise.resolve(new PublicKey(new Blob(a.encoding)))})};
IndexedDbPrivateKeyStorage.prototype.signPromise=function(a,b,c,d){d="boolean"===typeof c?c:d;c="boolean"!==typeof c&&c?c:DigestAlgorithm.SHA256;if(d)return Promise.reject(new SecurityException(Error("IndexedDbPrivateKeyStorage.signPromise is only supported for async")));if(c!=DigestAlgorithm.SHA256)return Promise.reject(new SecurityException(Error("IndexedDbPrivateKeyStorage.sign: Unsupported digest algorithm")));var e={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};return this.database.privateKey.get(IndexedDbPrivateKeyStorage.transformName(b)).then(function(a){return crypto.subtle.importKey("pkcs8",
(new Blob(a.encoding)).buf(),e,!0,["sign"])}).then(function(b){return crypto.subtle.sign(e,b,a)}).then(function(a){return Promise.resolve(new Blob(new Uint8Array(a),!0))})};
IndexedDbPrivateKeyStorage.prototype.doesKeyExistPromise=function(a,b,c){if(c)return Promise.reject(new SecurityException(Error("IndexedDbPrivateKeyStorage.doesKeyExistPromise is only supported for async")));c=null;if(b==KeyClass.PUBLIC)c=this.database.publicKey;else if(b==KeyClass.PRIVATE)c=this.database.privateKey;else return Promise.resolve(!1);return c.where("nameHash").equals(IndexedDbPrivateKeyStorage.transformName(a)).count().then(function(a){return Promise.resolve(0<a)})};
IndexedDbPrivateKeyStorage.transformName=function(a){var b=Crypto.createHash("sha256");b.update(new Buffer(a.toUri()));return b.digest("base64").replace(/\//g,"%")};
var Crypto=require("../../crypto.js"),Name=require("../../name.js").Name,Data=require("../../data.js").Data,Blob=require("../../util/blob.js").Blob,ConfigFile=require("../../util/config-file.js").ConfigFile,DigestSha256Signature=require("../../digest-sha256-signature.js").DigestSha256Signature,Sha256WithRsaSignature=require("../../sha256-with-rsa-signature.js").Sha256WithRsaSignature,Sha256WithEcdsaSignature=require("../../sha256-with-ecdsa-signature.js").Sha256WithEcdsaSignature,KeyLocatorType=require("../../key-locator.js").KeyLocatorType,
WireFormat=require("../../encoding/wire-format.js").WireFormat,SecurityException=require("../security-exception.js").SecurityException,DigestAlgorithm=require("../security-types.js").DigestAlgorithm,KeyType=require("../security-types.js").KeyType,RsaKeyParams=require("../key-params.js").RsaKeyParams,IdentityCertificate=require("../certificate/identity-certificate.js").IdentityCertificate,PublicKey=require("../certificate/public-key.js").PublicKey,CertificateSubjectDescription=require("../certificate/certificate-subject-description.js").CertificateSubjectDescription,
SyncPromise=require("../../util/sync-promise.js").SyncPromise,BasicIdentityStorage=require("./basic-identity-storage.js").BasicIdentityStorage,FilePrivateKeyStorage=require("./file-private-key-storage.js").FilePrivateKeyStorage,IdentityManager=function IdentityManager(b,c){if(c){if(!b)throw Error("IdentityManager: A custom privateKeyStorage is supplied with a null identityStorage");this.identityStorage=b;this.privateKeyStorage=c}else{if(!ConfigFile)throw new SecurityException(Error("IdentityManager: If not in Node.js then you must supply identityStorage and privateKeyStorage."));
var d=new ConfigFile,e=[null],f=this;this.identityStorage=b?b:IdentityManager.getDefaultIdentityStorage_(d,function(){return f.checkTpmPromise_(e[0])});this.privateKeyStorage=IdentityManager.getDefaultPrivateKeyStorage_(d,e)}};exports.IdentityManager=IdentityManager;
IdentityManager.prototype.createIdentityAndCertificatePromise=function(a,b,c){var d=this,e=!0,f=null;return this.identityStorage.addIdentityPromise(a,c).then(function(){return d.identityStorage.getDefaultKeyNameForIdentityPromise(a,c).then(function(a){f=a;return d.identityStorage.getKeyPromise(f,c).then(function(a){(new PublicKey(a)).getKeyType()==b.getKeyType()&&(e=!1);return SyncPromise.resolve()})},function(a){if(!(a instanceof SecurityException))throw a;return SyncPromise.resolve()})}).then(function(){return e?
d.generateKeyPairPromise(a,!0,b,c).then(function(a){f=a;return d.identityStorage.setDefaultKeyNameForIdentityPromise(f,c)}):SyncPromise.resolve()}).then(function(){return d.identityStorage.getDefaultCertificateNameForKeyPromise(f,c).then(function(a){return SyncPromise.resolve(a)},function(a){if(!(a instanceof SecurityException))throw a;var b;return d.selfSignPromise(f,c).then(function(a){b=a.getName();return d.addCertificateAsIdentityDefaultPromise(a,c)}).then(function(){return SyncPromise.resolve(b)})})})};
IdentityManager.prototype.createIdentityAndCertificate=function(a,b,c,d){return SyncPromise.complete(c,d,this.createIdentityAndCertificatePromise(a,b,!c))};IdentityManager.prototype.createIdentity=function(a,b){return IdentityCertificate.certificateNameToPublicKeyName(this.createIdentityAndCertificate(a,b))};
IdentityManager.prototype.deleteIdentity=function(a,b,c){var d=this,e=!0,f=this.identityStorage.getDefaultIdentityPromise(!b).then(function(b){b.equals(a)&&(e=!1);return SyncPromise.resolve()},function(a){return SyncPromise.resolve()}).then(function(){if(!e)return SyncPromise.resolve();var b=[];return d.identityStorage.getAllKeyNamesOfIdentityPromise(a,b,!0).then(function(){return d.identityStorage.getAllKeyNamesOfIdentityPromise(a,b,!1)}).then(function(){return d.identityStorage.deleteIdentityInfoPromise(a)}).then(function(){function a(c){return c>=
b.length?SyncPromise.resolve():d.privateKeyStorage.deleteKeyPairPromise(b[c]).then(function(){return a(c+1)})}return a(0)})});return SyncPromise.complete(b,c,f)};IdentityManager.prototype.setDefaultIdentityPromise=function(a,b){return this.identityStorage.setDefaultIdentityPromise(a,b)};IdentityManager.prototype.setDefaultIdentity=function(a,b,c){return SyncPromise.complete(b,c,this.identityStorage.setDefaultIdentityPromise(a,!b))};IdentityManager.prototype.getDefaultIdentityPromise=function(a){return this.identityStorage.getDefaultIdentityPromise(a)};
IdentityManager.prototype.getDefaultIdentity=function(a,b){return SyncPromise.complete(a,b,this.identityStorage.getDefaultIdentityPromise(!a))};IdentityManager.prototype.getDefaultCertificatePromise=function(a){return this.identityStorage.getDefaultCertificatePromise(a)};IdentityManager.prototype.generateRSAKeyPair=function(a,b,c){return SyncPromise.getValue(this.generateKeyPairPromise(a,b,new RsaKeyParams(c),!0))};
IdentityManager.prototype.setDefaultKeyForIdentity=function(a,b,c,d){d="function"===typeof b?c:d;c="function"===typeof b?b:c;b="function"!==typeof b&&b?b:new Name;return SyncPromise.complete(c,d,this.identityStorage.setDefaultKeyNameForIdentityPromise(a,b,!c))};IdentityManager.prototype.getDefaultKeyNameForIdentity=function(a,b,c){return SyncPromise.complete(b,c,this.identityStorage.getDefaultKeyNameForIdentityPromise(a,!b))};
IdentityManager.prototype.generateRSAKeyPairAsDefaultPromise=function(a,b,c,d){var e,f=this;return this.generateKeyPairPromise(a,b,new RsaKeyParams(c)).then(function(a){e=a;return f.identityStorage.setDefaultKeyNameForIdentityPromise(e)}).then(function(){return SyncPromise.resolve(e)})};IdentityManager.prototype.generateRSAKeyPairAsDefault=function(a,b,c){return SyncPromise.getValue(this.generateRSAKeyPairAsDefaultPromise(a,b,c,!0))};
IdentityManager.prototype.getPublicKey=function(a,b,c){return SyncPromise.complete(b,c,this.identityStorage.getKeyPromise(a,!b).then(function(a){return SyncPromise.resolve(new PublicKey(a))}))};
IdentityManager.prototype.prepareUnsignedIdentityCertificate=function(a,b,c,d,e,f,g,h,k){b instanceof PublicKey||(k=h,h=g,g=f,f=e,e=d,d=c,c=b,b=null);var l=g,m=h;g=l instanceof Name?l:null;"function"===typeof l?(h=l,k=m):"function"===typeof m?h=m:k=h=null;a=null==b?this.prepareUnsignedIdentityCertificatePromise(a,c,d,e,f,g,!h):this.prepareUnsignedIdentityCertificatePromise(a,b,c,d,e,f,g,!h);return SyncPromise.complete(h,k,a)};
IdentityManager.prototype.prepareUnsignedIdentityCertificatePromise=function(a,b,c,d,e,f,g,h){b instanceof PublicKey||(h=g,g=f,f=e,e=d,d=c,c=b,b=null);var k=g;g=k instanceof Name?k:null;return(null==b?this.identityStorage.getKeyPromise(a,"boolean"===typeof k?k:"boolean"===typeof h?h:!1).then(function(a){b=new PublicKey(a);return SyncPromise.resolve()}):SyncPromise.resolve()).then(function(){return SyncPromise.resolve(IdentityManager.prepareUnsignedIdentityCertificateHelper_(a,b,c,d,e,f,g))})};
IdentityManager.prepareUnsignedIdentityCertificateHelper_=function(a,b,c,d,e,f,g){if(1>a.size())return null;var h=a.get(-1).toEscapedString();if(4>h.length)return null;keyIdPrefix=h.substr(0,4);if("ksk-"!=keyIdPrefix&&"dsk-"!=keyIdPrefix)return null;var h=new IdentityCertificate,k=new Name;if(null==g)c.match(a)?k.append(c).append("KEY").append(a.getSubName(c.size())).append("ID-CERT").appendVersion((new Date).getTime()):k.append(a.getPrefix(-1)).append("KEY").append(a.get(-1)).append("ID-CERT").appendVersion((new Date).getTime());
else if(g.match(a)&&!g.equals(a))k.append(g).append("KEY").append(a.getSubName(g.size())).append("ID-CERT").appendVersion((new Date).getTime());else return null;h.setName(k);h.setNotBefore(d);h.setNotAfter(e);h.setPublicKeyInfo(b);if(null==f||0===f.length)h.addSubjectDescription(new CertificateSubjectDescription("2.5.4.41",a.getPrefix(-1).toUri()));else for(a=0;a<f.length;++a)h.addSubjectDescription(f[a]);try{h.encode()}catch(l){throw SecurityException(Error("DerEncodingException: "+l));}return h};
IdentityManager.prototype.addCertificate=function(a,b,c){return SyncPromise.complete(b,c,this.identityStorage.addCertificatePromise(a,!b))};IdentityManager.prototype.setDefaultCertificateForKeyPromise=function(a,b){var c=this,d=a.getPublicKeyName();return this.identityStorage.doesKeyExistPromise(d,b).then(function(e){if(!e)throw new SecurityException(Error("No corresponding Key record for certificate!"));return c.identityStorage.setDefaultCertificateNameForKeyPromise(d,a.getName(),b)})};
IdentityManager.prototype.setDefaultCertificateForKey=function(a,b,c){return SyncPromise.complete(b,c,this.setDefaultCertificateForKeyPromise(a,!b))};IdentityManager.prototype.addCertificateAsIdentityDefaultPromise=function(a,b){var c=this;return this.identityStorage.addCertificatePromise(a,b).then(function(){var d=a.getPublicKeyName();return c.identityStorage.setDefaultKeyNameForIdentityPromise(d,b)}).then(function(){return c.setDefaultCertificateForKeyPromise(a,b)})};
IdentityManager.prototype.addCertificateAsDefault=function(a,b,c){var d=!b,e=this;return SyncPromise.complete(b,c,this.identityStorage.addCertificatePromise(a,d).then(function(){return e.setDefaultCertificateForKeyPromise(a,d)}))};IdentityManager.prototype.getCertificate=function(a,b,c){return SyncPromise.complete(b,c,this.identityStorage.getCertificatePromise(a,!1,!b))};
IdentityManager.prototype.getDefaultCertificateNameForIdentityPromise=function(a,b){return this.identityStorage.getDefaultCertificateNameForIdentityPromise(a,b)};IdentityManager.prototype.getDefaultCertificateNameForIdentity=function(a,b,c){return SyncPromise.complete(b,c,this.identityStorage.getDefaultCertificateNameForIdentityPromise(a,!b))};
IdentityManager.prototype.getDefaultCertificateName=function(a,b){var c=!a,d=this;return SyncPromise.complete(a,b,this.identityStorage.getDefaultIdentityPromise(c).then(function(a){return d.identityStorage.getDefaultCertificateNameForIdentityPromise(a,c)}))};IdentityManager.prototype.getAllIdentities=function(a,b,c,d){return SyncPromise.complete(c,d,this.identityStorage.getAllIdentitiesPromise(a,b,!c))};
IdentityManager.prototype.getAllKeyNamesOfIdentity=function(a,b,c,d,e){return SyncPromise.complete(d,e,this.identityStorage.getAllKeyNamesOfIdentityPromise(a,b,c,!d))};IdentityManager.prototype.getAllCertificateNamesOfKey=function(a,b,c,d,e){return SyncPromise.complete(d,e,this.identityStorage.getAllCertificateNamesOfKeyPromise(a,b,c,!d))};
IdentityManager.prototype.signByCertificatePromise=function(a,b,c,d){d="boolean"===typeof c?c:d;c="boolean"!==typeof c&&c?c:WireFormat.getDefaultWireFormat();var e=IdentityManager.certificateNameToPublicKeyName(b),f=this;if(a instanceof Data){var g=[0];return this.makeSignatureByCertificatePromise(b,g,d).then(function(b){a.setSignature(b);b=a.wireEncode(c);return f.privateKeyStorage.signPromise(b.signedBuf(),e,g[0],d)}).then(function(b){a.getSignature().setSignature(b);a.wireEncode(c);return SyncPromise.resolve(a)})}g=
[0];return this.makeSignatureByCertificatePromise(b,g,d).then(function(b){return f.privateKeyStorage.signPromise(a,e,g[0],d)}).then(function(a){signature.setSignature(a);return SyncPromise.resolve(signature)})};IdentityManager.prototype.signByCertificate=function(a,b,c,d,e){e="function"===typeof c?d:e;d="function"===typeof c?c:d;c="function"!==typeof c&&c?c:WireFormat.getDefaultWireFormat();return SyncPromise.complete(d,e,this.signByCertificatePromise(a,b,c,!d))};
IdentityManager.prototype.signInterestByCertificatePromise=function(a,b,c,d){d="boolean"===typeof c?c:d;c="boolean"!==typeof c&&c?c:WireFormat.getDefaultWireFormat();var e=this,f,g=[0];return this.makeSignatureByCertificatePromise(b,g,d).then(function(h){f=h;a.getName().append(c.encodeSignatureInfo(f));a.getName().append(new Name.Component);h=a.wireEncode(c);var k=IdentityManager.certificateNameToPublicKeyName(b);return e.privateKeyStorage.signPromise(h.signedBuf(),k,g[0],d)}).then(function(b){f.setSignature(b);
a.setName(a.getName().getPrefix(-1).append(c.encodeSignatureValue(f)));return SyncPromise.resolve(a)})};IdentityManager.prototype.signInterestByCertificate=function(a,b,c,d,e){e="function"===typeof c?d:e;d="function"===typeof c?c:d;c="function"!==typeof c&&c?c:WireFormat.getDefaultWireFormat();return SyncPromise.complete(d,e,this.signInterestByCertificatePromise(a,b,c,!d))};
IdentityManager.prototype.signWithSha256=function(a,b){b=b||WireFormat.getDefaultWireFormat();a.setSignature(new DigestSha256Signature);var c=a.wireEncode(b),d=Crypto.createHash("sha256");d.update(c.signedBuf());a.getSignature().setSignature(new Blob(d.digest(),!1));a.wireEncode(b)};
IdentityManager.prototype.signInterestWithSha256=function(a,b){b=b||WireFormat.getDefaultWireFormat();var c=new DigestSha256Signature;a.getName().append(b.encodeSignatureInfo(c));a.getName().append(new Name.Component);var d=a.wireEncode(b),e=Crypto.createHash("sha256");e.update(d.signedBuf());c.setSignature(new Blob(e.digest(),!1));a.setName(a.getName().getPrefix(-1).append(b.encodeSignatureValue(c)))};
IdentityManager.prototype.selfSignPromise=function(a,b){var c=new IdentityCertificate,d=this;return this.identityStorage.getKeyPromise(a,b).then(function(e){e=new PublicKey(e);var f=(new Date).getTime(),g=f+63072E6;c.setNotBefore(f);c.setNotAfter(g);f=a.getPrefix(-1).append("KEY").append(a.get(-1)).append("ID-CERT").appendVersion(c.getNotBefore());c.setName(f);c.setPublicKeyInfo(e);c.addSubjectDescription(new CertificateSubjectDescription("2.5.4.41",a.toUri()));c.encode();return d.signByCertificatePromise(c,
c.getName(),b)})};IdentityManager.prototype.selfSign=function(a,b,c){return SyncPromise.complete(b,c,this.selfSignPromise(a,!b))};IdentityManager.certificateNameToPublicKeyName=function(a){for(var b=a.size()-1;0<=b&&"ID-CERT"!=a.get(b).toEscapedString();)--b;a=a.getSubName(0,b);for(b=0;b<a.size()&&"KEY"!=a.get(b).toEscapedString();)++b;return a.getSubName(0,b).append(a.getSubName(b+1,a.size()-b-1))};
IdentityManager.prototype.makeSignatureByCertificatePromise=function(a,b,c){var d=IdentityManager.certificateNameToPublicKeyName(a);return this.privateKeyStorage.getPublicKeyPromise(d,c).then(function(c){c=c.getKeyType();var d=null;if(c==KeyType.RSA)d=new Sha256WithRsaSignature,b[0]=DigestAlgorithm.SHA256,d.getKeyLocator().setType(KeyLocatorType.KEYNAME),d.getKeyLocator().setKeyName(a.getPrefix(-1));else if(c==KeyType.ECDSA)d=new Sha256WithEcdsaSignature,b[0]=DigestAlgorithm.SHA256,d.getKeyLocator().setType(KeyLocatorType.KEYNAME),
d.getKeyLocator().setKeyName(a.getPrefix(-1));else throw new SecurityException(Error("Key type is not recognized"));return SyncPromise.resolve(d)})};
IdentityManager.prototype.generateKeyPairPromise=function(a,b,c,d){var e,f=this;return this.identityStorage.getNewKeyNamePromise(a,b,d).then(function(a){e=a;return f.privateKeyStorage.generateKeyPairPromise(e,c,d)}).then(function(){return f.privateKeyStorage.getPublicKeyPromise(e,d)}).then(function(a){return f.identityStorage.addKeyPromise(e,c.getKeyType(),a.getKeyDer())}).then(function(){return SyncPromise.resolve(e)})};
IdentityManager.getDefaultIdentityStorage_=function(a,b){var c=a.get("pib","");if(""!==c&&"pib-sqlite3"!==c)throw new SecurityException(Error("Invalid config file pib value: "+c));return new BasicIdentityStorage(b)};
IdentityManager.getDefaultPrivateKeyStorage_=function(a,b){var c=a.get("tpm","");if(""===c){if("darwin"===process.platform)throw b[0]="tpm-osxkeychain:",new SecurityException(Error("IdentityManager: OS X key chain storage is not yet implemented. You must supply a privateKeyStorage."));b[0]="tpm-file:";return new FilePrivateKeyStorage}if("tpm-osxkeychain"===c)throw b[0]="tpm-osxkeychain:",new SecurityException(Error("IdentityManager: tpm-osxkeychain is not yet implemented."));if("tpm-file"===c)return b[0]=
"tpm-file:",new FilePrivateKeyStorage;throw new SecurityException(Error("Invalid config file tpm value: "+c));};IdentityManager.prototype.checkTpmPromise_=function(a){return this.identityStorage.getTpmLocatorPromise().then(function(b){return""!==b&&b!==a?Promise.reject(new SecurityException(Error("The TPM locator supplied does not match the TPM locator in the PIB: "+b+" != "+a))):Promise.resolve()},function(a){return Promise.resolve()})};
var ValidationRequest=function(a,b,c,d,e){this.interest=a;this.onVerified=b;this.onValidationFailed=c;this.retry=d;this.stepCount=e};exports.ValidationRequest=ValidationRequest;
var Crypto=require("../../crypto.js"),Blob=require("../../util/blob.js").Blob,DataUtils=require("../../encoding/data-utils.js").DataUtils,SecurityException=require("../security-exception.js").SecurityException,DigestSha256Signature=require("../../digest-sha256-signature.js").DigestSha256Signature,Sha256WithRsaSignature=require("../../sha256-with-rsa-signature.js").Sha256WithRsaSignature,Sha256WithEcdsaSignature=require("../../sha256-with-ecdsa-signature.js").Sha256WithEcdsaSignature,UseSubtleCrypto=
require("../../use-subtle-crypto-node.js").UseSubtleCrypto,PolicyManager=function(){};exports.PolicyManager=PolicyManager;PolicyManager.prototype.skipVerifyAndTrust=function(a){throw Error("PolicyManager.skipVerifyAndTrust is not implemented");};PolicyManager.prototype.requireVerify=function(a){throw Error("PolicyManager.requireVerify is not implemented");};PolicyManager.prototype.checkVerificationPolicy=function(a,b,c,d,e){throw Error("PolicyManager.checkVerificationPolicy is not implemented");};
PolicyManager.prototype.checkSigningPolicy=function(a,b){throw Error("PolicyManager.checkSigningPolicy is not implemented");};PolicyManager.prototype.inferSigningIdentity=function(a){throw Error("PolicyManager.inferSigningIdentity is not implemented");};PolicyManager.verifyUsesString_=null;PolicyManager.setVerifyUsesString_=function(){var a=Crypto.createHash("sha256").digest();PolicyManager.verifyUsesString_="string"===typeof a};
PolicyManager.verifySignature=function(a,b,c,d){if(a instanceof Sha256WithRsaSignature)c.isNull()?d(!1):PolicyManager.verifySha256WithRsaSignature(a.getSignature(),b,c,d);else if(a instanceof Sha256WithEcdsaSignature)c.isNull()?d(!1):PolicyManager.verifySha256WithEcdsaSignature(a.getSignature(),b,c,d);else if(a instanceof DigestSha256Signature)PolicyManager.verifyDigestSha256Signature(a.getSignature(),b,d);else throw new SecurityException(Error("PolicyManager.verify: Signature type is unknown"));
};
PolicyManager.verifySha256WithRsaSignature=function(a,b,c,d){if(UseSubtleCrypto()){var e={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};crypto.subtle.importKey("spki",c.buf().buffer,e,!0,["verify"]).then(function(c){return crypto.subtle.verify(e,c,a.buf(),b.signedBuf())}).then(function(a){d(a)})}else{null===PolicyManager.verifyUsesString_&&PolicyManager.setVerifyUsesString_();var f=c.buf().toString("base64");c="-----BEGIN PUBLIC KEY-----\n";for(var g=0;g<f.length;g+=64)c+=f.substr(g,64)+"\n";c+=
"-----END PUBLIC KEY-----";f=Crypto.createVerify("RSA-SHA256");f.update(b.signedBuf());g=PolicyManager.verifyUsesString_?DataUtils.toString(a.buf()):a.buf();d(f.verify(c,g))}};
PolicyManager.verifySha256WithEcdsaSignature=function(a,b,c,d){if(UseSubtleCrypto())d(!1);else{null===PolicyManager.verifyUsesString_&&PolicyManager.setVerifyUsesString_();var e=c.buf().toString("base64");c="-----BEGIN PUBLIC KEY-----\n";for(var f=0;f<e.length;f+=64)c+=e.substr(f,64)+"\n";c+="-----END PUBLIC KEY-----";e=Crypto.createVerify("sha256");e.update(b.signedBuf());a=PolicyManager.verifyUsesString_?DataUtils.toString(a.buf()):a.buf();d(e.verify(c,a))}};
PolicyManager.verifyDigestSha256Signature=function(a,b,c){var d=Crypto.createHash("sha256");d.update(b.signedBuf());b=new Blob(d.digest(),!1);c(b.equals(a))};var IdentityCertificate=require("../certificate/identity-certificate.js").IdentityCertificate,CertificateCache=function(){this.cache={}};exports.CertificateCache=CertificateCache;CertificateCache.prototype.insertCertificate=function(a){var b=a.getName().getPrefix(-1);this.cache[b.toUri()]=a.wireEncode()};
CertificateCache.prototype.deleteCertificate=function(a){delete this.cache[a.toUri()]};CertificateCache.prototype.getCertificate=function(a){a=this.cache[a.toUri()];if(void 0===a)return null;var b=new IdentityCertificate;b.wireDecode(a);return b};CertificateCache.prototype.reset=function(){this.cache={}};
var fs=require("fs"),path=require("path"),Name=require("../../name.js").Name,Data=require("../../data.js").Data,Interest=require("../../interest.js").Interest,KeyLocator=require("../../key-locator.js").KeyLocator,KeyLocatorType=require("../../key-locator.js").KeyLocatorType,Blob=require("../../util/blob.js").Blob,IdentityCertificate=require("../certificate/identity-certificate.js").IdentityCertificate,BoostInfoParser=require("../../util/boost-info-parser.js").BoostInfoParser,NdnRegexMatcher=require("../../util/ndn-regex-matcher.js").NdnRegexMatcher,
CertificateCache=require("./certificate-cache.js").CertificateCache,ValidationRequest=require("./validation-request.js").ValidationRequest,SecurityException=require("../security-exception.js").SecurityException,WireFormat=require("../../encoding/wire-format.js").WireFormat,PolicyManager=require("./policy-manager.js").PolicyManager,NdnCommon=require("../../util/ndn-common.js").NdnCommon,ConfigPolicyManager=function(a,b,c,d,e,f){PolicyManager.call(this);void 0==b&&(b=null);void 0==c&&(c=5);void 0==
d&&(d=3E3);void 0==e&&(e=36E5);void 0==f&&(f=1E3);this.certificateCache=null==b?new CertificateCache:b;this.maxDepth=c;this.keyGraceInterval=d;this.keyTimestampTtl=e;this.maxTrackedKeys=f;this.reset();null!=a&&""!=a&&this.load(a)};ConfigPolicyManager.prototype=new PolicyManager;ConfigPolicyManager.prototype.name="ConfigPolicyManager";exports.ConfigPolicyManager=ConfigPolicyManager;
ConfigPolicyManager.prototype.reset=function(){this.certificateCache.reset();this.fixedCertificateCache={};this.keyTimestamps={};this.requiresVerification=!0;this.config=new BoostInfoParser;this.refreshManager=new ConfigPolicyManager.TrustAnchorRefreshManager};ConfigPolicyManager.prototype.load=function(a,b){this.reset();this.config.read(a,b);this.loadTrustAnchorCertificates()};ConfigPolicyManager.prototype.requireVerify=function(a){return this.requiresVerification};
ConfigPolicyManager.prototype.checkSigningPolicy=function(a,b){return!0};ConfigPolicyManager.prototype.skipVerifyAndTrust=function(a){return!this.requiresVerification};
ConfigPolicyManager.prototype.checkVerificationPolicy=function(a,b,c,d,e){if(b>this.maxDepth){try{d(a,"The verification stepCount "+b+" exceeded the maxDepth "+this.maxDepth)}catch(f){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(f))}return null}e=ConfigPolicyManager.extractSignature(a,e);if(null==e){try{d(a,"Cannot extract the signature from "+a.getName().toUri())}catch(g){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(g))}return null}if(!KeyLocator.canGetFromSignature(e)){try{d(a,
"The signature type does not support a KeyLocator")}catch(h){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(h))}return null}var k=null;try{k=KeyLocator.getFromSignature(e)}catch(l){try{d(a,"Error in KeyLocator.getFromSignature: "+l)}catch(m){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(m))}return null}k=k.getKeyName();if(0==k.size()){try{d(a,"The signature KeyLocator doesn't have a key name")}catch(q){console.log("Error in onValidationFailed: "+
NdnCommon.getErrorWithStackTrace(q))}return null}var p=a.getName(),s="data";a instanceof Interest&&(p=p.getPrefix(-4),s="interest");var w=this.findMatchingRule(p,s);if(null==w){try{d(a,"No matching rule found for "+p.toUri())}catch(M){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(M))}return null}s=["unknown"];if(!this.checkSignatureMatch(k,p,w,s)){try{d(a,s[0])}catch(O){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(O))}return null}this.refreshManager.refreshAnchors();
p=this.refreshManager.getCertificate(k);null==p&&(p=this.certificateCache.getCertificate(k));var K=this;if(null==p)return e=new Interest(k),new ValidationRequest(e,function(e){var f;try{f=new IdentityCertificate(e)}catch(g){try{d(a,"Cannot decode certificate "+e.getName().toUri())}catch(h){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(h))}return null}K.certificateCache.insertCertificate(f);K.checkVerificationPolicy(a,b+1,c,d)},d,2,b+1);if(a instanceof Interest){var x=
p.getPublicKeyName(),A=a.getName().get(-4).toNumber();if(!this.interestTimestampIsFresh(x,A,s)){try{d(a,s[0])}catch(I){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(I))}return null}}this.verify(e,a.wireEncode(),function(b,e){if(b){try{c(a)}catch(f){console.log("Error in onVerified: "+NdnCommon.getErrorWithStackTrace(f))}a instanceof Interest&&K.updateTimestampForKey(x,A)}else try{d(a,e)}catch(g){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(g))}})};
ConfigPolicyManager.prototype.loadTrustAnchorCertificates=function(){for(var a=this.config.getRoot().get("validator/trust-anchor"),b=0;b<a.length;++b){var c=a[b],d=c.get("type")[0].getValue(),e=!1,f;if("file"==d)f=c.get("file-name")[0].getValue(),e=!0;else if("base64"==d)f=c.get("base64-string")[0].getValue(),e=!1;else if("dir"==d){d=c.get("dir")[0].getValue();e=0;c=c.get("refresh");1<=c.length&&(c=c[0].getValue().match(/(\d+)([hms])/),null==c?e=0:(e=parseInt(c[1]),"s"!=c[2]&&(e*=60,"m"!=c[2]&&(e*=
60))));this.refreshManager.addDirectory(d,1E3*e);continue}else if("any"==d){this.requiresVerification=!1;break}this.lookupCertificate(f,e)}};
ConfigPolicyManager.prototype.checkSignatureMatch=function(a,b,c,d){c=c.get("checker")[0];var e=c.get("type")[0].getValue();if("fixed-signer"==e){b=c.get("signer")[0];c=b.get("type")[0].getValue();if("file"==c){if(c=this.lookupCertificate(b.get("file-name")[0].getValue(),!0),null==c)return d[0]="Can't find fixed-signer certificate file: "+b.get("file-name")[0].getValue(),!1}else if("base64"==c){if(c=this.lookupCertificate(b.get("base64-string")[0].getValue(),!1),null==c)return d[0]="Can't find fixed-signer certificate base64: "+
b.get("base64-string")[0].getValue(),!1}else return d[0]="Unrecognized fixed-signer signerType: "+c,!1;if(c.getName().equals(a))return!0;d[0]='fixed-signer cert name "'+c.getName().toUri()+'" does not equal signatureName "'+a.toUri()+'"';return!1}if("hierarchical"==e){c=NdnRegexMatcher.match("^([^<KEY>]*)<KEY>(<>*)<ksk-.+><ID-CERT>",a);if(null!=c){a=(new Name(c[1])).append(new Name(c[2]));if(ConfigPolicyManager.matchesRelation(b,a,"is-prefix-of"))return!0;d[0]='The hierarchical objectName "'+b.toUri()+
'" is not a prefix of "'+a.toUri()+'"';return!1}d[0]='The hierarchical identityRegex "^([^<KEY>]*)<KEY>(<>*)<ksk-.+><ID-CERT>" does not match signatureName "'+a.toUri()+'"';return!1}if("customized"==e){var f=c.get("key-locator")[0];c=f.getFirstValue("relation");if(null!=c){b=new Name(f.get("name")[0].getValue());if(ConfigPolicyManager.matchesRelation(a,b,c))return!0;d[0]='The custom signatureName "'+a.toUri()+'" does not match matchName "'+b.toUri()+'" using relation '+c;return!1}var g=f.getFirstValue("regex");
if(null!=g){if(null!=NdnRegexMatcher.match(g,a))return!0;d[0]='The custom signatureName "'+a.toUri()+'" does not regex match simpleKeyRegex "'+g+'"';return!1}c=f.get("hyper-relation");if(1<=c.length){c=c[0];var g=c.getFirstValue("k-regex"),h=c.getFirstValue("k-expand"),f=c.getFirstValue("p-regex"),k=c.getFirstValue("p-expand");c=c.getFirstValue("h-relation");if(null!=g&&null!=h&&null!=f&&null!=k&&null!=c){e=NdnRegexMatcher.match(g,a);if(null==e||void 0===e[1])return d[0]='The custom hyper-relation signatureName "'+
a.toUri()+'" does not match the keyRegex "'+g+'"',!1;a=ConfigPolicyManager.expand(e,h);e=NdnRegexMatcher.match(f,b);if(null==e||void 0===e[1])return d[0]='The custom hyper-relation objectName "'+b.toUri()+'" does not match the nameRegex "'+f+'"',!1;b=ConfigPolicyManager.expand(e,k);if(ConfigPolicyManager.matchesRelation(new Name(b),new Name(a),c))return!0;d[0]='The custom hyper-relation nameMatch "'+b+'" does not match the keyMatchPrefix "'+a+'" using relation '+c;return!1}}}d[0]="Unrecognized checkerType: "+
e;return!1};ConfigPolicyManager.expand=function(a,b){return b.replace(/\\(\d)/g,function(b,d){return a[parseInt(d)]})};
ConfigPolicyManager.prototype.lookupCertificate=function(a,b){var c;c=this.fixedCertificateCache[a];if(void 0===c){if(b)c=ConfigPolicyManager.TrustAnchorRefreshManager.loadIdentityCertificateFromFile(a);else{var d=new Buffer(a,"base64");c=new IdentityCertificate;c.wireDecode(d)}d=c.getName().getPrefix(-1).toUri();this.fixedCertificateCache[a]=d;this.certificateCache.insertCertificate(c)}else c=this.certificateCache.getCertificate(new Name(c));return c};
ConfigPolicyManager.prototype.findMatchingRule=function(a,b){for(var c=this.config.getRoot().get("validator/rule"),d=0;d<c.length;++d){var e=c[d];if(e.get("for")[0].getValue()==b){var f=!0,g=e.get("filter");if(0==g.length)return e;for(var h=0;h<g.length;++h){var k=g[h],f=k.getFirstValue("regex");null===f?(f=k.get("relation")[0].getValue(),k=k.get("name")[0].getValue(),k=new Name(k),f=ConfigPolicyManager.matchesRelation(a,k,f)):f=null!==NdnRegexMatcher.match(f,a);if(!f)break}if(f)return e}}return null};
ConfigPolicyManager.matchesRelation=function(a,b,c){var d=!1;"is-strict-prefix-of"==c?b.size()==a.size()?d=!1:b.match(a)&&(d=!0):"is-prefix-of"==c?b.match(a)&&(d=!0):"equal"==c&&b.equals(a)&&(d=!0);return d};ConfigPolicyManager.extractSignature=function(a,b){if(a instanceof Data)return a.getSignature();if(a instanceof Interest){b=b||WireFormat.getDefaultWireFormat();try{var c=b.decodeSignatureInfoAndValue(a.getName().get(-2).getValue().buf(),a.getName().get(-1).getValue().buf(),!1)}catch(d){return null}return c}return null};
ConfigPolicyManager.prototype.interestTimestampIsFresh=function(a,b,c){a=this.keyTimestamps[a.toUri()];if(void 0==a){a=(new Date).getTime();var d=a+this.keyGraceInterval;if(b>a-this.keyGraceInterval&&b<d)return!0;c[0]="The command interest timestamp is not within the first use grace period of "+this.keyGraceInterval+" milliseconds.";return!1}return b<=a?(c[0]="The command interest timestamp is not newer than the previous timestamp",!1):!0};
ConfigPolicyManager.prototype.updateTimestampForKey=function(a,b){this.keyTimestamps[a.toUri()]=b;var c=0,d=[],e=(new Date).getTime(),f=e,g=null,h;for(h in this.keyTimestamps){++c;var k=this.keyTimestamps[h];e-k>this.keyTimestampTtl?d.push(h):k<f&&(f=k,g=h)}if(c>=this.maxTrackedKeys){for(e=0;e<d.length;++e)delete this.keyTimestamps[d[e]],--c;c>this.maxTrackedKeys&&delete this.keyTimestamps[g]}};
ConfigPolicyManager.prototype.verify=function(a,b,c){var d=KeyLocator.getFromSignature(a);if(d.getType()==KeyLocatorType.KEYNAME){var e=d.getKeyName(),d=this.refreshManager.getCertificate(e);null==d&&(d=this.certificateCache.getCertificate(e));null==d?c(!1,"Cannot find a certificate with name "+e.toUri()):(e=d.getPublicKeyInfo().getKeyDer(),e.isNull()?c(!1,"There is no public key in the certificate with name "+d.getName().toUri()):PolicyManager.verifySignature(a,b,e,function(a){a?c(!0):c(!1,"The signature did not verify with the given public key")}))}else c(!1,
"The KeyLocator does not have a key name")};ConfigPolicyManager.TrustAnchorRefreshManager=function(){this.certificateCache=new CertificateCache;this.refreshDirectories={}};ConfigPolicyManager.TrustAnchorRefreshManager.loadIdentityCertificateFromFile=function(a){a=fs.readFileSync(a).toString();a=new Buffer(a,"base64");var b=new IdentityCertificate;b.wireDecode(new Blob(a,!1));return b};ConfigPolicyManager.TrustAnchorRefreshManager.prototype.getCertificate=function(a){return this.certificateCache.getCertificate(a)};
ConfigPolicyManager.TrustAnchorRefreshManager.prototype.addDirectory=function(a,b){var c;try{c=fs.readdirSync(a)}catch(d){throw new SecurityException(Error("Cannot list files in directory "+a));}for(var e=[],f=0;f<c.length;++f){var g;try{var h=path.join(a,c[f]);g=ConfigPolicyManager.TrustAnchorRefreshManager.loadIdentityCertificateFromFile(h)}catch(k){continue}var l=g.getName().getPrefix(-1).toUri();this.certificateCache.insertCertificate(g);e.push(l)}this.refreshDirectories[a]={certificates:e,nextRefresh:(new Date).getTime()+
b,refreshPeriod:b}};ConfigPolicyManager.TrustAnchorRefreshManager.prototype.refreshAnchors=function(){var a=(new Date).getTime(),b;for(b in this.refreshDirectories){var c=this.refreshDirectories[b];if(c.nextRefresh<=a){var d=c.certificates.slice(0),e;for(e in d)this.certificateCache.deleteCertificate(new Name(e));this.addDirectory(b,c.refreshPeriod)}}};
var Name=require("../../name.js").Name,PolicyManager=require("./policy-manager.js").PolicyManager,NdnCommon=require("../../util/ndn-common.js").NdnCommon,NoVerifyPolicyManager=function(){PolicyManager.call(this)};NoVerifyPolicyManager.prototype=new PolicyManager;NoVerifyPolicyManager.prototype.name="NoVerifyPolicyManager";exports.NoVerifyPolicyManager=NoVerifyPolicyManager;NoVerifyPolicyManager.prototype.skipVerifyAndTrust=function(a){return!0};NoVerifyPolicyManager.prototype.requireVerify=function(a){return!1};
NoVerifyPolicyManager.prototype.checkVerificationPolicy=function(a,b,c,d,e){try{c(a)}catch(f){console.log("Error in onVerified: "+NdnCommon.getErrorWithStackTrace(f))}return null};NoVerifyPolicyManager.prototype.checkSigningPolicy=function(a,b){return!0};NoVerifyPolicyManager.prototype.inferSigningIdentity=function(a){return new Name};
var Name=require("../../name.js").Name,Interest=require("../../interest.js").Interest,Data=require("../../data.js").Data,Blob=require("../../util/blob.js").Blob,IdentityCertificate=require("../certificate/identity-certificate.js").IdentityCertificate,KeyLocator=require("../../key-locator.js").KeyLocator,KeyLocatorType=require("../../key-locator.js").KeyLocatorType,SecurityException=require("../security-exception.js").SecurityException,WireFormat=require("../../encoding/wire-format.js").WireFormat,
SyncPromise=require("../../util/sync-promise.js").SyncPromise,PolicyManager=require("./policy-manager.js").PolicyManager,NdnCommon=require("../../util/ndn-common.js").NdnCommon,SelfVerifyPolicyManager=function(a){PolicyManager.call(this);this.identityStorage=a};SelfVerifyPolicyManager.prototype=new PolicyManager;SelfVerifyPolicyManager.prototype.name="SelfVerifyPolicyManager";exports.SelfVerifyPolicyManager=SelfVerifyPolicyManager;SelfVerifyPolicyManager.prototype.skipVerifyAndTrust=function(a){return!1};
SelfVerifyPolicyManager.prototype.requireVerify=function(a){return!0};
SelfVerifyPolicyManager.prototype.checkVerificationPolicy=function(a,b,c,d,e){e=e||WireFormat.getDefaultWireFormat();if(a instanceof Data)this.verify(a.getSignature(),a.wireEncode(),function(b,e){if(b)try{c(a)}catch(f){console.log("Error in onVerified: "+NdnCommon.getErrorWithStackTrace(f))}else try{d(a,e)}catch(g){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(g))}});else if(a instanceof Interest){if(2>a.getName().size()){try{d(a,"The signed interest has less than 2 components: "+
a.getName().toUri())}catch(f){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(f))}return}var g;try{g=e.decodeSignatureInfoAndValue(a.getName().get(-2).getValue().buf(),a.getName().get(-1).getValue().buf(),!1)}catch(h){try{d(a,"Error decoding the signed interest signature: "+h)}catch(k){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(k))}return}this.verify(g,a.wireEncode(),function(b,e){if(b)try{c(a)}catch(f){console.log("Error in onVerified: "+
NdnCommon.getErrorWithStackTrace(f))}else try{d(a,e)}catch(g){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(g))}})}else throw new SecurityException(Error("checkVerificationPolicy: unrecognized type for dataOrInterest"));return null};SelfVerifyPolicyManager.prototype.checkSigningPolicy=function(a,b){return!0};SelfVerifyPolicyManager.prototype.inferSigningIdentity=function(a){return new Name};
SelfVerifyPolicyManager.prototype.verify=function(a,b,c){if(KeyLocator.canGetFromSignature(a))this.getPublicKeyDer(KeyLocator.getFromSignature(a),function(d,f){if(d.isNull())c(!1,f);else try{PolicyManager.verifySignature(a,b,d,function(a){a?c(!0):c(!1,"The signature did not verify with the given public key")})}catch(g){c(!1,"Error in verifySignature: "+g)}});else try{PolicyManager.verifySignature(a,b,null,function(a){a?c(!0):c(!1,"The signature did not verify with the given public key")})}catch(d){c(!1,
"Error in verifySignature: "+d)}};
SelfVerifyPolicyManager.prototype.getPublicKeyDer=function(a,b){if(a.getType()==KeyLocatorType.KEYNAME&&null!=this.identityStorage){var c;try{c=IdentityCertificate.certificateNameToPublicKeyName(a.getKeyName())}catch(d){b(new Blob,"Cannot get a public key name from the certificate named: "+a.getKeyName().toUri());return}SyncPromise.complete(b,function(a){b(new Blob,"The identityStorage doesn't have the key named "+c.toUri())},this.identityStorage.getKeyPromise(c))}else b(new Blob,"The signature KeyLocator doesn't have a key name")};
Crypto=require("../crypto.js");Name=require("../name.js").Name;Interest=require("../interest.js").Interest;Data=require("../data.js").Data;Blob=require("../util/blob.js").Blob;WireFormat=require("../encoding/wire-format.js").WireFormat;SecurityException=require("./security-exception.js").SecurityException;RsaKeyParams=require("./key-params.js").RsaKeyParams;IdentityCertificate=require("./certificate/identity-certificate.js").IdentityCertificate;SyncPromise=require("../util/sync-promise.js").SyncPromise;
NdnCommon=require("../util/ndn-common.js").NdnCommon;IdentityManager=require("./identity/identity-manager.js").IdentityManager;NoVerifyPolicyManager=require("./policy/no-verify-policy-manager.js").NoVerifyPolicyManager;KeyChain=function(a,b){a||(a=new IdentityManager);b||(b=new NoVerifyPolicyManager);this.identityManager=a;this.policyManager=b;this.face=null};exports.KeyChain=KeyChain;
KeyChain.prototype.createIdentityAndCertificate=function(a,b,c,d){d="function"===typeof b?c:d;c="function"===typeof b?b:c;b="function"!==typeof b&&b?b:KeyChain.DEFAULT_KEY_PARAMS;return this.identityManager.createIdentityAndCertificate(a,b,c,d)};KeyChain.prototype.createIdentity=function(a,b){return IdentityCertificate.certificateNameToPublicKeyName(this.createIdentityAndCertificate(a,b))};KeyChain.prototype.deleteIdentity=function(a,b,c){this.identityManager.deleteIdentity(a,b,c)};
KeyChain.prototype.getDefaultIdentity=function(a,b){return this.identityManager.getDefaultIdentity(a,b)};KeyChain.prototype.getDefaultCertificateName=function(a,b){return this.identityManager.getDefaultCertificateName(a,b)};KeyChain.prototype.generateRSAKeyPair=function(a,b,c){(c="boolean"===typeof b?b:c)||(c=2048);return this.identityManager.generateRSAKeyPair(a,"boolean"===typeof b?b:!1,c)};
KeyChain.prototype.setDefaultKeyForIdentity=function(a,b,c,d){return this.identityManager.setDefaultKeyForIdentity(a,b,c,d)};KeyChain.prototype.generateRSAKeyPairAsDefault=function(a,b,c){return this.identityManager.generateRSAKeyPairAsDefault(a,b,c)};KeyChain.prototype.createSigningRequest=function(a){return this.identityManager.getPublicKey(a).getKeyDer()};KeyChain.prototype.installIdentityCertificate=function(a,b,c){this.identityManager.addCertificate(a,b,c)};
KeyChain.prototype.setDefaultCertificateForKey=function(a,b,c){this.identityManager.setDefaultCertificateForKey(a,b,c)};KeyChain.prototype.getCertificate=function(a,b,c){return this.identityManager.getCertificate(a,b,c)};KeyChain.prototype.getIdentityCertificate=function(a,b,c){return this.identityManager.getCertificate(a,b,c)};KeyChain.prototype.revokeKey=function(a){};KeyChain.prototype.revokeCertificate=function(a){};KeyChain.prototype.getIdentityManager=function(){return this.identityManager};
KeyChain.prototype.getPolicyManager=function(){return this.policyManager};KeyChain.prototype.sign=function(a,b,c,d,e){var f=b,g=c,h=d;b=f instanceof Name?f:null;c=f instanceof WireFormat?f:g instanceof WireFormat?g:null;"function"===typeof f?(d=f,e=g):"function"===typeof g?(d=g,e=h):"function"===typeof h?d=h:e=d=null;return SyncPromise.complete(d,e,this.signPromise(a,b,c,!d))};
KeyChain.prototype.signPromise=function(a,b,c,d){var e=b,f=c,g=d;b=e instanceof Name?e:null;c=e instanceof WireFormat?e:f instanceof WireFormat?f:null;d="boolean"===typeof e?e:"boolean"===typeof f?f:"boolean"===typeof g?g:!1;var h=this;return SyncPromise.resolve().then(function(){return null!=b?SyncPromise.resolve():h.identityManager.getDefaultCertificatePromise(d).then(function(a){return null!=a?(b=a.getName(),SyncPromise.resolve()):h.prepareDefaultCertificateNamePromise_(d).then(function(a){b=a;
return SyncPromise.resolve()})})}).then(function(){return a instanceof Interest?h.identityManager.signInterestByCertificatePromise(a,b,c,d):a instanceof Data?h.identityManager.signByCertificatePromise(a,b,c,d):h.identityManager.signByCertificatePromise(a,b,d)})};
KeyChain.prototype.signByIdentity=function(a,b,c,d,e){e="function"===typeof c?d:e;d="function"===typeof c?c:d;c="function"!==typeof c&&c?c:WireFormat.getDefaultWireFormat();var f=!d,g=this;null==b&&(b=new Name);if(a instanceof Data){var h=SyncPromise.resolve().then(function(){if(0==b.size()){var c=g.policyManager.inferSigningIdentity(a.getName());return 0==c.size()?g.identityManager.getDefaultCertificateNamePromise(f):g.identityManager.getDefaultCertificateNameForIdentityPromise(c,f)}return g.identityManager.getDefaultCertificateNameForIdentityPromise(b,
f)}).then(function(b){if(0==b.size())throw new SecurityException(Error("No qualified certificate name found!"));if(!g.policyManager.checkSigningPolicy(a.getName(),b))throw new SecurityException(Error("Signing Cert name does not comply with signing policy"));return g.identityManager.signByCertificatePromise(a,b,c,f)});return SyncPromise.complete(d,e,h)}return SyncPromise.complete(d,e,this.identityManager.getDefaultCertificateNameForIdentityPromise(b,f).then(function(b){if(0==b.size())throw new SecurityException(Error("No qualified certificate name found!"));
return g.identityManager.signByCertificatePromise(a,b,c,f)}))};KeyChain.prototype.signWithSha256=function(a,b){a instanceof Interest?this.identityManager.signInterestWithSha256(a,b):this.identityManager.signWithSha256(a,b)};
KeyChain.prototype.verifyData=function(a,b,c,d){null==d&&(d=0);if(this.policyManager.requireVerify(a)){var e=this.policyManager.checkVerificationPolicy(a,d,b,c);if(null!=e){var f=this;this.face.expressInterest(e.interest,function(a,b){f.onCertificateData(a,b,e)},function(b){f.onCertificateInterestTimeout(b,e.retry,c,a,e)})}}else if(this.policyManager.skipVerifyAndTrust(a))try{b(a)}catch(g){console.log("Error in onVerified: "+NdnCommon.getErrorWithStackTrace(g))}else try{c(a,"The packet has no verify rule but skipVerifyAndTrust is false")}catch(h){console.log("Error in onValidationFailed: "+
NdnCommon.getErrorWithStackTrace(h))}};
KeyChain.prototype.verifyInterest=function(a,b,c,d,e){null==d&&(d=0);e=e||WireFormat.getDefaultWireFormat();if(this.policyManager.requireVerify(a)){var f=this.policyManager.checkVerificationPolicy(a,d,b,c,e);if(null!=f){var g=this;this.face.expressInterest(f.interest,function(a,b){g.onCertificateData(a,b,f)},function(b){g.onCertificateInterestTimeout(b,f.retry,c,a,f)})}}else if(this.policyManager.skipVerifyAndTrust(a))try{b(a)}catch(h){console.log("Error in onVerified: "+NdnCommon.getErrorWithStackTrace(h))}else try{c(a,
"The packet has no verify rule but skipVerifyAndTrust is false")}catch(k){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(k))}};KeyChain.prototype.setFace=function(a){this.face=a};
KeyChain.signWithHmacWithSha256=function(a,b,c){c=c||WireFormat.getDefaultWireFormat();if(a instanceof Data)c=a.wireEncode(c),b=Crypto.createHmac("sha256",b.buf()),b.update(c.signedBuf()),a.getSignature().setSignature(new Blob(b.digest(),!1));else throw new SecurityException(Error("signWithHmacWithSha256: Unrecognized target type"));};
KeyChain.verifyDataWithHmacWithSha256=function(a,b,c){c=c||WireFormat.getDefaultWireFormat();c=a.wireEncode(c);b=Crypto.createHmac("sha256",b.buf());b.update(c.signedBuf());return(new Blob(b.digest(),!1)).equals(a.getSignature().getSignature())};KeyChain.DEFAULT_KEY_PARAMS=new RsaKeyParams;KeyChain.prototype.onCertificateData=function(a,b,c){this.verifyData(b,c.onVerified,c.onValidationFailed,c.stepCount)};
KeyChain.prototype.onCertificateInterestTimeout=function(a,b,c,d,e){if(0<b){var f=this;this.face.expressInterest(a,function(a,b){f.onCertificateData(a,b,e)},function(a){f.onCertificateInterestTimeout(a,b-1,c,d,e)})}else try{c(d,"The retry count is zero after timeout for fetching "+a.getName().toUri())}catch(g){console.log("Error in onValidationFailed: "+NdnCommon.getErrorWithStackTrace(g))}};
KeyChain.prototype.prepareDefaultCertificateNamePromise_=function(a){var b,c=this;return this.identityManager.getDefaultCertificatePromise(a).then(function(d){b=d;return null!=b?SyncPromise.resolve():c.setDefaultCertificatePromise_(a).then(function(){return c.identityManager.getDefaultCertificatePromise(a)}).then(function(a){b=a;return SyncPromise.resolve()})}).then(function(){return SyncPromise.resolve(b.getName())})};
KeyChain.prototype.setDefaultCertificatePromise_=function(a){var b=this;return this.identityManager.getDefaultCertificatePromise(a).then(function(c){if(null!=c)return SyncPromise.resolve();var d;return b.identityManager.getDefaultIdentityPromise(a).then(function(a){d=a;return SyncPromise.resolve()},function(a){randomComponent=Crypto.randomBytes(4);d=(new Name).append("tmp-identity").append(new Blob(randomComponent,!1));return SyncPromise.resolve()}).then(function(){return b.identityManager.createIdentityAndCertificatePromise(d,
KeyChain.DEFAULT_KEY_PARAMS,a)}).then(function(){return b.identityManager.setDefaultIdentityPromise(d,a)})})};var Name=require("./name.js").Name,DataUtils=require("./encoding/data-utils.js").DataUtils,Blob=require("./util/blob.js").Blob,Exclude=function Exclude(b){this.values=[];if("object"===typeof b&&b instanceof Exclude)this.values=b.values.slice(0);else if(b)for(var c=this.changeCount=0;c<b.length;++c)b[c]==Exclude.ANY?this.appendAny():this.appendComponent(b[c]);this.changeCount=0};
exports.Exclude=Exclude;Exclude.ANY="*";Exclude.prototype.size=function(){return this.values.length};Exclude.prototype.get=function(a){return this.values[a]};Exclude.prototype.appendAny=function(){this.values.push(Exclude.ANY);++this.changeCount;return this};Exclude.prototype.appendComponent=function(a){this.values.push(new Name.Component(a));++this.changeCount;return this};Exclude.prototype.clear=function(){++this.changeCount;this.values=[]};
Exclude.prototype.toUri=function(){if(null==this.values||0==this.values.length)return"";for(var a="",b=0;b<this.values.length;++b)0<b&&(a+=","),a=this.values[b]==Exclude.ANY?a+"*":a+this.values[b].toEscapedString();return a};
Exclude.prototype.matches=function(a){"object"==typeof a&&a instanceof Name.Component||(a=new Name.Component(a));for(var b=0;b<this.values.length;++b)if(this.values[b]==Exclude.ANY){var c=null;0<b&&(c=this.values[b-1]);var d,e=null;for(d=b+1;d<this.values.length;++d)if(this.values[d]!=Exclude.ANY){e=this.values[d];break}if(null!=e){if(null!=c){if(0<a.compare(c)&&0>a.compare(e))return!0}else if(0>a.compare(e))return!0;b=d-1}else if(null!=c){if(0<a.compare(c))return!0}else return!0}else if(a.equals(this.values[b]))return!0;
return!1};Exclude.compareComponents=function(a,b){"object"==typeof a&&a instanceof Name.Component&&(a=a.getValue().buf());"object"==typeof b&&b instanceof Name.Component&&(b=b.getValue().buf());return Name.Component.compareBuffers(a,b)};Exclude.prototype.getChangeCount=function(){return this.changeCount};
var Crypto=require("./crypto.js"),Blob=require("./util/blob.js").Blob,SignedBlob=require("./util/signed-blob.js").SignedBlob,ChangeCounter=require("./util/change-counter.js").ChangeCounter,Name=require("./name.js").Name,Exclude=require("./exclude.js").Exclude,Link=require("./link.js").Link,KeyLocator=require("./key-locator.js").KeyLocator,IncomingFaceId=require("./lp/incoming-face-id.js").IncomingFaceId,WireFormat=require("./encoding/wire-format.js").WireFormat,Interest=function Interest(b,c,d,e,
f,g,h,k,l,m){if(e)throw Error("Interest constructor: PublisherPublicKeyDigest support has been removed.");if(h)throw Error("Interest constructor: answerOriginKind support has been removed. Use setMustBeFresh().");if(k)throw Error("Interest constructor: scope support has been removed.");"object"===typeof b&&b instanceof Interest?(this.name_=new ChangeCounter(new Name(b.getName())),this.maxSuffixComponents_=b.maxSuffixComponents_,this.minSuffixComponents_=b.minSuffixComponents_,this.keyLocator_=new ChangeCounter(new KeyLocator(b.getKeyLocator())),
this.exclude_=new ChangeCounter(new Exclude(b.getExclude())),this.childSelector_=b.childSelector_,this.mustBeFresh_=b.mustBeFresh_,this.interestLifetimeMilliseconds_=b.interestLifetimeMilliseconds_,this.nonce_=b.nonce_,this.linkWireEncoding_=b.linkWireEncoding_,this.linkWireEncodingFormat_=b.linkWireEncodingFormat_,this.link_=new ChangeCounter(null),null!=b.link_.get()&&this.link_.set(new Link(b.link_.get())),this.selectedDelegationIndex_=b.selectedDelegationIndex_,this.defaultWireEncoding_=b.getDefaultWireEncoding(),
this.defaultWireEncodingFormat_=b.defaultWireEncodingFormat_):(this.name_=new ChangeCounter("object"===typeof b&&b instanceof Name?new Name(b):new Name),this.maxSuffixComponents_=d,this.minSuffixComponents_=c,this.keyLocator_=new ChangeCounter(new KeyLocator),this.exclude_=new ChangeCounter("object"===typeof f&&f instanceof Exclude?new Exclude(f):new Exclude),this.childSelector_=g,this.mustBeFresh_=!0,this.interestLifetimeMilliseconds_=l,this.nonce_="object"===typeof m&&m instanceof Blob?m:new Blob(m,
!0),this.linkWireEncoding_=new Blob,this.linkWireEncodingFormat_=null,this.link_=new ChangeCounter(null),this.selectedDelegationIndex_=null,this.defaultWireEncoding_=new SignedBlob,this.defaultWireEncodingFormat_=null);this.changeCount_=this.getDefaultWireEncodingChangeCount_=this.getNonceChangeCount_=0;this.lpPacket_=null};exports.Interest=Interest;Interest.RECURSIVE_POSTFIX="*";Interest.CHILD_SELECTOR_LEFT=0;Interest.CHILD_SELECTOR_RIGHT=1;
Interest.prototype.matchesName=function(a){return!this.getName().match(a)||null!=this.minSuffixComponents_&&!(a.size()+1-this.getName().size()>=this.minSuffixComponents_)||null!=this.maxSuffixComponents_&&!(a.size()+1-this.getName().size()<=this.maxSuffixComponents_)||null!=this.getExclude()&&a.size()>this.getName().size()&&this.getExclude().matches(a.get(this.getName().size()))?!1:!0};Interest.prototype.matches_name=function(a){return this.matchesName(a)};
Interest.prototype.matchesData=function(a,b){b=b||WireFormat.getDefaultWireFormat();var c=this.getName().size(),d=a.getName(),e=d.size()+1,f=null!=this.getMinSuffixComponents()?this.getMinSuffixComponents():0;if(!(c+f<=e&&(null==this.getMaxSuffixComponents()||c+this.getMaxSuffixComponents()>=e)))return!1;if(c===e)if(this.getName().get(-1).isImplicitSha256Digest()){if(!this.getName().equals(a.getFullName(b)))return!1}else return!1;else if(!this.getName().isPrefixOf(d))return!1;if(0<this.getExclude().size()&&
e>c)if(c==e-1){if(this.getExclude().matches(a.getFullName(b).get(c)))return!1}else if(this.getExclude().matches(d.get(c)))return!1;c=this.getKeyLocator();return!c.getType()||(d=a.getSignature(),KeyLocator.canGetFromSignature(d)&&c.equals(KeyLocator.getFromSignature(d)))?!0:!1};Interest.prototype.clone=function(){return new Interest(this)};Interest.prototype.getName=function(){return this.name_.get()};Interest.prototype.getMinSuffixComponents=function(){return this.minSuffixComponents_};
Interest.prototype.getMaxSuffixComponents=function(){return this.maxSuffixComponents_};Interest.prototype.getKeyLocator=function(){return this.keyLocator_.get()};Interest.prototype.getExclude=function(){return this.exclude_.get()};Interest.prototype.getChildSelector=function(){return this.childSelector_};Interest.prototype.getMustBeFresh=function(){return this.mustBeFresh_};
Interest.prototype.getNonce=function(){this.getNonceChangeCount_!=this.getChangeCount()&&(this.nonce_=new Blob,this.getNonceChangeCount_=this.getChangeCount());return this.nonce_};Interest.prototype.getNonceAsBuffer=function(){return this.getNonce().buf()};Interest.prototype.hasLink=function(){return null!=this.link_.get()||!this.linkWireEncoding_.isNull()};
Interest.prototype.getLink=function(){if(null!=this.link_.get())return this.link_.get();if(this.linkWireEncoding_.isNull())return null;var a=new Link;a.wireDecode(this.linkWireEncoding_,this.linkWireEncodingFormat_);this.link_.set(a);this.linkWireEncoding_=new Blob;this.linkWireEncodingFormat_=null;return a};
Interest.prototype.getLinkWireEncoding=function(a){a=a||WireFormat.getDefaultWireFormat();if(!this.linkWireEncoding_.isNull()&&this.linkWireEncodingFormat_==a)return this.linkWireEncoding_;var b=this.getLink();return null!=b?b.wireEncode(a):new Blob};Interest.prototype.getSelectedDelegationIndex=function(){return this.selectedDelegationIndex_};Interest.prototype.getInterestLifetimeMilliseconds=function(){return this.interestLifetimeMilliseconds_};
Interest.prototype.getDefaultWireEncoding=function(){this.getDefaultWireEncodingChangeCount_!=this.getChangeCount()&&(this.defaultWireEncoding_=new SignedBlob,this.defaultWireEncodingFormat_=null,this.getDefaultWireEncodingChangeCount_=this.getChangeCount());return this.defaultWireEncoding_};Interest.prototype.getDefaultWireEncodingFormat=function(){return this.defaultWireEncodingFormat_};
Interest.prototype.getIncomingFaceId=function(){var a=null===this.lpPacket_?null:IncomingFaceId.getFirstHeader(this.lpPacket_);return null===a?null:a.getFaceId()};Interest.prototype.setName=function(a){this.name_.set("object"===typeof a&&a instanceof Name?new Name(a):new Name);++this.changeCount_;return this};Interest.prototype.setMinSuffixComponents=function(a){this.minSuffixComponents_=a;++this.changeCount_;return this};
Interest.prototype.setMaxSuffixComponents=function(a){this.maxSuffixComponents_=a;++this.changeCount_;return this};Interest.prototype.setKeyLocator=function(a){this.keyLocator_.set("object"===typeof a&&a instanceof KeyLocator?new KeyLocator(a):new KeyLocator);++this.changeCount_;return this};Interest.prototype.setExclude=function(a){this.exclude_.set("object"===typeof a&&a instanceof Exclude?new Exclude(a):new Exclude);++this.changeCount_;return this};
Interest.prototype.setLinkWireEncoding=function(a,b){b=b||WireFormat.getDefaultWireFormat();this.linkWireEncoding_=a;this.linkWireEncodingFormat_=b;this.link_.set(null);++this.changeCount_;return this};Interest.prototype.unsetLink=function(){return this.setLinkWireEncoding(new Blob,null)};Interest.prototype.setSelectedDelegationIndex=function(a){this.selectedDelegationIndex_=a;++this.changeCount_;return this};
Interest.prototype.setChildSelector=function(a){this.childSelector_=a;++this.changeCount_;return this};Interest.prototype.setMustBeFresh=function(a){this.mustBeFresh_=a?!0:!1;++this.changeCount_;return this};Interest.prototype.setInterestLifetimeMilliseconds=function(a){this.interestLifetimeMilliseconds_=a;++this.changeCount_;return this};
Interest.prototype.setNonce=function(a){this.nonce_="object"===typeof a&&a instanceof Blob?a:new Blob(a,!0);++this.changeCount_;this.getNonceChangeCount_=this.getChangeCount();return this};
Interest.prototype.toUri=function(){var a="";null!=this.minSuffixComponents_&&(a+="&ndn.MinSuffixComponents="+this.minSuffixComponents_);null!=this.maxSuffixComponents_&&(a+="&ndn.MaxSuffixComponents="+this.maxSuffixComponents_);null!=this.childSelector_&&(a+="&ndn.ChildSelector="+this.childSelector_);a+="&ndn.MustBeFresh="+(this.mustBeFresh_?1:0);null!=this.interestLifetimeMilliseconds_&&(a+="&ndn.InterestLifetime="+this.interestLifetimeMilliseconds_);0<this.getNonce().size()&&(a+="&ndn.Nonce="+
Name.toEscapedString(this.getNonce().buf()));null!=this.getExclude()&&0<this.getExclude().size()&&(a+="&ndn.Exclude="+this.getExclude().toUri());var b=this.getName().toUri();""!=a&&(b+="?"+a.substr(1));return b};
Interest.prototype.wireEncode=function(a){a=a||WireFormat.getDefaultWireFormat();if(!this.getDefaultWireEncoding().isNull()&&this.getDefaultWireEncodingFormat()==a)return this.getDefaultWireEncoding();var b=a.encodeInterest(this),b=new SignedBlob(b.encoding,b.signedPortionBeginOffset,b.signedPortionEndOffset);a==WireFormat.getDefaultWireFormat()&&this.setDefaultWireEncoding(b,WireFormat.getDefaultWireFormat());return b};
Interest.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();var c;c="object"===typeof a&&a instanceof Blob?b.decodeInterest(this,a.buf(),!1):b.decodeInterest(this,a,!0);b==WireFormat.getDefaultWireFormat()?this.setDefaultWireEncoding(new SignedBlob(new Blob(a,!0),c.signedPortionBeginOffset,c.signedPortionEndOffset),WireFormat.getDefaultWireFormat()):this.setDefaultWireEncoding(new SignedBlob,null)};
Interest.prototype.refreshNonce=function(){var a=this.getNonce();if(0!==a.size()){for(var b;b=new Blob(Crypto.randomBytes(a.size()),!1),b.equals(a););this.nonce_=b;++this.changeCount_;this.getNonceChangeCount_=this.getChangeCount()}};Interest.prototype.setLpPacket=function(a){this.lpPacket_=a;return this};Interest.prototype.getChangeCount=function(){var a=this.name_.checkChanged(),a=this.keyLocator_.checkChanged()||a;(a=this.exclude_.checkChanged()||a)&&++this.changeCount_;return this.changeCount_};
Interest.prototype.setDefaultWireEncoding=function(a,b){this.defaultWireEncoding_=a;this.defaultWireEncodingFormat_=b;this.getDefaultWireEncodingChangeCount_=this.getChangeCount()};Object.defineProperty(Interest.prototype,"name",{get:function(){return this.getName()},set:function(a){this.setName(a)}});Object.defineProperty(Interest.prototype,"minSuffixComponents",{get:function(){return this.getMinSuffixComponents()},set:function(a){this.setMinSuffixComponents(a)}});
Object.defineProperty(Interest.prototype,"maxSuffixComponents",{get:function(){return this.getMaxSuffixComponents()},set:function(a){this.setMaxSuffixComponents(a)}});Object.defineProperty(Interest.prototype,"keyLocator",{get:function(){return this.getKeyLocator()},set:function(a){this.setKeyLocator(a)}});Object.defineProperty(Interest.prototype,"exclude",{get:function(){return this.getExclude()},set:function(a){this.setExclude(a)}});
Object.defineProperty(Interest.prototype,"childSelector",{get:function(){return this.getChildSelector()},set:function(a){this.setChildSelector(a)}});Object.defineProperty(Interest.prototype,"interestLifetime",{get:function(){return this.getInterestLifetimeMilliseconds()},set:function(a){this.setInterestLifetimeMilliseconds(a)}});Object.defineProperty(Interest.prototype,"nonce",{get:function(){return this.getNonceAsBuffer()},set:function(a){this.setNonce(a)}});
ForwardingFlags=function ForwardingFlags(b){"object"===typeof b&&b instanceof ForwardingFlags?(this.childInherit=b.childInherit,this.capture=b.capture):(this.childInherit=!0,this.capture=!1)};exports.ForwardingFlags=ForwardingFlags;ForwardingFlags.NfdForwardingFlags_CHILD_INHERIT=1;ForwardingFlags.NfdForwardingFlags_CAPTURE=2;
ForwardingFlags.prototype.getNfdForwardingFlags=function(){var a=0;this.childInherit&&(a|=ForwardingFlags.NfdForwardingFlags_CHILD_INHERIT);this.capture&&(a|=ForwardingFlags.NfdForwardingFlags_CAPTURE);return a};ForwardingFlags.prototype.setNfdForwardingFlags=function(a){this.childInherit=0!=(a&ForwardingFlags.NfdForwardingFlags_CHILD_INHERIT);this.capture=0!=(a&ForwardingFlags.NfdForwardingFlags_CAPTURE)};ForwardingFlags.prototype.getChildInherit=function(){return this.childInherit};
ForwardingFlags.prototype.getCapture=function(){return this.capture};ForwardingFlags.prototype.setChildInherit=function(a){this.childInherit=a};ForwardingFlags.prototype.setCapture=function(a){this.capture=a};
var ForwardingFlags=require("./forwarding-flags.js").ForwardingFlags,Name=require("./name.js").Name,WireFormat=require("./encoding/wire-format.js").WireFormat,Blob=require("./util/blob.js").Blob,ControlParameters=function ControlParameters(b){"object"===typeof b&&b instanceof ControlParameters?(this.name=null==b.name?null:new Name(b.name),this.faceId=b.faceId,this.uri=b.uri,this.localControlFeature=b.localControlFeature,this.origin=b.origin,this.cost=b.cost,this.forwardingFlags=new ForwardingFlags(b.forwardingFlags),
this.strategy=new Name(b.strategy),this.expirationPeriod=b.expirationPeriod):(this.faceId=this.name=null,this.uri="",this.cost=this.origin=this.localControlFeature=null,this.forwardingFlags=new ForwardingFlags,this.strategy=new Name,this.expirationPeriod=null)};exports.ControlParameters=ControlParameters;
ControlParameters.prototype.clear=function(){this.faceId=this.name=null;this.uri="";this.cost=this.origin=this.localControlFeature=null;this.forwardingFlags=new ForwardingFlags;this.strategy=new Name;this.expirationPeriod=null};ControlParameters.prototype.wireEncode=function(a){a=a||WireFormat.getDefaultWireFormat();return a.encodeControlParameters(this)};
ControlParameters.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();"object"===typeof a&&a instanceof Blob?b.decodeControlParameters(this,a.buf(),!1):b.decodeControlParameters(this,a,!0)};ControlParameters.prototype.getName=function(){return this.name};ControlParameters.prototype.getFaceId=function(){return this.faceId};ControlParameters.prototype.getUri=function(){return this.uri};ControlParameters.prototype.getLocalControlFeature=function(){return this.localControlFeature};
ControlParameters.prototype.getOrigin=function(){return this.origin};ControlParameters.prototype.getCost=function(){return this.cost};ControlParameters.prototype.getForwardingFlags=function(){return this.forwardingFlags};ControlParameters.prototype.getStrategy=function(){return this.strategy};ControlParameters.prototype.getExpirationPeriod=function(){return this.expirationPeriod};ControlParameters.prototype.setName=function(a){this.name="object"===typeof a&&a instanceof Name?new Name(a):null};
ControlParameters.prototype.setFaceId=function(a){this.faceId=a};ControlParameters.prototype.setUri=function(a){this.uri=a||""};ControlParameters.prototype.setLocalControlFeature=function(a){this.localControlFeature=a};ControlParameters.prototype.setOrigin=function(a){this.origin=a};ControlParameters.prototype.setCost=function(a){this.cost=a};ControlParameters.prototype.setForwardingFlags=function(a){this.forwardingFlags="object"===typeof a&&a instanceof ForwardingFlags?new ForwardingFlags(a):new ForwardingFlags};
ControlParameters.prototype.setStrategy=function(a){this.strategy="object"===typeof a&&a instanceof Name?new Name(a):new Name};ControlParameters.prototype.setExpirationPeriod=function(a){this.expirationPeriod=a};
var ControlParameters=require("./control-parameters.js").ControlParameters,WireFormat=require("./encoding/wire-format.js").WireFormat,Blob=require("./util/blob.js").Blob,ControlResponse=function ControlResponse(b){"object"===typeof b&&b instanceof ControlResponse?(this.statusCode_=b.statusCode_,this.statusText_=b.statusText_,this.bodyAsControlParameters_=null==b.bodyAsControlParameters_?null:new ControlParameters(b.bodyAsControlParameters_)):(this.statusCode_=null,this.statusText_="",this.bodyAsControlParameters_=
null)};exports.ControlResponse=ControlResponse;ControlResponse.prototype.clear=function(){this.statusCode_=null;this.statusText_="";this.bodyAsControlParameters_=null};ControlResponse.prototype.wireEncode=function(a){a=a||WireFormat.getDefaultWireFormat();return a.encodeControlResponse(this)};ControlResponse.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();"object"===typeof a&&a instanceof Blob?b.decodeControlResponse(this,a.buf(),!1):b.decodeControlResponse(this,a,!0)};
ControlResponse.prototype.getStatusCode=function(){return this.statusCode_};ControlResponse.prototype.getStatusText=function(){return this.statusText_};ControlResponse.prototype.getBodyAsControlParameters=function(){return this.bodyAsControlParameters_};ControlResponse.prototype.setStatusCode=function(a){this.statusCode_=a;return this};ControlResponse.prototype.setStatusText=function(a){this.statusText_=a||"";return this};
ControlResponse.prototype.setBodyAsControlParameters=function(a){this.bodyAsControlParameters_="object"===typeof a&&a instanceof ControlParameters?new ControlParameters(a):null;return this};Name=require("./name.js").Name;NdnRegexMatcher=require("./util/ndn-regex-matcher.js").NdnRegexMatcher;
InterestFilter=function InterestFilter(b,c){"object"===typeof b&&b instanceof InterestFilter?(this.prefix=new Name(b.prefix),this.regexFilter=b.regexFilter,this.regexFilterPattern=b.regexFilterPattern):(this.prefix=new Name(b),c?(this.regexFilter=c,this.regexFilterPattern=InterestFilter.makePattern(c)):this.regexFilterPattern=this.regexFilter=null)};exports.InterestFilter=InterestFilter;
InterestFilter.prototype.doesMatch=function(a){return a.size()<this.prefix.size()?!1:this.hasRegexFilter()?this.prefix.match(a)?null!=NdnRegexMatcher.match(this.regexFilterPattern,a.getSubName(this.prefix.size())):!1:this.prefix.match(a)};InterestFilter.prototype.getPrefix=function(){return this.prefix};InterestFilter.prototype.hasRegexFilter=function(){return null!=this.regexFilter};InterestFilter.prototype.getRegexFilter=function(){return this.regexFilter};
InterestFilter.makePattern=function(a){if(0==a.length)return"^$";"^"!=a[0]&&(a="^"+a);"$"!=a[a.length-1]&&(a+="$");return a};var Name=require("./name.js").Name,Blob=require("./util/blob.js").Blob,WireFormat=require("./encoding/wire-format.js").WireFormat,DelegationSet=function DelegationSet(b){this.delegations_="object"===typeof b&&b instanceof DelegationSet?b.delegations_.slice(0):[]};exports.DelegationSet=DelegationSet;DelegationSet.Delegation=function(a,b){this.preference_=a;this.name_=new Name(b)};
DelegationSet.Delegation.prototype.getPreference=function(){return this.preference_};DelegationSet.Delegation.prototype.getName=function(){return this.name_};DelegationSet.Delegation.prototype.compare=function(a){return this.preference_<a.preference_?-1:this.preference_>a.preference_?1:this.name_.compare(a.name_)};
DelegationSet.prototype.add=function(a,b){this.remove(b);for(var c=new DelegationSet.Delegation(a,b),d=0;d<this.delegations_.length&&!(0<=this.delegations_[d].compare(c));)++d;this.delegations_.splice(d,0,c)};DelegationSet.prototype.addUnsorted=function(a,b){this.delegations_.push(new DelegationSet.Delegation(a,b))};DelegationSet.prototype.remove=function(a){for(var b=!1,c=this.delegations_.length-1;0<=c;--c)this.delegations_[c].getName().equals(a)&&(b=!0,this.delegations_.splice(c,1));return b};
DelegationSet.prototype.clear=function(){this.delegations_=[]};DelegationSet.prototype.size=function(){return this.delegations_.length};DelegationSet.prototype.get=function(a){return this.delegations_[a]};DelegationSet.prototype.find=function(a){for(var b=0;b<this.delegations_.length;++b)if(this.delegations_[b].getName().equals(a))return b;return-1};DelegationSet.prototype.wireEncode=function(a){a=a||WireFormat.getDefaultWireFormat();return a.encodeDelegationSet(this)};
DelegationSet.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();"object"===typeof a&&a instanceof Blob?b.decodeDelegationSet(this,a.buf(),!1):b.decodeDelegationSet(this,a,!0)};DelegationSet=require("./delegation-set.js").DelegationSet;ContentType=require("./meta-info.js").ContentType;WireFormat=require("./encoding/wire-format.js").WireFormat;Data=require("./data.js").Data;
Link=function(a){this.delegations_=new DelegationSet;if(a instanceof Data){if(Data.call(this,a),!this.getContent().isNull())try{this.delegations_.wireDecode(this.getContent()),this.getMetaInfo().setType(ContentType.LINK)}catch(b){this.delegations_.clear()}}else void 0!=a?Data.call(this,a):Data.call(this),this.getMetaInfo().setType(ContentType.LINK)};Link.prototype=new Data;Link.prototype.name="Link";exports.Link=Link;
Link.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();Data.prototype.wireDecode.call(this,a,b);if(this.getMetaInfo().getType()!=ContentType.LINK)throw Error("Link.wireDecode: MetaInfo ContentType is not LINK.");this.delegations_.wireDecode(this.getContent())};Link.prototype.addDelegation=function(a,b,c){c=c||WireFormat.getDefaultWireFormat();this.delegations_.add(a,b);this.encodeContent(c);return this};
Link.prototype.removeDelegation=function(a,b){b=b||WireFormat.getDefaultWireFormat();var c=this.delegations_.remove(a);c&&this.encodeContent(b);return c};Link.prototype.getDelegations=function(){return this.delegations_};Link.prototype.encodeContent=function(a){this.setContent(this.delegations_.wireEncode(a));this.getMetaInfo().setType(ContentType.LINK)};var NetworkNack=function NetworkNack(){this.reason_=NetworkNack.Reason.NONE;this.otherReasonCode_=-1};exports.NetworkNack=NetworkNack;
NetworkNack.Reason={NONE:0,CONGESTION:50,DUPLICATE:100,NO_ROUTE:150,OTHER_CODE:32767};NetworkNack.prototype.getReason=function(){return this.reason_};NetworkNack.prototype.getOtherReasonCode=function(){return this.otherReasonCode_};NetworkNack.prototype.setReason=function(a){this.reason_=a};NetworkNack.prototype.setOtherReasonCode=function(a){if(0>a)throw Error("NetworkNack other reason code must be non-negative");this.otherReasonCode_=a};
NetworkNack.getFirstHeader=function(a){for(var b=0;b<a.countHeaderFields();++b){var c=a.getHeaderField(b);if(c instanceof NetworkNack)return c}return null};
var Crypto=require("../crypto.js"),Blob=require("../util/blob.js").Blob,Name=require("../name.js").Name,ForwardingFlags=require("../forwarding-flags").ForwardingFlags,Tlv=require("./tlv/tlv.js").Tlv,TlvEncoder=require("./tlv/tlv-encoder.js").TlvEncoder,TlvDecoder=require("./tlv/tlv-decoder.js").TlvDecoder,WireFormat=require("./wire-format.js").WireFormat,Exclude=require("../exclude.js").Exclude,ContentType=require("../meta-info.js").ContentType,KeyLocatorType=require("../key-locator.js").KeyLocatorType,
Sha256WithRsaSignature=require("../sha256-with-rsa-signature.js").Sha256WithRsaSignature,Sha256WithEcdsaSignature=require("../sha256-with-ecdsa-signature.js").Sha256WithEcdsaSignature,GenericSignature=require("../generic-signature.js").GenericSignature,HmacWithSha256Signature=require("../hmac-with-sha256-signature.js").HmacWithSha256Signature,DigestSha256Signature=require("../digest-sha256-signature.js").DigestSha256Signature,ControlParameters=require("../control-parameters.js").ControlParameters,
ForwardingFlags=require("../forwarding-flags.js").ForwardingFlags,NetworkNack=require("../network-nack.js").NetworkNack,IncomingFaceId=require("../lp/incoming-face-id.js").IncomingFaceId,DecodingException=require("./decoding-exception.js").DecodingException,Tlv0_2WireFormat=function(){WireFormat.call(this)};Tlv0_2WireFormat.prototype=new WireFormat;Tlv0_2WireFormat.prototype.name="Tlv0_2WireFormat";exports.Tlv0_2WireFormat=Tlv0_2WireFormat;Tlv0_2WireFormat.instance=null;
Tlv0_2WireFormat.prototype.encodeName=function(a){var b=new TlvEncoder;Tlv0_2WireFormat.encodeName(a,b);return new Blob(b.getOutput(),!1)};Tlv0_2WireFormat.prototype.decodeName=function(a,b,c){null==c&&(c=!0);b=new TlvDecoder(b);Tlv0_2WireFormat.decodeName(a,b,c)};
Tlv0_2WireFormat.prototype.encodeInterest=function(a){var b=new TlvEncoder(256),c=b.getLength();b.writeOptionalNonNegativeIntegerTlv(Tlv.SelectedDelegation,a.getSelectedDelegationIndex());var d=a.getLinkWireEncoding(this);d.isNull()||b.writeBuffer(d.buf());b.writeOptionalNonNegativeIntegerTlv(Tlv.InterestLifetime,a.getInterestLifetimeMilliseconds());if(a.getNonce().isNull()||0==a.getNonce().size())b.writeBlobTlv(Tlv.Nonce,Crypto.randomBytes(4));else if(4>a.getNonce().size()){d=Buffer(4);a.getNonce().buf().copy(d);
for(var e=a.getNonce().size();4>e;++e)d[e]=Crypto.randomBytes(1)[0];b.writeBlobTlv(Tlv.Nonce,d)}else 4==a.getNonce().size()?b.writeBlobTlv(Tlv.Nonce,a.getNonce().buf()):b.writeBlobTlv(Tlv.Nonce,a.getNonce().buf().slice(0,4));Tlv0_2WireFormat.encodeSelectors(a,b);d=Tlv0_2WireFormat.encodeName(a.getName(),b);a=b.getLength()-d.signedPortionBeginOffset;d=b.getLength()-d.signedPortionEndOffset;b.writeTypeAndLength(Tlv.Interest,b.getLength()-c);c=b.getLength()-a;a=b.getLength()-d;return{encoding:new Blob(b.getOutput(),
!1),signedPortionBeginOffset:c,signedPortionEndOffset:a}};
Tlv0_2WireFormat.prototype.decodeInterest=function(a,b,c){null==c&&(c=!0);b=new TlvDecoder(b);var d=b.readNestedTlvsStart(Tlv.Interest),e=Tlv0_2WireFormat.decodeName(a.getName(),b,c);b.peekType(Tlv.Selectors,d)&&Tlv0_2WireFormat.decodeSelectors(a,b,c);var f=b.readBlobTlv(Tlv.Nonce);a.setInterestLifetimeMilliseconds(b.readOptionalNonNegativeIntegerTlv(Tlv.InterestLifetime,d));if(b.peekType(Tlv.Data,d)){var g=b.getOffset(),h=b.readNestedTlvsStart(Tlv.Data);b.seek(h);a.setLinkWireEncoding(new Blob(b.getSlice(g,
h),c),this)}else a.unsetLink();a.setSelectedDelegationIndex(b.readOptionalNonNegativeIntegerTlv(Tlv.SelectedDelegation,d));if(null!=a.getSelectedDelegationIndex()&&0<=a.getSelectedDelegationIndex()&&!a.hasLink())throw Error("Interest has a selected delegation, but no link object");a.setNonce(new Blob(f,c));b.finishNestedTlvs(d);return e};
Tlv0_2WireFormat.prototype.encodeData=function(a){var b=new TlvEncoder(1500),c=b.getLength();b.writeBlobTlv(Tlv.SignatureValue,a.getSignature().getSignature().buf());var d=b.getLength();Tlv0_2WireFormat.encodeSignatureInfo_(a.getSignature(),b);b.writeBlobTlv(Tlv.Content,a.getContent().buf());Tlv0_2WireFormat.encodeMetaInfo(a.getMetaInfo(),b);Tlv0_2WireFormat.encodeName(a.getName(),b);a=b.getLength();b.writeTypeAndLength(Tlv.Data,b.getLength()-c);c=b.getLength()-a;d=b.getLength()-d;return{encoding:new Blob(b.getOutput(),
!1),signedPortionBeginOffset:c,signedPortionEndOffset:d}};
Tlv0_2WireFormat.prototype.decodeData=function(a,b,c){null==c&&(c=!0);b=new TlvDecoder(b);var d=b.readNestedTlvsStart(Tlv.Data),e=b.getOffset();Tlv0_2WireFormat.decodeName(a.getName(),b,c);Tlv0_2WireFormat.decodeMetaInfo(a.getMetaInfo(),b,c);a.setContent(new Blob(b.readBlobTlv(Tlv.Content),c));Tlv0_2WireFormat.decodeSignatureInfo(a,b,c);var f=b.getOffset();a.getSignature().setSignature(new Blob(b.readBlobTlv(Tlv.SignatureValue),c));b.finishNestedTlvs(d);return{signedPortionBeginOffset:e,signedPortionEndOffset:f}};
Tlv0_2WireFormat.prototype.encodeControlParameters=function(a){var b=new TlvEncoder(256);Tlv0_2WireFormat.encodeControlParameters(a,b);return new Blob(b.getOutput(),!1)};Tlv0_2WireFormat.prototype.decodeControlParameters=function(a,b,c){null==c&&(c=!0);b=new TlvDecoder(b);Tlv0_2WireFormat.decodeControlParameters(a,b,c)};
Tlv0_2WireFormat.prototype.encodeControlResponse=function(a){var b=new TlvEncoder(256),c=b.getLength();null!=a.getBodyAsControlParameters()&&Tlv0_2WireFormat.encodeControlParameters(a.getBodyAsControlParameters(),b);b.writeBlobTlv(Tlv.NfdCommand_StatusText,(new Blob(a.getStatusText())).buf());b.writeNonNegativeIntegerTlv(Tlv.NfdCommand_StatusCode,a.getStatusCode());b.writeTypeAndLength(Tlv.NfdCommand_ControlResponse,b.getLength()-c);return new Blob(b.getOutput(),!1)};
Tlv0_2WireFormat.prototype.decodeControlResponse=function(a,b,c){null==c&&(c=!0);b=new TlvDecoder(b);var d=b.readNestedTlvsStart(Tlv.NfdCommand_ControlResponse);a.setStatusCode(b.readNonNegativeIntegerTlv(Tlv.NfdCommand_StatusCode));var e=new Blob(b.readBlobTlv(Tlv.NfdCommand_StatusText),!1);a.setStatusText(e.toString());b.peekType(Tlv.ControlParameters_ControlParameters,d)?(a.setBodyAsControlParameters(new ControlParameters),Tlv0_2WireFormat.decodeControlParameters(a.getBodyAsControlParameters(),
b,c)):a.setBodyAsControlParameters(null);b.finishNestedTlvs(d)};Tlv0_2WireFormat.prototype.encodeSignatureInfo=function(a){var b=new TlvEncoder(256);Tlv0_2WireFormat.encodeSignatureInfo_(a,b);return new Blob(b.getOutput(),!1)};Tlv0_2WireFormat.SignatureHolder=function(){};Tlv0_2WireFormat.SignatureHolder.prototype.setSignature=function(a){this.signature=a};Tlv0_2WireFormat.SignatureHolder.prototype.getSignature=function(){return this.signature};
Tlv0_2WireFormat.prototype.decodeSignatureInfoAndValue=function(a,b,c){null==c&&(c=!0);var d=new Tlv0_2WireFormat.SignatureHolder;a=new TlvDecoder(a);Tlv0_2WireFormat.decodeSignatureInfo(d,a,c);a=new TlvDecoder(b);d.getSignature().setSignature(new Blob(a.readBlobTlv(Tlv.SignatureValue),c));return d.getSignature()};Tlv0_2WireFormat.prototype.encodeSignatureValue=function(a){var b=new TlvEncoder(256);b.writeBlobTlv(Tlv.SignatureValue,a.getSignature().buf());return new Blob(b.getOutput(),!1)};
Tlv0_2WireFormat.prototype.decodeLpPacket=function(a,b,c){null==c&&(c=!0);a.clear();for(var d=new TlvDecoder(b),e=d.readNestedTlvsStart(Tlv.LpPacket_LpPacket);d.getOffset()<e;){var f=d.readVarNumber(),g=d.readVarNumber(),h=d.getOffset()+g;if(h>b.length)throw new DecodingException(Error("TLV length exceeds the buffer length"));if(f==Tlv.LpPacket_Fragment){a.setFragmentWireEncoding(new Blob(d.getSlice(d.getOffset(),h),c));d.seek(h);break}else if(f==Tlv.LpPacket_Nack)g=new NetworkNack,f=d.readOptionalNonNegativeIntegerTlv(Tlv.LpPacket_NackReason,
h),0>f||f==NetworkNack.Reason.NONE?g.setReason(NetworkNack.Reason.NONE):f==NetworkNack.Reason.CONGESTION||f==NetworkNack.Reason.DUPLICATE||f==NetworkNack.Reason.NO_ROUTE?g.setReason(f):(g.setReason(NetworkNack.Reason.OTHER_CODE),g.setOtherReasonCode(f)),a.addHeaderField(g);else if(f==Tlv.LpPacket_IncomingFaceId)f=new IncomingFaceId,f.setFaceId(d.readNonNegativeInteger(g)),a.addHeaderField(f);else{if(!(f>=Tlv.LpPacket_IGNORE_MIN&&f<=Tlv.LpPacket_IGNORE_MAX&&1===(f&1)))throw new DecodingException(Error("Did not get the expected TLV type"));
d.seek(h)}d.finishNestedTlvs(h)}d.finishNestedTlvs(e)};Tlv0_2WireFormat.prototype.encodeDelegationSet=function(a){for(var b=new TlvEncoder(256),c=a.size()-1;0<=c;--c){var d=b.getLength();Tlv0_2WireFormat.encodeName(a.get(c).getName(),b);b.writeNonNegativeIntegerTlv(Tlv.Link_Preference,a.get(c).getPreference());b.writeTypeAndLength(Tlv.Link_Delegation,b.getLength()-d)}return new Blob(b.getOutput(),!1)};
Tlv0_2WireFormat.prototype.decodeDelegationSet=function(a,b,c){null==c&&(c=!0);var d=new TlvDecoder(b);b=b.length;for(a.clear();d.getOffset()<b;){d.readTypeAndLength(Tlv.Link_Delegation);var e=d.readNonNegativeIntegerTlv(Tlv.Link_Preference),f=new Name;Tlv0_2WireFormat.decodeName(f,d,c);a.addUnsorted(e,f)}};
Tlv0_2WireFormat.prototype.encodeEncryptedContent=function(a){var b=new TlvEncoder(256),c=b.getLength();b.writeBlobTlv(Tlv.Encrypt_EncryptedPayload,a.getPayload().buf());b.writeOptionalBlobTlv(Tlv.Encrypt_InitialVector,a.getInitialVector().buf());b.writeNonNegativeIntegerTlv(Tlv.Encrypt_EncryptionAlgorithm,a.getAlgorithmType());Tlv0_2WireFormat.encodeKeyLocator(Tlv.KeyLocator,a.getKeyLocator(),b);b.writeTypeAndLength(Tlv.Encrypt_EncryptedContent,b.getLength()-c);return new Blob(b.getOutput(),!1)};
Tlv0_2WireFormat.prototype.decodeEncryptedContent=function(a,b,c){null==c&&(c=!0);b=new TlvDecoder(b);var d=b.readNestedTlvsStart(Tlv.Encrypt_EncryptedContent);Tlv0_2WireFormat.decodeKeyLocator(Tlv.KeyLocator,a.getKeyLocator(),b,c);a.setAlgorithmType(b.readNonNegativeIntegerTlv(Tlv.Encrypt_EncryptionAlgorithm));a.setInitialVector(new Blob(b.readOptionalBlobTlv(Tlv.Encrypt_InitialVector,d),c));a.setPayload(new Blob(b.readBlobTlv(Tlv.Encrypt_EncryptedPayload),c));b.finishNestedTlvs(d)};
Tlv0_2WireFormat.get=function(){null===Tlv0_2WireFormat.instance&&(Tlv0_2WireFormat.instance=new Tlv0_2WireFormat);return Tlv0_2WireFormat.instance};Tlv0_2WireFormat.encodeNameComponent=function(a,b){var c=a.isImplicitSha256Digest()?Tlv.ImplicitSha256DigestComponent:Tlv.NameComponent;b.writeBlobTlv(c,a.getValue().buf())};
Tlv0_2WireFormat.decodeNameComponent=function(a,b){null==b&&(b=!0);var c=a.getOffset(),d=a.readVarNumber();a.seek(c);c=new Blob(a.readBlobTlv(d),b);return d===Tlv.ImplicitSha256DigestComponent?Name.Component.fromImplicitSha256Digest(c):new Name.Component(c)};
Tlv0_2WireFormat.encodeName=function(a,b){for(var c=b.getLength(),d,e=a.size()-1;0<=e;--e)Tlv0_2WireFormat.encodeNameComponent(a.get(e),b),e==a.size()-1&&(d=b.getLength());e=b.getLength();b.writeTypeAndLength(Tlv.Name,b.getLength()-c);c=b.getLength()-e;d=0==a.size()?c:b.getLength()-d;return{signedPortionBeginOffset:c,signedPortionEndOffset:d}};
Tlv0_2WireFormat.decodeName=function(a,b,c){a.clear();for(var d=b.readNestedTlvsStart(Tlv.Name),e=b.getOffset(),f=e;b.getOffset()<d;)f=b.getOffset(),a.append(Tlv0_2WireFormat.decodeNameComponent(b,c));b.finishNestedTlvs(d);return{signedPortionBeginOffset:e,signedPortionEndOffset:f}};
Tlv0_2WireFormat.encodeSelectors=function(a,b){var c=b.getLength();a.getMustBeFresh()&&b.writeTypeAndLength(Tlv.MustBeFresh,0);b.writeOptionalNonNegativeIntegerTlv(Tlv.ChildSelector,a.getChildSelector());0<a.getExclude().size()&&Tlv0_2WireFormat.encodeExclude(a.getExclude(),b);null!=a.getKeyLocator().getType()&&Tlv0_2WireFormat.encodeKeyLocator(Tlv.PublisherPublicKeyLocator,a.getKeyLocator(),b);b.writeOptionalNonNegativeIntegerTlv(Tlv.MaxSuffixComponents,a.getMaxSuffixComponents());b.writeOptionalNonNegativeIntegerTlv(Tlv.MinSuffixComponents,
a.getMinSuffixComponents());b.getLength()!=c&&b.writeTypeAndLength(Tlv.Selectors,b.getLength()-c)};
Tlv0_2WireFormat.decodeSelectors=function(a,b,c){null==c&&(c=!0);var d=b.readNestedTlvsStart(Tlv.Selectors);a.setMinSuffixComponents(b.readOptionalNonNegativeIntegerTlv(Tlv.MinSuffixComponents,d));a.setMaxSuffixComponents(b.readOptionalNonNegativeIntegerTlv(Tlv.MaxSuffixComponents,d));b.peekType(Tlv.PublisherPublicKeyLocator,d)?Tlv0_2WireFormat.decodeKeyLocator(Tlv.PublisherPublicKeyLocator,a.getKeyLocator(),b,c):a.getKeyLocator().clear();b.peekType(Tlv.Exclude,d)?Tlv0_2WireFormat.decodeExclude(a.getExclude(),
b,c):a.getExclude().clear();a.setChildSelector(b.readOptionalNonNegativeIntegerTlv(Tlv.ChildSelector,d));a.setMustBeFresh(b.readBooleanTlv(Tlv.MustBeFresh,d));b.finishNestedTlvs(d)};Tlv0_2WireFormat.encodeExclude=function(a,b){for(var c=b.getLength(),d=a.size()-1;0<=d;--d){var e=a.get(d);e==Exclude.ANY?b.writeTypeAndLength(Tlv.Any,0):Tlv0_2WireFormat.encodeNameComponent(e,b)}b.writeTypeAndLength(Tlv.Exclude,b.getLength()-c)};
Tlv0_2WireFormat.decodeExclude=function(a,b,c){null==c&&(c=!0);var d=b.readNestedTlvsStart(Tlv.Exclude);for(a.clear();b.getOffset()<d;)b.peekType(Tlv.Any,d)?(b.readBooleanTlv(Tlv.Any,d),a.appendAny()):a.appendComponent(Tlv0_2WireFormat.decodeNameComponent(b,c));b.finishNestedTlvs(d)};
Tlv0_2WireFormat.encodeKeyLocator=function(a,b,c){var d=c.getLength();if(null!=b.getType())if(b.getType()==KeyLocatorType.KEYNAME)Tlv0_2WireFormat.encodeName(b.getKeyName(),c);else if(b.getType()==KeyLocatorType.KEY_LOCATOR_DIGEST&&0<b.getKeyData().size())c.writeBlobTlv(Tlv.KeyLocatorDigest,b.getKeyData().buf());else throw Error("Unrecognized KeyLocatorType "+b.getType());c.writeTypeAndLength(a,c.getLength()-d)};
Tlv0_2WireFormat.decodeKeyLocator=function(a,b,c,d){null==d&&(d=!0);a=c.readNestedTlvsStart(a);b.clear();if(c.getOffset()!=a){if(c.peekType(Tlv.Name,a))b.setType(KeyLocatorType.KEYNAME),Tlv0_2WireFormat.decodeName(b.getKeyName(),c,d);else if(c.peekType(Tlv.KeyLocatorDigest,a))b.setType(KeyLocatorType.KEY_LOCATOR_DIGEST),b.setKeyData(new Blob(c.readBlobTlv(Tlv.KeyLocatorDigest),d));else throw new DecodingException(Error("decodeKeyLocator: Unrecognized key locator type"));c.finishNestedTlvs(a)}};
Tlv0_2WireFormat.encodeSignatureInfo_=function(a,b){if(a instanceof GenericSignature){var c=a.getSignatureInfoEncoding();try{var d=new TlvDecoder(c.buf()),e=d.readNestedTlvsStart(Tlv.SignatureInfo);d.readNonNegativeIntegerTlv(Tlv.SignatureType);d.finishNestedTlvs(e)}catch(f){throw Error("The GenericSignature encoding is not a valid NDN-TLV SignatureInfo: "+f.message);}b.writeBuffer(c.buf())}else{c=b.getLength();if(a instanceof Sha256WithRsaSignature)Tlv0_2WireFormat.encodeKeyLocator(Tlv.KeyLocator,
a.getKeyLocator(),b),b.writeNonNegativeIntegerTlv(Tlv.SignatureType,Tlv.SignatureType_SignatureSha256WithRsa);else if(a instanceof Sha256WithEcdsaSignature)Tlv0_2WireFormat.encodeKeyLocator(Tlv.KeyLocator,a.getKeyLocator(),b),b.writeNonNegativeIntegerTlv(Tlv.SignatureType,Tlv.SignatureType_SignatureSha256WithEcdsa);else if(a instanceof HmacWithSha256Signature)Tlv0_2WireFormat.encodeKeyLocator(Tlv.KeyLocator,a.getKeyLocator(),b),b.writeNonNegativeIntegerTlv(Tlv.SignatureType,Tlv.SignatureType_SignatureHmacWithSha256);
else if(a instanceof DigestSha256Signature)b.writeNonNegativeIntegerTlv(Tlv.SignatureType,Tlv.SignatureType_DigestSha256);else throw Error("encodeSignatureInfo: Unrecognized Signature object type");b.writeTypeAndLength(Tlv.SignatureInfo,b.getLength()-c)}};
Tlv0_2WireFormat.decodeSignatureInfo=function(a,b,c){null==c&&(c=!0);var d=b.getOffset(),e=b.readNestedTlvsStart(Tlv.SignatureInfo),f=b.readNonNegativeIntegerTlv(Tlv.SignatureType);f==Tlv.SignatureType_SignatureSha256WithRsa?(a.setSignature(new Sha256WithRsaSignature),a=a.getSignature(),Tlv0_2WireFormat.decodeKeyLocator(Tlv.KeyLocator,a.getKeyLocator(),b,c)):f==Tlv.SignatureType_SignatureSha256WithEcdsa?(a.setSignature(new Sha256WithEcdsaSignature),a=a.getSignature(),Tlv0_2WireFormat.decodeKeyLocator(Tlv.KeyLocator,
a.getKeyLocator(),b,c)):f==Tlv.SignatureType_SignatureHmacWithSha256?(a.setSignature(new HmacWithSha256Signature),a=a.getSignature(),Tlv0_2WireFormat.decodeKeyLocator(Tlv.KeyLocator,a.getKeyLocator(),b,c)):f==Tlv.SignatureType_DigestSha256?a.setSignature(new DigestSha256Signature):(a.setSignature(new GenericSignature),a=a.getSignature(),a.setSignatureInfoEncoding(new Blob(b.getSlice(d,e),c),f));b.finishNestedTlvs(e)};
Tlv0_2WireFormat.encodeMetaInfo=function(a,b){var c=b.getLength(),d=a.getFinalBlockId().getValue().buf();null!=d&&0<d.length&&(d=b.getLength(),Tlv0_2WireFormat.encodeNameComponent(a.getFinalBlockId(),b),b.writeTypeAndLength(Tlv.FinalBlockId,b.getLength()-d));b.writeOptionalNonNegativeIntegerTlv(Tlv.FreshnessPeriod,a.getFreshnessPeriod());if(a.getType()!=ContentType.BLOB)if(a.getType()==ContentType.LINK||a.getType()==ContentType.KEY||a.getType()==ContentType.NACK)b.writeNonNegativeIntegerTlv(Tlv.ContentType,
a.getType());else if(a.getType()==ContentType.OTHER_CODE)b.writeNonNegativeIntegerTlv(Tlv.ContentType,a.getOtherTypeCode());else throw Error("unrecognized TLV ContentType");b.writeTypeAndLength(Tlv.MetaInfo,b.getLength()-c)};
Tlv0_2WireFormat.decodeMetaInfo=function(a,b,c){null==c&&(c=!0);var d=b.readNestedTlvsStart(Tlv.MetaInfo),e=b.readOptionalNonNegativeIntegerTlv(Tlv.ContentType,d);null==e||0>e||e===ContentType.BLOB?a.setType(ContentType.BLOB):e===ContentType.LINK||e===ContentType.KEY||e===ContentType.NACK?a.setType(e):(a.setType(ContentType.OTHER_CODE),a.setOtherTypeCode(e));a.setFreshnessPeriod(b.readOptionalNonNegativeIntegerTlv(Tlv.FreshnessPeriod,d));b.peekType(Tlv.FinalBlockId,d)?(e=b.readNestedTlvsStart(Tlv.FinalBlockId),
a.setFinalBlockId(Tlv0_2WireFormat.decodeNameComponent(b,c)),b.finishNestedTlvs(e)):a.setFinalBlockId(null);b.finishNestedTlvs(d)};
Tlv0_2WireFormat.encodeControlParameters=function(a,b){var c=b.getLength();b.writeOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_ExpirationPeriod,a.getExpirationPeriod());if(0<a.getStrategy().size()){var d=b.getLength();Tlv0_2WireFormat.encodeName(a.getStrategy(),b);b.writeTypeAndLength(Tlv.ControlParameters_Strategy,b.getLength()-d)}d=a.getForwardingFlags().getNfdForwardingFlags();d!=(new ForwardingFlags).getNfdForwardingFlags()&&b.writeNonNegativeIntegerTlv(Tlv.ControlParameters_Flags,d);b.writeOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_Cost,
a.getCost());b.writeOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_Origin,a.getOrigin());b.writeOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_LocalControlFeature,a.getLocalControlFeature());0!=a.getUri().length&&b.writeBlobTlv(Tlv.ControlParameters_Uri,(new Blob(a.getUri())).buf());b.writeOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_FaceId,a.getFaceId());null!=a.getName()&&Tlv0_2WireFormat.encodeName(a.getName(),b);b.writeTypeAndLength(Tlv.ControlParameters_ControlParameters,b.getLength()-
c)};
Tlv0_2WireFormat.decodeControlParameters=function(a,b,c){null==c&&(c=!0);a.clear();var d=b.readNestedTlvsStart(Tlv.ControlParameters_ControlParameters);if(b.peekType(Tlv.Name,d)){var e=new Name;Tlv0_2WireFormat.decodeName(e,b,c);a.setName(e)}a.setFaceId(b.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_FaceId,d));b.peekType(Tlv.ControlParameters_Uri,d)&&(e=new Blob(b.readOptionalBlobTlv(Tlv.ControlParameters_Uri,d),!1),a.setUri(e.toString()));a.setLocalControlFeature(b.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_LocalControlFeature,d));
a.setOrigin(b.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_Origin,d));a.setCost(b.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_Cost,d));b.peekType(Tlv.ControlParameters_Flags,d)&&(e=new ForwardingFlags,e.setNfdForwardingFlags(b.readNonNegativeIntegerTlv(Tlv.ControlParameters_Flags,d)),a.setForwardingFlags(e));b.peekType(Tlv.ControlParameters_Strategy,d)&&(e=b.readNestedTlvsStart(Tlv.ControlParameters_Strategy),Tlv0_2WireFormat.decodeName(a.getStrategy(),b,c),b.finishNestedTlvs(e));
a.setExpirationPeriod(b.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_ExpirationPeriod,d));b.finishNestedTlvs(d)};var Tlv0_2WireFormat=require("./tlv-0_2-wire-format.js").Tlv0_2WireFormat,Tlv0_1_1WireFormat=function(){Tlv0_2WireFormat.call(this)};Tlv0_1_1WireFormat.prototype=new Tlv0_2WireFormat;Tlv0_1_1WireFormat.prototype.name="Tlv0_1_1WireFormat";exports.Tlv0_1_1WireFormat=Tlv0_1_1WireFormat;Tlv0_1_1WireFormat.instance=null;
Tlv0_1_1WireFormat.get=function(){null===Tlv0_1_1WireFormat.instance&&(Tlv0_1_1WireFormat.instance=new Tlv0_1_1WireFormat);return Tlv0_1_1WireFormat.instance};var WireFormat=require("./wire-format.js").WireFormat,Tlv0_1_1WireFormat=require("./tlv-0_1_1-wire-format.js").Tlv0_1_1WireFormat,Tlv0_1WireFormat=function(){Tlv0_1_1WireFormat.call(this)};Tlv0_1WireFormat.prototype=new Tlv0_1_1WireFormat;Tlv0_1WireFormat.prototype.name="Tlv0_1WireFormat";exports.Tlv0_1WireFormat=Tlv0_1WireFormat;
Tlv0_1WireFormat.instance=null;Tlv0_1WireFormat.get=function(){null===Tlv0_1WireFormat.instance&&(Tlv0_1WireFormat.instance=new Tlv0_1WireFormat);return Tlv0_1WireFormat.instance};WireFormat=require("./wire-format.js").WireFormat;Tlv0_2WireFormat=require("./tlv-0_2-wire-format.js").Tlv0_2WireFormat;TlvWireFormat=function(){Tlv0_2WireFormat.call(this)};TlvWireFormat.prototype=new Tlv0_2WireFormat;TlvWireFormat.prototype.name="TlvWireFormat";exports.TlvWireFormat=TlvWireFormat;
TlvWireFormat.instance=null;TlvWireFormat.get=function(){null===TlvWireFormat.instance&&(TlvWireFormat.instance=new TlvWireFormat);return TlvWireFormat.instance};WireFormat.setDefaultWireFormat(TlvWireFormat.get());
var DataUtils=require("./data-utils.js").DataUtils,KeyLocatorType=require("../key-locator.js").KeyLocatorType,Interest=require("../interest.js").Interest,Data=require("../data.js").Data,Sha256WithRsaSignature=require("../sha256-with-rsa-signature.js").Sha256WithRsaSignature,Sha256WithEcdsaSignature=require("../sha256-with-ecdsa-signature.js").Sha256WithEcdsaSignature,HmacWithSha256Signature=require("../hmac-with-sha256-signature.js").HmacWithSha256Signature,DigestSha256Signature=require("../digest-sha256-signature.js").DigestSha256Signature,
ContentType=require("../meta-info.js").ContentType,WireFormat=require("./wire-format.js").WireFormat,EncodingUtils=function(){};exports.EncodingUtils=EncodingUtils;EncodingUtils.encodeToHexInterest=function(a,b){b=b||WireFormat.getDefaultWireFormat();return DataUtils.toHex(a.wireEncode(b).buf())};EncodingUtils.encodeToHexData=function(a,b){b=b||WireFormat.getDefaultWireFormat();return DataUtils.toHex(a.wireEncode(b).buf())};
EncodingUtils.decodeHexInterest=function(a,b){b=b||WireFormat.getDefaultWireFormat();var c=new Interest;c.wireDecode(DataUtils.toNumbers(a),b);return c};EncodingUtils.decodeHexData=function(a,b){b=b||WireFormat.getDefaultWireFormat();var c=new Data;c.wireDecode(DataUtils.toNumbers(a),b);return c};
EncodingUtils.decodeSubjectPublicKeyInfo=function(a){a=DataUtils.toHex(a).toLowerCase();a=_x509_getPublicKeyHexArrayFromCertHex(a,_x509_getSubjectPublicKeyPosFromCertHex(a,0));var b=new RSAKey;b.setPublic(a[0],a[1]);return b};
EncodingUtils.dataToHtml=function(a){function b(a){a=a.replace(/&/g,"&amp;");a=a.replace(/</g,"&lt;");c+=a;c+="<br/>"}if(-1==a)return"NO CONTENT FOUND";if(-2==a)return"CONTENT NAME IS EMPTY";var c="";b("name: "+a.getName().toUri());0<a.getContent().size()?(b("content (raw): "+a.getContent().buf().toString("binary")),b("content (hex): "+a.getContent().toHex())):b("content: <empty>");a.getMetaInfo().getType()!=ContentType.BLOB&&(a.getMetaInfo().getType()==ContentType.KEY?b("metaInfo.type: KEY"):a.getMetaInfo().getType()==
ContentType.LINK?b("metaInfo.type: LINK"):a.getMetaInfo().getType()==ContentType.NACK?b("metaInfo.type: NACK"):a.getMetaInfo().getType()==ContentType.OTHER_CODE&&b("metaInfo.type: other code "+a.getMetaInfo().getOtherTypeCode()));b("metaInfo.freshnessPeriod (milliseconds): "+(0<=a.getMetaInfo().getFreshnessPeriod()?""+a.getMetaInfo().getFreshnessPeriod():"<none>"));b("metaInfo.finalBlockId: "+(0<a.getMetaInfo().getFinalBlockId().getValue().size()?a.getMetaInfo().getFinalBlockId().getValue().toHex():
"<none>"));var d=null,e=a.getSignature();e instanceof Sha256WithRsaSignature?(e=a.getSignature(),b("Sha256WithRsa signature.signature: "+(0<e.getSignature().size()?e.getSignature().toHex():"<none>")),d=e.getKeyLocator()):e instanceof Sha256WithEcdsaSignature?(e=a.getSignature(),b("Sha256WithEcdsa signature.signature: "+(0<e.getSignature().size()?e.getSignature().toHex():"<none>")),d=e.getKeyLocator()):e instanceof HmacWithSha256Signature?(e=a.getSignature(),b("HmacWithSha256 signature.signature: "+
(0<e.getSignature().size()?e.getSignature().toHex():"<none>")),d=e.getKeyLocator()):e instanceof DigestSha256Signature&&(e=a.getSignature(),b("DigestSha256 signature.signature: "+(0<e.getSignature().size()?e.getSignature().toHex():"<none>")));null!==d&&(null==d.getType()?b("signature.keyLocator: <none>"):d.getType()==KeyLocatorType.KEY_LOCATOR_DIGEST?b("signature.keyLocator: KeyLocatorDigest: "+d.getKeyData().toHex()):d.getType()==KeyLocatorType.KEYNAME?b("signature.keyLocator: KeyName: "+d.getKeyName().toUri()):
b("signature.keyLocator: <unrecognized ndn_KeyLocatorType>"));return c};var encodeToHexInterest=function(a){return EncodingUtils.encodeToHexInterest(a)},decodeHexInterest=function(a){return EncodingUtils.decodeHexInterest(a)},decodeSubjectPublicKeyInfo=function(a){return EncodingUtils.decodeSubjectPublicKeyInfo(a)};function encodeToBinaryInterest(a){return a.wireEncode().buf()}
var Crypto=require("../../crypto.js"),Blob=require("../../util/blob.js").Blob,DecryptKey=require("../decrypt-key.js").DecryptKey,EncryptKey=require("../encrypt-key.js").EncryptKey,EncryptAlgorithmType=require("./encrypt-params.js").EncryptAlgorithmType,UseSubtleCrypto=require("../../use-subtle-crypto-node.js").UseSubtleCrypto,SyncPromise=require("../../util/sync-promise.js").SyncPromise,AesAlgorithm=function(){};exports.AesAlgorithm=AesAlgorithm;
AesAlgorithm.generateKey=function(a){a=Crypto.randomBytes(a.getKeySize()/8);return new DecryptKey(new Blob(a,!1))};AesAlgorithm.deriveEncryptKey=function(a){return new EncryptKey(a)};
AesAlgorithm.decryptPromise=function(a,b,c,d){if(UseSubtleCrypto()&&!d&&c.getAlgorithmType()!=EncryptAlgorithmType.AesEcb)return c.getAlgorithmType()==EncryptAlgorithmType.AesCbc?crypto.subtle.importKey("raw",a.buf(),{name:"AES-CBC"},!1,["encrypt","decrypt"]).then(function(a){return crypto.subtle.decrypt({name:"AES-CBC",iv:c.getInitialVector().buf()},a,b.buf())}).then(function(a){return Promise.resolve(new Blob(new Uint8Array(a),!1))}):Promise.reject(Error("unsupported encryption mode"));if(c.getAlgorithmType()==
EncryptAlgorithmType.AesEcb)try{var e=Crypto.createDecipheriv("aes-128-ecb",a.buf(),"");return SyncPromise.resolve(new Blob(Buffer.concat([e.update(b.buf()),e["final"]()]),!1))}catch(f){return SyncPromise.reject(f)}else if(c.getAlgorithmType()==EncryptAlgorithmType.AesCbc)try{return e=Crypto.createDecipheriv("aes-128-cbc",a.buf(),c.getInitialVector().buf()),SyncPromise.resolve(new Blob(Buffer.concat([e.update(b.buf()),e["final"]()]),!1))}catch(g){return SyncPromise.reject(g)}else return SyncPromise.reject(Error("unsupported encryption mode"))};
AesAlgorithm.decrypt=function(a,b,c){return SyncPromise.getValue(this.decryptPromise(a,b,c,!0))};
AesAlgorithm.encryptPromise=function(a,b,c,d){return c.getAlgorithmType()==EncryptAlgorithmType.AesCbc&&c.getInitialVector().size()!=AesAlgorithm.BLOCK_SIZE?SyncPromise.reject(Error("incorrect initial vector size")):UseSubtleCrypto()&&!d&&c.getAlgorithmType()!=EncryptAlgorithmType.AesEcb?c.getAlgorithmType()==EncryptAlgorithmType.AesCbc?crypto.subtle.importKey("raw",a.buf(),{name:"AES-CBC"},!1,["encrypt","decrypt"]).then(function(a){return crypto.subtle.encrypt({name:"AES-CBC",iv:c.getInitialVector().buf()},
a,b.buf())}).then(function(a){return Promise.resolve(new Blob(new Uint8Array(a),!1))}):Promise.reject(Error("unsupported encryption mode")):c.getAlgorithmType()==EncryptAlgorithmType.AesEcb?(a=Crypto.createCipheriv("aes-128-ecb",a.buf(),""),SyncPromise.resolve(new Blob(Buffer.concat([a.update(b.buf()),a["final"]()]),!1))):c.getAlgorithmType()==EncryptAlgorithmType.AesCbc?(a=Crypto.createCipheriv("aes-128-cbc",a.buf(),c.getInitialVector().buf()),SyncPromise.resolve(new Blob(Buffer.concat([a.update(b.buf()),
a["final"]()]),!1))):SyncPromise.reject(Error("unsupported encryption mode"))};AesAlgorithm.encrypt=function(a,b,c){return SyncPromise.getValue(this.encryptPromise(a,b,c,!0))};AesAlgorithm.BLOCK_SIZE=16;Crypto=require("../../crypto.js");Blob=require("../../util/blob.js").Blob;EncryptAlgorithmType=function(){};exports.EncryptAlgorithmType=EncryptAlgorithmType;EncryptAlgorithmType.AesEcb=0;EncryptAlgorithmType.AesCbc=1;EncryptAlgorithmType.RsaPkcs=2;EncryptAlgorithmType.RsaOaep=3;
var EncryptParams=function(a,b){this.algorithmType_=a;if(null!=b&&0<b){var c=Crypto.randomBytes(b);this.initialVector_=new Blob(c,!1)}else this.initialVector_=new Blob};exports.EncryptParams=EncryptParams;EncryptParams.prototype.getAlgorithmType=function(){return this.algorithmType_};EncryptParams.prototype.getInitialVector=function(){return this.initialVector_};EncryptParams.prototype.setAlgorithmType=function(a){this.algorithmType_=a;return this};
EncryptParams.prototype.setInitialVector=function(a){this.initialVector_="object"===typeof a&&a instanceof Blob?a:new Blob(a);return this};
var Crypto=require("../../crypto.js"),Name=require("../../name.js").Name,KeyLocator=require("../../key-locator.js").KeyLocator,KeyLocatorType=require("../../key-locator.js").KeyLocatorType,TlvWireFormat=require("../../encoding/tlv-wire-format.js").TlvWireFormat,Blob=require("../../util/blob.js").Blob,AesAlgorithm=require("./aes-algorithm.js").AesAlgorithm,RsaAlgorithm=require("./rsa-algorithm.js").RsaAlgorithm,EncryptParams=require("./encrypt-params.js").EncryptParams,EncryptAlgorithmType=require("./encrypt-params.js").EncryptAlgorithmType,
EncryptedContent=require("../encrypted-content.js").EncryptedContent,SyncPromise=require("../../util/sync-promise.js").SyncPromise,Encryptor=function(a){};exports.Encryptor=Encryptor;Encryptor.NAME_COMPONENT_FOR=new Name.Component("FOR");Encryptor.NAME_COMPONENT_READ=new Name.Component("READ");Encryptor.NAME_COMPONENT_SAMPLE=new Name.Component("SAMPLE");Encryptor.NAME_COMPONENT_ACCESS=new Name.Component("ACCESS");Encryptor.NAME_COMPONENT_E_KEY=new Name.Component("E-KEY");
Encryptor.NAME_COMPONENT_D_KEY=new Name.Component("D-KEY");Encryptor.NAME_COMPONENT_C_KEY=new Name.Component("C-KEY");
Encryptor.encryptDataPromise=function(a,b,c,d,e,f){a.getName().append(Encryptor.NAME_COMPONENT_FOR).append(c);var g=e.getAlgorithmType();return g==EncryptAlgorithmType.AesCbc||g==EncryptAlgorithmType.AesEcb?Encryptor.encryptSymmetricPromise_(b,d,c,e,f).then(function(b){a.setContent(b.wireEncode(TlvWireFormat.get()));return SyncPromise.resolve()}):g==EncryptAlgorithmType.RsaPkcs||g==EncryptAlgorithmType.RsaOaep?Encryptor.encryptAsymmetricPromise_(b,d,c,e,f).then(function(b){a.setContent(b.wireEncode(TlvWireFormat.get()));
return SyncPromise.resolve()},function(g){if(0>g.message.indexOf("data too large for key size"))throw g;g=Crypto.randomBytes(16);var k=new Blob(g,!1);g=new Name(c);g.append("nonce");var l=new EncryptParams(EncryptAlgorithmType.AesCbc,AesAlgorithm.BLOCK_SIZE),m;return Encryptor.encryptSymmetricPromise_(b,k,g,l,f).then(function(a){m=a;return Encryptor.encryptAsymmetricPromise_(k,d,c,e,f)}).then(function(b){var c=m.wireEncode();b=b.wireEncode();var d=new Buffer(c.size()+b.size());b.buf().copy(d,0);c.buf().copy(d,
b.size());a.setContent(new Blob(d,!1));return SyncPromise.resolve()})}):SyncPromise.reject(Error("Unsupported encryption method"))};Encryptor.encryptData=function(a,b,c,d,e){return SyncPromise.getValue(Encryptor.encryptDataPromise(a,b,c,d,e,!0))};
Encryptor.encryptSymmetricPromise_=function(a,b,c,d,e){var f=d.getAlgorithmType(),g=d.getInitialVector(),h=new KeyLocator;h.setType(KeyLocatorType.KEYNAME);h.setKeyName(c);return f==EncryptAlgorithmType.AesCbc||f==EncryptAlgorithmType.AesEcb?f==EncryptAlgorithmType.AesCbc&&g.size()!=AesAlgorithm.BLOCK_SIZE?SyncPromise.reject(Error("incorrect initial vector size")):AesAlgorithm.encryptPromise(b,a,d,e).then(function(a){var b=new EncryptedContent;b.setAlgorithmType(f);b.setKeyLocator(h);b.setPayload(a);
b.setInitialVector(g);return SyncPromise.resolve(b)}):SyncPromise.reject(Error("Unsupported encryption method"))};
Encryptor.encryptAsymmetricPromise_=function(a,b,c,d,e){var f=d.getAlgorithmType(),g=new KeyLocator;g.setType(KeyLocatorType.KEYNAME);g.setKeyName(c);return f==EncryptAlgorithmType.RsaPkcs||f==EncryptAlgorithmType.RsaOaep?RsaAlgorithm.encryptPromise(b,a,d,e).then(function(a){var b=new EncryptedContent;b.setAlgorithmType(f);b.setKeyLocator(g);b.setPayload(a);return SyncPromise.resolve(b)}):SyncPromise.reject(Error("Unsupported encryption method"))};
var constants=require("constants"),Crypto=require("../../crypto.js"),Blob=require("../../util/blob.js").Blob,DecryptKey=require("../decrypt-key.js").DecryptKey,EncryptKey=require("../encrypt-key.js").EncryptKey,EncryptAlgorithmType=require("./encrypt-params.js").EncryptAlgorithmType,DerNode=require("../../encoding/der/der-node.js").DerNode,OID=require("../../encoding/oid.js").OID,PrivateKeyStorage=require("../../security/identity/private-key-storage.js").PrivateKeyStorage,UseSubtleCrypto=require("../../use-subtle-crypto-node.js").UseSubtleCrypto,
SyncPromise=require("../../util/sync-promise.js").SyncPromise,rsaKeygen=null;try{rsaKeygen=require("rsa-keygen")}catch(e$$48){}RsaAlgorithm=function(){};exports.RsaAlgorithm=RsaAlgorithm;
RsaAlgorithm.generateKeyPromise=function(a,b){if(UseSubtleCrypto()&&!b)return crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:a.getKeySize(),publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(function(a){return Promise.resolve(new DecryptKey(new Blob(new Uint8Array(a),!1)))});if(!rsaKeygen)return SyncPromise.reject(Error("Need to install rsa-keygen: sudo npm install rsa-keygen"));
try{var c=rsaKeygen.generate(a.getKeySize()).private_key.toString().replace("-----BEGIN RSA PRIVATE KEY-----","").replace("-----END RSA PRIVATE KEY-----",""),d=new Buffer(c,"base64"),e=PrivateKeyStorage.encodePkcs8PrivateKey(d,new OID(PrivateKeyStorage.RSA_ENCRYPTION_OID),new DerNode.DerNull).buf();return SyncPromise.resolve(new DecryptKey(e))}catch(f){return SyncPromise.reject(f)}};RsaAlgorithm.generateKey=function(a){return SyncPromise.getValue(this.generateKeyPromise(a,!0))};
RsaAlgorithm.deriveEncryptKey=function(a){a=RsaAlgorithm.getRsaPrivateKeyDer(a);var b=DerNode.parse(a.buf(),0).getChildren();a=b[1];var b=b[2],c=new DerNode.DerSequence;c.addChild(a);c.addChild(b);a=c.encode();b=new DerNode.DerSequence;b.addChild(new DerNode.DerOid(new OID(PrivateKeyStorage.RSA_ENCRYPTION_OID)));b.addChild(new DerNode.DerNull);c=new DerNode.DerSequence;c.addChild(b);c.addChild(new DerNode.DerBitString(a.buf(),0));return new EncryptKey(c.encode())};
RsaAlgorithm.decryptPromise=function(a,b,c,d){if(UseSubtleCrypto()&&!d&&c.getAlgorithmType()!=EncryptAlgorithmType.RsaPkcs)return c.getAlgorithmType()==EncryptAlgorithmType.RsaOaep?crypto.subtle.importKey("pkcs8",a.buf(),{name:"RSA-OAEP",hash:{name:"SHA-1"}},!1,["decrypt"]).then(function(a){return crypto.subtle.decrypt({name:"RSA-OAEP"},a,b.buf())}).then(function(a){return Promise.resolve(new Blob(new Uint8Array(a),!1))}):Promise.reject(Error("unsupported padding scheme"));d=RsaAlgorithm.getRsaPrivateKeyDer(a).buf().toString("base64");
a="-----BEGIN RSA PRIVATE KEY-----\n";for(var e=0;e<d.length;e+=64)a+=d.substr(e,64)+"\n";a+="-----END RSA PRIVATE KEY-----";if(c.getAlgorithmType()==EncryptAlgorithmType.RsaPkcs)c=constants.RSA_PKCS1_PADDING;else if(c.getAlgorithmType()==EncryptAlgorithmType.RsaOaep)c=constants.RSA_PKCS1_OAEP_PADDING;else return SyncPromise.reject(Error("unsupported padding scheme"));try{return SyncPromise.resolve(new Blob(Crypto.privateDecrypt({key:a,padding:c},b.buf()),!1))}catch(f){return SyncPromise.reject(f)}};
RsaAlgorithm.decrypt=function(a,b,c){return SyncPromise.getValue(this.decryptPromise(a,b,c,!0))};
RsaAlgorithm.encryptPromise=function(a,b,c,d){if(UseSubtleCrypto()&&!d&&c.getAlgorithmType()!=EncryptAlgorithmType.RsaPkcs)return c.getAlgorithmType()==EncryptAlgorithmType.RsaOaep?crypto.subtle.importKey("spki",a.buf(),{name:"RSA-OAEP",hash:{name:"SHA-1"}},!1,["encrypt"]).then(function(a){return crypto.subtle.encrypt({name:"RSA-OAEP"},a,b.buf())}).then(function(a){return Promise.resolve(new Blob(new Uint8Array(a),!1))}):Promise.reject(Error("unsupported padding scheme"));d=a.buf().toString("base64");
a="-----BEGIN PUBLIC KEY-----\n";for(var e=0;e<d.length;e+=64)a+=d.substr(e,64)+"\n";a+="-----END PUBLIC KEY-----";if(c.getAlgorithmType()==EncryptAlgorithmType.RsaPkcs)c=constants.RSA_PKCS1_PADDING;else if(c.getAlgorithmType()==EncryptAlgorithmType.RsaOaep)c=constants.RSA_PKCS1_OAEP_PADDING;else return SyncPromise.reject(Error("unsupported padding scheme"));try{return SyncPromise.resolve(new Blob(Crypto.publicEncrypt({key:a,padding:c},b.buf()),!1))}catch(f){return SyncPromise.reject(f)}};
RsaAlgorithm.encrypt=function(a,b,c){return SyncPromise.getValue(this.encryptPromise(a,b,c,!0))};RsaAlgorithm.getRsaPrivateKeyDer=function(a){a=DerNode.parse(a.buf(),0).getChildren();if(DerNode.getSequence(a,1).getChildren()[0].toVal()!=PrivateKeyStorage.RSA_ENCRYPTION_OID)throw Error("The PKCS #8 private key is not RSA_ENCRYPTION");return a[2].getPayload()};var SyncPromise=require("../util/sync-promise.js").SyncPromise,ConsumerDb=function(){};exports.ConsumerDb=ConsumerDb;
ConsumerDb.Error=function(a){if(a)return a.__proto__=ConsumerDb.Error.prototype,a};ConsumerDb.Error.prototype=Error();ConsumerDb.Error.prototype.name="ConsumerDbError";ConsumerDb.prototype.getKeyPromise=function(a,b){return SyncPromise.reject(Error("ConsumerDb.getKeyPromise is not implemented"))};ConsumerDb.prototype.addKeyPromise=function(a,b,c){return SyncPromise.reject(Error("ConsumerDb.addKeyPromise is not implemented"))};ConsumerDb.prototype.deleteKeyPromise=function(a,b){return SyncPromise.reject(Error("ConsumerDb.addKeyPromise is not implemented"))};
var Blob=require("../util/blob.js").Blob,Name=require("../name.js").Name,Interest=require("../interest.js").Interest,NetworkNack=require("../network-nack.js").NetworkNack,Link=require("../link.js").Link,EncryptedContent=require("./encrypted-content.js").EncryptedContent,EncryptError=require("./encrypt-error.js").EncryptError,EncryptParams=require("./algo/encrypt-params.js").EncryptParams,EncryptAlgorithmType=require("./algo/encrypt-params.js").EncryptAlgorithmType,RsaAlgorithm=require("./algo/rsa-algorithm.js").RsaAlgorithm,
AesAlgorithm=require("./algo/aes-algorithm.js").AesAlgorithm,Encryptor=require("./algo/encryptor.js").Encryptor,SyncPromise=require("../util/sync-promise.js").SyncPromise,NdnCommon=require("../util/ndn-common.js").NdnCommon,Consumer=function Consumer(b,c,d,e,f,g,h){this.database_=f;this.keyChain_=c;this.face_=b;this.groupName_=new Name(d);this.consumerName_=new Name(e);this.cKeyLink_=void 0==g?Consumer.NO_LINK:new Link(g);this.dKeyLink_=void 0==h?Consumer.NO_LINK:new Link(h);this.cKeyMap_={};this.dKeyMap_=
{}};exports.Consumer=Consumer;Consumer.prototype.consume=function(a,b,c,d){void 0==d&&(d=Consumer.NO_LINK);a=new Interest(a);var e=this;this.sendInterest_(a,1,new Link(d),function(a){e.decryptContent_(a,function(c){try{b(a,c)}catch(d){console.log("Error in onConsumeComplete: "+NdnCommon.getErrorWithStackTrace(d))}},c)},c)};Consumer.prototype.setGroup=function(a){this.groupName_=new Name(a)};
Consumer.prototype.addDecryptionKeyPromise=function(a,b,c){return this.consumerName_.match(a)?this.database_.addKeyPromise(a,b,c):SyncPromise.reject(Error("addDecryptionKey: The consumer name must be a prefix of the key name"))};Consumer.prototype.addDecryptionKey=function(a,b,c,d){return SyncPromise.complete(c,d,this.addDecryptionKeyPromise(a,b,!c))};Consumer.Error=function(a,b){this.errorCode=a;this.message=b};
Consumer.Error.callOnError=function(a,b,c){c||(c="");if(b instanceof Consumer.Error)try{a(b.errorCode,b.message)}catch(d){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(d))}else try{a(EncryptError.ErrorCode.General,c+b)}catch(e){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(e))}};
Consumer.decryptPromise_=function(a,b){return SyncPromise.resolve().then(function(){if("object"==typeof a&&a instanceof Blob){var c=a;a=new EncryptedContent;a.wireDecode(c)}c=a.getPayload();if(a.getAlgorithmType()==EncryptAlgorithmType.AesCbc){var d=new EncryptParams(EncryptAlgorithmType.AesCbc);d.setInitialVector(a.getInitialVector());return AesAlgorithm.decryptPromise(b,c,d)}return a.getAlgorithmType()==EncryptAlgorithmType.RsaOaep?(d=new EncryptParams(EncryptAlgorithmType.RsaOaep),RsaAlgorithm.decryptPromise(b,
c,d)):SyncPromise.reject(new Consumer.Error(EncryptError.ErrorCode.UnsupportedEncryptionScheme,""+a.getAlgorithmType()))})};Consumer.decrypt_=function(a,b,c,d){Consumer.decryptPromise_(a,b).then(function(a){c(a)},function(a){Consumer.Error.callOnError(d,a)})};
Consumer.prototype.decryptContent_=function(a,b,c){var d=new EncryptedContent;try{d.wireDecode(a.getContent())}catch(e){Consumer.Error.callOnError(c,e,"Error decoding EncryptedContent: ");return}var f=d.getKeyLocator().getKeyName();if(a=this.cKeyMap_[f.toUri()])this.decrypt_(d,a,b,c);else{a=new Name(f);a.append(Encryptor.NAME_COMPONENT_FOR).append(this.groupName_);a=new Interest(a);var g=this;this.sendInterest_(a,1,this.cKeyLink_,function(a){g.decryptCKey_(a,function(a){g.cKeyMap_[f.toUri()]=a;Consumer.decrypt_(d,
a,b,c)},c)},c)}};
Consumer.prototype.decryptCKey_=function(a,b,c){a=a.getContent();var d=new EncryptedContent;try{d.wireDecode(a)}catch(e){Consumer.Error.callOnError(c,e,"Error decoding EncryptedContent: ");return}a=d.getKeyLocator().getKeyName();var f=a.getPrefix(-3);f.append(Encryptor.NAME_COMPONENT_D_KEY).append(a.getSubName(-2));if(a=this.dKeyMap_[f.toUri()])this.decrypt_(d,a,b,c);else{a=new Name(f);a.append(Encryptor.NAME_COMPONENT_FOR).append(this.consumerName_);a=new Interest(a);var g=this;this.sendInterest_(a,
1,this.dKeyLink_,function(a){g.decryptDKeyPromise_(a).then(function(a){g.dKeyMap_[f.toUri()]=a;Consumer.decrypt_(d,a,b,c)},function(a){Consumer.Error.callOnError(c,a,"decryptDKey error: ")})},c)}};
Consumer.prototype.decryptDKeyPromise_=function(a){var b,c,d,e=this;return SyncPromise.resolve().then(function(){b=a.getContent();c=new EncryptedContent;c.wireDecode(b);var d=c.getKeyLocator().getKeyName();return e.getDecryptionKeyPromise_(d)}).then(function(a){if(0==a.size())return SyncPromise.reject(new Consumer.Error(EncryptError.ErrorCode.NoDecryptKey,"The desired consumer decryption key in not in the database"));var e=b.buf().slice(c.wireEncode().size());d=new Blob(e,!1);return 0==d.size()?SyncPromise.reject(new Consumer.Error(EncryptError.ErrorCode.InvalidEncryptedFormat,
"The data packet does not satisfy the D-KEY packet format")):Consumer.decryptPromise_(c,a)}).then(function(a){return Consumer.decryptPromise_(d,a)})};
Consumer.prototype.sendInterest_=function(a,b,c,d,e){function f(a,b){try{e(EncryptError.ErrorCode.DataRetrievalFailure,a.getName().toUri())}catch(c){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(c))}}var g=this,h=function(a,b){try{g.keyChain_.verifyData(b,d,function(a,b){try{e(EncryptError.ErrorCode.Validation,"verifyData failed. Reason: "+b)}catch(c){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(c))}})}catch(c){Consumer.Error.callOnError(e,c,"verifyData error: ")}},
k=function(a){0<b?g.sendInterest_(a,b-1,c,d,e):f(a,new NetworkNack)};0!==c.getDelegations().size()&&(a=new Interest(a),a.setLinkWireEncoding(c.wireEncode()));try{this.face_.expressInterest(a,h,k,f)}catch(l){Consumer.Error.callOnError(e,l,"expressInterest error: ")}};Consumer.prototype.getDecryptionKeyPromise_=function(a){return this.database_.getKeyPromise(a)};Consumer.NO_LINK=new Link;Blob=require("../util/blob.js").Blob;
DecryptKey=function DecryptKey(b){this.keyBits_="object"===typeof b&&b instanceof DecryptKey?b.keyBits_:"object"===typeof b&&b instanceof Blob?b:new Blob(b)};exports.DecryptKey=DecryptKey;DecryptKey.prototype.getKeyBits=function(){return this.keyBits_};EncryptError=function(){};exports.EncryptError=EncryptError;EncryptError.ErrorCode={Timeout:1,Validation:2,UnsupportedEncryptionScheme:32,InvalidEncryptedFormat:33,NoDecryptKey:34,EncryptionFailure:35,DataRetrievalFailure:36,General:100};Blob=require("../util/blob.js").Blob;
EncryptKey=function EncryptKey(b){this.keyBits_="object"===typeof b&&b instanceof EncryptKey?b.keyBits_:"object"===typeof b&&b instanceof Blob?b:new Blob(b)};exports.EncryptKey=EncryptKey;EncryptKey.prototype.getKeyBits=function(){return this.keyBits_};KeyLocator=require("../key-locator.js").KeyLocator;WireFormat=require("../encoding/wire-format.js").WireFormat;Blob=require("../util/blob.js").Blob;
EncryptedContent=function EncryptedContent(b){"object"===typeof b&&b instanceof EncryptedContent?(this.algorithmType_=b.algorithmType_,this.keyLocator_=new KeyLocator(b.keyLocator_),this.initialVector_=b.initialVector_,this.payload_=b.payload_):(this.algorithmType_=null,this.keyLocator_=new KeyLocator,this.initialVector_=new Blob,this.payload_=new Blob)};exports.EncryptedContent=EncryptedContent;EncryptedContent.prototype.getAlgorithmType=function(){return this.algorithmType_};
EncryptedContent.prototype.getKeyLocator=function(){return this.keyLocator_};EncryptedContent.prototype.getInitialVector=function(){return this.initialVector_};EncryptedContent.prototype.getPayload=function(){return this.payload_};EncryptedContent.prototype.setAlgorithmType=function(a){this.algorithmType_=a;return this};EncryptedContent.prototype.setKeyLocator=function(a){this.keyLocator_="object"===typeof a&&a instanceof KeyLocator?new KeyLocator(a):new KeyLocator;return this};
EncryptedContent.prototype.setInitialVector=function(a){this.initialVector_="object"===typeof a&&a instanceof Blob?a:new Blob(a);return this};EncryptedContent.prototype.setPayload=function(a){this.payload_="object"===typeof a&&a instanceof Blob?a:new Blob(a);return this};EncryptedContent.prototype.wireEncode=function(a){a=a||WireFormat.getDefaultWireFormat();return a.encodeEncryptedContent(this)};
EncryptedContent.prototype.wireDecode=function(a,b){b=b||WireFormat.getDefaultWireFormat();"object"===typeof a&&a instanceof Blob?b.decodeEncryptedContent(this,a.buf(),!1):b.decodeEncryptedContent(this,a,!0)};var SyncPromise=require("../util/sync-promise.js").SyncPromise,GroupManagerDb=function(){};exports.GroupManagerDb=GroupManagerDb;GroupManagerDb.Error=function(a){if(a)return a.__proto__=GroupManagerDb.Error.prototype,a};GroupManagerDb.Error.prototype=Error();
GroupManagerDb.Error.prototype.name="GroupManagerDbError";GroupManagerDb.prototype.hasSchedulePromise=function(a,b){return SyncPromise.reject(Error("GroupManagerDb.hasSchedulePromise is not implemented"))};GroupManagerDb.prototype.listAllScheduleNamesPromise=function(a){return SyncPromise.reject(Error("GroupManagerDb.listAllScheduleNamesPromise is not implemented"))};GroupManagerDb.prototype.getSchedulePromise=function(a,b){return SyncPromise.reject(Error("GroupManagerDb.getSchedulePromise is not implemented"))};
GroupManagerDb.prototype.getScheduleMembersPromise=function(a,b){return SyncPromise.reject(Error("GroupManagerDb.getScheduleMembersPromise is not implemented"))};GroupManagerDb.prototype.addSchedulePromise=function(a,b,c){return SyncPromise.reject(Error("GroupManagerDb.addSchedulePromise is not implemented"))};GroupManagerDb.prototype.deleteSchedulePromise=function(a,b){return SyncPromise.reject(Error("GroupManagerDb.deleteSchedulePromise is not implemented"))};
GroupManagerDb.prototype.renameSchedulePromise=function(a,b,c){return SyncPromise.reject(Error("GroupManagerDb.renameSchedulePromise is not implemented"))};GroupManagerDb.prototype.updateSchedulePromise=function(a,b,c){return SyncPromise.reject(Error("GroupManagerDb.updateSchedulePromise is not implemented"))};GroupManagerDb.prototype.hasMemberPromise=function(a,b){return SyncPromise.reject(Error("GroupManagerDb.hasMemberPromise is not implemented"))};
GroupManagerDb.prototype.listAllMembersPromise=function(a){return SyncPromise.reject(Error("GroupManagerDb.listAllMembersPromise is not implemented"))};GroupManagerDb.prototype.getMemberSchedulePromise=function(a,b){return SyncPromise.reject(Error("GroupManagerDb.getMemberSchedulePromise is not implemented"))};GroupManagerDb.prototype.addMemberPromise=function(a,b,c,d){return SyncPromise.reject(Error("GroupManagerDb.addMemberPromise is not implemented"))};
GroupManagerDb.prototype.updateMemberSchedulePromise=function(a,b,c){return SyncPromise.reject(Error("GroupManagerDb.updateMemberSchedulePromise is not implemented"))};GroupManagerDb.prototype.deleteMemberPromise=function(a,b){return SyncPromise.reject(Error("GroupManagerDb.deleteMemberPromise is not implemented"))};
var Name=require("../name.js").Name,Data=require("../data.js").Data,SyncPromise=require("../util/sync-promise.js").SyncPromise,IdentityCertificate=require("../security/certificate/identity-certificate.js").IdentityCertificate,SecurityException=require("../security/security-exception.js").SecurityException,RsaKeyParams=require("../security/key-params.js").RsaKeyParams,EncryptParams=require("./algo/encrypt-params.js").EncryptParams,EncryptAlgorithmType=require("./algo/encrypt-params.js").EncryptAlgorithmType,
Encryptor=require("./algo/encryptor.js").Encryptor,RsaAlgorithm=require("./algo/rsa-algorithm.js").RsaAlgorithm,Interval=require("./interval.js").Interval,Schedule=require("./schedule.js").Schedule,GroupManager=function(a,b,c,d,e,f){this.namespace_=(new Name(a)).append(Encryptor.NAME_COMPONENT_READ).append(b);this.database_=c;this.keySize_=d;this.freshnessHours_=e;this.keyChain_=f};exports.GroupManager=GroupManager;
GroupManager.prototype.getGroupKeyPromise=function(a,b){var c=[],d=[],e=this,f,g,h,k;return this.calculateIntervalPromise_(a,c,b).then(function(a){if(!1==a.isValid())return SyncPromise.resolve(d);h=Schedule.toIsoString(a.getStartTime());k=Schedule.toIsoString(a.getEndTime());return e.generateKeyPairPromise_(b).then(function(a){f=a.privateKeyBlob;g=a.publicKeyBlob;return e.createEKeyDataPromise_(h,k,g,b)}).then(function(a){function g(a){return a>=c.length?SyncPromise.resolve():e.createDKeyDataPromise_(h,
k,c[a].keyName,f,c[a].publicKey,b).then(function(b){d.push(b);return g(a+1)})}d.push(a);return g(0)}).then(function(){return SyncPromise.resolve(d)})})};GroupManager.prototype.addSchedulePromise=function(a,b,c){return this.database_.addSchedulePromise(a,b,c)};GroupManager.prototype.deleteSchedulePromise=function(a,b){return this.database_.deleteSchedulePromise(a,b)};GroupManager.prototype.updateSchedulePromise=function(a,b,c){return this.database_.updateSchedulePromise(b,schedule,c)};
GroupManager.prototype.addMemberPromise=function(a,b,c){b=new IdentityCertificate(b);return this.database_.addMemberPromise(a,b.getPublicKeyName(),b.getPublicKeyInfo().getKeyDer(),c)};GroupManager.prototype.removeMemberPromise=function(a,b){return this.database_.deleteMemberPromise(a,b)};GroupManager.prototype.updateMemberSchedulePromise=function(a,b,c){return this.database_.updateMemberSchedulePromise(a,b,c)};
GroupManager.prototype.calculateIntervalPromise_=function(a,b,c){var d=new Interval,e=new Interval;b.splice(0,b.length);var f=this;return this.database_.listAllScheduleNamesPromise(c).then(function(g){function h(k){if(k>=g.length)return SyncPromise.resolve();var l=g[k];return f.database_.getSchedulePromise(l,c).then(function(g){g=g.getCoveringInterval(a);var q=g.interval;if(g.isPositive)return d.isValid()||(d=q),d.intersectWith(q),f.database_.getScheduleMembersPromise(l,c).then(function(a){for(var c=
0;c<a.length;++c)GroupManager.memberKeysAdd_(b,a[c]);return h(k+1)});e.isValid()||(e=q);e.intersectWith(q);return h(k+1)})}return h(0)}).then(function(){if(!d.isValid())return SyncPromise.resolve(new Interval(!1));var a;a=e.isValid()?d.intersectWith(e):d;return SyncPromise.resolve(a)})};GroupManager.memberKeysAdd_=function(a,b){for(var c=0;c<a.length;){var d=a[c].keyName.compare(b.keyName);if(0==d)return;if(0<d)break;c+=1}a.splice(c,0,b)};
GroupManager.prototype.generateKeyPairPromise_=function(a){a=new RsaKeyParams(this.keySize_);return RsaAlgorithm.generateKeyPromise(a).then(function(a){a=a.getKeyBits();var c=RsaAlgorithm.deriveEncryptKey(a).getKeyBits();return SyncPromise.resolve({privateKeyBlob:a,publicKeyBlob:c})})};
GroupManager.prototype.createEKeyDataPromise_=function(a,b,c,d){d=new Name(this.namespace_);d.append(Encryptor.NAME_COMPONENT_E_KEY).append(a).append(b);a=new Data(d);a.getMetaInfo().setFreshnessPeriod(this.freshnessHours_*GroupManager.MILLISECONDS_IN_HOUR);a.setContent(c);return this.keyChain_.signPromise(a)};
GroupManager.prototype.createDKeyDataPromise_=function(a,b,c,d,e,f){var g=new Name(this.namespace_);g.append(Encryptor.NAME_COMPONENT_D_KEY);g.append(a).append(b);var h=new Data(g);h.getMetaInfo().setFreshnessPeriod(this.freshnessHours_*GroupManager.MILLISECONDS_IN_HOUR);a=new EncryptParams(EncryptAlgorithmType.RsaOaep);var k=this;return Encryptor.encryptDataPromise(h,d,c,e,a,f)["catch"](function(a){return SyncPromise.reject(SecurityException(Error("createDKeyData: Error in encryptData: "+a)))}).then(function(){return k.keyChain_.signPromise(h)})};
GroupManager.MILLISECONDS_IN_HOUR=36E5;Interval=function Interval(b,c){if("object"===typeof b&&b instanceof Interval)this.startTime_=b.startTime_,this.endTime_=b.endTime_,this.isValid_=b.isValid_;else if("number"===typeof b){if(!(b<c))throw Error("Interval start time must be less than the end time");this.startTime_=b;this.endTime_=c;this.isValid_=!0}else this.startTime_=-Number.MAX_VALUE,this.endTime_=-Number.MAX_VALUE,this.isValid_=b?!0:!1};exports.Interval=Interval;
Interval.prototype.set=function(a){this.startTime_=a.startTime_;this.endTime_=a.endTime_;this.isValid_=a.isValid_};Interval.prototype.covers=function(a){if(!this.isValid_)throw Error("Interval.covers: This Interval is invalid");return this.isEmpty()?!1:this.startTime_<=a&&a<this.endTime_};
Interval.prototype.intersectWith=function(a){if(!this.isValid_)throw Error("Interval.intersectWith: This Interval is invalid");if(!a.isValid_)throw Error("Interval.intersectWith: The other Interval is invalid");if(this.isEmpty()||a.isEmpty()||this.startTime_>=a.endTime_||this.endTime_<=a.startTime_)return this.startTime_=this.endTime_,this;this.startTime_<=a.startTime_&&(this.startTime_=a.startTime_);this.endTime_>a.endTime_&&(this.endTime_=a.endTime_);return this};
Interval.prototype.unionWith=function(a){if(!this.isValid_)throw Error("Interval.intersectWith: This Interval is invalid");if(!a.isValid_)throw Error("Interval.intersectWith: The other Interval is invalid");if(this.isEmpty())return this.startTime_=a.startTime_,this.endTime_=a.endTime_,this;if(a.isEmpty())return this;if(this.startTime_>=a.endTime_||this.endTime_<=a.startTime_)throw Error("Interval.unionWith: The two intervals do not have an intersection");this.startTime_>a.startTime_&&(this.startTime_=
a.startTime_);this.endTime_<a.endTime_&&(this.endTime_=a.endTime_);return this};Interval.prototype.getStartTime=function(){if(!this.isValid_)throw Error("Interval.getStartTime: This Interval is invalid");return this.startTime_};Interval.prototype.getEndTime=function(){if(!this.isValid_)throw Error("Interval.getEndTime: This Interval is invalid");return this.endTime_};Interval.prototype.isValid=function(){return this.isValid_};
Interval.prototype.isEmpty=function(){if(!this.isValid_)throw Error("Interval.isEmpty: This Interval is invalid");return this.startTime_==this.endTime_};var SyncPromise=require("../util/sync-promise.js").SyncPromise,ProducerDb=function(){};exports.ProducerDb=ProducerDb;ProducerDb.Error=function(a){if(a)return a.__proto__=ProducerDb.Error.prototype,a};ProducerDb.Error.prototype=Error();ProducerDb.Error.prototype.name="ProducerDbError";ProducerDb.prototype.hasContentKeyPromise=function(a,b){return SyncPromise.reject(Error("ProducerDb.hasContentKeyPromise is not implemented"))};
ProducerDb.prototype.getContentKeyPromise=function(a,b){return SyncPromise.reject(Error("ProducerDb.getContentKeyPromise is not implemented"))};ProducerDb.prototype.addContentKeyPromise=function(a,b,c){return SyncPromise.reject(Error("ProducerDb.addContentKeyPromise is not implemented"))};ProducerDb.prototype.deleteContentKeyPromise=function(a,b){return SyncPromise.reject(Error("ProducerDb.deleteContentKeyPromise is not implemented"))};
ProducerDb.getFixedTimeSlot=function(a){return Math.floor(Math.round(a)/36E5)};
var Name=require("../name.js").Name,Interest=require("../interest.js").Interest,Data=require("../data.js").Data,Link=require("../link.js").Link,NetworkNack=require("../network-nack.js").NetworkNack,Exclude=require("../exclude.js").Exclude,Encryptor=require("./algo/encryptor.js").Encryptor,EncryptParams=require("./algo/encrypt-params.js").EncryptParams,EncryptAlgorithmType=require("./algo/encrypt-params.js").EncryptAlgorithmType,AesKeyParams=require("../security/key-params.js").AesKeyParams,AesAlgorithm=
require("./algo/aes-algorithm.js").AesAlgorithm,Schedule=require("./schedule.js").Schedule,EncryptError=require("./encrypt-error.js").EncryptError,NdnCommon=require("../util/ndn-common.js").NdnCommon,SyncPromise=require("../util/sync-promise.js").SyncPromise,Producer=function Producer(b,c,d,e,f,g,h){this.face_=d;this.keyChain_=e;this.database_=f;this.maxRepeatAttempts_=void 0==g?3:g;this.keyRetrievalLink_=void 0==h?Producer.NO_LINK:new Link(h);this.eKeyInfo_={};this.keyRequests_={};d=new Name(b);
e=new Name(c);for(d.append(Encryptor.NAME_COMPONENT_READ);0<e.size();)f=new Name(d),f.append(e),f.append(Encryptor.NAME_COMPONENT_E_KEY),this.eKeyInfo_[f.toUri()]={keyName:f,keyInfo:new Producer.KeyInfo_},e=e.getPrefix(-1);d.append(c);this.namespace_=new Name(b);this.namespace_.append(Encryptor.NAME_COMPONENT_SAMPLE);this.namespace_.append(c)};exports.Producer=Producer;
Producer.prototype.createContentKey=function(a,b,c,d){d||(d=Producer.defaultOnError);var e=Producer.getRoundedTimeSlot_(a),f=new Name(this.namespace_);f.append(Encryptor.NAME_COMPONENT_C_KEY);f.append(Schedule.toIsoString(e));var g,h=this;this.database_.hasContentKeyPromise(a).then(function(e){e?null!=c&&c(f):(e=new AesKeyParams(128),g=AesAlgorithm.generateKey(e).getKeyBits(),h.database_.addContentKeyPromise(a,g).then(function(){var e=Math.round(a);h.keyRequests_[e]=new Producer.KeyRequest_(h.getEKeyInfoSize_());
var e=h.keyRequests_[e],g=new Exclude;Producer.excludeAfter(g,new Name.Component(Schedule.toIsoString(a)));for(var k in h.eKeyInfo_){var p=h.eKeyInfo_[k],s=p.keyInfo;a<s.beginTimeSlot||a>=s.endTimeSlot?(e.repeatAttempts[k]=0,h.sendKeyInterest_((new Interest(p.keyName)).setExclude(g).setChildSelector(1),a,b,d)):(p=new Name(p.keyName),p.append(Schedule.toIsoString(s.beginTimeSlot)),p.append(Schedule.toIsoString(s.endTimeSlot)),h.encryptContentKeyPromise_(s.keyBits,p,a,b,d))}null!=c&&c(f)}))})};
Producer.prototype.produce=function(a,b,c,d,e){e||(e=Producer.defaultOnError);var f=this;this.createContentKey(b,null,function(g){f.database_.getContentKeyPromise(b).then(function(d){var e=new Name(f.namespace_);e.append(Schedule.toIsoString(b));a.setName(e);e=new EncryptParams(EncryptAlgorithmType.AesCbc,16);return Encryptor.encryptData(a,c,g,d,e)}).then(function(){return f.keyChain_.signPromise(a)}).then(function(){try{d()}catch(a){console.log("Error in onComplete: "+NdnCommon.getErrorWithStackTrace(a))}},
function(a){try{e(EncryptError.ErrorCode.General,""+a)}catch(b){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(b))}})},e)};Producer.defaultOnError=function(a,b){};Producer.KeyInfo_=function(){this.endTimeSlot=this.beginTimeSlot=0;this.keyBits=null};Producer.KeyRequest_=function(a){this.interestCount=a;this.repeatAttempts={};this.encryptedKeys=[]};Producer.getRoundedTimeSlot_=function(a){return Math.round(36E5*Math.floor(Math.round(a)/36E5))};
Producer.prototype.sendKeyInterest_=function(a,b,c,d){var e=this;0!==this.keyRetrievalLink_.getDelegations().size()&&(a=new Interest(a),a.setLinkWireEncoding(this.keyRetrievalLink_.wireEncode()));this.face_.expressInterest(a,function(a,g){e.handleCoveringKey_(a,g,b,c,d)},function(a){e.handleTimeout_(a,b,c,d)},function(a,g){e.handleNetworkNack_(a,g,b,c,d)})};
Producer.prototype.handleTimeout_=function(a,b,c,d){var e=Math.round(b),e=this.keyRequests_[e],f=a.getName().toUri();e.repeatAttempts[f]<this.maxRepeatAttempts_?(++e.repeatAttempts[f],this.sendKeyInterest_(a,b,c,d)):this.handleNetworkNack_(a,new NetworkNack,b,c,d)};Producer.prototype.handleNetworkNack_=function(a,b,c,d,e){a=Math.round(c);this.updateKeyRequest_(this.keyRequests_[a],a,d)};
Producer.prototype.updateKeyRequest_=function(a,b,c){--a.interestCount;if(0==a.interestCount&&null!=c){try{c(a.encryptedKeys)}catch(d){console.log("Error in onEncryptedKeys: "+NdnCommon.getErrorWithStackTrace(d))}delete this.keyRequests_[b]}};
Producer.prototype.handleCoveringKey_=function(a,b,c,d,e){var f=Math.round(c),f=this.keyRequests_[f],g=a.getName(),h=g.toUri(),k=b.getName(),l=Schedule.fromIsoString(k.get(Producer.START_TIME_STAMP_INDEX).getValue().toString()),m=Schedule.fromIsoString(k.get(Producer.END_TIME_STAMP_INDEX).getValue().toString());if(c>=m)a=new Exclude(a.getExclude()),Producer.excludeBefore(a,k.get(Producer.START_TIME_STAMP_INDEX)),f.repeatAttempts[h]=0,this.sendKeyInterest_((new Interest(g)).setExclude(a).setChildSelector(1),
c,d,e);else{var q=b.getContent(),p=this;this.encryptContentKeyPromise_(q,k,c,d,e).then(function(a){a&&(a=p.eKeyInfo_[h].keyInfo,a.beginTimeSlot=l,a.endTimeSlot=m,a.keyBits=q)})}};
Producer.prototype.encryptContentKeyPromise_=function(a,b,c,d,e){var f=Math.round(c),g=this.keyRequests_[f],h=new Name(this.namespace_);h.append(Encryptor.NAME_COMPONENT_C_KEY);h.append(Schedule.toIsoString(Producer.getRoundedTimeSlot_(c)));var k,l=this;return this.database_.getContentKeyPromise(c).then(function(c){k=new Data;k.setName(h);var d=new EncryptParams(EncryptAlgorithmType.RsaOaep);return Encryptor.encryptDataPromise(k,c,b,a,d)}).then(function(){return SyncPromise.resolve(!0)},function(a){try{e(EncryptError.ErrorCode.EncryptionFailure,
"encryptData failed: "+a)}catch(b){console.log("Error in onError: "+NdnCommon.getErrorWithStackTrace(b))}return SyncPromise.resolve(!1)}).then(function(a){return a?l.keyChain_.signPromise(k).then(function(){g.encryptedKeys.push(k);l.updateKeyRequest_(g,f,d);return SyncPromise.resolve(!0)}):SyncPromise.resolve(!1)})};Producer.prototype.getEKeyInfoSize_=function(){var a=0;for(key in this.eKeyInfo_)this.eKeyInfo_.hasOwnProperty(key)&&++a;return a};
Producer.ExcludeEntry=function(a,b){this.component_=a;this.anyFollowsComponent_=b};Producer.getExcludeEntries=function(a){for(var b=[],c=0;c<a.size();++c)a.get(c)==Exclude.ANY?0==b.length?b.push(new Producer.ExcludeEntry(new Name.Component,!0)):b[b.length-1].anyFollowsComponent_=!0:b.push(new Producer.ExcludeEntry(a.get(c),!1));return b};
Producer.setExcludeEntries=function(a,b){a.clear();for(var c=0;c<b.length;++c){var d=b[c];0==c&&0==d.component_.getValue().size()&&d.anyFollowsComponent_?a.appendAny():(a.appendComponent(d.component_),d.anyFollowsComponent_&&a.appendAny())}};Producer.findEntryBeforeOrAt=function(a,b){for(var c=a.length-1;0<=c&&!(0>=a[c].component_.compare(b));)--c;return c};
Producer.excludeAfter=function(a,b){var c=Producer.getExcludeEntries(a),d;d=Producer.findEntryBeforeOrAt(c,b);if(0>d)c.splice(0,0,new Producer.ExcludeEntry(b,!0)),d=0;else{var e=c[d];e.anyFollowsComponent_||(e.component_.equals(b)?e.anyFollowsComponent_=!0:(c.splice(d+1,0,new Producer.ExcludeEntry(b,!0)),d+=1))}d+=1;c.splice(d,c.length-d);Producer.setExcludeEntries(a,c)};Producer.excludeBefore=function(a,b){Producer.excludeRange(a,new Name.Component,b)};
Producer.excludeRange=function(a,b,c){if(0<=b.compare(c)){if(0==b.compare(c))throw Error("excludeRange: from == to. To exclude a single component, sue excludeOne.");throw Error("excludeRange: from must be less than to. Invalid range: ["+b.toEscapedString()+", "+c.toEscapedString()+"]");}var d=Producer.getExcludeEntries(a),e=Producer.findEntryBeforeOrAt(d,b);if(0>e)d.splice(0,0,new Producer.ExcludeEntry(b,!0)),b=0;else{var f=d[e];f.anyFollowsComponent_?b=e:f.component_.equals(b)?(f.anyFollowsComponent_=
!0,b=e):(d.splice(e+1,0,new Producer.ExcludeEntry(b,!0)),b=e+1)}e=Producer.findEntryBeforeOrAt(d,c);f=d[e];e==b?d.splice(b+1,0,new Producer.ExcludeEntry(c,!1)):(f.anyFollowsComponent_?c=e+1:f.component_.equals(c)?c=e:(d.splice(e+1,0,new Producer.ExcludeEntry(c,!1)),c=e+1),b+=1,d.splice(b,c-b));Producer.setExcludeEntries(a,d)};Producer.START_TIME_STAMP_INDEX=-2;Producer.END_TIME_STAMP_INDEX=-1;Producer.NO_LINK=new Link;
var Interval=require("./interval.js").Interval,RepetitiveInterval=function RepetitiveInterval(b,c,d,e,f,g){if("object"===typeof b&&b instanceof RepetitiveInterval)repetitiveInterval=b,this.startDate_=repetitiveInterval.startDate_,this.endDate_=repetitiveInterval.endDate_,this.intervalStartHour_=repetitiveInterval.intervalStartHour_,this.intervalEndHour_=repetitiveInterval.intervalEndHour_,this.nRepeats_=repetitiveInterval.nRepeats_,this.repeatUnit_=repetitiveInterval.repeatUnit_;else if("number"===
typeof b){void 0==f&&(f=0);void 0==g&&(g=RepetitiveInterval.RepeatUnit.NONE);this.startDate_=RepetitiveInterval.toDateOnlyMilliseconds_(b);this.endDate_=RepetitiveInterval.toDateOnlyMilliseconds_(c);this.intervalStartHour_=Math.round(d);this.intervalEndHour_=Math.round(e);this.nRepeats_=Math.round(f);this.repeatUnit_=g;if(!(this.intervalStartHour_<this.intervalEndHour_))throw Error("ReptitiveInterval: startHour must be less than endHour");if(!(this.startDate_<=this.endDate_))throw Error("ReptitiveInterval: startDate must be earlier than or same as endDate");
if(!(0<=this.intervalStartHour_))throw Error("ReptitiveInterval: intervalStartHour must be non-negative");if(!(1<=this.intervalEndHour_&&24>=this.intervalEndHour_))throw Error("ReptitiveInterval: intervalEndHour must be from 1 to 24");if(this.repeatUnit_==RepetitiveInterval.RepeatUnit.NONE&&this.startDate_!=this.endDate_)throw Error("ReptitiveInterval: With RepeatUnit.NONE, startDate must equal endDate");}else this.startDate_=-Number.MAX_VALUE,this.endDate_=-Number.MAX_VALUE,this.intervalStartHour_=
0,this.intervalEndHour_=24,this.nRepeats_=0,this.repeatUnit_=RepetitiveInterval.RepeatUnit.NONE};exports.RepetitiveInterval=RepetitiveInterval;RepetitiveInterval.RepeatUnit={NONE:0,DAY:1,MONTH:2,YEAR:3};
RepetitiveInterval.prototype.getInterval=function(a){var b,c;this.hasIntervalOnDate_(a)?(b=RepetitiveInterval.toDateOnlyMilliseconds_(a)+this.intervalStartHour_*RepetitiveInterval.MILLISECONDS_IN_HOUR,c=RepetitiveInterval.toDateOnlyMilliseconds_(a)+this.intervalEndHour_*RepetitiveInterval.MILLISECONDS_IN_HOUR,a<b?(c=b,b=RepetitiveInterval.toDateOnlyMilliseconds_(a),a=!1):a>c?(b=c,c=RepetitiveInterval.toDateOnlyMilliseconds_(a)+RepetitiveInterval.MILLISECONDS_IN_DAY,a=!1):a=!0):(b=RepetitiveInterval.toDateOnlyMilliseconds_(a),
c=RepetitiveInterval.toDateOnlyMilliseconds_(a)+24*RepetitiveInterval.MILLISECONDS_IN_HOUR,a=!1);return{isPositive:a,interval:new Interval(b,c)}};
RepetitiveInterval.prototype.compare=function(a){return this.startDate_<a.startDate_?-1:this.startDate_>a.startDate_?1:this.endDate_<a.endDate_?-1:this.endDate_>a.endDate_?1:this.intervalStartHour_<a.intervalStartHour_?-1:this.intervalStartHour_>a.intervalStartHour_?1:this.intervalEndHour_<a.intervalEndHour_?-1:this.intervalEndHour_>a.intervalEndHour_?1:this.nRepeats_<a.nRepeats_?-1:this.nRepeats_>a.nRepeats_?1:this.repeatUnit_<a.repeatUnit_?-1:this.repeatUnit_>a.repeatUnit_?1:0};
RepetitiveInterval.prototype.getStartDate=function(){return this.startDate_};RepetitiveInterval.prototype.getEndDate=function(){return this.endDate_};RepetitiveInterval.prototype.getIntervalStartHour=function(){return this.intervalStartHour_};RepetitiveInterval.prototype.getIntervalEndHour=function(){return this.intervalEndHour_};RepetitiveInterval.prototype.getNRepeats=function(){return this.nRepeats_};RepetitiveInterval.prototype.getRepeatUnit=function(){return this.repeatUnit_};
RepetitiveInterval.prototype.hasIntervalOnDate_=function(a){a=RepetitiveInterval.toDateOnlyMilliseconds_(a);if(a<this.startDate_||a>this.endDate_)return!1;if(this.repeatUnit_==RepetitiveInterval.RepeatUnit.NONE)return!0;if(this.repeatUnit_==RepetitiveInterval.RepeatUnit.DAY){if(0==(a-this.startDate_)/RepetitiveInterval.MILLISECONDS_IN_DAY%this.nRepeats_)return!0}else{a=new Date(a);var b=new Date(this.startDate_);if(this.repeatUnit_==RepetitiveInterval.RepeatUnit.MONTH&&a.getUTCDate()==b.getUTCDate()){if(0==
(12*(a.getUTCFullYear()-b.getUTCFullYear())+a.getUTCMonth()-b.getUTCMonth())%this.nRepeats_)return!0}else if(this.repeatUnit_==RepetitiveInterval.RepeatUnit.YEAR&&a.getUTCDate()==b.getUTCDate()&&a.getUTCMonth()==b.getUTCMonth()&&0==(a.getUTCFullYear()-b.getUTCFullYear())%this.nRepeats_)return!0}return!1};RepetitiveInterval.toDateOnlyMilliseconds_=function(a){a=Math.round(a);return a-=a%RepetitiveInterval.MILLISECONDS_IN_DAY};RepetitiveInterval.MILLISECONDS_IN_HOUR=36E5;
RepetitiveInterval.MILLISECONDS_IN_DAY=864E5;Interval=require("./interval.js").Interval;RepetitiveInterval=require("./repetitive-interval.js").RepetitiveInterval;Tlv=require("../encoding/tlv/tlv.js").Tlv;TlvEncoder=require("../encoding/tlv/tlv-encoder.js").TlvEncoder;TlvDecoder=require("../encoding/tlv/tlv-decoder.js").TlvDecoder;Blob=require("../util/blob.js").Blob;
Schedule=function Schedule(b){"object"===typeof b&&b instanceof Schedule?(this.whiteIntervalList_=b.whiteIntervalList_.slice(0),this.blackIntervalList_=b.blackIntervalList_.slice(0)):(this.whiteIntervalList_=[],this.blackIntervalList_=[])};exports.Schedule=Schedule;Schedule.prototype.addWhiteInterval=function(a){Schedule.sortedSetAdd_(this.whiteIntervalList_,a);return this};Schedule.prototype.addBlackInterval=function(a){Schedule.sortedSetAdd_(this.blackIntervalList_,a);return this};
Schedule.prototype.getCoveringInterval=function(a){var b=new Interval(!0),c=new Interval(!0),d=new Interval,e=new Interval;Schedule.calculateIntervalResult_(this.blackIntervalList_,a,b,d);if(!b.isEmpty())return{isPositive:!1,interval:b};Schedule.calculateIntervalResult_(this.whiteIntervalList_,a,c,e);return c.isEmpty()&&!e.isValid()?(a=RepetitiveInterval.toDateOnlyMilliseconds_(a),{isPositive:!1,interval:new Interval(a,a+RepetitiveInterval.MILLISECONDS_IN_DAY)}):c.isEmpty()?{isPositive:!1,interval:e}:
d.isValid()?{isPositive:!0,interval:c.intersectWith(d)}:{isPositive:!0,interval:c}};
Schedule.prototype.wireEncode=function(){for(var a=new TlvEncoder(256),b=a.getLength(),c=a.getLength(),d=this.blackIntervalList_.length-1;0<=d;d--)Schedule.encodeRepetitiveInterval_(this.blackIntervalList_[d],a);a.writeTypeAndLength(Tlv.Encrypt_BlackIntervalList,a.getLength()-c);c=a.getLength();for(d=this.whiteIntervalList_.length-1;0<=d;d--)Schedule.encodeRepetitiveInterval_(this.whiteIntervalList_[d],a);a.writeTypeAndLength(Tlv.Encrypt_WhiteIntervalList,a.getLength()-c);a.writeTypeAndLength(Tlv.Encrypt_Schedule,
a.getLength()-b);return new Blob(a.getOutput(),!1)};
Schedule.prototype.wireDecode=function(a){a="object"===typeof a&&a instanceof Blob?a.buf():a;a=new TlvDecoder(a);var b=a.readNestedTlvsStart(Tlv.Encrypt_Schedule);this.whiteIntervalList_=[];for(var c=a.readNestedTlvsStart(Tlv.Encrypt_WhiteIntervalList);a.getOffset()<c;)Schedule.sortedSetAdd_(this.whiteIntervalList_,Schedule.decodeRepetitiveInterval_(a));a.finishNestedTlvs(c);this.blackIntervalList_=[];for(c=a.readNestedTlvsStart(Tlv.Encrypt_BlackIntervalList);a.getOffset()<c;)Schedule.sortedSetAdd_(this.blackIntervalList_,
Schedule.decodeRepetitiveInterval_(a));a.finishNestedTlvs(c);a.finishNestedTlvs(b)};Schedule.sortedSetAdd_=function(a,b){for(var c=0;c<a.length;){var d=a[c].compare(b);if(0==d)return;if(!(0>d))break;++c}a.splice(c,0,b)};
Schedule.encodeRepetitiveInterval_=function(a,b){var c=b.getLength();b.writeNonNegativeIntegerTlv(Tlv.Encrypt_RepeatUnit,a.getRepeatUnit());b.writeNonNegativeIntegerTlv(Tlv.Encrypt_NRepeats,a.getNRepeats());b.writeNonNegativeIntegerTlv(Tlv.Encrypt_IntervalEndHour,a.getIntervalEndHour());b.writeNonNegativeIntegerTlv(Tlv.Encrypt_IntervalStartHour,a.getIntervalStartHour());b.writeBlobTlv(Tlv.Encrypt_EndDate,(new Blob(Schedule.toIsoString(a.getEndDate()))).buf());b.writeBlobTlv(Tlv.Encrypt_StartDate,
(new Blob(Schedule.toIsoString(a.getStartDate()))).buf());b.writeTypeAndLength(Tlv.Encrypt_RepetitiveInterval,b.getLength()-c)};
Schedule.decodeRepetitiveInterval_=function(a){var b=a.readNestedTlvsStart(Tlv.Encrypt_RepetitiveInterval),c=Schedule.fromIsoString((new Blob(a.readBlobTlv(Tlv.Encrypt_StartDate),!0)).toString()),d=Schedule.fromIsoString((new Blob(a.readBlobTlv(Tlv.Encrypt_EndDate),!0)).toString()),e=a.readNonNegativeIntegerTlv(Tlv.Encrypt_IntervalStartHour),f=a.readNonNegativeIntegerTlv(Tlv.Encrypt_IntervalEndHour),g=a.readNonNegativeIntegerTlv(Tlv.Encrypt_NRepeats),h=a.readNonNegativeIntegerTlv(Tlv.Encrypt_RepeatUnit);
a.finishNestedTlvs(b);return new RepetitiveInterval(c,d,e,f,g,h)};Schedule.calculateIntervalResult_=function(a,b,c,d){for(var e=0;e<a.length;++e){var f=a[e].getInterval(b),g=f.interval;!0==f.isPositive?c.unionWith(g):d.isValid()?d.intersectWith(g):d.set(g)}};
Schedule.toIsoString=function(a){a=new Date(Math.round(a));return a.getUTCFullYear()+Schedule.to2DigitString(a.getUTCMonth()+1)+Schedule.to2DigitString(a.getUTCDate())+"T"+Schedule.to2DigitString(a.getUTCHours())+Schedule.to2DigitString(a.getUTCMinutes())+Schedule.to2DigitString(a.getUTCSeconds())};Schedule.to2DigitString=function(a){a=a.toString();return 1===a.length?"0"+a:a};
Schedule.fromIsoString=function(a){if(15!=a.length||"T"!=a.substr(8,1))throw Error("fromIsoString: Format is not the expected yyyymmddThhmmss");return Date.UTC(parseInt(a.substr(0,4)),parseInt(a.substr(4,2)-1),parseInt(a.substr(6,2)),parseInt(a.substr(9,2)),parseInt(a.substr(11,2)),parseInt(a.substr(13,2)))};var IndexedDbConsumerDb=function(a){ConsumerDb.call(this);this.database=new Dexie(a);this.database.version(1).stores({decryptionKeys:"keyName"});this.database.open()};
IndexedDbConsumerDb.prototype=new ConsumerDb;IndexedDbConsumerDb.prototype.name="IndexedDbConsumerDb";
IndexedDbConsumerDb.prototype.getKeyPromise=function(a,b){return b?Promise.reject(new ConsumerDb.Error(Error("IndexedDbConsumerDb.getKeyPromise is only supported for async"))):this.database.decryptionKeys.get(a.toUri()).then(function(a){return a?Promise.resolve(new Blob(a.key)):Promise.resolve(new Blob)})["catch"](function(a){return Promise.reject(new ConsumerDb.Error(Error("IndexedDbConsumerDb.getKeyPromise: Error: "+a)))})};
IndexedDbConsumerDb.prototype.addKeyPromise=function(a,b,c){return c?Promise.reject(new ConsumerDb.Error(Error("IndexedDbConsumerDb.addKeyPromise is only supported for async"))):this.database.decryptionKeys.add({keyName:a.toUri(),key:b.buf()})["catch"](function(a){return Promise.reject(new ConsumerDb.Error(Error("IndexedDbConsumerDb.addKeyPromise: Error: "+a)))})};
IndexedDbConsumerDb.prototype.deleteKeyPromise=function(a,b){return b?Promise.reject(new ConsumerDb.Error(Error("IndexedDbConsumerDb.deleteKeyPromise is only supported for async"))):this.database.decryptionKeys["delete"](a.toUri())["catch"](function(a){return Promise.reject(new ConsumerDb.Error(Error("IndexedDbConsumerDb.deleteKeyPromise: Error: "+a)))})};
var IndexedDbGroupManagerDb=function(a){GroupManagerDb.call(this);this.database=new Dexie(a);this.database.version(1).stores({schedules:"++scheduleId, &scheduleName",members:"memberNameUri, scheduleId"});this.database.open()};IndexedDbGroupManagerDb.prototype=new GroupManagerDb;IndexedDbGroupManagerDb.prototype.name="IndexedDbGroupManagerDb";
IndexedDbGroupManagerDb.prototype.hasSchedulePromise=function(a,b){return b?Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.hasSchedulePromise is only supported for async"))):this.getScheduleIdPromise_(a).then(function(a){return Promise.resolve(-1!=a)})};
IndexedDbGroupManagerDb.prototype.listAllScheduleNamesPromise=function(a){if(a)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.listAllScheduleNamesPromise is only supported for async")));var b=[];return this.database.schedules.each(function(a){b.push(a.scheduleName)}).then(function(){return Promise.resolve(b)})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.listAllScheduleNamesPromise: Error: "+a)))})};
IndexedDbGroupManagerDb.prototype.getSchedulePromise=function(a,b){if(b)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getSchedulePromise is only supported for async")));var c=this;return this.getScheduleIdPromise_(a).then(function(a){return-1!=a?c.database.schedules.get(a).then(function(a){var b=new Schedule;b.wireDecode(new Blob(a.schedule,!1));return Promise.resolve(b)})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getSchedulePromise: Error: "+
a)))}):Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getSchedulePromise: Cannot get the result from the database")))})};
IndexedDbGroupManagerDb.prototype.getScheduleMembersPromise=function(a,b){if(b)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getScheduleMembersPromise is only supported for async")));var c=[],d=this;return this.getScheduleIdPromise_(a).then(function(a){if(-1==a)return Promise.resolve(c);var b=null;return d.database.members.where("scheduleId").equals(a).each(function(a){try{var d=new Name;d.wireDecode(new Blob(a.keyName,!1),TlvWireFormat.get());c.push({keyName:d,publicKey:new Blob(a.publicKey,
!1)})}catch(e){b=new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getScheduleMembersPromise: Error decoding name: "+e))}}).then(function(){return b?Promise.reject(b):Promise.resolve(c)},function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getScheduleMembersPromise: Error: "+a)))})})};
IndexedDbGroupManagerDb.prototype.addSchedulePromise=function(a,b,c){return c?Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.addSchedulePromise is only supported for async"))):0==a.length?Promise.reject(new GroupManagerDb.Error("IndexedDbGroupManagerDb.addSchedulePromise: The schedule name cannot be empty")):this.database.schedules.add({scheduleName:a,schedule:b.wireEncode().buf()})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.addContentKeyPromise: Error: "+
a)))})};
IndexedDbGroupManagerDb.prototype.deleteSchedulePromise=function(a,b){if(b)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.deleteSchedulePromise is only supported for async")));var c,d=this;return this.getScheduleIdPromise_(a).then(function(a){c=a;return d.database.members.where("scheduleId").equals(c).toArray()}).then(function(a){a=a.map(function(a){return d.database.members["delete"](a.memberNameUri)});return Promise.all(a)}).then(function(){return d.database.schedules["delete"](c)})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.deleteSchedulePromise: Error: "+a)))})};
IndexedDbGroupManagerDb.prototype.renameSchedulePromise=function(a,b,c){if(c)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.renameSchedulePromise is only supported for async")));if(0==b.length)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.renameSchedule: The schedule newName cannot be empty")));var d=this;return this.getScheduleIdPromise_(a).then(function(a){return-1==a?Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.renameSchedule: The schedule oldName does not exist"))):
d.database.schedules.update(a,{scheduleName:b})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.renameSchedulePromise: Error: "+a)))})})};
IndexedDbGroupManagerDb.prototype.updateSchedulePromise=function(a,b,c){if(c)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.updateSchedulePromise is only supported for async")));var d=this;return this.getScheduleIdPromise_(a).then(function(c){return-1==c?d.addSchedulePromise(a,b):d.database.schedules.update(c,{schedule:b.wireEncode().buf()})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.updateSchedulePromise: Error: "+
a)))})})};IndexedDbGroupManagerDb.prototype.hasMemberPromise=function(a,b){return b?Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.hasMemberPromise is only supported for async"))):this.database.members.get(a.toUri()).then(function(a){return Promise.resolve(void 0!=a)})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.hasMemberPromise: Error: "+a)))})};
IndexedDbGroupManagerDb.prototype.listAllMembersPromise=function(a){if(a)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.listAllMembersPromise is only supported for async")));var b=[],c=null;return this.database.members.each(function(a){try{var e=new Name;e.wireDecode(new Blob(a.memberName,!1),TlvWireFormat.get());b.push(e)}catch(f){c=new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.listAllMembersPromise: Error decoding name: "+f))}}).then(function(){return c?
Promise.reject(c):Promise.resolve(b)},function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.listAllMembersPromise: Error: "+a)))})};
IndexedDbGroupManagerDb.prototype.getMemberSchedulePromise=function(a,b){if(b)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getMemberSchedulePromise is only supported for async")));var c=this;return this.database.members.get(a.toUri()).then(function(a){if(!a)throw Error("The member identity name does not exist in the database");return c.database.schedules.get(a.scheduleId)}).then(function(a){if(!a)throw Error("The schedule ID for the member identity name does not exist in the database");
return Promise.resolve(a.scheduleName)})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getScheduleIdPromise_: Error: "+a)))})};
IndexedDbGroupManagerDb.prototype.addMemberPromise=function(a,b,c,d){if(d)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.addMemberPromise is only supported for async")));var e=this;return this.getScheduleIdPromise_(a).then(function(a){if(-1==a)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.addMemberPromise: The schedule does not exist")));var d=b.getPrefix(-1);return e.database.members.add({memberNameUri:d.toUri(),memberName:d.wireEncode(TlvWireFormat.get()).buf(),
scheduleId:a,keyName:b.wireEncode(TlvWireFormat.get()).buf(),publicKey:c.buf()})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.addMemberPromise: Error: "+a)))})})};
IndexedDbGroupManagerDb.prototype.updateMemberSchedulePromise=function(a,b,c){if(c)return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.updateMemberSchedulePromise is only supported for async")));var d=this;return this.getScheduleIdPromise_(b).then(function(b){return-1==b?Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.updateMemberSchedulePromise: The schedule does not exist"))):d.database.members.update(a.toUri(),{scheduleId:b})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.updateMemberSchedulePromise: Error: "+
a)))})})};IndexedDbGroupManagerDb.prototype.deleteMemberPromise=function(a,b){return b?Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.deleteMemberPromise is only supported for async"))):this.database.members["delete"](a.toUri())["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.deleteMemberPromise: Error: "+a)))})};
IndexedDbGroupManagerDb.prototype.getScheduleIdPromise_=function(a){var b=-1;return this.database.schedules.where("scheduleName").equals(a).each(function(a){b=a.scheduleId}).then(function(){return Promise.resolve(b)})["catch"](function(a){return Promise.reject(new GroupManagerDb.Error(Error("IndexedDbGroupManagerDb.getScheduleIdPromise_: Error: "+a)))})};var IndexedDbProducerDb=function(a){ProducerDb.call(this);this.database=new Dexie(a);this.database.version(1).stores({contentKeys:"timeSlot"});this.database.open()};
IndexedDbProducerDb.prototype=new ProducerDb;IndexedDbProducerDb.prototype.name="IndexedDbProducerDb";
IndexedDbProducerDb.prototype.hasContentKeyPromise=function(a,b){if(b)return Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.hasContentKeyPromise is only supported for async")));var c=ProducerDb.getFixedTimeSlot(a);return this.database.contentKeys.get(c).then(function(a){return Promise.resolve(void 0!=a)})["catch"](function(a){return Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.hasContentKeyPromise: Error: "+a)))})};
IndexedDbProducerDb.prototype.getContentKeyPromise=function(a,b){if(b)return Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.getContentKeyPromise is only supported for async")));var c=ProducerDb.getFixedTimeSlot(a);return this.database.contentKeys.get(c).then(function(a){return a?Promise.resolve(new Blob(a.key)):Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.getContentKeyPromise: Cannot get the key from the database")))},function(a){return Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.getContentKeyPromise: Error: "+
a)))})};IndexedDbProducerDb.prototype.addContentKeyPromise=function(a,b,c){if(c)return Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.addContentKeyPromise is only supported for async")));a=ProducerDb.getFixedTimeSlot(a);return this.database.contentKeys.add({timeSlot:a,key:b.buf()})["catch"](function(a){return Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.addContentKeyPromise: Error: "+a)))})};
IndexedDbProducerDb.prototype.deleteContentKeyPromise=function(a,b){if(b)return Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.deleteContentKeyPromise is only supported for async")));var c=ProducerDb.getFixedTimeSlot(a);return this.database.contentKeys["delete"](c)["catch"](function(a){return Promise.reject(new ProducerDb.Error(Error("IndexedDbProducerDb.deleteContentKeyPromise: Error: "+a)))})};
var DigestTree=require("./digest-tree.js").DigestTree,Interest=require("../interest.js").Interest,Data=require("../data.js").Data,Name=require("../name.js").Name,Blob=require("../util/blob.js").Blob,MemoryContentCache=require("../util/memory-content-cache.js").MemoryContentCache,SyncStateProto=require("./sync-state.js").SyncStateProto,NdnCommon=require("../util/ndn-common.js").NdnCommon,ChronoSync2013=function ChronoSync2013(b,c,d,e,f,g,h,k,l,m){this.onReceivedSyncState=b;this.onInitialized=c;this.applicationDataPrefixUri=
d.toUri();this.applicationBroadcastPrefix=e;this.session=f;this.face=g;this.keyChain=h;this.certificateName=k;this.sync_lifetime=l;this.usrseq=-1;this.digest_tree=new DigestTree;this.contentCache=new MemoryContentCache(g);this.digest_log=[];this.digest_log.push(new ChronoSync2013.DigestLogEntry("00",[]));this.contentCache.registerPrefix(this.applicationBroadcastPrefix,m,this.onInterest.bind(this));this.enabled=!0;b=new Interest(this.applicationBroadcastPrefix);b.getName().append("00");b.setInterestLifetimeMilliseconds(1E3);
var q;try{q=dcodeIO.ProtoBuf.newBuilder()["import"](SyncStateProto).build("Sync")}catch(p){q=require("protobufjs").newBuilder()["import"](SyncStateProto).build("Sync")}this.SyncStateMsg=q.SyncStateMsg;this.SyncState=q.SyncState;this.face.expressInterest(b,this.onData.bind(this),this.initialTimeOut.bind(this))};exports.ChronoSync2013=ChronoSync2013;ChronoSync2013.prototype.getProducerSequenceNo=function(a,b){var c=this.digest_tree.find(a,b);return 0>c?-1:this.digest_tree.get(c).getSequenceNo()};
ChronoSync2013.prototype.publishNextSequenceNo=function(){this.usrseq++;var a=[new this.SyncState({name:this.applicationDataPrefixUri,type:"UPDATE",seqno:{seq:this.usrseq,session:this.session}})],b=new this.SyncStateMsg({ss:a});this.broadcastSyncState(this.digest_tree.getRoot(),b);this.update(a)||console.log("Warning: ChronoSync: update did not create a new digest log entry");a=new Interest(this.applicationBroadcastPrefix);a.getName().append(this.digest_tree.getRoot());a.setInterestLifetimeMilliseconds(this.sync_lifetime);
this.face.expressInterest(a,this.onData.bind(this),this.syncTimeout.bind(this))};ChronoSync2013.prototype.getSequenceNo=function(){return this.usrseq};ChronoSync2013.DigestLogEntry=function(a,b){this.digest=a;this.data=b};ChronoSync2013.DigestLogEntry.prototype.getDigest=function(){return this.digest};ChronoSync2013.DigestLogEntry.prototype.getData=function(){return this.data};ChronoSync2013.prototype.shutdown=function(){this.enabled=!1;this.contentCache.unregisterAll()};
ChronoSync2013.SyncState=function(a,b,c){this.dataPrefixUri_=a;this.sessionNo_=b;this.sequenceNo_=c};ChronoSync2013.SyncState.prototype.getDataPrefix=function(){return this.dataPrefixUri_};ChronoSync2013.SyncState.prototype.getSessionNo=function(){return this.sessionNo_};ChronoSync2013.SyncState.prototype.getSequenceNo=function(){return this.sequenceNo_};
ChronoSync2013.prototype.broadcastSyncState=function(a,b){var c=new Uint8Array(b.toArrayBuffer()),d=new Data(this.applicationBroadcastPrefix);d.getName().append(a);d.setContent(new Blob(c,!1));var e=this;this.keyChain.sign(d,this.certificateName,function(){e.contentCache.add(d)})};
ChronoSync2013.prototype.update=function(a){for(var b=0;b<a.length;b++)0==a[b].type&&this.digest_tree.update(a[b].name,a[b].seqno.session,a[b].seqno.seq)&&this.applicationDataPrefixUri==a[b].name&&(this.usrseq=a[b].seqno.seq);return-1==this.logfind(this.digest_tree.getRoot())?(a=new ChronoSync2013.DigestLogEntry(this.digest_tree.getRoot(),a),this.digest_log.push(a),!0):!1};
ChronoSync2013.prototype.logfind=function(a){for(var b=0;b<this.digest_log.length;b++)if(a==this.digest_log[b].digest)return b;return-1};
ChronoSync2013.prototype.onInterest=function(a,b,c,d,e){this.enabled&&(a=b.getName().get(this.applicationBroadcastPrefix.size()).toEscapedString(),b.getName().size()==this.applicationBroadcastPrefix.size()+2&&(a=b.getName().get(this.applicationBroadcastPrefix.size()+1).toEscapedString()),b.getName().size()==this.applicationBroadcastPrefix.size()+2||"00"==a?this.processRecoveryInst(b,a,c):(this.contentCache.storePendingInterest(b,c),a!=this.digest_tree.getRoot()&&(b=this.logfind(a),-1==b?(b=new Interest(new Name("/local/timeout")),
b.setInterestLifetimeMilliseconds(2E3),this.face.expressInterest(b,this.dummyOnData,this.judgeRecovery.bind(this,b,a,c))):this.processSyncInst(b,a,c))))};
ChronoSync2013.prototype.onData=function(a,b){if(this.enabled){var c=new Uint8Array(b.getContent().size());c.set(b.getContent().buf());var c=this.SyncStateMsg.decode(c.buffer).ss,d=!1;"00"==this.digest_tree.getRoot()?(d=!0,this.initialOndata(c)):(this.update(c),d=a.getName().size()==this.applicationBroadcastPrefix.size()+2?!0:!1);for(var e=[],f=0;f<c.length;f++)0==c[f].type&&e.push(new ChronoSync2013.SyncState(c[f].name,c[f].seqno.session,c[f].seqno.seq));try{this.onReceivedSyncState(e,d)}catch(g){console.log("Error in onReceivedSyncState: "+
NdnCommon.getErrorWithStackTrace(g))}c=new Name(this.applicationBroadcastPrefix);c.append(this.digest_tree.getRoot());a=new Interest(c);a.setInterestLifetimeMilliseconds(this.sync_lifetime);this.face.expressInterest(a,this.onData.bind(this),this.syncTimeout.bind(this))}};
ChronoSync2013.prototype.initialTimeOut=function(a){if(this.enabled){console.log("no other people");this.usrseq++;try{this.onInitialized()}catch(b){console.log("Error in onInitialized: "+NdnCommon.getErrorWithStackTrace(b))}a=[new this.SyncState({name:this.applicationDataPrefixUri,type:"UPDATE",seqno:{seq:this.usrseq,session:this.session}})];this.update(a);a=new Name(this.applicationBroadcastPrefix);a.append(this.digest_tree.getRoot());a=new Interest(a);a.setInterestLifetimeMilliseconds(this.sync_lifetime);
this.face.expressInterest(a,this.onData.bind(this),this.syncTimeout.bind(this))}};
ChronoSync2013.prototype.processRecoveryInst=function(a,b,c){if(-1!=this.logfind(b)){b=[];for(var d=0;d<this.digest_tree.digestnode.length;d++)b[d]=new this.SyncState({name:this.digest_tree.digestnode[d].getDataPrefix(),type:"UPDATE",seqno:{seq:this.digest_tree.digestnode[d].getSequenceNo(),session:this.digest_tree.digestnode[d].getSessionNo()}});if(0!=b.length){b=new this.SyncStateMsg({ss:b});b=new Uint8Array(b.toArrayBuffer());var e=new Data(a.getName());e.setContent(new Blob(b,!1));"00"==a.getName().get(-1).toEscapedString()&&
e.getMetaInfo().setFreshnessPeriod(1E3);this.keyChain.sign(e,this.certificateName,function(){try{c.putData(e)}catch(a){console.log(a.toString())}})}}};
ChronoSync2013.prototype.processSyncInst=function(a,b,c){for(var d=[],e=[],f=[],g=[],h=a+1;h<this.digest_log.length;h++)for(var k=this.digest_log[h].getData(),l=0;l<k.length;l++)0==k[l].type&&-1!=this.digest_tree.find(k[l].name,k[l].seqno.session)&&(a=e.indexOf(k[l].name),-1==a?(e.push(k[l].name),f.push(k[l].seqno.seq),g.push(k[l].seqno.session)):(f[a]=k[l].seqno.seq,g[a]=k[l].seqno.session));for(l=0;l<e.length;l++)d[l]=new this.SyncState({name:e[l],type:"UPDATE",seqno:{seq:f[l],session:g[l]}});if(0!=
d.length){d=new this.SyncStateMsg({ss:d});d=new Uint8Array(d.toArrayBuffer());a=new Name(this.prefix);a.append(this.chatroom).append(b);var m=new Data(a);m.setContent(new Blob(d,!1));this.keyChain.sign(m,this.certificateName,function(){try{c.putData(m)}catch(a){console.log(a.toString())}})}};
ChronoSync2013.prototype.sendRecovery=function(a){var b=new Name(this.applicationBroadcastPrefix);b.append("recovery").append(a);a=new Interest(b);a.setInterestLifetimeMilliseconds(this.sync_lifetime);this.face.expressInterest(a,this.onData.bind(this),this.syncTimeout.bind(this))};ChronoSync2013.prototype.judgeRecovery=function(a,b,c){a=this.logfind(b);-1!=a?b!=this.digest_tree.root&&this.processSyncInst(a,b,c):this.sendRecovery(b)};
ChronoSync2013.prototype.syncTimeout=function(a){if(this.enabled&&a.getName().get(4).toEscapedString()==this.digest_tree.root){var b=new Name(a.getName()),b=new Interest(b);a.setInterestLifetimeMilliseconds(this.sync_lifetime);this.face.expressInterest(b,this.onData.bind(this),this.syncTimeout.bind(this))}};
ChronoSync2013.prototype.initialOndata=function(a){this.update(a);for(var b=this.digest_tree.getRoot(),c=0;c<a.length;c++)if(a[c].name==this.applicationDataPrefixUri&&a[c].seqno.session==this.session){var d=[new this.SyncState({name:this.applicationDataPrefixUri,type:"UPDATE",seqno:{seq:a[c].seqno.seq+1,session:this.session}})];if(this.update(d)){d=new ChronoSync2013.DigestLogEntry(this.digest_tree.getRoot(),d);this.digest_log.push(d);try{this.onInitialized()}catch(e){console.log("Error in onInitialized: "+
NdnCommon.getErrorWithStackTrace(e))}}}d=0<=this.usrseq?new this.SyncState({name:this.applicationDataPrefixUri,type:"UPDATE",seqno:{seq:this.usrseq,session:this.session}}):new this.SyncState({name:this.applicationDataPrefixUri,type:"UPDATE",seqno:{seq:0,session:this.session}});a=new this.SyncStateMsg({ss:d});this.broadcastSyncState(b,a);if(-1==this.digest_tree.find(this.applicationDataPrefixUri,this.session)&&(this.usrseq++,a=[new this.SyncState({name:this.applicationDataPrefixUri,type:"UPDATE",seqno:{seq:this.usrseq,
session:this.session}})],this.update(a)))try{this.onInitialized()}catch(f){console.log("Error in onInitialized: "+NdnCommon.getErrorWithStackTrace(f))}};ChronoSync2013.prototype.dummyOnData=function(a,b){console.log("*** dummyOnData called. ***")};Crypto=require("../crypto.js");DigestTree=function(){this.root="00";this.digestnode=[]};exports.DigestTree=DigestTree;DigestTree.Node=function(a,b,c){this.dataPrefix=a;this.seqno_session=b;this.seqno_seq=c;this.recomputeDigest()};
DigestTree.Node.prototype.getDataPrefix=function(){return this.dataPrefix};DigestTree.Node.prototype.getSessionNo=function(){return this.seqno_session};DigestTree.Node.prototype.getSequenceNo=function(){return this.seqno_seq};DigestTree.Node.prototype.getDigest=function(){return this.digest};DigestTree.Node.prototype.setSequenceNo=function(a){this.seqno_seq=a;this.recomputeDigest()};
DigestTree.Node.prototype.Int32ToBuffer=function(a){for(var b=new Buffer(4),c=0;4>c;c++)b[c]=a%256,a=Math.floor(a/256);return b};DigestTree.Node.prototype.recomputeDigest=function(){var a=Crypto.createHash("sha256");a.update(this.Int32ToBuffer(this.seqno_session));a.update(this.Int32ToBuffer(this.seqno_seq));var a=a.digest(),b=Crypto.createHash("sha256");b.update(this.dataPrefix);var b=b.digest(),c=Crypto.createHash("sha256");c.update(b);c.update(a);this.digest=c.digest("hex")};
DigestTree.Node.Compare=function(a,b){return a.dataPrefix!=b.dataPrefix?a.dataPrefix<b.dataPrefix:a.seqno_session<b.seqno_session};DigestTree.prototype.update=function(a,b,c){var d=this.find(a,b);if(0<=d)if(this.digestnode[d].getSequenceNo()<c)this.digestnode[d].setSequenceNo(c);else return!1;else a=new DigestTree.Node(a,b,c),this.digestnode.push(a),this.digestnode.sort(this.sortNodes);this.recomputeRoot();return!0};
DigestTree.prototype.sortNodes=function(){for(var a,b=this.digestnode.length;0<b;b--)for(var c=0;c<b-1;c++)this.digestnode[c].getDataPrefix()>this.digestnode[c+1].getDataPrefix()&&(a=this.digestnode[c],this.digestnode[c]=this.digestnode[c+1],this.digestnode[c+1]=a)};
DigestTree.prototype.sortNodes=function(a,b){return a.getDataPrefix()==b.getDataPrefix()&&a.getSessionNo()==b.getSessionNo()?0:a.getDataPrefix()>b.getDataPrefix()||a.getDataPrefix()==b.getDataPrefix()&&a.getSessionNo()>b.getSessionNo()?1:-1};DigestTree.prototype.find=function(a,b){for(var c=0;c<this.digestnode.length;++c)if(this.digestnode[c].getDataPrefix()==a&&this.digestnode[c].getSessionNo()==b)return c;return-1};DigestTree.prototype.size=function(){return this.digestnode.size()};
DigestTree.prototype.get=function(a){return this.digestnode[a]};DigestTree.prototype.getRoot=function(){return this.root};DigestTree.prototype.recomputeRoot=function(){for(var a=Crypto.createHash("sha256"),b=0;b<this.digestnode.length;b++)a.update(new Buffer(this.digestnode[b].digest,"hex"));this.root=a.digest("hex")};
SyncStateProto={"package":"Sync",messages:[{name:"SyncState",fields:[{rule:"required",type:"string",name:"name",id:1,options:{}},{rule:"required",type:"ActionType",name:"type",id:2,options:{}},{rule:"optional",type:"SeqNo",name:"seqno",id:3,options:{}}],enums:[{name:"ActionType",values:[{name:"UPDATE",id:0},{name:"DELETE",id:1},{name:"OTHER",id:2}],options:{}}],messages:[{name:"SeqNo",fields:[{rule:"required",type:"uint32",name:"seq",id:1,options:{}},{rule:"required",type:"uint32",name:"session",
id:2,options:{}}],enums:[],messages:[],options:{}}],options:{}},{name:"SyncStateMsg",fields:[{rule:"repeated",type:"SyncState",name:"ss",id:1,options:{}}],enums:[],messages:[],options:{}}],enums:[],imports:[],options:{}};exports.SyncStateProto=SyncStateProto;
var Crypto=require("../crypto.js"),WireFormat=require("../encoding/wire-format.js").WireFormat,TlvEncoder=require("../encoding/tlv/tlv-encoder.js").TlvEncoder,Blob=require("./blob.js").Blob,CommandInterestGenerator=function(){this.lastTimestamp=Math.round((new Date).getTime())};exports.CommandInterestGenerator=CommandInterestGenerator;
CommandInterestGenerator.prototype.generate=function(a,b,c,d,e){e="function"===typeof d?d:e;d="function"!==typeof d&&d?d:WireFormat.getDefaultWireFormat();for(var f=Math.round((new Date).getTime());f<=this.lastTimestamp;)f+=1;var g=new TlvEncoder(8);g.writeNonNegativeInteger(f);a.getName().append(new Blob(g.getOutput(),!1));a.getName().append(new Blob(Crypto.randomBytes(8),!1));this.lastTimestamp=f;b.sign(a,c,d,function(){(null==a.getInterestLifetimeMilliseconds()||0>a.getInterestLifetimeMilliseconds())&&
a.setInterestLifetimeMilliseconds(1E3);e&&e()})};var LOG=require("../log.js").Log.LOG,InterestFilterTable=function(){this.table_=[]};exports.InterestFilterTable=InterestFilterTable;InterestFilterTable.Entry=function(a,b,c,d){this.interestFilterId_=a;this.filter_=b;this.onInterest_=c;this.face_=d};InterestFilterTable.Entry.prototype.getInterestFilterId=function(){return this.interestFilterId_};InterestFilterTable.Entry.prototype.getFilter=function(){return this.filter_};
InterestFilterTable.Entry.prototype.getOnInterest=function(){return this.onInterest_};InterestFilterTable.Entry.prototype.getFace=function(){return this.face_};InterestFilterTable.prototype.setInterestFilter=function(a,b,c,d){this.table_.push(new InterestFilterTable.Entry(a,b,c,d))};InterestFilterTable.prototype.getMatchedFilters=function(a,b){for(var c=0;c<this.table_.length;++c){var d=this.table_[c];d.getFilter().doesMatch(a.getName())&&b.push(d)}};
InterestFilterTable.prototype.unsetInterestFilter=function(a){for(var b=0,c=this.table_.length-1;0<=c;--c)this.table_[c].getInterestFilterId()==a&&(++b,this.table_.splice(c,1));0===b&&0<LOG&&console.log("unsetInterestFilter: Didn't find interestFilterId "+a)};var NdnCommon=require("../util/ndn-common.js").NdnCommon,LOG=require("../log.js").Log.LOG,PendingInterestTable=function(){this.table_=[];this.removeRequests_=[]};exports.PendingInterestTable=PendingInterestTable;
PendingInterestTable.Entry=function(a,b,c,d,e){this.pendingInterestId_=a;this.interest_=b;this.onData_=c;this.onTimeout_=d;this.onNetworkNack_=e;this.timerId_=-1};PendingInterestTable.Entry.prototype.getPendingInterestId=function(){return this.pendingInterestId_};PendingInterestTable.Entry.prototype.getInterest=function(){return this.interest_};PendingInterestTable.Entry.prototype.getOnData=function(){return this.onData_};PendingInterestTable.Entry.prototype.getOnNetworkNack=function(){return this.onNetworkNack_};
PendingInterestTable.Entry.prototype.callTimeout=function(){if(this.onTimeout_)try{this.onTimeout_(this.interest_)}catch(a){console.log("Error in onTimeout: "+NdnCommon.getErrorWithStackTrace(a))}};PendingInterestTable.Entry.prototype.setTimeout=function(a,b){-1===this.timerId_&&(this.timerId_=setTimeout(a,b))};PendingInterestTable.Entry.prototype.clearTimeout=function(){-1!==this.timerId_&&(clearTimeout(this.timerId_),this.timerId_=-1)};
PendingInterestTable.prototype.add=function(a,b,c,d,e){var f=this.removeRequests_.indexOf(a);if(0<=f)return this.removeRequests_.splice(f,1),null;var g=new PendingInterestTable.Entry(a,b,c,d,e);this.table_.push(g);a=b.getInterestLifetimeMilliseconds()||4E3;var h=this;g.setTimeout(function(){1<LOG&&console.log("Interest time out: "+b.getName().toUri());var a=h.table_.indexOf(g);0<=a&&h.table_.splice(a,1);g.callTimeout()},a);return g};
PendingInterestTable.prototype.extractEntriesForExpressedInterest=function(a,b){for(var c=this.table_.length-1;0<=c;--c){var d=this.table_[c];d.getInterest().matchesData(a)&&(d.clearTimeout(),b.push(d),this.table_.splice(c,1))}};PendingInterestTable.prototype.extractEntriesForNackInterest=function(a,b){for(var c=a.wireEncode(),d=this.table_.length-1;0<=d;--d){var e=this.table_[d];null!=e.getOnNetworkNack()&&e.getInterest().wireEncode().equals(c)&&(e.clearTimeout(),b.push(e),this.table_.splice(d,1))}};
PendingInterestTable.prototype.removePendingInterest=function(a){if(null!=a){for(var b=0,c=this.table_.length-1;0<=c;--c){var d=this.table_[c];d.getPendingInterestId()==a&&(d.clearTimeout(),this.table_.splice(c,1),++b)}0===b&&0<LOG&&console.log("removePendingInterest: Didn't find pendingInterestId "+a);0===b&&0>this.removeRequests_.indexOf(a)&&this.removeRequests_.push(a)}};
var LOG=require("../log.js").Log.LOG,RegisteredPrefixTable=function(a){this.interestFilterTable_=a;this.table_=[];this.removeRequests_=[]};exports.RegisteredPrefixTable=RegisteredPrefixTable;RegisteredPrefixTable.prototype.add=function(a,b,c){var d=this.removeRequests_.indexOf(a);if(0<=d)return this.removeRequests_.splice(d,1),!1;this.table_.push(new RegisteredPrefixTable._Entry(a,b,c));return!0};
RegisteredPrefixTable.prototype.removeRegisteredPrefix=function(a){for(var b=0,c=this.table_.length-1;0<=c;--c){var d=this.table_[c];d.getRegisteredPrefixId()==a&&(++b,0<d.getRelatedInterestFilterId()&&this.interestFilterTable_.unsetInterestFilter(d.getRelatedInterestFilterId()),this.table_.splice(c,1))}0===b&&0<LOG&&console.log("removeRegisteredPrefix: Didn't find registeredPrefixId "+a);0===b&&0>this.removeRequests_.indexOf(a)&&this.removeRequests_.push(a)};
RegisteredPrefixTable._Entry=function(a,b,c){this.registeredPrefixId_=a;this.prefix_=b;this.relatedInterestFilterId_=c};RegisteredPrefixTable._Entry.prototype.getRegisteredPrefixId=function(){return this.registeredPrefixId};RegisteredPrefixTable._Entry.prototype.getPrefix=function(){return this.prefix};RegisteredPrefixTable._Entry.prototype.getRelatedInterestFilterId=function(){return this.relatedInterestFilterId};IncomingFaceId=function(){this.faceId_=null};exports.IncomingFaceId=IncomingFaceId;
IncomingFaceId.prototype.getFaceId=function(){return this.faceId_};IncomingFaceId.prototype.setFaceId=function(a){this.faceId_=a};IncomingFaceId.getFirstHeader=function(a){for(var b=0;b<a.countHeaderFields();++b){var c=a.getHeaderField(b);if(c instanceof IncomingFaceId)return c}return null};var Blob=require("../util/blob.js").Blob,LpPacket=function(){this.headerFields_=[];this.fragmentWireEncoding_=new Blob};exports.LpPacket=LpPacket;LpPacket.prototype.getFragmentWireEncoding=function(){return this.fragmentWireEncoding_};
LpPacket.prototype.countHeaderFields=function(){return this.headerFields_.length};LpPacket.prototype.getHeaderField=function(a){return this.headerFields_[a]};LpPacket.prototype.clear=function(){this.headerFields_=[];this.fragmentWireEncoding_=new Blob};LpPacket.prototype.setFragmentWireEncoding=function(a){this.fragmentWireEncoding_="object"===typeof a&&a instanceof Blob?a:new Blob(a)};LpPacket.prototype.addHeaderField=function(a){this.headerFields_.push(a)};
var DataUtils=require("./encoding/data-utils.js").DataUtils,Name=require("./name.js").Name,Interest=require("./interest.js").Interest,Data=require("./data.js").Data,ControlParameters=require("./control-parameters.js").ControlParameters,ControlResponse=require("./control-response.js").ControlResponse,InterestFilter=require("./interest-filter.js").InterestFilter,WireFormat=require("./encoding/wire-format.js").WireFormat,TlvWireFormat=require("./encoding/tlv-wire-format.js").TlvWireFormat,Tlv=require("./encoding/tlv/tlv.js").Tlv,
TlvDecoder=require("./encoding/tlv/tlv-decoder.js").TlvDecoder,ForwardingFlags=require("./forwarding-flags.js").ForwardingFlags,Transport=require("./transport/transport.js").Transport,TcpTransport=require("./transport/tcp-transport.js").TcpTransport,UnixTransport=require("./transport/unix-transport.js").UnixTransport,CommandInterestGenerator=require("./util/command-interest-generator.js").CommandInterestGenerator,Blob=require("./util/blob.js").Blob,NdnCommon=require("./util/ndn-common.js").NdnCommon,
NetworkNack=require("./network-nack.js").NetworkNack,LpPacket=require("./lp/lp-packet.js").LpPacket,InterestFilterTable=require("./impl/interest-filter-table.js").InterestFilterTable,PendingInterestTable=require("./impl/pending-interest-table.js").PendingInterestTable,RegisteredPrefixTable=require("./impl/registered-prefix-table.js").RegisteredPrefixTable,fs=require("fs"),LOG=require("./log.js").Log.LOG;
Face=function Face(b,c){if(!Face.supported)throw Error("The necessary JavaScript support is not available on this platform.");var d;if("object"==typeof b&&b instanceof Transport){if(this.getConnectionInfo=null,this.transport=b,this.connectionInfo=c||null,d={},null==this.connectionInfo&&this.transport&&this.transport.__proto__&&"UnixTransport"==this.transport.__proto__.name){var e=Face.getUnixSocketFilePathForLocalhost();null!=e?this.connectionInfo=new UnixTransport.ConnectionInfo(e):console.log("Face constructor: Cannot determine the default Unix socket file path for UnixTransport");
0<LOG&&console.log("Using "+this.connectionInfo.toString())}}else d=b||{},this.transport=(d.getTransport||function(){return new TcpTransport})(),this.getConnectionInfo=d.getConnectionInfo||this.transport.defaultGetConnectionInfo,this.connectionInfo=d.connectionInfo||null,null==this.connectionInfo&&(e=void 0!==d.host?d.host:null,this.transport&&this.transport.__proto__&&"UnixTransport"==this.transport.__proto__.name?null!=e?this.connectionInfo=new UnixTransport.ConnectionInfo(e):null==this.getConnectionInfo&&
(e=Face.getUnixSocketFilePathForLocalhost(),null!=e?this.connectionInfo=new UnixTransport.ConnectionInfo(e):console.log("Face constructor: Cannot determine the default Unix socket file path for UnixTransport")):null!=e&&(this.connectionInfo="undefined"!=typeof WebSocketTransport?new WebSocketTransport.ConnectionInfo(e,d.port||9696):new TcpTransport.ConnectionInfo(e,d.port||6363)));null==this.connectionInfo?this.host=this.host=null:(this.host=this.connectionInfo.host,this.host=this.connectionInfo.port);
this.readyStatus=Face.UNOPEN;this.onopen=d.onopen||function(){3<LOG&&console.log("Face connection established.")};this.onclose=d.onclose||function(){3<LOG&&console.log("Face connection closed.")};this.onConnectedCallbacks=[];this.commandKeyChain=null;this.commandCertificateName=new Name;this.commandInterestGenerator=new CommandInterestGenerator;this.timeoutPrefix=new Name("/local/timeout");this.pendingInterestTable_=new PendingInterestTable;this.interestFilterTable_=new InterestFilterTable;this.registeredPrefixTable_=
new RegisteredPrefixTable(this.interestFilterTable_);this.lastEntryId=0};exports.Face=Face;Face.UNOPEN=0;Face.OPEN_REQUESTED=1;Face.OPENED=2;Face.CLOSED=3;TcpTransport.importFace(Face);Face.getUnixSocketFilePathForLocalhost=function(){var a="/var/run/nfd.sock";if(fs.existsSync(a))return a;a="/tmp/.ndnd.sock";return fs.existsSync(a)?a:""};Face.getSupported=function(){try{(new Buffer(1)).slice(0,1)}catch(a){return console.log("NDN not available: Buffer not supported. "+a),!1}return!0};
Face.supported=Face.getSupported();Face.prototype.createRoute=function(a,b){this.connectionInfo=a instanceof Transport.ConnectionInfo?a:new TcpTransport.ConnectionInfo(a,b);this.host=this.connectionInfo.host;this.host=this.connectionInfo.port};Face.prototype.close=function(){this.readyStatus==Face.OPENED&&(this.readyStatus=Face.CLOSED,this.transport.close())};Face.prototype.getNextEntryId=function(){return++this.lastEntryId};
Face.makeShuffledHostGetConnectionInfo=function(a,b,c){a=a.slice(0,a.length);DataUtils.shuffle(a);return function(){return 0==a.length?null:c(a.splice(0,1)[0],b)}};
Face.prototype.expressInterest=function(a,b,c,d,e,f){var g;"object"===typeof a&&a instanceof Interest?g=new Interest(a):b&&"object"===typeof b&&b instanceof Interest?(g=new Interest(b),g.setName(a),b=c,c=d,d=e,e=f):(g=new Interest(a),g.setInterestLifetimeMilliseconds(4E3));var h=b,k,l,m;k="function"===typeof c?c:function(){};l="function"===typeof d?d:null;m=c instanceof WireFormat?c:d instanceof WireFormat?d:e instanceof WireFormat?e:WireFormat.getDefaultWireFormat();var q=this.getNextEntryId();g.setNonce(Face.nonceTemplate_);
g.refreshNonce();if(null==this.connectionInfo)if(null==this.getConnectionInfo)console.log("ERROR: connectionInfo is NOT SET");else{var p=this;this.connectAndExecute(function(){p.reconnectAndExpressInterest(q,g,h,k,l,m)})}else this.reconnectAndExpressInterest(q,g,h,k,l,m);return q};
Face.prototype.reconnectAndExpressInterest=function(a,b,c,d,e,f){var g=this;if(this.connectionInfo.equals(this.transport.connectionInfo)&&this.readyStatus!==Face.UNOPEN)if(this.readyStatus===Face.OPEN_REQUESTED)this.onConnectedCallbacks.push(function(){g.expressInterestHelper(a,b,c,d,e,f)});else if(this.readyStatus===Face.OPENED)this.expressInterestHelper(a,b,c,d,e,f);else throw Error("reconnectAndExpressInterest: unexpected connection is not opened");else this.readyStatus=Face.OPEN_REQUESTED,this.onConnectedCallbacks.push(function(){g.expressInterestHelper(a,
b,c,d,e,f)}),this.transport.connect(this.connectionInfo,this,function(){for(g.readyStatus=Face.OPENED;0<g.onConnectedCallbacks.length;)try{g.onConnectedCallbacks.shift()()}catch(a){console.log("Face.reconnectAndExpressInterest: ignoring exception from onConnectedCallbacks: "+a)}if(g.onopen)g.onopen()},function(){g.closeByTransport()})};
Face.prototype.expressInterestHelper=function(a,b,c,d,e,f){if(null!=this.pendingInterestTable_.add(a,b,c,d,e)&&!this.timeoutPrefix.match(b.getName())){a=b.wireEncode(f);if(a.size()>Face.getMaxNdnPacketSize())throw Error("The encoded interest size exceeds the maximum limit getMaxNdnPacketSize()");this.transport.send(a.buf())}};Face.prototype.removePendingInterest=function(a){this.pendingInterestTable_.removePendingInterest(a)};
Face.prototype.setCommandSigningInfo=function(a,b){this.commandKeyChain=a;this.commandCertificateName=new Name(b)};Face.prototype.setCommandCertificateName=function(a){this.commandCertificateName=new Name(a)};Face.prototype.makeCommandInterest=function(a,b,c){c="function"===typeof b?b:c;b="function"!==typeof b&&b?b:WireFormat.getDefaultWireFormat();this.nodeMakeCommandInterest(a,this.commandKeyChain,this.commandCertificateName,b,c)};
Face.prototype.nodeMakeCommandInterest=function(a,b,c,d,e){this.commandInterestGenerator.generate(a,b,c,d,e)};
Face.prototype.registerPrefix=function(a,b,c,d,e,f){var g=d,h=e,k=f;d="function"===typeof g?g:null;e=g instanceof ForwardingFlags?g:h instanceof ForwardingFlags?h:new ForwardingFlags;f=g instanceof WireFormat?g:h instanceof WireFormat?h:k instanceof WireFormat?k:WireFormat.getDefaultWireFormat();c||(c=function(){});var l=this.getNextEntryId(),m=this,g=function(){m.nfdRegisterPrefix(l,a,b,e,c,d,m.commandKeyChain,m.commandCertificateName,f)};null==this.connectionInfo?null==this.getConnectionInfo?console.log("ERROR: connectionInfo is NOT SET"):
this.connectAndExecute(g):g();return l};Face.getMaxNdnPacketSize=function(){return NdnCommon.MAX_NDN_PACKET_SIZE};Face.RegisterResponse=function(a,b,c,d,e,f){this.prefix=a;this.onRegisterFailed=b;this.onRegisterSuccess=c;this.registeredPrefixId=d;this.parent=e;this.onInterest=f};
Face.RegisterResponse.prototype.onData=function(a,b){var c=new ControlResponse;try{c.wireDecode(b.getContent(),TlvWireFormat.get())}catch(d){0<LOG&&console.log("Register prefix failed: Error decoding the NFD response: "+d);if(this.onRegisterFailed)try{this.onRegisterFailed(this.prefix)}catch(e){console.log("Error in onRegisterFailed: "+NdnCommon.getErrorWithStackTrace(e))}return}if(200!=c.getStatusCode()){if(0<LOG&&console.log("Register prefix failed: Expected NFD status code 200, got: "+c.getStatusCode()),
this.onRegisterFailed)try{this.onRegisterFailed(this.prefix)}catch(f){console.log("Error in onRegisterFailed: "+NdnCommon.getErrorWithStackTrace(f))}}else{if(0!=this.registeredPrefixId&&(c=0,null!=this.onInterest&&(c=this.parent.setInterestFilter(new InterestFilter(this.prefix),this.onInterest)),!this.parent.registeredPrefixTable_.add(this.registeredPrefixId,this.prefix,c))){0<c&&this.parent.unsetInterestFilter(c);return}2<LOG&&console.log("Register prefix succeeded with the NFD forwarder for prefix "+
this.prefix.toUri());if(null!=this.onRegisterSuccess)try{this.onRegisterSuccess(this.prefix,this.registeredPrefixId)}catch(g){console.log("Error in onRegisterSuccess: "+NdnCommon.getErrorWithStackTrace(g))}}};Face.RegisterResponse.prototype.onTimeout=function(a){2<LOG&&console.log("Timeout for NFD register prefix command.");if(this.onRegisterFailed)try{this.onRegisterFailed(this.prefix)}catch(b){console.log("Error in onRegisterFailed: "+NdnCommon.getErrorWithStackTrace(b))}};
Face.prototype.nfdRegisterPrefix=function(a,b,c,d,e,f,g,h,k){if(null==g)throw Error("registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo.");if(0==h.size())throw Error("registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo.");var l=new ControlParameters;l.setName(b);l.setForwardingFlags(d);var m=this;this.isLocal(function(d){var p=new Interest;d?(p.setName(new Name("/localhost/nfd/rib/register")),p.setInterestLifetimeMilliseconds(2E3)):
(p.setName(new Name("/localhop/nfd/rib/register")),p.setInterestLifetimeMilliseconds(4E3));p.getName().append(l.wireEncode(TlvWireFormat.get()));m.nodeMakeCommandInterest(p,g,h,TlvWireFormat.get(),function(){var d=new Face.RegisterResponse(b,e,f,a,m,c);m.reconnectAndExpressInterest(null,p,d.onData.bind(d),d.onTimeout.bind(d),null,k)})},function(a){0<LOG&&console.log("Error in Transport.isLocal: "+a);if(e)try{e(b)}catch(c){console.log("Error in onRegisterFailed: "+NdnCommon.getErrorWithStackTrace(c))}})};
Face.prototype.removeRegisteredPrefix=function(a){this.registeredPrefixTable_.removeRegisteredPrefix(a)};Face.prototype.setInterestFilter=function(a,b){var c=this.getNextEntryId();this.interestFilterTable_.setInterestFilter(c,new InterestFilter(a),b,this);return c};Face.prototype.unsetInterestFilter=function(a){this.interestFilterTable_.unsetInterestFilter(a)};
Face.prototype.putData=function(a,b){b=b||WireFormat.getDefaultWireFormat();var c=a.wireEncode(b);if(c.size()>Face.getMaxNdnPacketSize())throw Error("The encoded Data packet size exceeds the maximum limit getMaxNdnPacketSize()");this.transport.send(c.buf())};Face.prototype.send=function(a){if(a.length>Face.getMaxNdnPacketSize())throw Error("The encoded packet size exceeds the maximum limit getMaxNdnPacketSize()");this.transport.send(a)};
Face.prototype.isLocal=function(a,b){null==this.connectionInfo?a(!1):this.transport.isLocal(this.connectionInfo,a,b)};
Face.prototype.onReceivedElement=function(a){3<LOG&&console.log("Complete element received. Length "+a.length+". Start decoding.");var b=null;a[0]==Tlv.LpPacket_LpPacket&&(b=new LpPacket,TlvWireFormat.get().decodeLpPacket(b,a,!1),a=b.getFragmentWireEncoding().buf());var c=null,d=null;if(a[0]==Tlv.Interest||a[0]==Tlv.Data){var e=new TlvDecoder(a);e.peekType(Tlv.Interest,a.length)?(c=new Interest,c.wireDecode(a,TlvWireFormat.get()),null!=b&&c.setLpPacket(b)):e.peekType(Tlv.Data,a.length)&&(d=new Data,
d.wireDecode(a,TlvWireFormat.get()),null!=b&&d.setLpPacket(b))}if(null!==b&&(b.setFragmentWireEncoding(new Blob),b=NetworkNack.getFirstHeader(b),null!=b)){if(null==c)return;d=[];this.pendingInterestTable_.extractEntriesForNackInterest(c,d);for(a=0;a<d.length;++a){c=d[a];try{c.getOnNetworkNack()(c.getInterest(),b)}catch(f){console.log("Error in onNetworkNack: "+NdnCommon.getErrorWithStackTrace(f))}}return}if(null!==c)for(3<LOG&&console.log("Interest packet received."),d=[],this.interestFilterTable_.getMatchedFilters(c,
d),a=0;a<d.length;++a){b=d[a];3<LOG&&console.log("Found interest filter for "+c.getName().toUri());try{b.getOnInterest()(b.getFilter().getPrefix(),c,this,b.getInterestFilterId(),b.getFilter())}catch(g){console.log("Error in onInterest: "+NdnCommon.getErrorWithStackTrace(g))}}else if(null!==d)for(3<LOG&&console.log("Data packet received."),b=[],this.pendingInterestTable_.extractEntriesForExpressedInterest(d,b),a=0;a<b.length;++a){c=b[a];try{c.getOnData()(c.getInterest(),d)}catch(h){console.log("Error in onData: "+
NdnCommon.getErrorWithStackTrace(h))}}};
Face.prototype.connectAndExecute=function(a){var b=this.getConnectionInfo();if(null==b)console.log("ERROR: No more connectionInfo from getConnectionInfo"),this.host=this.host=this.connectionInfo=null;else if(b.equals(this.connectionInfo))console.log("ERROR: The host returned by getConnectionInfo is not alive: "+this.connectionInfo.toString());else{this.connectionInfo=b;0<LOG&&console.log("connectAndExecute: trying host from getConnectionInfo: "+this.connectionInfo.toString());this.host=this.connectionInfo.host;
this.host=this.connectionInfo.port;b=new Interest(new Name("/"));b.setInterestLifetimeMilliseconds(4E3);var c=this,d=setTimeout(function(){0<LOG&&console.log("connectAndExecute: timeout waiting for host "+c.host);c.connectAndExecute(a)},3E3);this.reconnectAndExpressInterest(null,b,function(b,f){clearTimeout(d);0<LOG&&console.log("connectAndExecute: connected to host "+c.host);a()},function(a){},null,WireFormat.getDefaultWireFormat())}};
Face.prototype.closeByTransport=function(){this.readyStatus=Face.CLOSED;this.onclose()};Face.nonceTemplate_=new Blob(new Buffer(4),!1);
(function(a,b,c){function d(a,b){return"object"!=typeof b&&(b=b()),Object.keys(b).forEach(function(c){a[c]=b[c]}),a}function e(a){return{from:function(b){return a.prototype=Object.create(b.prototype),a.prototype.constructor=a,{extend:function(c){d(a.prototype,"object"!=typeof c?c(b.prototype):c)}}}}}function f(a,b){return b(a)}function g(a,b){function u(a){this._cfg={version:a,storesSource:null,dbschema:{},tables:{},contentUpgrade:null};this.stores({})}function m(a,b,d,e){var g,h,da,k,ra;if(0===a)Object.keys(F).forEach(function(a){W(b,
a,F[a].primKey,F[a].indexes)}),g=v._createTransaction(H,R,F),g.idbtrans=b,g.idbtrans.onerror=G(d,["populating database"]),g.on("error").subscribe(d),r.newPSD(function(){r.PSD.trans=g;try{v.on("populate").fire(g)}catch(a){e.onerror=b.onerror=function(a){a.preventDefault()};try{b.abort()}catch(c){}b.db.close();d(a)}});else{if(h=[],da=S.filter(function(b){return b._cfg.version===a})[0],!da)throw new y("Dexie specification of currently installed DB version is missing");F=v._dbSchema=da._cfg.dbschema;
k=!1;da=S.filter(function(b){return b._cfg.version>a});da.forEach(function(a){var e=F,g=a._cfg.dbschema;sa(e,b);sa(g,b);F=v._dbSchema=g;e=ja(e,g);e.add.forEach(function(a){h.push(function(b,c){W(b,a[0],a[1].primKey,a[1].indexes);c()})});e.change.forEach(function(a){if(a.recreate)throw new y("Not yet support for changing primary key");h.push(function(b,c){var d=b.objectStore(a.name);a.add.forEach(function(a){A(d,a)});a.change.forEach(function(a){d.deleteIndex(a.name);A(d,a)});a.del.forEach(function(a){d.deleteIndex(a)});
c()})});a._cfg.contentUpgrade&&h.push(function(b,c){var e,h;k=!0;e=v._createTransaction(H,[].slice.call(b.db.objectStoreNames,0),g);e.idbtrans=b;h=0;e._promise=f(e._promise,function(a){return function(b,d,e){function f(a){return function(){a.apply(this,arguments);0==--h&&c()}}return++h,a.call(this,b,function(a,b){arguments[0]=f(a);arguments[1]=f(b);d.apply(this,arguments)},e)}});b.onerror=G(d,["running upgrader function for version",a._cfg.version]);e.on("error").subscribe(d);a._cfg.contentUpgrade(e);
0===h&&c()});k&&(0<=navigator.userAgent.indexOf("Trident")||0<=navigator.userAgent.indexOf("MSIE"))||h.push(function(a,b){for(var d,e=0;e<a.db.objectStoreNames.length;++e)d=a.db.objectStoreNames[e],null!==g[d]&&g[d]!==c||a.db.deleteObjectStore(d);b()})});ra=function(){try{h.length?h.shift()(b,ra):s(F,b)}catch(a){e.onerror=b.onerror=function(a){a.preventDefault()};try{b.abort()}catch(c){}b.db.close();d(a)}};ra()}}function ja(a,b){var c={del:[],add:[],change:[]},d,e,f,g,h,k,n,u;for(d in a)b[d]||c.del.push(d);
for(d in b)if(e=a[d],f=b[d],e)if(g={name:d,def:b[d],recreate:!1,del:[],add:[],change:[]},e.primKey.src!==f.primKey.src)g.recreate=!0,c.change.push(g);else{h=e.indexes.reduce(function(a,b){return a[b.name]=b,a},{});f=f.indexes.reduce(function(a,b){return a[b.name]=b,a},{});for(k in h)f[k]||g.del.push(k);for(k in f)n=h[k],u=f[k],n?n.src!==u.src&&g.change.push(u):g.add.push(u);(g.recreate||0<g.del.length||0<g.add.length||0<g.change.length)&&c.change.push(g)}else c.add.push([d,f]);return c}function W(a,
b,c,d){var e=a.db.createObjectStore(b,c.keyPath?{keyPath:c.keyPath,autoIncrement:c.auto}:{autoIncrement:c.auto});return d.forEach(function(a){A(e,a)}),e}function s(a,b){Object.keys(a).forEach(function(c){b.db.objectStoreNames.contains(c)||W(b,c,a[c].primKey,a[c].indexes)})}function A(a,b){a.createIndex(b.name,b.keyPath,{unique:b.unique,multiEntry:b.multi})}function Ha(a,b){throw new y("Table "+b[0]+" not part of transaction. Original Scope Function Source: "+g.Promise.PSD.trans.scopeFunc.toString());
}function T(a,b,c,d){this.name=a;this.schema=c;this.hook=N[a]?N[a].hook:K(null,{creating:[q,h],reading:[l,k],updating:[p,h],deleting:[M,h]});this._tpf=b;this._collClass=d||X}function ta(a,b,c,d){T.call(this,a,b,c,d||ua)}function va(a,b,c,d){function e(a,b,c,d){return f._promise(a,c,d)}var f=this,g,h;this.db=v;this.mode=a;this.storeNames=b;this.idbtrans=null;this.on=K(this,["complete","error"],"abort");this._reculock=0;this._blockedFuncs=[];this._psd=null;this.active=!0;this._dbschema=c;d&&(this.parent=
d);this._tpf=e;this.tables=Object.create(wa);for(d=b.length-1;-1!==d;--d)g=b[d],h=v._tableFactory(a,c[g],e),this.tables[g]=h,this[g]||(this[g]=h)}function Y(a,b,c){this._ctx={table:a,index:":id"===b?null:b,collClass:a._collClass,or:c}}function X(a,b){var c=null,d=null,e;if(b)try{c=b()}catch(f){d=f}e=a._ctx;this._ctx={table:e.table,index:e.index,isPrimKey:!e.index||e.table.schema.primKey.keyPath&&e.index===e.table.schema.primKey.name,range:c,op:"openCursor",dir:"next",unique:"",algorithm:null,filter:null,
isMatch:null,offset:0,limit:Infinity,error:d,or:e.or}}function ua(){X.apply(this,arguments)}function Ia(a,b){return a._cfg.version-b._cfg.version}function U(a,b,c,d,e,f){c.forEach(function(c){var g=v._tableFactory(d,e[c],b);a.forEach(function(a){a[c]||(f?Object.defineProperty(a,c,{configurable:!0,enumerable:!0,get:function(){var a=r.PSD&&r.PSD.trans;return a&&a.db===v?a.tables[c]:g}}):a[c]=g)})})}function ea(a){a.forEach(function(a){for(var b in a)a[b]instanceof T&&delete a[b]})}function ka(a,b,c,
d,e,f){var g=r.PSD;f=f||k;a.onerror||(a.onerror=G(e));a.onsuccess=b?I(function(){var g=a.result,h;g?(h=function(){g["continue"]()},b(g,function(a){h=a},d,e)&&c(f(g.value),g,function(a){h=a}),h()):d()},e,g):I(function(){var b=a.result,e;b?(e=function(){b["continue"]()},c(f(b.value),b,function(a){e=a}),e()):d()},e,g)}function fa(a){var b=[];return a.split(",").forEach(function(a){a=a.trim();var c=a.replace("&","").replace("++","").replace("*",""),d=0!==c.indexOf("[")?c:a.substring(a.indexOf("[")+1,
a.indexOf("]")).split("+");b.push(new Z(c,d||null,-1!==a.indexOf("&"),-1!==a.indexOf("*"),-1!==a.indexOf("++"),Array.isArray(d),-1!==d.indexOf(".")))}),b}function la(a,b){return a<b?-1:a>b?1:0}function Da(a,b){return a<b?1:a>b?-1:0}function Ea(a){return function(b,c){for(var d=0,e;;){if(e=a(b[d],c[d]),0!==e)return e;if(++d,d===b.length||d===c.length)return a(b.length,c.length)}}}function ma(a,b){return a?b?function(){return a.apply(this,arguments)&&b.apply(this,arguments)}:a:b}function Ja(){if(v.verno=
D.version/10,v._dbSchema=F={},R=[].slice.call(D.objectStoreNames,0),0!==R.length){var a=D.transaction(xa(R),"readonly");R.forEach(function(b){for(var c,d=a.objectStore(b),e=d.keyPath,f=e&&"string"==typeof e&&-1!==e.indexOf("."),g=new Z(e,e||"",!1,!1,!!d.autoIncrement,e&&"string"!=typeof e,f),h=[],k=0;k<d.indexNames.length;++k)c=d.index(d.indexNames[k]),f=(e=c.keyPath)&&"string"==typeof e&&-1!==e.indexOf("."),c=new Z(c.name,e,!!c.unique,!!c.multiEntry,!1,e&&"string"!=typeof e,f),h.push(c);F[b]=new ya(b,
g,h,{})});U([N],v._transPromiseFactory,Object.keys(F),H,F)}}function sa(a,b){for(var c,d,e,f,g=b.db.objectStoreNames,h=0;h<g.length;++h)for(c=g[h],d=b.objectStore(c),e=0;e<d.indexNames.length;++e){var k=d.indexNames[e],n=d.index(k).keyPath,n="string"==typeof n?n:"["+[].slice.call(n).join("+")+"]";a[c]&&(f=a[c].idxByName[n],f&&(f.name=k))}}var ca=b&&b.addons||g.addons,na=g.dependencies,ga=na.indexedDB,L=na.IDBKeyRange,oa=na.TypeError,y=na.Error,F=this._dbSchema={},S=[],R=[],N={},wa={},D=null,$=!0,
V=null,ha=!1,H="readwrite",v=this,Q=[],aa=!1,ia=!!Fa();this.version=function(a){if(D)throw new y("Cannot add version when database is open");this.verno=Math.max(this.verno,a);var b=S.filter(function(b){return b._cfg.version===a})[0];return b?b:(b=new u(a),S.push(b),S.sort(Ia),b)};d(u.prototype,{stores:function(a){var b,c;return this._cfg.storesSource=this._cfg.storesSource?d(this._cfg.storesSource,a):a,b={},S.forEach(function(a){d(b,a._cfg.storesSource)}),c=this._cfg.dbschema={},this._parseStoresSpec(b,
c),F=v._dbSchema=c,ea([N,v,wa]),U([wa],Ha,Object.keys(c),H,c),U([N,v,this._cfg.tables],v._transPromiseFactory,Object.keys(c),H,c,!0),R=Object.keys(c),this},upgrade:function(a){var b=this;return B(function(){a(v._createTransaction(H,Object.keys(b._cfg.dbschema),b._cfg.dbschema))}),this._cfg.contentUpgrade=a,this},_parseStoresSpec:function(a,b){Object.keys(a).forEach(function(c){if(null!==a[c]){var d={},e=fa(a[c]),f=e.shift();if(f.multi)throw new y("Primary key cannot be multi-valued");f.keyPath&&f.auto&&
J(d,f.keyPath,0);e.forEach(function(a){if(a.auto)throw new y("Only primary key can be marked as autoIncrement (++)");if(!a.keyPath)throw new y("Index must have a name and cannot be an empty string");J(d,a.keyPath,a.compound?a.keyPath.map(function(){return""}):"")});b[c]=new ya(c,f,e,d)}})}});this._allTables=N;this._tableFactory=function(a,b,c){return"readonly"===a?new T(b.name,c,b,X):new ta(b.name,c,b)};this._createTransaction=function(a,b,c,d){return new va(a,b,c,d)};this._transPromiseFactory=function(a,
b,c){var d,e;return!$||r.PSD&&r.PSD.letThrough?(e=v._createTransaction(a,b,F),e._promise(a,function(a,b){e.error(function(a){v.on("error").fire(a)});c(function(b){e.complete(function(){a(b)})},b,e)})):d=new r(function(e,f){Q.push({resume:function(){var g=v._transPromiseFactory(a,b,c);d.onuncatched=g.onuncatched;g.then(e,f)}})})};this._whenReady=function(a){return!$||r.PSD&&r.PSD.letThrough?new r(a):new r(function(b,c){B(function(){new r(function(){a(b,c)})});Q.push({resume:function(){a(b,c)}})})};
this.verno=0;this.open=function(){return new r(function(b,c){function d(a){try{e.transaction.abort()}catch(b){}ha=!1;V=a;$=!1;c(V);Q.forEach(function(a){a.resume()});Q=[]}if(D||ha)throw new y("Database already opened or being opened");var e;try{if(V=null,ha=!0,0===S.length&&(aa=!0),!ga)throw new y("indexedDB API not found. If using IE10+, make sure to run your code on a server URL (not locally). If using Safari, make sure to include indexedDB polyfill.");e=aa?ga.open(a):ga.open(a,Math.round(10*v.verno));
e.onerror=G(d,["opening database",a]);e.onblocked=function(a){v.on("blocked").fire(a)};e.onupgradeneeded=I(function(b){var c,f;aa&&!v._allowEmptyDB?(e.onerror=function(a){a.preventDefault()},e.transaction.abort(),e.result.close(),c=ga.deleteDatabase(a),c.onsuccess=c.onerror=function(){d(new y("Database '"+a+"' doesnt exist"))}):(e.transaction.onerror=G(d),f=b.oldVersion>Math.pow(2,62)?0:b.oldVersion,m(f/10,e.transaction,d,e))},d);e.onsuccess=I(function(){ha=!1;D=e.result;aa?Ja():0<D.objectStoreNames.length&&
sa(F,D.transaction(xa(D.objectStoreNames),"readonly"));D.onversionchange=v.on("versionchange").fire;ia||za(function(b){if(-1===b.indexOf(a))return b.push(a)});r.newPSD(function(){function a(){$=!1;Q.forEach(function(a){a.resume()});Q=[];b()}r.PSD.letThrough=!0;try{var c=v.on.ready.fire();c&&"function"==typeof c.then?c.then(a,function(a){D.close();D=null;d(a)}):x(a)}catch(e){d(e)}})},d)}catch(f){d(f)}})};this.close=function(){D&&(D.close(),D=null,$=!0,V=null)};this["delete"]=function(){var b=arguments;
return new r(function(c,d){function e(){v.close();var b=ga.deleteDatabase(a);b.onsuccess=function(){ia||za(function(b){var c=b.indexOf(a);if(0<=c)return b.splice(c,1)});c()};b.onerror=G(d,["deleting",a]);b.onblocked=function(){v.on("blocked").fire()}}if(0<b.length)throw new y("Arguments not allowed in db.delete()");ha?Q.push({resume:e}):e()})};this.backendDB=function(){return D};this.isOpen=function(){return null!==D};this.hasFailed=function(){return null!==V};this.dynamicallyOpened=function(){return aa};
this.name=a;Object.defineProperty(this,"tables",{get:function(){return Object.keys(N).map(function(a){return N[a]})}});this.on=K(this,"error","populate","blocked",{ready:[O,h],versionchange:[w,h]});this.on.ready.subscribe=f(this.on.ready.subscribe,function(a){return function(b,c){function d(){return c||v.on.ready.unsubscribe(d),b.apply(this,arguments)}a.call(this,d);v.isOpen()&&($?Q.push({resume:d}):d())}});B(function(){v.on("populate").fire(v._createTransaction(H,R,F));v.on("error").fire(new y)});
this.transaction=function(a,b,c){function d(b,g){var n=null,u,l,E;try{if(h)throw h;n=v._createTransaction(a,k,F,e);u=k.map(function(a){return n.tables[a]});u.push(n);E=0;r.newPSD(function(){r.PSD.trans=n;n.scopeFunc=c;e&&(n.idbtrans=e.idbtrans,n._promise=f(n._promise,function(a){return function(b,c,d){function e(a){return function(b){var c;return r._rootExec(function(){c=a(b);r._tickFinalize(function(){0==--E&&n.active&&(n.active=!1,n.on.complete.fire())})}),c}}return++E,a.call(this,b,function(a,
b,d){return c(e(a),e(b),d)},d)}}));n.complete(function(){b(l)});n.error(function(a){n.idbtrans&&(n.idbtrans.onerror=Ga);try{n.abort()}catch(b){}e&&(e.active=!1,e.on.error.fire(a));var c=g(a);e||c||v.on.error.fire(a)});r._rootExec(function(){l=c.apply(n,u)})});(!n.idbtrans||e&&0===E)&&n._nop()}catch(m){n&&n.idbtrans&&(n.idbtrans.onerror=Ga),n&&n.abort(),e&&e.on.error.fire(m),x(function(){g(m)||v.on("error").fire(m)})}}var e,g;b=[].slice.call(arguments,1,arguments.length-1);c=arguments[arguments.length-
1];(e=r.PSD&&r.PSD.trans)&&e.db===v&&-1===a.indexOf("!")||(e=null);g=-1!==a.indexOf("?");a=a.replace("!","").replace("?","");var h=null,k=(Array.isArray(b[0])?b.reduce(function(a,b){return a.concat(b)}):b).map(function(a){return"string"==typeof a?a:(a instanceof T||(h=h||new oa("Invalid type. Arguments following mode must be instances of Table or String")),a.name)});return"r"==a||"readonly"==a?a="readonly":"rw"==a||a==H?a=H:h=new y("Invalid transaction mode: "+a),e&&(h||(e&&"readonly"===e.mode&&a===
H&&(g?e=null:h=h||new y("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY")),e&&k.forEach(function(a){e.tables.hasOwnProperty(a)||(g?e=null:h=h||new y("Table "+a+" not included in parent transaction. Parent Transaction function: "+e.scopeFunc.toString()))}))),e?e._promise(a,d,"lock"):v._whenReady(d)};this.table=function(a){if(!aa&&!N.hasOwnProperty(a))throw new y("Table does not exist");return N[a]};d(T.prototype,function(){function a(){throw new y("Current Transaction is READONLY");
}return{_trans:function(a,b,c){return this._tpf(a,[this.name],b,c)},_idbstore:function(a,b,c){var d=this;return this._tpf(a,[this.name],function(a,c,e){b(a,c,e.idbtrans.objectStore(d.name),e)},c)},get:function(a,b){var c=this;return B(function(){b(c.schema.instanceTemplate)}),this._idbstore("readonly",function(b,d,e){var f=e.get(a);f.onerror=G(d,["getting",a,"from",c.name]);f.onsuccess=function(){b(c.hook.reading.fire(f.result))}}).then(b)},where:function(a){return new Y(this,a)},count:function(a){return this.toCollection().count(a)},
offset:function(a){return this.toCollection().offset(a)},limit:function(a){return this.toCollection().limit(a)},reverse:function(){return this.toCollection().reverse()},filter:function(a){return this.toCollection().and(a)},each:function(a){var b=this;return B(function(){a(b.schema.instanceTemplate)}),this._idbstore("readonly",function(c,d,e){e=e.openCursor();e.onerror=G(d,["calling","Table.each()","on",b.name]);ka(e,null,a,c,d,b.hook.reading.fire)})},toArray:function(a){var b=this;return B(function(){a([b.schema.instanceTemplate])}),
this._idbstore("readonly",function(a,c,d){var e=[];d=d.openCursor();d.onerror=G(c,["calling","Table.toArray()","on",b.name]);ka(d,null,function(a){e.push(a)},function(){a(e)},c,b.hook.reading.fire)}).then(a)},orderBy:function(a){return new this._collClass(new Y(this,a))},toCollection:function(){return new this._collClass(new Y(this))},mapToClass:function(a,b){var c,d;return this.schema.mappedClass=a,c=Object.create(a.prototype),this.schema.primKey.keyPath&&(J(c,this.schema.primKey.keyPath,this.schema.primKey.auto?
0:""),Ba(a.prototype,this.schema.primKey.keyPath)),b&&Aa(c,b),this.schema.instanceTemplate=c,d=Object.setPrototypeOf?function(b){return b?(Object.setPrototypeOf(b,a.prototype),b):b}:function(b){var c,d;if(!b)return b;c=Object.create(a.prototype);for(d in b)b.hasOwnProperty(d)&&(c[d]=b[d]);return c},this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=d,this.hook("reading",d),a},defineClass:function(a){return this.mapToClass(g.defineClass(a),a)},add:a,put:a,
"delete":a,clear:a,update:a}});e(ta).from(T).extend(function(){return{add:function(a,b){var d=this,e=this.hook.creating.fire;return this._idbstore(H,function(f,g,k,n){var u={},l,E,m;e!==h&&(l=b||(k.keyPath?P(a,k.keyPath):c),E=e.call(u,l,a,n),l===c&&E!==c&&(k.keyPath?J(a,k.keyPath,E):b=E));m=b?k.add(a,b):k.add(a);m.onerror=G(function(a){if(u.onerror)u.onerror(a);return g(a)},["adding",a,"into",d.name]);m.onsuccess=function(b){var c=k.keyPath;if(c&&J(a,c,b.target.result),u.onsuccess)u.onsuccess(b.target.result);
f(m.result)}})},put:function(a,b){var d=this,e=this.hook.updating.fire;return this.hook.creating.fire!==h||e!==h?this._trans(H,function(e,f,g){var h=b||d.schema.primKey.keyPath&&P(a,d.schema.primKey.keyPath);h===c?g.tables[d.name].add(a).then(e,f):(g._lock(),a=ba(a),g.tables[d.name].where(":id").equals(h).modify(function(){this.value=a}).then(function(c){return 0===c?g.tables[d.name].add(a,b):h})["finally"](function(){g._unlock()}).then(e,f))}):this._idbstore(H,function(c,e,f){var g=b?f.put(a,b):
f.put(a);g.onerror=G(e,["putting",a,"into",d.name]);g.onsuccess=function(b){var d=f.keyPath;d&&J(a,d,b.target.result);c(g.result)}})},"delete":function(a){return this.hook.deleting.subscribers.length?this.where(":id").equals(a)["delete"]():this._idbstore(H,function(b,c,d){var e=d["delete"](a);e.onerror=G(c,["deleting",a,"from",d.name]);e.onsuccess=function(){b(e.result)}})},clear:function(){return this.hook.deleting.subscribers.length?this.toCollection()["delete"]():this._idbstore(H,function(a,b,
c){var d=c.clear();d.onerror=G(b,["clearing",c.name]);d.onsuccess=function(){a(d.result)}})},update:function(a,b){if("object"!=typeof b||Array.isArray(b))throw new y("db.update(keyOrObject, modifications). modifications must be an object.");if("object"!=typeof a||Array.isArray(a))return this.where(":id").equals(a).modify(b);Object.keys(b).forEach(function(c){J(a,c,b[c])});var d=P(a,this.schema.primKey.keyPath);return d===c&&r.reject(new y("Object does not contain its primary key")),this.where(":id").equals(d).modify(b)}}});
d(va.prototype,{_lock:function(){return++this._reculock,1===this._reculock&&r.PSD&&(r.PSD.lockOwnerFor=this),this},_unlock:function(){if(0==--this._reculock)for(r.PSD&&(r.PSD.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var a=this._blockedFuncs.shift();try{a()}catch(b){}}return this},_locked:function(){return this._reculock&&(!r.PSD||r.PSD.lockOwnerFor!==this)},_nop:function(a){this.tables[this.storeNames[0]].get(0).then(a)},_promise:function(a,b,c){var d=this;return r.newPSD(function(){var e;
return d._locked()?e=new r(function(e,f){d._blockedFuncs.push(function(){d._promise(a,b,c).then(e,f)})}):(e=d.active?new r(function(e,f){if(!d.idbtrans&&a){if(!D)throw V?new y("Database not open. Following error in populate, ready or upgrade function made Dexie.open() fail: "+V):new y("Database not open");var h=d.idbtrans=D.transaction(xa(d.storeNames),d.mode);h.onerror=function(a){d.on("error").fire(a&&a.target.error);a.preventDefault();d.abort()};h.onabort=function(a){d.active=!1;d.on("abort").fire(a)};
h.oncomplete=function(a){d.active=!1;d.on("complete").fire(a)}}c&&d._lock();try{b(e,f,d)}catch(k){g.ignoreTransaction(function(){d.on("error").fire(k)}),d.abort(),f(k)}}):r.reject(Ka(new y("Transaction is inactive. Original Scope Function Source: "+d.scopeFunc.toString()))),d.active&&c&&e["finally"](function(){d._unlock()})),e.onuncatched=function(a){g.ignoreTransaction(function(){d.on("error").fire(a)});d.abort()},e})},complete:function(a){return this.on("complete",a)},error:function(a){return this.on("error",
a)},abort:function(){if(this.idbtrans&&this.active)try{this.active=!1,this.idbtrans.abort(),this.on.error.fire(new y("Transaction Aborted"))}catch(a){}},table:function(a){if(!this.tables.hasOwnProperty(a))throw new y("Table "+a+" not in transaction");return this.tables[a]}});d(Y.prototype,function(){function a(b,c){try{throw c;}catch(d){b._ctx.error=d}return b}function b(a){return Array.prototype.slice.call(1===a.length&&Array.isArray(a[0])?a[0]:a)}function c(a){return"next"===a?function(a){return a.toUpperCase()}:
function(a){return a.toLowerCase()}}function d(a){return"next"===a?function(a){return a.toLowerCase()}:function(a){return a.toUpperCase()}}function e(a,b,c,d,f,g){for(var h,k=Math.min(a.length,d.length),n=-1,u=0;u<k;++u){if(h=b[u],h!==d[u])return 0>f(a[u],c[u])?a.substr(0,u)+c[u]+c.substr(u+1):0>f(a[u],d[u])?a.substr(0,u)+d[u]+c.substr(u+1):0<=n?a.substr(0,n)+b[n]+c.substr(n+1):null;0>f(a[u],h)&&(n=u)}return k<d.length&&"next"===g?a+c.substr(a.length):k<a.length&&"prev"===g?a.substr(0,c.length):0>
n?null:a.substr(0,n)+d[n]+c.substr(n+1)}function f(a,b,g){function h(a){k=c(a);n=d(a);u="next"===a?la:Da;l=k(g);E=n(g);m=a}var k,n,u,l,E,m;h("next");a._ondirectionchange=function(a){h(a)};a._addAlgorithm(function(a,c,d){var f=a.key,g,h;return"string"!=typeof f?!1:(g=n(f),b(g,E)?(c(function(){a["continue"]()}),!0):(h=e(f,g,l,E,u,m),h?c(function(){a["continue"](h)}):c(d),!1))})}return{between:function(a,b,c,d){return(c=!1!==c,d=!0===d,a>b||a===b&&!(!c&&!d||c&&d))?(new this._ctx.collClass(this,function(){return L.only(a)})).limit(0):
new this._ctx.collClass(this,function(){return L.bound(a,b,!c,!d)})},equals:function(a){return new this._ctx.collClass(this,function(){return L.only(a)})},above:function(a){return new this._ctx.collClass(this,function(){return L.lowerBound(a,!0)})},aboveOrEqual:function(a){return new this._ctx.collClass(this,function(){return L.lowerBound(a)})},below:function(a){return new this._ctx.collClass(this,function(){return L.upperBound(a,!0)})},belowOrEqual:function(a){return new this._ctx.collClass(this,
function(){return L.upperBound(a)})},startsWith:function(b){return"string"!=typeof b?a(new this._ctx.collClass(this),new oa("String expected")):this.between(b,b+String.fromCharCode(65535),!0,!0)},startsWithIgnoreCase:function(b){if("string"!=typeof b)return a(new this._ctx.collClass(this),new oa("String expected"));if(""===b)return this.startsWith(b);var c=new this._ctx.collClass(this,function(){return L.bound(b.toUpperCase(),b.toLowerCase()+String.fromCharCode(65535))});return f(c,function(a,b){return 0===
a.indexOf(b)},b),c._ondirectionchange=function(){a(c,new y("reverse() not supported with WhereClause.startsWithIgnoreCase()"))},c},equalsIgnoreCase:function(b){if("string"!=typeof b)return a(new this._ctx.collClass(this),new oa("String expected"));var c=new this._ctx.collClass(this,function(){return L.bound(b.toUpperCase(),b.toLowerCase())});return f(c,function(a,b){return a===b},b),c},anyOf:function(){var a=this._ctx,c=a.table.schema,d=(a=a.index?c.idxByName[a.index]:c.primKey)&&a.compound,e=b(arguments),
f=d?Ea(la):la,g,h;return(e.sort(f),0===e.length)?(new this._ctx.collClass(this,function(){return L.only("")})).limit(0):(g=new this._ctx.collClass(this,function(){return L.bound(e[0],e[e.length-1])}),g._ondirectionchange=function(a){f="next"===a?la:Da;d&&(f=Ea(f));e.sort(f)},h=0,g._addAlgorithm(function(a,b,c){for(var d=a.key;0<f(d,e[h]);)if(++h,h===e.length)return b(c),!1;return 0===f(d,e[h])?(b(function(){a["continue"]()}),!0):(b(function(){a["continue"](e[h])}),!1)}),g)}}});d(X.prototype,function(){function a(b,
c){b.filter=ma(b.filter,c)}function b(a,c){a.isMatch=ma(a.isMatch,c)}function c(a,b){if(a.isPrimKey)return b;var d=a.table.schema.idxByName[a.index];if(!d)throw new y("KeyPath "+a.index+" on object store "+b.name+" is not indexed");return a.isPrimKey?b:b.index(d.name)}function d(a,b){return c(a,b)[a.op](a.range||null,a.dir+a.unique)}function e(a,b,c,f,g){a.or?function(){function e(){2==++u&&c()}function h(a,c,d){if(!k||k(c,d,e,f)){var g=c.primaryKey.toString();n.hasOwnProperty(g)||(n[g]=!0,b(a,c,
d))}}var k=a.filter,n={},u=0;a.or._iterate(h,e,f,g);ka(d(a,g),a.algorithm,h,e,f,a.table.hook.reading.fire)}():ka(d(a,g),ma(a.algorithm,a.filter),b,c,f,a.table.hook.reading.fire)}function f(a){return a.table.schema.instanceTemplate}return{_read:function(a,b){var c=this._ctx;return c.error?c.table._trans(null,function(a,b){b(c.error)}):c.table._idbstore("readonly",a).then(b)},_write:function(a){var b=this._ctx;return b.error?b.table._trans(null,function(a,c){c(b.error)}):b.table._idbstore(H,a,"locked")},
_addAlgorithm:function(a){var b=this._ctx;b.algorithm=ma(b.algorithm,a)},_iterate:function(a,b,c,d){return e(this._ctx,a,b,c,d)},each:function(a){var b=this._ctx;return B(function(){a(f(b))}),this._read(function(c,d,f){e(b,a,c,d,f)})},count:function(a){var b,d,f;return B(function(){a(0)}),b=this,d=this._ctx,d.filter||d.algorithm||d.or?(f=0,this._read(function(a,b,c){e(d,function(){return++f,!1},function(){a(f)},b,c)},a)):this._read(function(a,e,f){f=c(d,f);f=d.range?f.count(d.range):f.count();f.onerror=
G(e,["calling","count()","on",b.name]);f.onsuccess=function(b){a(Math.min(b.target.result,Math.max(0,d.limit-d.offset)))}},a)},sortBy:function(a,b){function c(a,b){return b?c(a[h[b]],b-1):a[k]}function d(a,b){var e=c(a,n),f=c(b,n);return e<f?-g:e>f?g:0}var e=this._ctx,g;B(function(){b([f(e)])});var h=a.split(".").reverse(),k=h[0],n=h.length-1;return g="next"===this._ctx.dir?1:-1,this.toArray(function(a){return a.sort(d)}).then(b)},toArray:function(a){var b=this._ctx;return B(function(){a([f(b)])}),
this._read(function(a,c,d){var f=[];e(b,function(a){f.push(a)},function(){a(f)},c,d)},a)},offset:function(b){var c=this._ctx;return 0>=b?this:(c.offset+=b,c.or||c.algorithm||c.filter?a(c,function(){return 0>--b}):a(c,function(a,c){return 0===b?!0:1===b?(--b,!1):(c(function(){a.advance(b);b=0}),!1)}),this)},limit:function(b){return this._ctx.limit=Math.min(this._ctx.limit,b),a(this._ctx,function(a,c,d){return 0>=--b&&c(d),0<=b}),this},until:function(b,c){var d=this._ctx;return B(function(){b(f(d))}),
a(this._ctx,function(a,d,e){return b(a.value)?(d(e),c):!0}),this},first:function(a){var b=this;return B(function(){a(f(b._ctx))}),this.limit(1).toArray(function(a){return a[0]}).then(a)},last:function(a){return this.reverse().first(a)},and:function(c){var d=this;return B(function(){c(f(d._ctx))}),a(this._ctx,function(a){return c(a.value)}),b(this._ctx,c),this},or:function(a){return new Y(this._ctx.table,a,this)},reverse:function(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&
this._ondirectionchange(this._ctx.dir),this},desc:function(){return this.reverse()},eachKey:function(a){var b=this,c=this._ctx;return B(function(){a(f(b._ctx)[b._ctx.index])}),c.isPrimKey||(c.op="openKeyCursor"),this.each(function(b,c){a(c.key,c)})},eachUniqueKey:function(a){return this._ctx.unique="unique",this.eachKey(a)},keys:function(a){var b,c,d;return B(function(){a([f(c)[b._ctx.index]])}),b=this,c=this._ctx,c.isPrimKey||(c.op="openKeyCursor"),d=[],this.each(function(a,b){d.push(b.key)}).then(function(){return d}).then(a)},
uniqueKeys:function(a){return this._ctx.unique="unique",this.keys(a)},firstKey:function(a){return this.limit(1).keys(function(a){return a[0]}).then(a)},lastKey:function(a){return this.reverse().firstKey(a)},distinct:function(){var b={};return a(this._ctx,function(a){a=a.primaryKey.toString();var c=b.hasOwnProperty(a);return b[a]=!0,!c}),this}}});e(ua).from(X).extend({modify:function(a){var b=this,c=this._ctx,e=c.table.hook,f=e.updating.fire,g=e.deleting.fire;return B(function(){"function"==typeof a&&
a.call({value:c.table.schema.instanceTemplate},c.table.schema.instanceTemplate)}),this._write(function(e,k,n,u){function l(a){return a&&(r.push(a),fa.push(W)),k(new pa("Error modifying one or more objects",r,p,fa))}function E(){ja&&p+r.length===q&&(0<r.length?l():e(p))}var m,U,Ca,ea;"function"==typeof a?m=f===h&&g===h?a:function(b){var c=ba(b),d,e;if(!1===a.call(this,b))return!1;this.hasOwnProperty("value")?(d=La(c,this.value),e=f.call(this,d,this.primKey,c,u),e&&(b=this.value,Object.keys(e).forEach(function(a){J(b,
a,e[a])}))):g.call(this,this.primKey,b,u)}:f===h?(U=Object.keys(a),Ca=U.length,m=function(b){for(var c,d,e=!1,f=0;f<Ca;++f)c=U[f],d=a[c],P(b,c)!==d&&(J(b,c,d),e=!0);return e}):(ea=a,a=qa(ea),m=function(b){var c=!1,e=f.call(this,a,this.primKey,ba(b),u);return e&&d(a,e),Object.keys(a).forEach(function(d){var e=a[d];P(b,d)!==e&&(J(b,d,e),c=!0)}),e&&(a=qa(ea)),c});var q=0,p=0,ja=!1,r=[],fa=[],W=null;b._iterate(function(a,b){var d,e,f;if(W=b.primaryKey,d={primKey:b.primaryKey,value:a},!1!==m.call(d,a))f=
(e=!d.hasOwnProperty("value"))?b["delete"]():b.update(d.value),++q,f.onerror=G(function(a){if(r.push(a),fa.push(d.primKey),d.onerror)d.onerror(a);return E(),!0},e?["deleting",a,"from",c.table.name]:["modifying",a,"on",c.table.name]),f.onsuccess=function(){if(d.onsuccess)d.onsuccess(d.value);++p;E()};else if(d.onsuccess)d.onsuccess(d.value)},function(){ja=!0;E()},l,n)})},"delete":function(){return this.modify(function(){delete this.value})}});d(this,{Collection:X,Table:T,Transaction:va,Version:u,WhereClause:Y,
WriteableCollection:ua,WriteableTable:ta});(function(){v.on("versionchange",function(){v.close();v.on("error").fire(new y("Database version changed by other database connection."))})})();ca.forEach(function(a){a(v)})}function h(){}function k(a){return a}function l(a,b){return a===k?b:function(c){return b(a(c))}}function m(a,b){return function(){a.apply(this,arguments);b.apply(this,arguments)}}function q(a,b){return a===h?b:function(){var d=a.apply(this,arguments),e,f,g;return d!==c&&(arguments[0]=
d),e=this.onsuccess,f=this.onerror,delete this.onsuccess,delete this.onerror,g=b.apply(this,arguments),e&&(this.onsuccess=this.onsuccess?m(e,this.onsuccess):e),f&&(this.onerror=this.onerror?m(f,this.onerror):f),g!==c?g:d}}function p(a,b){return a===h?b:function(){var e=a.apply(this,arguments),f,g,h;return e!==c&&d(arguments[0],e),f=this.onsuccess,g=this.onerror,delete this.onsuccess,delete this.onerror,h=b.apply(this,arguments),f&&(this.onsuccess=this.onsuccess?m(f,this.onsuccess):f),g&&(this.onerror=
this.onerror?m(g,this.onerror):g),e===c?h===c?c:h:h===c?e:d(e,h)}}function s(a,b){return a===h?b:function(){return!1===a.apply(this,arguments)?!1:b.apply(this,arguments)}}function w(a,b){return a===h?b:function(){return!1===b.apply(this,arguments)?!1:a.apply(this,arguments)}}function M(a,b){return a===h?b:function(){a.apply(this,arguments);b.apply(this,arguments)}}function O(a,b){return a===h?b:function(){var c=a.apply(this,arguments),d,e;return c&&"function"==typeof c.then?(d=this,e=arguments,c.then(function(){return b.apply(d,
e)})):b.apply(this,arguments)}}function K(b){function c(a,b,f){if(Array.isArray(a))return e(a);if("object"==typeof a)return d(a);b||(b=s);f||(f=h);var n={subscribers:[],fire:f,subscribe:function(a){n.subscribers.push(a);n.fire=b(n.fire,a)},unsubscribe:function(a){n.subscribers=n.subscribers.filter(function(b){return b!==a});n.fire=n.subscribers.reduce(b,f)}};return g[a]=k[a]=n,n}function d(b){Object.keys(b).forEach(function(d){var e=b[d],f;if(Array.isArray(e))c(d,b[d][0],b[d][1]);else if("asap"===
e)f=c(d,null,function(){var b=arguments;f.subscribers.forEach(function(c){x(function(){c.apply(a,b)})})}),f.subscribe=function(a){-1===f.subscribers.indexOf(a)&&f.subscribers.push(a)},f.unsubscribe=function(a){a=f.subscribers.indexOf(a);-1!==a&&f.subscribers.splice(a,1)};else throw Error("Invalid event config");})}function e(a){function b(){if(d)return!1;d=!0}var d=!1;a.forEach(function(a){c(a).subscribe(b)})}var f=arguments,g={},k=function(a,c){if(c){var d=[].slice.call(arguments,1),e=g[a];return e.subscribe.apply(e,
d),b}if("string"==typeof a)return g[a]},l,m;k.addEventType=c;l=1;for(m=f.length;l<m;++l)c(f[l]);return k}function x(b){a.setImmediate?setImmediate(b):setTimeout(b,0)}function A(a){a=setTimeout(a,1E3);clearTimeout(a)}function I(a,b,c){return function(){var d=r.PSD;r.PSD=c;try{a.apply(this,arguments)}catch(e){b(e)}finally{r.PSD=d}}}function P(a,b){var d,e,f,g;if(a.hasOwnProperty(b))return a[b];if(!b)return a;if("string"!=typeof b){d=[];e=0;for(f=b.length;e<f;++e)g=P(a,b[e]),d.push(g);return d}return(d=
b.indexOf("."),-1!==d)?(e=a[b.substr(0,d)],e===c?c:P(e,b.substr(d+1))):c}function J(a,b,d){var e,f,g,h;if(a&&b!==c)if("string"!=typeof b&&"length"in b){if(!("string"!=typeof d&&"length"in d))throw Error("Assertion failed");e=0;for(f=b.length;e<f;++e)J(a,b[e],d[e])}else e=b.indexOf("."),-1!==e?(f=b.substr(0,e),g=b.substr(e+1),""===g?d===c?delete a[f]:a[f]=d:(h=a[f],h||(h=a[f]={}),J(h,g,d))):d===c?delete a[b]:a[b]=d}function Ba(a,b){J(a,b,c)}function qa(a){var b={},c;for(c in a)a.hasOwnProperty(c)&&
(b[c]=a[c]);return b}function ba(a){var b,c,d;if(!a||"object"!=typeof a)return a;if(Array.isArray(a))for(b=[],c=0,d=a.length;c<d;++c)b.push(ba(a[c]));else if(a instanceof Date)b=new Date,b.setTime(a.getTime());else for(c in b=a.constructor?Object.create(a.constructor.prototype):{},a)a.hasOwnProperty(c)&&(b[c]=ba(a[c]));return b}function La(a,b){var d={},e;for(e in a)a.hasOwnProperty(e)&&(b.hasOwnProperty(e)?a[e]!==b[e]&&JSON.stringify(a[e])!=JSON.stringify(b[e])&&(d[e]=b[e]):d[e]=c);for(e in b)b.hasOwnProperty(e)&&
!a.hasOwnProperty(e)&&(d[e]=b[e]);return d}function ia(a){if("function"==typeof a)return new a;if(Array.isArray(a))return[ia(a[0])];if(a&&"object"==typeof a){var b={};return Aa(b,a),b}return a}function Aa(a,b){Object.keys(b).forEach(function(c){var d=ia(b[c]);a[c]=d})}function G(a,b){return function(c){var d=c&&c.target.error||Error(),e;return b&&(e=" occurred when "+b.map(function(a){switch(typeof a){case "function":return a();case "string":return a;default:return JSON.stringify(a)}}).join(" "),
d.name?d.toString=function(){return d.name+e+(d.message?". "+d.message:"")}:d+=e),a(d),c&&(c.stopPropagation&&c.stopPropagation(),c.preventDefault&&c.preventDefault()),!1}}function Ka(a){try{throw a;}catch(b){return b}}function Ga(a){a.preventDefault()}function za(a){var b,c=g.dependencies.localStorage;if(!c)return a([]);try{b=JSON.parse(c.getItem("Dexie.DatabaseNames")||"[]")}catch(d){b=[]}a(b)&&c.setItem("Dexie.DatabaseNames",JSON.stringify(b))}function Z(a,b,c,d,e,f,g){this.name=a;this.keyPath=
b;this.unique=c;this.multi=d;this.auto=e;this.compound=f;this.dotted=g;a="string"==typeof b?b:b&&"["+[].join.call(b,"+")+"]";this.src=(c?"&":"")+(d?"*":"")+(e?"++":"")+a}function ya(a,b,c,d){this.name=a;this.primKey=b||new Z;this.indexes=c||[new Z];this.instanceTemplate=d;this.mappedClass=null;this.idxByName=c.reduce(function(a,b){return a[b.name]=b,a},{})}function pa(a,b,c,d){this.name="ModifyError";this.failures=b;this.failedKeys=d;this.successCount=c;this.message=b.join("\n")}function xa(a){return 1===
a.length?a[0]:a}function Fa(){var a=g.dependencies.indexedDB,b=a&&(a.getDatabaseNames||a.webkitGetDatabaseNames);return b&&b.bind(a)}var r=function(){function b(a){x.push([a,p.call(arguments,1)])}function c(){var b=x,d,e,f;x=[];d=0;for(e=b.length;d<e;++d)f=b[d],f[0].apply(a,f[1])}function d(a){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");this._value=this._state=null;this._deferreds=[];this._catched=
!1;var b=this,c=!0;this._PSD=d.PSD;try{q(this,a,function(a){c?s(g,b,a):g(b,a)},function(a){return c?(s(k,b,a),!1):k(b,a)})}finally{c=!1}}function e(a,g){var h,k,l,m,q,p;if(null===a._state)a._deferreds.push(g);else{if(h=a._state?g.onFulfilled:g.onRejected,null===h)return(a._state?g.resolve:g.reject)(a._value);l=w;w=!1;s=b;try{m=d.PSD,d.PSD=a._PSD,k=h(a._value),a._state||k&&"function"==typeof k.then&&!1===k._state||f(a),g.resolve(k)}catch(B){if(q=g.reject(B),!q&&a.onuncatched)try{a.onuncatched(B)}catch(G){}}finally{if(d.PSD=
m,l){do{for(;0<x.length;)c();if(p=A.pop(),p)try{p()}catch(I){}}while(0<A.length||0<x.length);s=r;w=!0}}}}function f(a){a._catched=!0;a._parent&&f(a._parent)}function g(a,b){var c=d.PSD;d.PSD=a._PSD;try{if(b===a)throw new TypeError("A promise cannot be resolved with itself.");!b||"object"!=typeof b&&"function"!=typeof b||"function"!=typeof b.then?(a._state=!0,a._value=b,l.call(a)):q(a,function(a,c){b.then(a,c)},function(b){g(a,b)},function(b){k(a,b)})}catch(e){k(e)}finally{d.PSD=c}}function k(a,b){var c=
d.PSD;if(d.PSD=a._PSD,a._state=!1,a._value=b,l.call(a),!a._catched)try{if(a.onuncatched)a.onuncatched(a._value);d.on.error.fire(a._value)}catch(e){}return d.PSD=c,a._catched}function l(){for(var a=0,b=this._deferreds.length;a<b;a++)e(this,this._deferreds[a]);this._deferreds=[]}function m(a,b,c,d){this.onFulfilled="function"==typeof a?a:null;this.onRejected="function"==typeof b?b:null;this.resolve=c;this.reject=d}function q(a,b,c,d){var e=!1;try{b(function(a){e||(e=!0,c(a))},function(b){return e?a._catched:
(e=!0,d(b))})}catch(f){return e?void 0:d(f)}}var p=[].slice,r="undefined"==typeof setImmediate?function(b){var c=arguments;setTimeout(function(){b.apply(a,p.call(c,1))},0)}:setImmediate,s=r,w=!0,x=[],A=[];return d.on=K(null,"error"),d.all=function(){var a=Array.prototype.slice.call(1===arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments);return new d(function(b,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h){h.call(g,
function(a){d(f,a)},c);return}}a[f]=g;0==--e&&b(a)}catch(k){c(k)}}var e,f;if(0===a.length)return b([]);e=a.length;for(f=0;f<a.length;f++)d(f,a[f])})},d.prototype.then=function(a,b){var c=this,f=new d(function(d,f){null===c._state?e(c,new m(a,b,d,f)):s(e,c,new m(a,b,d,f))});return f._PSD=this._PSD,f.onuncatched=this.onuncatched,f._parent=this,f},d.prototype._then=function(a,b){e(this,new m(a,b,h,h))},d.prototype["catch"]=function(a){if(1===arguments.length)return this.then(null,a);var b=arguments[0],
c=arguments[1];return"function"==typeof b?this.then(null,function(a){return a instanceof b?c(a):d.reject(a)}):this.then(null,function(a){return a&&a.name===b?c(a):d.reject(a)})},d.prototype["finally"]=function(a){return this.then(function(b){return a(),b},function(b){return a(),d.reject(b)})},d.prototype.onuncatched=null,d.resolve=function(a){var b=new d(function(){});return b._state=!0,b._value=a,b},d.reject=function(a){var b=new d(function(){});return b._state=!1,b._value=a,b},d.race=function(a){return new d(function(b,
c){a.map(function(a){a.then(b,c)})})},d.PSD=null,d.newPSD=function(a){var b=d.PSD;d.PSD=b?Object.create(b):{};try{return a()}finally{d.PSD=b}},d._rootExec=function(a){var d=w,e;w=!1;s=b;try{a()}finally{if(d){do{for(;0<x.length;)c();if(e=A.pop(),e)try{e()}catch(f){}}while(0<A.length||0<x.length);s=r;w=!0}}},d._tickFinalize=function(a){if(w)throw Error("Not in a virtual tick");A.push(a)},d}(),B=function(){},ca;e(pa).from(Error);g["delete"]=function(a){var b=new g(a);a=b["delete"]();return a.onblocked=
function(a){b.on("blocked",a);return this},a};g.getDatabaseNames=function(a){return(new r(function(a,b){var c=Fa(),d;c?(d=c(),d.onsuccess=function(b){a([].slice.call(b.target.result,0))},d.onerror=G(b)):za(function(b){return a(b),!1})})).then(a)};g.defineClass=function(a){function b(a){a&&d(this,a)}return Aa(b.prototype,a),b};g.ignoreTransaction=function(a){return r.newPSD(function(){return r.PSD.trans=null,a()})};g.spawn=function(){return a.console&&console.warn("Dexie.spawn() is deprecated. Use Dexie.ignoreTransaction() instead."),
g.ignoreTransaction.apply(this,arguments)};g.vip=function(a){return r.newPSD(function(){return r.PSD.letThrough=!0,a()})};Object.defineProperty(g,"currentTransaction",{get:function(){return r.PSD&&r.PSD.trans||null}});g.Promise=r;g.derive=e;g.extend=d;g.override=f;g.events=K;g.getByKeyPath=P;g.setByKeyPath=J;g.delByKeyPath=Ba;g.shallowClone=qa;g.deepClone=ba;g.addons=[];g.fakeAutoComplete=B;g.asap=x;g.ModifyError=pa;g.MultiModifyError=pa;g.IndexSpec=Z;g.TableSchema=ya;ca=a.idbModules&&a.idbModules.shimIndexedDB?
a.idbModules:{};g.dependencies={indexedDB:ca.shimIndexedDB||a.indexedDB||a.mozIndexedDB||a.webkitIndexedDB||a.msIndexedDB,IDBKeyRange:ca.IDBKeyRange||a.IDBKeyRange||a.webkitIDBKeyRange,IDBTransaction:ca.IDBTransaction||a.IDBTransaction||a.webkitIDBTransaction,Error:a.Error||String,SyntaxError:a.SyntaxError||String,TypeError:a.TypeError||String,DOMError:a.DOMError||String,localStorage:null!=("undefined"!=typeof chrome&&null!==chrome?chrome.storage:void 0)?null:a.localStorage};g.version=1.1;b("Dexie",
g);A(function(){B=A})}).apply(null,"function"==typeof define&&define.amd?[self||window,function(a,b){define(a,function(){return b})}]:"undefined"!=typeof global&&"undefined"!=typeof module&&module.exports?[global,function(a,b){module.exports=b}]:[self||window,function(a,b){(self||window)[a]=b}]);