/*
 <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="http://kjur.github.io/jsrsasign/license/">MIT License</a>
 <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
*/
var ndn=ndn||{},exports=ndn,module={};function require(){return ndn}
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 if(65535<c.length)for(e=0;e<a;e+=4)b[d+e>>>2]=c[e>>>2];else b.push.apply(b,c);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 p.HMAC.init(a,c)).finalize(b)}}});var p=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],x=c[2],t=c[3],u=c[4],Q=c[5],Z=c[6],P=c[7],z=0;64>z;z++){if(16>
z)g[z]=a[b+z]|0;else{var G=g[z-15],L=g[z-2];g[z]=((G<<25|G>>>7)^(G<<14|G>>>18)^G>>>3)+g[z-7]+((L<<15|L>>>17)^(L<<13|L>>>19)^L>>>10)+g[z-16]}G=P+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&Q^~u&Z)+f[z]+g[z];L=((d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22))+(d&e^d&x^e&x);P=Z;Z=Q;Q=u;u=t+G|0;t=x;x=e;e=d;d=G+L|0}c[0]=c[0]+d|0;c[1]=c[1]+e|0;c[2]=c[2]+x|0;c[3]=c[3]+t|0;c[4]=c[4]+u|0;c[5]=c[5]+Q|0;c[6]=c[6]+Z|0;c[7]=c[7]+P|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;var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64pad="=",BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";
function int2char(a){return BI_RM.charAt(a)}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;for(c=0;c<a.length&&a.charAt(c)!=b64pad;++c)v=b64map.indexOf(a.charAt(c)),0>v||(0==d?(b+=int2char(v>>2),e=v&3,d=1):1==d?(b+=int2char(e<<2|v>>4),e=v&15,d=2):2==d?(b+=int2char(e),b+=int2char(v>>2),e=v&3,d=3):(b+=int2char(e<<2|v>>4),b+=int2char(v&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;var intShim=require("jsbn"),BigInteger=intShim.BigInteger?intShim.BigInteger:intShim;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))}
var RSAKey=function(){this.n=null;this.e=0;this.coeff=this.dmq1=this.dmp1=this.q=this.p=this.d=null};function RSASetPublic(a,b){"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;exports.RSAKey=RSAKey;module.exports=exports;intShim=require("jsbn");BigInteger=intShim.BigInteger?intShim.BigInteger:intShim;RSAKey=require("./rsa.js").RSAKey;function parseBigInt(a,b){return new BigInteger(a,b)}
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){"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){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}}}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");BigInteger=intShim.BigInteger?intShim.BigInteger:intShim;function parseBigInt(a,b){return new BigInteger(a,b)}"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.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.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.sha512=function(a){return(new KJUR.crypto.MessageDigest({alg:"sha512",
prov:"cryptojs"})).digestString(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)}};
KJUR.crypto.MessageDigest=function(a){var b={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.setAlgAndProvider=function(a,d){if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(a)&&"cryptojs"==d){try{this.md=eval(b[a]).create()}catch(e){throw"setAlgAndProvider hash alg set fail alg="+a+"/"+e;}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"==d){try{this.md=new sjcl.hash.sha256}catch(f){throw"setAlgAndProvider hash alg set fail alg="+a+"/"+f;}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;};"undefined"!=typeof a&&"undefined"!=typeof a.alg&&(this.algName=a.alg,this.provName=a.prov,this.setAlgAndProvider(a.alg,a.prov))};
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,prov:"cryptojs"})}catch(c){throw"setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+c;}this.initSign=function(a){this.prvKey=a;this.state="SIGN"};this.initVerifyByPublicKey=function(a){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(){var a=KJUR.crypto.Util,b=this.prvKey.n.bitLength();this.sHashHex=this.md.digest();this.hDigestInfo=a.getDigestInfoHex(this.sHashHex,this.mdAlgName);this.hPaddedDigestInfo=a.getPaddedDigestInfoHex(this.sHashHex,this.mdAlgName,b);a=parseBigInt(this.hPaddedDigestInfo,16);this.hoge=a.toString(16);a=this.prvKey.doPrivate(a);return this.hSign=this._zeroPaddingOfSignature(a.toString(16),b)};this.signString=function(a){this.updateString(a);this.sign()};this.signHex=function(a){this.updateHex(a);
this.sign()};this.verify=function(a){this.pubKey.n.bitLength();this.sHashHex=this.md.digest();a=parseBigInt(a,16);a=this.hPaddedDigestInfo=this.pubKey.doPublic(a).toString(16);a=a.replace(/^1ff+00/,"");var b=KJUR.crypto.Util.DIGESTINFOHEAD[this.mdAlgName];return 0!=a.indexOf(b)?!1:a.substr(b.length)==this.sHashHex}}};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;};if("undefined"!=typeof a&&("undefined"!=typeof a.alg&&(this.algName=a.alg,this.provName=a.prov,this.algProvName=a.alg+":"+a.prov,this.setAlgAndProvider(a.alg,a.prov),this._setAlgNames()),"undefined"!=typeof a.prvkeypem)){if("undefined"!=typeof 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;}}};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;intShim=require("jsbn");BigInteger=intShim.BigInteger?intShim.BigInteger:intShim;RSAKey=require("./rsapem-1.1.js").RSAKey;function parseBigInt(a,b){return new BigInteger(a,b)}var _RSASIGN_DIHEAD=[];_RSASIGN_DIHEAD.sha1="3021300906052b0e03021a05000414";_RSASIGN_DIHEAD.sha256="3031300d060960864801650304020105000420";_RSASIGN_DIHEAD.sha384="3041300d060960864801650304020205000430";_RSASIGN_DIHEAD.sha512="3051300d060960864801650304020305000440";
_RSASIGN_DIHEAD.md2="3020300c06082a864886f70d020205000410";_RSASIGN_DIHEAD.md5="3020300c06082a864886f70d020505000410";_RSASIGN_DIHEAD.ripemd160="3021300906052b2403020105000414";var _RSASIGN_HASHHEXFUNC=[];_RSASIGN_HASHHEXFUNC.sha1=function(a){return KJUR.crypto.Util.sha1(a)};_RSASIGN_HASHHEXFUNC.sha256=function(a){return KJUR.crypto.Util.sha256(a)};_RSASIGN_HASHHEXFUNC.sha512=function(a){return KJUR.crypto.Util.sha512(a)};_RSASIGN_HASHHEXFUNC.md5=function(a){return KJUR.crypto.Util.md5(a)};
_RSASIGN_HASHHEXFUNC.ripemd160=function(a){return KJUR.crypto.Util.ripemd160(a)};var _RE_HEXDECONLY=RegExp("");_RE_HEXDECONLY.compile("[^0-9a-f]","gi");function _rsasign_getHexPaddedDigestInfoForString(a,b,c){b/=4;a=(0,_RSASIGN_HASHHEXFUNC[c])(a);c="00"+_RSASIGN_DIHEAD[c]+a;a="";b=b-4-c.length;for(var d=0;d<b;d+=2)a+="ff";return sPaddedMessageHex="0001"+a+c}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=_rsasign_getHexPaddedDigestInfoForString(a,this.n.bitLength(),b),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+=c(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){var d=_RSASIGN_HASHRAWFUNC[b],e=d(a);a=e.length;b=this.n.bitLength()-1;var f=Math.ceil(b/8);if(-1===c)c=a;else if(-2===c||void 0===c)c=f-a-2;else if(-2>c)throw"invalid salt length";if(f<a+c+2)throw"data too long";var g="";0<c&&(g=Array(c),(new SecureRandom).nextBytes(g),g=String.fromCharCode.apply(String,g));for(var h=d("\x00\x00\x00\x00\x00\x00\x00\x00"+e+g),k=[],e=0;e<f-c-a-2;e+=1)k[e]=0;c=String.fromCharCode.apply(String,k)+"\u0001"+g;d=pss_mgf1_str(h,c.length,
d);g=[];for(e=0;e<c.length;e+=1)g[e]=c.charCodeAt(e)^d.charCodeAt(e);g[0]&=~(65280>>8*f-b&255);for(e=0;e<a;e++)g.push(h.charCodeAt(e));g.push(188);return _zeroPaddingOfSignature(this.doPrivate(new BigInteger(g)).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 _RSASIGN_DIHEAD){var c=_RSASIGN_DIHEAD[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=(0,_RSASIGN_HASHHEXFUNC[c[0]])(a);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,"");if(b.length!=this.n.bitLength()/4)return 0;b=b.replace(/[ \n]+/g,"");var c=parseBigInt(b,16),c=this.doPublic(c).toString(16).replace(/^1f+00/,""),d=_rsasign_getAlgNameAndHashFromHexDisgestInfo(c);if(0==d.length)return!1;c=d[1];d=(0,_RSASIGN_HASHHEXFUNC[d[0]])(a);return c==d}
function _rsasign_verifyStringPSS(a,b,c,d){if(b.length!==this.n.bitLength()/4)return!1;c=_RSASIGN_HASHRAWFUNC[c];a=c(a);var e=a.length,f=this.n.bitLength()-1,g=Math.ceil(f/8);if(-1===d)d=e;else if(-2===d||void 0===d)d=g-e-2;else if(-2>d)throw"invalid salt length";if(g<e+d+2)throw"data too long";var h=this.doPublic(parseBigInt(b,16)).toByteArray();for(b=0;b<h.length;b+=1)h[b]&=255;for(;h.length<g;)h.unshift(0);if(188!==h[g-1])throw"encoded message does not end in 0xbc";var h=String.fromCharCode.apply(String,
h),k=h.substr(0,g-e-1),h=h.substr(k.length,e),l=65280>>8*g-f&255;if(0!==(k.charCodeAt(0)&l))throw"bits beyond keysize not zero";var m=pss_mgf1_str(h,k.length,c),f=[];for(b=0;b<k.length;b+=1)f[b]=k.charCodeAt(b)^m.charCodeAt(b);f[0]&=~l;e=g-e-d-2;for(b=0;b<e;b+=1)if(0!==f[b])throw"leftmost octets not zero";if(1!==f[e])throw"0x01 marker not found";return h===c("\x00\x00\x00\x00\x00\x00\x00\x00"+a+String.fromCharCode.apply(String,f.slice(-d)))}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.signStringPSS=_rsasign_signStringPSS;RSAKey.prototype.signPSS=_rsasign_signStringPSS;RSAKey.SALT_LEN_HLEN=-1;RSAKey.SALT_LEN_MAX=-2;RSAKey.prototype.verifyString=_rsasign_verifyString;
RSAKey.prototype.verifyHexSignatureForMessage=_rsasign_verifyHexSignatureForMessage;RSAKey.prototype.verify=_rsasign_verifyString;RSAKey.prototype.verifyHexSignatureForByteArrayMessage=_rsasign_verifyHexSignatureForMessage;RSAKey.prototype.verifyStringPSS=_rsasign_verifyStringPSS;RSAKey.prototype.verifyPSS=_rsasign_verifyStringPSS;RSAKey.SALT_LEN_RECOVER=-2;exports.RSAKey=RSAKey;module.exports=exports;intShim=require("jsbn");BigInteger=intShim.BigInteger?intShim.BigInteger:intShim;
function parseBigInt(a,b){return new BigInteger(a,b)}function _asnhex_getByteLengthOfL_AtObj(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}function _asnhex_getHexOfL_AtObj(a,b){var c=_asnhex_getByteLengthOfL_AtObj(a,b);return 1>c?"":a.substring(b+2,b+2+2*c)}
function _asnhex_getIntOfL_AtObj(a,b){var c=_asnhex_getHexOfL_AtObj(a,b);return""==c?-1:(8>parseInt(c.substring(0,1))?parseBigInt(c,16):parseBigInt(c.substring(2),16)).intValue()}function _asnhex_getStartPosOfV_AtObj(a,b){var c=_asnhex_getByteLengthOfL_AtObj(a,b);return 0>c?c:b+2*(c+1)}function _asnhex_getHexOfV_AtObj(a,b){var c=_asnhex_getStartPosOfV_AtObj(a,b),d=_asnhex_getIntOfL_AtObj(a,b);return a.substring(c,c+2*d)}
function _asnhex_getHexOfTLV_AtObj(a,b){var c=a.substr(b,2),d=_asnhex_getHexOfL_AtObj(a,b),e=_asnhex_getHexOfV_AtObj(a,b);return c+d+e}function _asnhex_getPosOfNextSibling_AtObj(a,b){var c=_asnhex_getStartPosOfV_AtObj(a,b),d=_asnhex_getIntOfL_AtObj(a,b);return c+2*d}
function _asnhex_getPosArrayOfChildren_AtObj(a,b){var c=[],d=_asnhex_getStartPosOfV_AtObj(a,b);c.push(d);for(var e=_asnhex_getIntOfL_AtObj(a,b),f=d,g=0;;){f=_asnhex_getPosOfNextSibling_AtObj(a,f);if(null==f||f-d>=2*e)break;if(200<=g)break;c.push(f);g++}return c}function _asnhex_getNthChildIndex_AtObj(a,b,c){return _asnhex_getPosArrayOfChildren_AtObj(a,b)[c]}
function _asnhex_getDecendantIndexByNthList(a,b,c){if(0==c.length)return b;var d=c.shift();b=_asnhex_getPosArrayOfChildren_AtObj(a,b);return _asnhex_getDecendantIndexByNthList(a,b[d],c)}function _asnhex_getDecendantHexTLVByNthList(a,b,c){b=_asnhex_getDecendantIndexByNthList(a,b,c);return _asnhex_getHexOfTLV_AtObj(a,b)}function _asnhex_getDecendantHexVByNthList(a,b,c){b=_asnhex_getDecendantIndexByNthList(a,b,c);return _asnhex_getHexOfV_AtObj(a,b)}ASN1HEX=function ASN1HEX(){return ASN1HEX};
ASN1HEX.getByteLengthOfL_AtObj=_asnhex_getByteLengthOfL_AtObj;ASN1HEX.getHexOfL_AtObj=_asnhex_getHexOfL_AtObj;ASN1HEX.getIntOfL_AtObj=_asnhex_getIntOfL_AtObj;ASN1HEX.getStartPosOfV_AtObj=_asnhex_getStartPosOfV_AtObj;ASN1HEX.getHexOfV_AtObj=_asnhex_getHexOfV_AtObj;ASN1HEX.getHexOfTLV_AtObj=_asnhex_getHexOfTLV_AtObj;ASN1HEX.getPosOfNextSibling_AtObj=_asnhex_getPosOfNextSibling_AtObj;ASN1HEX.getPosArrayOfChildren_AtObj=_asnhex_getPosArrayOfChildren_AtObj;ASN1HEX.getNthChildIndex_AtObj=_asnhex_getNthChildIndex_AtObj;
ASN1HEX.getDecendantIndexByNthList=_asnhex_getDecendantIndexByNthList;ASN1HEX.getDecendantHexVByNthList=_asnhex_getDecendantHexVByNthList;ASN1HEX.getDecendantHexTLVByNthList=_asnhex_getDecendantHexTLVByNthList;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_pemToBase64(a){a=a.replace("-----BEGIN CERTIFICATE-----","");a=a.replace("-----END CERTIFICATE-----","");return a=a.replace(/[ \n]+/g,"")}function _x509_pemToHex(a){a=_x509_pemToBase64(a);return b64tohex(a)}function _x509_getHexTbsCertificateFromCert(a){return ASN1HEX.getStartPosOfV_AtObj(a,0)}
function _x509_getSubjectPublicKeyInfoPosFromCertHex(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]}
function _x509_getSubjectPublicKeyPosFromCertHex(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}
function _x509_getPublicKeyHexArrayFromCertHex(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]:[]}function _x509_getPublicKeyHexArrayFromCertPEM(a){a=_x509_pemToHex(a);return _x509_getPublicKeyHexArrayFromCertHex(a)}function _x509_getSerialNumberHex(){return ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,1])}
function _x509_getIssuerHex(){return ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,3])}function _x509_getIssuerString(){return _x509_hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,3]))}function _x509_getSubjectHex(){return ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,5])}function _x509_getSubjectString(){return _x509_hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,5]))}
function _x509_getNotBefore(){var a=ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,4,0]),a=a.replace(/(..)/g,"%$1");return a=decodeURIComponent(a)}function _x509_getNotAfter(){var a=ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,4,1]),a=a.replace(/(..)/g,"%$1");return a=decodeURIComponent(a)}_x509_DN_ATTRHEX={"0603550406":"C","060355040a":"O","060355040b":"OU","0603550403":"CN","0603550405":"SN","0603550408":"ST","0603550407":"L"};
function _x509_hex2dn(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}function _x509_hex2rdn(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}
function _x509_readCertPEM(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}function _x509_readCertPEMWithoutRSAInit(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}
function X509(){this.hex=this.subjectPublicKeyRSA_hE=this.subjectPublicKeyRSA_hN=this.subjectPublicKeyRSA=null}X509.prototype.readCertPEM=_x509_readCertPEM;X509.prototype.readCertPEMWithoutRSAInit=_x509_readCertPEMWithoutRSAInit;X509.prototype.getSerialNumberHex=_x509_getSerialNumberHex;X509.prototype.getIssuerHex=_x509_getIssuerHex;X509.prototype.getSubjectHex=_x509_getSubjectHex;X509.prototype.getIssuerString=_x509_getIssuerString;X509.prototype.getSubjectString=_x509_getSubjectString;
X509.prototype.getNotBefore=_x509_getNotBefore;X509.prototype.getNotAfter=_x509_getNotAfter;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+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,p=c.t,x=p-d,t=null==b?nbi():b;f.dlShiftTo(x,t);0<=c.compareTo(t)&&(c[c.t++]=1,c.subTo(t,c));BigInteger.ONE.dlShiftTo(d,
t);for(t.subTo(f,f);f.t<d;)f[f.t++]=0;for(;0<=--x;){var u=c[--p]==e?this.DM:Math.floor(c[p]*l+(c[p-1]+m)*k);if((c[p]+=f.am(0,u,c,x,0,d))<u)for(f.dlShiftTo(x,t),c.subTo(t,c);c[p]<--u;)c.subTo(t,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,p,x=!0,t=nbi(),c=nbits(a[m])-1;0<=m;){c>=k?p=a[m]>>c-k&l:(p=(a[m]&(1<<c+1)-1)<<k-c,0<m&&(p|=a[m-1]>>this.DB+c-k));for(h=d;0==(p&1);)p>>=1,--h;0>(c-=h)&&(c+=this.DB,--m);if(x)g[p].copyTo(e),
x=!1;else{for(;1<h;)f.sqrTo(e,t),f.sqrTo(t,e),h-=2;0<h?f.sqrTo(e,t):(h=e,e=t,t=h);f.mulTo(t,g[p],e)}for(;0<=m&&0==(a[m]&1<<c);)f.sqrTo(e,t),h=e,e=t,t=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.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){u[Q++]=a}var e,f,g,h,u;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;u=new c(3*a.length/4-h);f=0<h?a.length-4:a.length;var Q=
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 u};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 p=d?1:-1,x=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+=p,b/=256,e-=8);d=d<<e|b;for(h+=e;0<h;a[c+f]=d&255,f+=p,d/=256,h-=8);a[c+f-p]|=128*x}};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 NdnCommon={};exports.NdnCommon=NdnCommon;NdnCommon.MAX_NDN_PACKET_SIZE=8800;var 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)return this.callerOnTimeout(a);b*=2;if(b>this.maxInterestLifetime)return this.callerOnTimeout(a);a=a.clone();a.setInterestLifetimeMilliseconds(b);var c=this;this.face.expressInterest(a,this.callerOnData,function(a){c.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 null!=this.signedBuffer?this.signedBuffer:null};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=a.getChangeCount()};exports.ChangeCounter=ChangeCounter;ChangeCounter.prototype.get=function(){return this.target};ChangeCounter.prototype.set=function(a){this.target=a;this.changeCount=a.getChangeCount()};ChangeCounter.prototype.checkChanged=function(){var a=this.target.getChangeCount();return this.changeCount!=a?(this.changeCount=a,!0):!1};var 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){a(b)},function(a){if(d)d(a);else{if(c instanceof SyncPromise)throw a;console.log("Uncaught exception from a Promise: "+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){for(var b in a)this[b]=a[b];this.message=a.message;this.stack=a.stack}}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.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.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.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.LocalControlHeader_LocalControlHeader=80;Tlv.LocalControlHeader_IncomingFaceId=81;Tlv.LocalControlHeader_NextHopFaceId=82;Tlv.LocalControlHeader_CachingPolicy=83;Tlv.LocalControlHeader_NoCache=96;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.writeBlobTlv=function(a,b){null==b?this.writeTypeAndLength(a,0):(this.length+=b.length,this.output.copyFromBack(b,this.length),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};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,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 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);throw Error("ProtobufTlv.decode: Unknown field type");};
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){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){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){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){throw Error("decodeControlParameters 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){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.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){this.dataParts.push(a.slice(0,c));var 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){for(var b in a)this[b]=a[b];this.message=a.message;this.stack=a.stack}}DerDecodingException.prototype=Error();DerDecodingException.prototype.name="DerDecodingException";exports.DerDecodingException=DerDecodingException;function DerEncodingException(a){if(a){for(var b in a)this[b]=a[b];this.message=a.message;this.stack=a.stack}}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),c=c+e.getSize(),d=d+e.getSize();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){a=Math.round(a);for(var b=new DynamicBuffer(10),c=0;!(++c,b.ensureLengthFromBack(c),b.array[b.array.length-c]=a&255,a>>=8,0>=a););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(){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,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.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){c&&(this.onDataNotFoundForPrefix[a.toUri()]=c);a=this.face.registerPrefix(a,this.onInterest.bind(this),b,d,e);this.registeredPrefixIdList.push(a)};MemoryContentCache.prototype.unregisterAll=function(){for(var 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 p=!1;null===g?p=!0:0==b.getChildSelector()?
0>m.compare(f)&&(p=!0):0<m.compare(f)&&(p=!0);p&&(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,SegmentFetcher=function(a,b,c,d){this.face=a;this.verifySegment=b;this.onComplete=c;this.onError=d;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){(new SegmentFetcher(a,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.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(this.verifySegment(b))if(SegmentFetcher.endsWithSegmentNumber(b.getName())){var c=0;try{c=b.getName().get(-1).toSegment()}catch(d){this.onError(SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,"Error decoding the name segment number "+b.getName().get(-1).toEscapedString()+": "+d);return}var e=this.contentParts.length;if(c!=e)this.fetchNextSegment(a,b.getName(),e);else{this.contentParts.push(b.getContent().buf());if(0<b.getMetaInfo().getFinalBlockId().getValue().size()){var f=
0;try{f=b.getMetaInfo().getFinalBlockId().toSegment()}catch(g){this.onError(SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,"Error decoding the FinalBlockId segment number "+b.getMetaInfo().getFinalBlockId().toEscapedString()+": "+g);return}if(c==f){c=Buffer.concat(this.contentParts);this.onComplete(new Blob(c,!1));return}}this.fetchNextSegment(a,b.getName(),e+1)}}else this.onError(SegmentFetcher.ErrorCode.DATA_HAS_NO_SEGMENT,"Got an unexpected packet without a segment number: "+b.getName().toUri());
else this.onError(SegmentFetcher.ErrorCode.SEGMENT_VERIFICATION_FAILED,"Segment verification failed")};SegmentFetcher.prototype.onTimeout=function(a){this.onError(SegmentFetcher.ErrorCode.INTEREST_TIMEOUT,"Time out for interest "+a.getName().toUri())};SegmentFetcher.endsWithSegmentNumber=function(a){return 1<=a.size()&&1<=a.get(-1).getValue().size()&&0==a.get(-1).getValue().buf()[0]};var Transport=function(){};exports.Transport=Transport;Transport.ConnectionInfo=function(){};
Transport.prototype.isLocal=function(a,b,c){c("Transport.isLocal is not implemented")};
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"{ host: "+this.host+", port: "+this.port+" }"};WebSocketTransport.prototype.isLocal=function(a,b,c){b(!1)};
WebSocketTransport.prototype.connect=function(a,b,c,d){this.close();this.ws=new WebSocket("ws://"+a.host+":"+a.port);0<LOG&&console.log("ws connection created.");this.connectionInfo=a;this.ws.binaryType="arraybuffer";this.elementReader=new ElementReader(b);var e=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{e.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.");e.ws=null;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;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){if("string"===typeof a)this.value=DataUtils.stringToUtf8Array(a);else if("object"===typeof a&&a instanceof Name.Component)this.value=new Buffer(a.value);else if("object"===typeof a&&a instanceof Blob)a.isNull()?this.value=new Buffer(0):this.value=new Buffer(a.buf());else if(Buffer.isBuffer(a))this.value=new Buffer(a);else if("object"===typeof a&&"undefined"!==typeof ArrayBuffer&&a instanceof ArrayBuffer)this.value=new Buffer(new Uint8Array(a));else if(a)if("object"===typeof a)this.value=
new Buffer(a);else throw Error("Name.Component constructor: Invalid type");else this.value=new Buffer(0)};Name.Component.prototype.getValue=function(){return new Blob(this.value,!1)};Name.Component.prototype.getValueAsBuffer=function(){return this.value};Name.Component.prototype.toEscapedString=function(){return Name.toEscapedString(this.value)};Name.Component.prototype.toNumber=function(){return DataUtils.bigEndianToUnsignedInt(this.value)};
Name.Component.prototype.toNumberWithMarker=function(a){if(0==this.value.length||this.value[0]!=a)throw Error("Name component does not begin with the expected marker");return DataUtils.bigEndianToUnsignedInt(this.value.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.prototype.equals=function(a){return DataUtils.arraysEqual(this.value,a.value)};Name.Component.prototype.compare=function(a){return Name.Component.compareBuffers(this.value,a.value)};
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)c=Name.fromEscapedString(a[b]),c.isNull()?(a.splice(b,1),--b):a[b]=new Name.Component(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 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+="/"+Name.toEscapedString(this.components[b].getValue().buf());return a};Name.prototype.to_uri=function(){return this.toUri()};Name.prototype.appendSegment=function(a){return this.append(Name.Component.fromNumberWithMarker(a,0))};Name.prototype.appendSegmentOffset=function(a){return this.append(Name.Component.fromNumberWithMarker(a,251))};
Name.prototype.appendVersion=function(a){return this.append(Name.Component.fromNumberWithMarker(a,253))};Name.prototype.appendTimestamp=function(a){return this.append(Name.Component.fromNumberWithMarker(a,252))};Name.prototype.appendSequenceNumber=function(a){return this.append(Name.Component.fromNumberWithMarker(a,254))};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 new Name.Component(this.components[a])}if(a<-this.components.length)throw Error("Name.get: Index is out of bounds");return new Name.Component(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();var c="object"===typeof a&&a instanceof Blob?a.buf():a;b.decodeName(this,c)};
Name.prototype.compare=function(a){for(var b=0;b<this.size()&&b<a.size();++b){var c=this.components[b].compare(a.components[b]);if(0!=c)return c}return this.size()<a.size()?-1:this.size()>a.size()?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.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.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,LOG=require("./log.js").Log.LOG,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.canGetFromSignature=function(a){return a instanceof Sha256WithRsaSignature};
KeyLocator.getFromSignature=function(a){if(a instanceof Sha256WithRsaSignature)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,Blob=require("./util/blob.js").Blob,KeyLocator=require("./key-locator.js").KeyLocator,KeyLocatorType=require("./key-locator.js").KeyLocatorType,Name=require("./name.js").Name,WireFormat=require("./encoding/wire-format.js").WireFormat,LOG=require("./log.js").Log.LOG,ContentType={BLOB:0,LINK:1,KEY:2,NACK:3};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.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.freshnessSeconds=
f;this.finalBlockID=g}this.changeCount_=0};exports.MetaInfo=MetaInfo;MetaInfo.prototype.getType=function(){return this.type_};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.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;LOG=require("./log.js").Log.LOG;WireFormat=require("./encoding/wire-format.js").WireFormat;
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,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,DataUtils=require("./encoding/data-utils.js").DataUtils,Name=require("./name.js").Name,Sha256WithRsaSignature=require("./sha256-with-rsa-signature.js").Sha256WithRsaSignature,MetaInfo=require("./meta-info.js").MetaInfo,KeyLocator=require("./key-locator.js").KeyLocator,WireFormat=require("./encoding/wire-format.js").WireFormat,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.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.defaultWireEncodingFormat_=null);this.changeCount_=this.getDefaultWireEncodingChangeCount_=0};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.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="object"===typeof a&&a instanceof Blob?a.buf():a,c=b.decodeData(this,c);b==WireFormat.getDefaultWireFormat()?this.setDefaultWireEncoding(new SignedBlob(new Blob(a,!0),c.signedPortionBeginOffset,c.signedPortionEndOffset),WireFormat.getDefaultWireFormat()):this.setDefaultWireEncoding(new SignedBlob,null)};
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){for(var b in a)this[b]=a[b];this.message=a.message;this.stack=a.stack}}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").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 Crypto=require("crypto"),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").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,c){return SyncPromise.reject(Error("IdentityStorage.getCertificatePromise is not implemented"))};IdentityStorage.prototype.getCertificate=function(a,b){return SyncPromise.getValue(this.getValuePromise(a,b,!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.getAllKeyNamesOfIdentityPromise=function(a,b,c,d){return SyncPromise.reject(Error("IdentityStorage.getAllKeyNamesOfIdentityPromise 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.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")));d=a.getSubName(0,a.size()-1);var e=this;return this.addIdentityPromise(d).then(function(){return e.doesKeyExistPromise(a)}).then(function(d){if(d)throw new SecurityException(Error("A key with the same name already exists!"));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"))):this.database.publicKey.get(a.toUri()).then(function(a){return a?Promise.resolve(new Blob(a.keyDer)):Promise.resolve(new Blob)})};
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.doesKeyExistPromise(d).then(function(a){if(!a)throw new SecurityException(Error("No corresponding Key record for certificate! "+d.toUri()+" "+c.toUri()));return e.doesCertificateExistPromise(c)}).then(function(a){if(a)throw new SecurityException(Error("Certificate has already been installed!"));
return e.getKeyPromise(d)}).then(function(b){if(b.isNull()||!DataUtils.arraysEqual(b.buf(),a.getPublicKeyInfo().getKeyDer().buf()))throw new SecurityException(Error("The certificate does not match the public key!"));return e.database.certificate.put({certificateNameUri:c.toUri(),encoding:a.wireEncode().buf()})})};
IndexedDbIdentityStorage.prototype.getCertificatePromise=function(a,b,c){return c?Promise.reject(new SecurityException(Error("IndexedDbIdentityStorage.getCertificatePromise is only supported for async"))):b?this.database.certificate.get(a.toUri()).then(function(a){if(a){var b=new IdentityCertificate;b.wireDecode(a.encoding);return Promise.resolve(b)}return Promise.resolve(null)}):Promise.reject(Error("IndexedDbIdentityStorage.getCertificate for !allowAny is not implemented"))};
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.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.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 Data=require("../../data.js").Data,Name=require("../../name.js").Name,Blob=require("../../util/blob.js").Blob,KeyType=require("../security-types.js").KeyType,DataUtils=require("../../encoding/data-utils.js").DataUtils,SecurityException=require("../security-exception.js").SecurityException,SyncPromise=require("../../util/sync-promise").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){var d=a.getSubName(0,a.size()-1);this.addIdentity(d);if(this.doesKeyExist(a))return SyncPromise.reject(new SecurityException(Error("A key with the same name already exists!")));this.keyStore[a.toUri()]={keyType:b,keyDer:new Blob(c),defaultCertificate:null};return SyncPromise.resolve()};
MemoryIdentityStorage.prototype.getKeyPromise=function(a){a=a.toUri();a=this.keyStore[a];return void 0===a?SyncPromise.resolve(new Blob):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();if(!this.doesKeyExist(c))return SyncPromise.reject(new SecurityException(Error("No corresponding Key record for certificate! "+c.toUri()+" "+b.toUri())));if(this.doesCertificateExist(b))return SyncPromise.reject(new SecurityException(Error("Certificate has already been installed!")));c=this.getKey(c);if(c.isNull()||!DataUtils.arraysEqual(c.buf(),a.getPublicKeyInfo().getKeyDer().buf()))return SyncPromise.reject(new SecurityException(Error("The certificate does not match the public key!")));
this.certificateStore[b.toUri()]=a.wireEncode();return SyncPromise.resolve()};MemoryIdentityStorage.prototype.getCertificatePromise=function(a,b){if(!b)return SyncPromise.reject(Error("MemoryIdentityStorage.getCertificate for !allowAny is not implemented"));var c=a.toUri();if(void 0===this.certificateStore[c])return SyncPromise.resolve(null);var d=new IdentityCertificate;d.wireDecode(this.certificateStore[c]);return SyncPromise.resolve(d)};
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").SyncPromise,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))};
var Crypto=require("crypto"),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").DerNode,
OID=require("../../encoding/oid").OID,SyncPromise=require("../../util/sync-promise").SyncPromise,UseSubtleCrypto=require("../../use-subtle-crypto-node.js").UseSubtleCrypto,rsaKeygen=null;try{rsaKeygen=require("rsa-keygen")}catch(e$$23){}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");for(var d="-----BEGIN RSA PRIVATE KEY-----\n",e=0;e<c.length;e+=64)d+=c.substr(e,64)+"\n";d+="-----END RSA PRIVATE KEY-----";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")));if(UseSubtleCrypto()&&!c){var d=this;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")))}if(b.getKeyType()===
KeyType.RSA){if(!rsaKeygen)return SyncPromise.reject(new SecurityException(Error("Need to install rsa-keygen: sudo npm install rsa-keygen")));c=rsaKeygen.generate(b.getKeySize());var g=c.public_key.toString().replace("-----BEGIN PUBLIC KEY-----","").replace("-----END PUBLIC KEY-----",""),f=new Buffer(g,"base64");c=c.private_key.toString()}else return SyncPromise.reject(new SecurityException(Error("Only RSA key generation currently supported")));this.setPublicKeyForKeyName(a,b.getKeyType(),f);this.privateKeyStore[a.toUri()]=
{keyType:b.getKeyType(),privateKey:c};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.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()};MemoryPrivateKeyStorage.RSA_ENCRYPTION_OID="1.2.840.113549.1.1.1";
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=MemoryPrivateKeyStorage.encodePkcs8PrivateKey(d,new OID(MemoryPrivateKeyStorage.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)})}d=Crypto.createSign("RSA-SHA256");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"),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"),Name=require("../../name.js").Name,Data=require("../../data.js").Data,Blob=require("../../util/blob.js").Blob,DigestSha256Signature=require("../../digest-sha256-signature.js").DigestSha256Signature,Sha256WithRsaSignature=require("../../sha256-with-rsa-signature.js").Sha256WithRsaSignature,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").SyncPromise,IdentityManager=
function(a,b){this.identityStorage=a;this.privateKeyStorage=b};exports.IdentityManager=IdentityManager;
IdentityManager.prototype.createIdentityAndCertificate=function(a,b,c,d){var e=!c,f=this,g=!0,h=null,k=this.identityStorage.addIdentityPromise(a,e).then(function(){return f.identityStorage.getDefaultKeyNameForIdentityPromise(a,e).then(function(a){h=a;return f.identityStorage.getKeyPromise(h,e).then(function(a){(new PublicKey(a)).getKeyType()==b.getKeyType()&&(g=!1);return SyncPromise.resolve()})},function(a){if(!(a instanceof SecurityException))throw a;return SyncPromise.resolve()})}).then(function(){return g?
f.generateKeyPairPromise(a,!0,b,e).then(function(a){h=a;return f.identityStorage.setDefaultKeyNameForIdentityPromise(h,e)}):SyncPromise.resolve()}).then(function(){return f.identityStorage.getDefaultCertificateNameForKeyPromise(h,e).then(function(a){return SyncPromise.resolve(a)},function(a){if(!(a instanceof SecurityException))throw a;var b;return f.selfSignPromise(h,e).then(function(a){b=a.getName();return f.addCertificateAsIdentityDefaultPromise(a,e)}).then(function(){return SyncPromise.resolve(b)})})});
return SyncPromise.complete(c,d,k)};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(a).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,f,c)};IdentityManager.prototype.setDefaultIdentity=function(a,b,c){return SyncPromise.complete(b,c,this.identityStorage.setDefaultIdentityPromise(a,!b))};IdentityManager.prototype.getDefaultIdentity=function(a,b){return SyncPromise.complete(a,b,this.identityStorage.getDefaultIdentityPromise(!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.generateRSAKeyPairAsDefault=function(a,b,c){a=this.generateRSAKeyPair(a,b,c);this.identityStorage.setDefaultKeyNameForIdentity(a);return a};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.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.getAnyCertificate=function(a,b,c){return SyncPromise.complete(b,c,this.identityStorage.getCertificatePromise(a,!0,!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.getDefaultIdentityPromise(c).then(function(a){return d.identityStorage.getDefaultCertificateNameForIdentityPromise(a,c)}))};
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.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();var f=!d,g=this,h,k=[0];return SyncPromise.complete(d,e,this.makeSignatureByCertificatePromise(b,k,f).then(function(d){h=d;a.getName().append(c.encodeSignatureInfo(h));a.getName().append(new Name.Component);d=a.wireEncode(c);var e=IdentityManager.certificateNameToPublicKeyName(b);return g.privateKeyStorage.signPromise(d.signedBuf(),
e,k[0],f)}).then(function(b){h.setSignature(b);a.setName(a.getName().getPrefix(-1).append(c.encodeSignatureValue(h)));return SyncPromise.resolve(a)}))};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){var d=null;if(c.getKeyType()==KeyType.RSA)d=new Sha256WithRsaSignature,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)})};
var ValidationRequest=function(a,b,c,d,e){this.interest=a;this.onVerified=b;this.onVerifyFailed=c;this.retry=d;this.stepCount=e};exports.ValidationRequest=ValidationRequest;
var Crypto=require("crypto"),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,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.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 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{if(null===PolicyManager.verifyUsesString){var f=Crypto.createHash("sha256").digest();PolicyManager.verifyUsesString="string"===typeof f}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.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,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)return d(a),null;e=ConfigPolicyManager.extractSignature(a,e);if(null==e||!KeyLocator.canGetFromSignature(e))return d(a),null;var f=null;try{f=KeyLocator.getFromSignature(e)}catch(g){return d(a),null}f=f.getKeyName();if(0==f.size())return d(a),null;var h=a.getName(),k="data";a instanceof Interest&&(h=h.getPrefix(-4),k="interest");k=this.findMatchingRule(h,k);if(null==k||!this.checkSignatureMatch(f,h,k))return d(a),
null;this.refreshManager.refreshAnchors();h=this.refreshManager.getCertificate(f);null==h&&(h=this.certificateCache.getCertificate(f));var l=this;if(null==h)return e=new Interest(f),new ValidationRequest(e,function(e){e=new IdentityCertificate(e);l.certificateCache.insertCertificate(e);l.checkVerificationPolicy(a,b+1,c,d)},d,2,b+1);if(a instanceof Interest){var m=h.getPublicKeyName(),p=a.getName().get(-4).toNumber();if(!this.interestTimestampIsFresh(m,p))return d(a),null}this.verify(e,a.wireEncode(),
function(b){b?(c(a),a instanceof Interest&&l.updateTimestampForKey(m,p)):d(a)})};
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){c=c.get("checker")[0];var d=c.get("type")[0].getValue();if("fixed-signer"==d){b=c.get("signer")[0];c=b.get("type")[0].getValue();if("file"==c)b=this.lookupCertificate(b.get("file-name")[0].getValue(),!0);else if("base64"==c)b=this.lookupCertificate(b.get("base64-string")[0].getValue(),!1);else return!1;if(null!=b)return b.getName().equals(a)}else if("hierarchical"==d){if(a=NdnRegexMatcher.match("^([^<KEY>]*)<KEY>(<>*)<ksk-.+><ID-CERT>",
a),null!=a)return a=(new Name(a[1])).append(new Name(a[2])),ConfigPolicyManager.matchesRelation(b,a,"is-prefix-of")}else if("customized"==d){d=c.get("key-locator")[0];c=d.getFirstValue("relation");if(null!=c)return b=new Name(d.get("name")[0].getValue()),ConfigPolicyManager.matchesRelation(a,b,c);var e=d.getFirstValue("regex");if(null!=e)return null!=NdnRegexMatcher.match(e,a);c=d.get("hyper-relation");if(1<=c.length){c=c[0];var e=c.getFirstValue("k-regex"),f=c.getFirstValue("k-expand"),g=c.getFirstValue("p-regex"),
d=c.getFirstValue("p-expand");c=c.getFirstValue("h-relation");if(null!=e&&null!=f&&null!=g&&null!=d&&null!=c){a=NdnRegexMatcher.match(e,a);if(null==a||void 0===a[1])return!1;a=ConfigPolicyManager.expand(a,f);b=NdnRegexMatcher.match(g,b);if(null==b||void 0===b[1])return!1;b=ConfigPolicyManager.expand(b,d);return ConfigPolicyManager.matchesRelation(new Name(b),new Name(a),c)}}}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())}catch(d){return null}return c}return null};
ConfigPolicyManager.prototype.interestTimestampIsFresh=function(a,b){var c=this.keyTimestamps[a.toUri()];if(void 0==c){var c=(new Date).getTime(),d=c+this.keyGraceInterval;return b>c-this.keyGraceInterval&&b<d}return b>c};
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 d=d.getKeyName(),e=this.refreshManager.getCertificate(d);null==e&&(e=this.certificateCache.getCertificate(d));if(null==e)return c(!1);d=e.getPublicKeyInfo().getKeyDer();return d.isNull()?c(!1):PolicyManager.verifySignature(a,b,d,c)}return c(!1)};
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,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){c(a);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").SyncPromise,PolicyManager=require("./policy-manager.js").PolicyManager,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){b?c(a):d(a)});else if(a instanceof Interest)b=e.decodeSignatureInfoAndValue(a.getName().get(-2).getValue().buf(),a.getName().get(-1).getValue().buf()),this.verify(b,a.wireEncode(),function(b){b?c(a):d(a)});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){KeyLocator.canGetFromSignature(a)?this.getPublicKeyDer(KeyLocator.getFromSignature(a),function(d){d.isNull()?c(!1):PolicyManager.verifySignature(a,b,d,c)}):PolicyManager.verifySignature(a,b,null,c)};
SelfVerifyPolicyManager.prototype.getPublicKeyDer=function(a,b){a.getType()==KeyLocatorType.KEYNAME&&null!=this.identityStorage?SyncPromise.complete(b,this.identityStorage.getKeyPromise(IdentityCertificate.certificateNameToPublicKeyName(a.getKeyName()))):b(new Blob)};
var Name=require("../name.js").Name,Interest=require("../interest.js").Interest,Data=require("../data.js").Data,KeyLocatorType=require("../key-locator.js").KeyLocatorType,Sha256WithRsaSignature=require("../sha256-with-rsa-signature.js").Sha256WithRsaSignature,WireFormat=require("../encoding/wire-format.js").WireFormat,Tlv=require("../encoding/tlv/tlv.js").Tlv,TlvEncoder=require("../encoding/tlv/tlv-encoder.js").TlvEncoder,SecurityException=require("./security-exception.js").SecurityException,RsaKeyParams=
require("./key-params.js").RsaKeyParams,IdentityCertificate=require("./certificate/identity-certificate.js").IdentityCertificate,SyncPromise=require("../util/sync-promise").SyncPromise,KeyChain=function(a,b){this.identityManager=a;this.policyManager=b;this.face=null;this.maxSteps=100};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()};KeyChain.prototype.generateRSAKeyPair=function(a,b,c){return this.identityManager.generateRSAKeyPair(a,b,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.getAnyCertificate=function(a,b,c){return this.identityManager.getAnyCertificate(a,b,c)};KeyChain.prototype.getIdentityCertificate=function(a,b,c){return this.identityManager.getCertificate(a,b,c)};KeyChain.prototype.getAnyIdentityCertificate=function(a,b,c){return this.identityManager.getAnyCertificate(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){return a instanceof Interest?this.identityManager.signInterestByCertificate(a,b,c,d,e):a instanceof Data?this.identityManager.signByCertificate(a,b,c,d,e):this.identityManager.signByCertificate(a,b,d,e)};
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){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 this.policyManager.skipVerifyAndTrust(a)?b(a):c(a)};
KeyChain.prototype.verifyInterest=function(a,b,c,d,e){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(a){g.onCertificateInterestTimeout(a,f.retry,c,data,f)})}}else this.policyManager.skipVerifyAndTrust(a)?b(a):c(a)};KeyChain.prototype.setFace=function(a){this.face=a};KeyChain.DEFAULT_KEY_PARAMS=new RsaKeyParams;
KeyChain.prototype.onCertificateData=function(a,b,c){this.verifyData(b,c.onVerified,c.onVerifyFailed,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 c(d)};
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+Name.toEscapedString(this.values[b].getValue().buf());return a};
Exclude.prototype.matches=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=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<Exclude.compareComponents(a,c)&&0>Exclude.compareComponents(a,e))return!0}else if(0>Exclude.compareComponents(a,
e))return!0;b=d-1}else if(null!=c){if(0<Exclude.compareComponents(a,c))return!0}else return!0}else if(DataUtils.arraysEqual(a,this.values[b].getValue().buf()))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};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;KeyLocator=require("./key-locator.js").KeyLocator;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.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.defaultWireEncoding_=new SignedBlob,this.defaultWireEncodingFormat_=null);this.changeCount_=this.getDefaultWireEncodingChangeCount_=this.getNonceChangeCount_=0};
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.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.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.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.setExclude=function(a){this.exclude_.set("object"===typeof a&&a instanceof Exclude?new Exclude(a):new Exclude);++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="object"===typeof a&&a instanceof Blob?a.buf():a,c=b.decodeInterest(this,c);b==WireFormat.getDefaultWireFormat()?this.setDefaultWireEncoding(new SignedBlob(new Blob(a,!0),c.signedPortionBeginOffset,c.signedPortionEndOffset),WireFormat.getDefaultWireFormat()):this.setDefaultWireEncoding(new SignedBlob,null)};
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)}});var 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").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();var c="object"===typeof a&&a instanceof Blob?a.buf():a;b.decodeControlParameters(this,c)};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 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 Crypto=require("../crypto.js"),Blob=require("../util/blob.js").Blob,Name=require("../name").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,KeyLocator=require("../key-locator.js").KeyLocator,KeyLocatorType=
require("../key-locator.js").KeyLocatorType,Sha256WithRsaSignature=require("../sha256-with-rsa-signature.js").Sha256WithRsaSignature,DigestSha256Signature=require("../digest-sha256-signature.js").DigestSha256Signature,ForwardingFlags=require("../forwarding-flags.js").ForwardingFlags,DecodingException=require("./decoding-exception.js").DecodingException,Tlv0_1_1WireFormat=function(){WireFormat.call(this)};Tlv0_1_1WireFormat.prototype=new WireFormat;Tlv0_1_1WireFormat.prototype.name="Tlv0_1_1WireFormat";
exports.Tlv0_1_1WireFormat=Tlv0_1_1WireFormat;Tlv0_1_1WireFormat.instance=null;Tlv0_1_1WireFormat.prototype.encodeName=function(a){var b=new TlvEncoder;Tlv0_1_1WireFormat.encodeName(a,b);return new Blob(b.getOutput(),!1)};Tlv0_1_1WireFormat.prototype.decodeName=function(a,b){var c=new TlvDecoder(b);Tlv0_1_1WireFormat.decodeName(a,c)};
Tlv0_1_1WireFormat.prototype.encodeInterest=function(a){var b=new TlvEncoder(256),c=b.getLength();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()){var 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_1_1WireFormat.encodeSelectors(a,b);d=Tlv0_1_1WireFormat.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_1_1WireFormat.prototype.decodeInterest=function(a,b){var c=new TlvDecoder(b),d=c.readNestedTlvsStart(Tlv.Interest),e=Tlv0_1_1WireFormat.decodeName(a.getName(),c);c.peekType(Tlv.Selectors,d)&&Tlv0_1_1WireFormat.decodeSelectors(a,c);var f=c.readBlobTlv(Tlv.Nonce);a.setInterestLifetimeMilliseconds(c.readOptionalNonNegativeIntegerTlv(Tlv.InterestLifetime,d));a.setNonce(f);c.finishNestedTlvs(d);return e};
Tlv0_1_1WireFormat.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_1_1WireFormat.encodeSignatureInfo_(a.getSignature(),b);b.writeBlobTlv(Tlv.Content,a.getContent().buf());Tlv0_1_1WireFormat.encodeMetaInfo(a.getMetaInfo(),b);Tlv0_1_1WireFormat.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_1_1WireFormat.prototype.decodeData=function(a,b){var c=new TlvDecoder(b),d=c.readNestedTlvsStart(Tlv.Data),e=c.getOffset();Tlv0_1_1WireFormat.decodeName(a.getName(),c);Tlv0_1_1WireFormat.decodeMetaInfo(a.getMetaInfo(),c);a.setContent(c.readBlobTlv(Tlv.Content));Tlv0_1_1WireFormat.decodeSignatureInfo(a,c);var f=c.getOffset();a.getSignature().setSignature(new Blob(c.readBlobTlv(Tlv.SignatureValue),!0));c.finishNestedTlvs(d);return{signedPortionBeginOffset:e,signedPortionEndOffset:f}};
Tlv0_1_1WireFormat.prototype.encodeControlParameters=function(a){var b=new TlvEncoder(256),c=b.getLength();b.writeOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_ExpirationPeriod,a.getExpirationPeriod());if(0<a.getStrategy().size()){var d=b.getLength();Tlv0_1_1WireFormat.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_1_1WireFormat.encodeName(a.getName(),
b);b.writeTypeAndLength(Tlv.ControlParameters_ControlParameters,b.getLength()-c);return new Blob(b.getOutput(),!1)};
Tlv0_1_1WireFormat.prototype.decodeControlParameters=function(a,b){a.clear();var c=new TlvDecoder(b),d=c.readNestedTlvsStart(Tlv.ControlParameters_ControlParameters);if(c.peekType(Tlv.Name,d)){var e=new Name;Tlv0_1_1WireFormat.decodeName(e,c);a.setName(e)}a.setFaceId(c.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_FaceId,d));c.peekType(Tlv.ControlParameters_Uri,d)&&(e=new Blob(c.readOptionalBlobTlv(Tlv.ControlParameters_Uri,d),!1),a.setUri(e.toString()));a.setLocalControlFeature(c.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_LocalControlFeature,
d));a.setOrigin(c.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_Origin,d));a.setCost(c.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_Cost,d));c.peekType(Tlv.ControlParameters_Flags,d)&&(e=new ForwardingFlags,e.setNfdForwardingFlags(c.readNonNegativeIntegerTlv(Tlv.ControlParameters_Flags,d)),a.setForwardingFlags(e));c.peekType(Tlv.ControlParameters_Strategy,d)&&(e=c.readNestedTlvsStart(Tlv.ControlParameters_Strategy),Tlv0_1_1WireFormat.decodeName(a.getStrategy(),c),c.finishNestedTlvs(e));
a.setExpirationPeriod(c.readOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_ExpirationPeriod,d));c.finishNestedTlvs(d)};Tlv0_1_1WireFormat.prototype.encodeSignatureInfo=function(a){var b=new TlvEncoder(256);Tlv0_1_1WireFormat.encodeSignatureInfo_(a,b);return new Blob(b.getOutput(),!1)};Tlv0_1_1WireFormat.SignatureHolder=function(){};Tlv0_1_1WireFormat.SignatureHolder.prototype.setSignature=function(a){this.signature=a};Tlv0_1_1WireFormat.SignatureHolder.prototype.getSignature=function(){return this.signature};
Tlv0_1_1WireFormat.prototype.decodeSignatureInfoAndValue=function(a,b){var c=new Tlv0_1_1WireFormat.SignatureHolder,d=new TlvDecoder(a);Tlv0_1_1WireFormat.decodeSignatureInfo(c,d);d=new TlvDecoder(b);c.getSignature().setSignature(new Blob(d.readBlobTlv(Tlv.SignatureValue),!0));return c.getSignature()};Tlv0_1_1WireFormat.prototype.encodeSignatureValue=function(a){var b=new TlvEncoder(256);b.writeBlobTlv(Tlv.SignatureValue,a.getSignature().buf());return new Blob(b.getOutput(),!1)};
Tlv0_1_1WireFormat.get=function(){null===Tlv0_1_1WireFormat.instance&&(Tlv0_1_1WireFormat.instance=new Tlv0_1_1WireFormat);return Tlv0_1_1WireFormat.instance};Tlv0_1_1WireFormat.encodeName=function(a,b){for(var c=b.getLength(),d,e=a.size()-1;0<=e;--e)b.writeBlobTlv(Tlv.NameComponent,a.get(e).getValue().buf()),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_1_1WireFormat.decodeName=function(a,b){a.clear();for(var c=b.readNestedTlvsStart(Tlv.Name),d=b.getOffset(),e=d;b.getOffset()<c;)e=b.getOffset(),a.append(b.readBlobTlv(Tlv.NameComponent));b.finishNestedTlvs(c);return{signedPortionBeginOffset:d,signedPortionEndOffset:e}};
Tlv0_1_1WireFormat.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_1_1WireFormat.encodeExclude(a.getExclude(),b);null!=a.getKeyLocator().getType()&&Tlv0_1_1WireFormat.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_1_1WireFormat.decodeSelectors=function(a,b){var c=b.readNestedTlvsStart(Tlv.Selectors);a.setMinSuffixComponents(b.readOptionalNonNegativeIntegerTlv(Tlv.MinSuffixComponents,c));a.setMaxSuffixComponents(b.readOptionalNonNegativeIntegerTlv(Tlv.MaxSuffixComponents,c));b.peekType(Tlv.PublisherPublicKeyLocator,c)?Tlv0_1_1WireFormat.decodeKeyLocator(Tlv.PublisherPublicKeyLocator,a.getKeyLocator(),b):a.getKeyLocator().clear();b.peekType(Tlv.Exclude,c)?Tlv0_1_1WireFormat.decodeExclude(a.getExclude(),
b):a.getExclude().clear();a.setChildSelector(b.readOptionalNonNegativeIntegerTlv(Tlv.ChildSelector,c));a.setMustBeFresh(b.readBooleanTlv(Tlv.MustBeFresh,c));b.finishNestedTlvs(c)};Tlv0_1_1WireFormat.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):b.writeBlobTlv(Tlv.NameComponent,e.getValue().buf())}b.writeTypeAndLength(Tlv.Exclude,b.getLength()-c)};
Tlv0_1_1WireFormat.decodeExclude=function(a,b){var c=b.readNestedTlvsStart(Tlv.Exclude);for(a.clear();;)if(b.peekType(Tlv.NameComponent,c))a.appendComponent(b.readBlobTlv(Tlv.NameComponent));else if(b.readBooleanTlv(Tlv.Any,c))a.appendAny();else break;b.finishNestedTlvs(c)};
Tlv0_1_1WireFormat.encodeKeyLocator=function(a,b,c){var d=c.getLength();if(null!=b.getType())if(b.getType()==KeyLocatorType.KEYNAME)Tlv0_1_1WireFormat.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_1_1WireFormat.decodeKeyLocator=function(a,b,c){a=c.readNestedTlvsStart(a);b.clear();if(c.getOffset()!=a){if(c.peekType(Tlv.Name,a))b.setType(KeyLocatorType.KEYNAME),Tlv0_1_1WireFormat.decodeName(b.getKeyName(),c);else if(c.peekType(Tlv.KeyLocatorDigest,a))b.setType(KeyLocatorType.KEY_LOCATOR_DIGEST),b.setKeyData(c.readBlobTlv(Tlv.KeyLocatorDigest));else throw new DecodingException(Error("decodeKeyLocator: Unrecognized key locator type"));c.finishNestedTlvs(a)}};
Tlv0_1_1WireFormat.encodeSignatureInfo_=function(a,b){var c=b.getLength();if(a instanceof Sha256WithRsaSignature)Tlv0_1_1WireFormat.encodeKeyLocator(Tlv.KeyLocator,a.getKeyLocator(),b),b.writeNonNegativeIntegerTlv(Tlv.SignatureType,Tlv.SignatureType_SignatureSha256WithRsa);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_1_1WireFormat.decodeSignatureInfo=function(a,b){var c=b.readNestedTlvsStart(Tlv.SignatureInfo),d=b.readNonNegativeIntegerTlv(Tlv.SignatureType);if(d==Tlv.SignatureType_SignatureSha256WithRsa)a.setSignature(new Sha256WithRsaSignature),d=a.getSignature(),Tlv0_1_1WireFormat.decodeKeyLocator(Tlv.KeyLocator,d.getKeyLocator(),b);else if(d==Tlv.SignatureType_DigestSha256)a.setSignature(new DigestSha256Signature);else throw new DecodingException(Error("decodeSignatureInfo: unrecognized SignatureInfo type"+d));
b.finishNestedTlvs(c)};
Tlv0_1_1WireFormat.encodeMetaInfo=function(a,b){var c=b.getLength(),d=a.getFinalBlockId().getValue().buf();if(null!=d&&0<d.length){var e=b.getLength();b.writeBlobTlv(Tlv.NameComponent,d);b.writeTypeAndLength(Tlv.FinalBlockId,b.getLength()-e)}b.writeOptionalNonNegativeIntegerTlv(Tlv.FreshnessPeriod,a.getFreshnessPeriod());if(a.getType()!=ContentType.BLOB)if(a.getType()==ContentType.LINK||a.getType()==ContentType.KEY)b.writeNonNegativeIntegerTlv(Tlv.ContentType,a.getType());else throw Error("unrecognized TLV ContentType");b.writeTypeAndLength(Tlv.MetaInfo,
b.getLength()-c)};Tlv0_1_1WireFormat.decodeMetaInfo=function(a,b){var c=b.readNestedTlvsStart(Tlv.MetaInfo);a.setType(b.readOptionalNonNegativeIntegerTlv(Tlv.ContentType,c));a.setFreshnessPeriod(b.readOptionalNonNegativeIntegerTlv(Tlv.FreshnessPeriod,c));if(b.peekType(Tlv.FinalBlockId,c)){var d=b.readNestedTlvsStart(Tlv.FinalBlockId);a.setFinalBlockId(b.readBlobTlv(Tlv.NameComponent));b.finishNestedTlvs(d)}else a.setFinalBlockId(null);b.finishNestedTlvs(c)};
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_1_1WireFormat=require("./tlv-0_1_1-wire-format.js").Tlv0_1_1WireFormat;TlvWireFormat=function(){Tlv0_1_1WireFormat.call(this)};TlvWireFormat.prototype=new Tlv0_1_1WireFormat;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,WireFormat=require("./wire-format.js").WireFormat,LOG=require("../log.js").Log.LOG,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"));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 DigestSha256Signature&&(e=a.getSignature(),b("DigestSha256 signature.signature: "+(0<e.getSignature().size()?e.getSignature().toHex():"<none>")));null!==d&&(d.getType()==KeyLocatorType.NONE?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 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").SyncStateProto,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 p;try{p=dcodeIO.ProtoBuf.newBuilder()["import"](SyncStateProto).build("Sync")}catch(x){p=
require("protobufjs").newBuilder()["import"](SyncStateProto).build("Sync")}this.SyncStateMsg=p.SyncStateMsg;this.SyncState=p.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));this.keyChain.sign(d,this.certificateName);this.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("/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));this.onReceivedSyncState(e,d);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){this.enabled&&(console.log("no other people"),this.usrseq++,this.onInitialized(),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());a=new Data(a.getName());a.setContent(new Blob(b,!1));this.keyChain.sign(a,
this.certificateName);try{c.putData(a)}catch(e){console.log(e.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);b=new Data(a);b.setContent(new Blob(d,!1));this.keyChain.sign(b,this.certificateName);try{c.putData(b)}catch(m){console.log(m.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}})];this.update(d)&&(d=new ChronoSync2013.DigestLogEntry(this.digest_tree.getRoot(),d),this.digest_log.push(d),this.onInitialized())}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)))this.onInitialized()};
ChronoSync2013.prototype.dummyOnData=function(a,b){console.log("*** dummyOnData called. ***")};Crypto=require("crypto");DataUtils=require("../encoding/data-utils.js").DataUtils;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"),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 Crypto=require("crypto"),DataUtils=require("./encoding/data-utils.js").DataUtils,Name=require("./name.js").Name,Interest=require("./interest.js").Interest,Data=require("./data.js").Data,MetaInfo=require("./meta-info.js").MetaInfo,ControlParameters=require("./control-parameters.js").ControlParameters,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,KeyLocatorType=require("./key-locator.js").KeyLocatorType,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,NdnCommon=require("./util/ndn-common.js").NdnCommon,
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");
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=[];this.pitRemoveRequests=[];this.registeredPrefixTable=[];this.registeredPrefixRemoveRequests=
[];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.PendingInterest=function(a,b,c,d){this.pendingInterestId=a;this.interest=b;this.onData=c;this.onTimeout=d;this.timerID=-1};Face.prototype.extractEntriesForExpressedInterest=function(a){for(var b=[],c=this.pendingInterestTable.length-1;0<=c;--c){var d=this.pendingInterestTable[c];d.interest.matchesName(a)&&(clearTimeout(d.timerID),b.push(d),this.pendingInterestTable.splice(c,1))}return b};
Face.RegisteredPrefix=function(a,b,c){this.registeredPrefixId=a;this.prefix=b;this.relatedInterestFilterId=c};Face.RegisteredPrefix.prototype.getRegisteredPrefixId=function(){return this.registeredPrefixId};Face.RegisteredPrefix.prototype.getPrefix=function(){return this.prefix};Face.RegisteredPrefix.prototype.getRelatedInterestFilterId=function(){return this.relatedInterestFilterId};Face.InterestFilterEntry=function(a,b,c){this.interestFilterId=a;this.filter=b;this.onInterest=c};
Face.InterestFilterEntry.prototype.getInterestFilterId=function(){return this.interestFilterId};Face.InterestFilterEntry.prototype.getFilter=function(){return this.filter};Face.InterestFilterEntry.prototype.getOnInterest=function(){return this.onInterest};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){var e,f,g;"object"==typeof a&&a instanceof Interest?(e=new Interest(a),f=b,g=c?c:function(){}):b&&"object"==typeof b&&b instanceof Interest?(e=new Interest(b),e.setName(a),f=c,g=d?d:function(){}):(e=new Interest(a),e.setInterestLifetimeMilliseconds(4E3),f=b,g=c?c:function(){});var h=this.getNextEntryId();if(null==this.connectionInfo)if(null==this.getConnectionInfo)console.log("ERROR: connectionInfo is NOT SET");else{var k=this;this.connectAndExecute(function(){k.reconnectAndExpressInterest(h,
e,f,g)})}else this.reconnectAndExpressInterest(h,e,f,g);return h};
Face.prototype.reconnectAndExpressInterest=function(a,b,c,d){var e=this;if(this.connectionInfo.equals(this.transport.connectionInfo)&&this.readyStatus!==Face.UNOPEN)if(this.readyStatus===Face.OPEN_REQUESTED)this.onConnectedCallbacks.push(function(){e.expressInterestHelper(a,b,c,d)});else if(this.readyStatus===Face.OPENED)this.expressInterestHelper(a,b,c,d);else throw Error("reconnectAndExpressInterest: unexpected connection is not opened");else this.readyStatus=Face.OPEN_REQUESTED,this.onConnectedCallbacks.push(function(){e.expressInterestHelper(a,
b,c,d)}),this.transport.connect(this.connectionInfo,this,function(){for(e.readyStatus=Face.OPENED;0<e.onConnectedCallbacks.length;)try{e.onConnectedCallbacks.shift()()}catch(a){console.log("Face.reconnectAndExpressInterest: ignoring exception from onConnectedCallbacks: "+a)}if(e.onopen)e.onopen()},function(){e.closeByTransport()})};
Face.prototype.expressInterestHelper=function(a,b,c,d){var e=b.wireEncode();if(e.size()>Face.getMaxNdnPacketSize())throw Error("The encoded interest size exceeds the maximum limit getMaxNdnPacketSize()");var f=f=this.pitRemoveRequests.indexOf(a);if(0<=f)this.pitRemoveRequests.splice(f,1);else{var g=new Face.PendingInterest(a,b,c,d);this.pendingInterestTable.push(g);a=b.getInterestLifetimeMilliseconds()||4E3;var h=this;g.timerID=setTimeout(function(){1<LOG&&console.log("Interest time out: "+b.getName().toUri());
var a=h.pendingInterestTable.indexOf(g);0<=a&&h.pendingInterestTable.splice(a,1);if(g.onTimeout)g.onTimeout(g.interest)},a)}this.timeoutPrefix.match(b.getName())||this.transport.send(e.buf())};
Face.prototype.removePendingInterest=function(a){if(null!=a){for(var b=0,c=this.pendingInterestTable.length-1;0<=c;--c){var d=this.pendingInterestTable[c];d.pendingInterestId==a&&(clearTimeout(d.timerID),this.pendingInterestTable.splice(c,1),++b)}0==b&&0<LOG&&console.log("removePendingInterest: Didn't find pendingInterestId "+a);0==b&&0>this.pitRemoveRequests.indexOf(a)&&this.pitRemoveRequests.push(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){b=b||WireFormat.getDefaultWireFormat();this.nodeMakeCommandInterest(a,this.commandKeyChain,this.commandCertificateName,b)};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){c||(c=function(){});d||(d=new ForwardingFlags);var e=this.getNextEntryId(),f=this,g=function(){f.nfdRegisterPrefix(e,a,b,d,c,f.commandKeyChain,f.commandCertificateName)};null==this.connectionInfo?null==this.getConnectionInfo?console.log("ERROR: connectionInfo is NOT SET"):this.connectAndExecute(g):g();return e};Face.getMaxNdnPacketSize=function(){return NdnCommon.MAX_NDN_PACKET_SIZE};
Face.RegisterResponse=function(a,b,c,d,e,f){this.face=a;this.prefix=b;this.onInterest=c;this.onRegisterFailed=d;this.flags=e;this.wireFormat=f};
Face.RegisterResponse.prototype.onData=function(a,b){var c;try{var d=new TlvDecoder(b.getContent().buf());d.readNestedTlvsStart(Tlv.NfdCommand_ControlResponse);c=d.readNonNegativeIntegerTlv(Tlv.NfdCommand_StatusCode)}catch(e){0<LOG&&console.log("Register prefix failed: Error decoding the NFD response: "+e);if(this.onRegisterFailed)this.onRegisterFailed(this.prefix);return}if(200!=c){if(0<LOG&&console.log("Register prefix failed: Expected NFD status code 200, got: "+c),this.onRegisterFailed)this.onRegisterFailed(this.prefix)}else 2<
LOG&&console.log("Register prefix succeeded with the NFD forwarder for prefix "+this.prefix.toUri())};Face.RegisterResponse.prototype.onTimeout=function(a){2<LOG&&console.log("Timeout for NFD register prefix command.");if(this.onRegisterFailed)this.onRegisterFailed(this.prefix)};
Face.prototype.nfdRegisterPrefix=function(a,b,c,d,e,f,g){var h=-1;null!=h&&(h=this.registeredPrefixRemoveRequests.indexOf(a));if(0<=h)this.registeredPrefixRemoveRequests.splice(h,1);else{if(null==f)throw Error("registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo.");if(0==g.size())throw Error("registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo.");var k=new ControlParameters;k.setName(b);k.setForwardingFlags(d);var l=
this;this.isLocal(function(h){var p=new Interest;h?(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(k.wireEncode(TlvWireFormat.get()));l.nodeMakeCommandInterest(p,f,g,TlvWireFormat.get(),function(){if(0!=a){var f=0;null!=c&&(f=l.setInterestFilter(new InterestFilter(b),c));l.registeredPrefixTable.push(new Face.RegisteredPrefix(a,b,f))}f=new Face.RegisterResponse(l,
b,c,e,d,TlvWireFormat.get());l.reconnectAndExpressInterest(null,p,f.onData.bind(f),f.onTimeout.bind(f))})},function(a){0<LOG&&console.log("Error in Transport.isLocal: "+a);e&&e(b)})}};
Face.prototype.removeRegisteredPrefix=function(a){for(var b=0,c=this.registeredPrefixTable.length-1;0<=c;--c){var d=this.registeredPrefixTable[c];d.getRegisteredPrefixId()==a&&(++b,0<d.getRelatedInterestFilterId()&&this.unsetInterestFilter(d.getRelatedInterestFilterId()),this.registeredPrefixTable.splice(c,1))}0==b&&0<LOG&&console.log("removeRegisteredPrefix: Didn't find registeredPrefixId "+a);0==b&&0>this.registeredPrefixRemoveRequests.indexOf(a)&&this.registeredPrefixRemoveRequests.push(a)};
Face.prototype.setInterestFilter=function(a,b){var c;c="object"===typeof a&&a instanceof InterestFilter?a:new InterestFilter(a);var d=this.getNextEntryId();this.interestFilterTable.push(new Face.InterestFilterEntry(d,c,b));return d};
Face.prototype.unsetInterestFilter=function(a){for(var b=0,c=this.interestFilterTable.length-1;0<=c;--c)this.interestFilterTable[c].getInterestFilterId()==a&&(++b,this.interestFilterTable.splice(c,1));0==b&&0<LOG&&console.log("unsetInterestFilter: Didn't find interestFilterId "+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,c=null;if(a[0]==Tlv.Interest||a[0]==Tlv.Data){var d=new TlvDecoder(a);d.peekType(Tlv.Interest,a.length)?(b=new Interest,b.wireDecode(a,TlvWireFormat.get())):d.peekType(Tlv.Data,a.length)&&(c=new Data,c.wireDecode(a,TlvWireFormat.get()))}if(null!==b)for(3<LOG&&console.log("Interest packet received."),a=0;a<this.interestFilterTable.length;++a)c=this.interestFilterTable[a],
c.getFilter().doesMatch(b.getName())&&(3<LOG&&console.log("Found interest filter for "+b.getName().toUri()),c.getOnInterest()(c.getFilter().getPrefix(),b,this,c.getInterestFilterId(),c.getFilter()));else if(null!==c)for(3<LOG&&console.log("Data packet received."),b=this.extractEntriesForExpressedInterest(c.getName()),a=0;a<b.length;++a)d=b[a],d.onData(d.interest,c)};
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){})}};Face.prototype.closeByTransport=function(){this.readyStatus=Face.CLOSED;this.onclose()};
(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 s(a){this._cfg={version:a,storesSource:null,dbschema:{},tables:{},contentUpgrade:null};this.stores({})}function H(a,b,d,e){var g,h,D,qa,N;if(0===a)Object.keys(E).forEach(function(a){T(b,
a,E[a].primKey,E[a].indexes)}),g=r._createTransaction(I,U,E),g.idbtrans=b,g.idbtrans.onerror=F(d,["populating database"]),g.on("error").subscribe(d),q.newPSD(function(){q.PSD.trans=g;try{r.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=[],D=V.filter(function(b){return b._cfg.version===a})[0],!D)throw new w("Dexie specification of currently installed DB version is missing");E=r._dbSchema=D._cfg.dbschema;qa=
!1;D=V.filter(function(b){return b._cfg.version>a});D.forEach(function(a){var e=E,g=a._cfg.dbschema;ra(e,b);ra(g,b);E=r._dbSchema=g;e=m(e,g);e.add.forEach(function(a){h.push(function(b,c){T(b,a[0],a[1].primKey,a[1].indexes);c()})});e.change.forEach(function(a){if(a.recreate)throw new w("Not yet support for changing primary key");h.push(function(b,c){var d=b.objectStore(a.name);a.add.forEach(function(a){G(d,a)});a.change.forEach(function(a){d.deleteIndex(a.name);G(d,a)});a.del.forEach(function(a){d.deleteIndex(a)});
c()})});a._cfg.contentUpgrade&&h.push(function(b,c){var e,D;qa=!0;e=r._createTransaction(I,[].slice.call(b.db.objectStoreNames,0),g);e.idbtrans=b;D=0;e._promise=f(e._promise,function(a){return function(b,d,e){function f(a){return function(){a.apply(this,arguments);0==--D&&c()}}return++D,a.call(this,b,function(a,b){arguments[0]=f(a);arguments[1]=f(b);d.apply(this,arguments)},e)}});b.onerror=F(d,["running upgrader function for version",a._cfg.version]);e.on("error").subscribe(d);a._cfg.contentUpgrade(e);
0===D&&c()});qa&&(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()})});N=function(){try{h.length?h.shift()(b,N):t(E,b)}catch(a){e.onerror=b.onerror=function(a){a.preventDefault()};try{b.abort()}catch(c){}b.db.close();d(a)}};N()}}function m(a,b){var c={del:[],add:[],change:[]},d,e,f,g,h,N,k,n;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(N in h)f[N]||g.del.push(N);for(N in f)k=h[N],n=f[N],k?k.src!==n.src&&g.change.push(n):g.add.push(n);(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 T(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){G(e,a)}),e}function t(a,b){Object.keys(a).forEach(function(c){b.db.objectStoreNames.contains(c)||T(b,c,a[c].primKey,a[c].indexes)})}function G(a,b){a.createIndex(b.name,b.keyPath,{unique:b.unique,multiEntry:b.multi})}function Ha(a,b){throw new w("Table "+b[0]+" not part of transaction. Original Scope Function Source: "+g.Promise.PSD.trans.scopeFunc.toString());
}function W(a,b,c,d){this.name=a;this.schema=c;this.hook=O[a]?O[a].hook:P(null,{creating:[p,h],reading:[l,k],updating:[x,h],deleting:[Q,h]});this._tpf=b;this._collClass=d||$}function sa(a,b,c,d){W.call(this,a,b,c,d||ta)}function ua(a,b,c,d){function e(a,b,c,d){return f._promise(a,c,d)}var f=this,g,h;this.db=r;this.mode=a;this.storeNames=b;this.idbtrans=null;this.on=P(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(va);for(d=b.length-1;-1!==d;--d)g=b[d],h=r._tableFactory(a,c[g],e),this.tables[g]=h,this[g]||(this[g]=h)}function aa(a,b,c){this._ctx={table:a,index:":id"===b?null:b,collClass:a._collClass,or:c}}function $(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 ta(){$.apply(this,arguments)}function Ia(a,b){return a._cfg.version-b._cfg.version}function A(a,b,c,d,e,f){c.forEach(function(c){var g=r._tableFactory(d,e[c],b);a.forEach(function(a){a[c]||(f?Object.defineProperty(a,c,{configurable:!0,enumerable:!0,get:function(){var a=q.PSD&&q.PSD.trans;return a&&a.db===r?a.tables[c]:g}}):a[c]=g)})})}function ja(a){a.forEach(function(a){for(var b in a)a[b]instanceof W&&delete a[b]})}function ka(a,b,c,
d,e,f){var g=q.PSD;f=f||k;a.onerror||(a.onerror=F(e));a.onsuccess=b?L(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):L(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 X(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 ba(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 Ca(a,b){return a<b?1:a>b?-1:0}function Da(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(r.verno=B.version/10,r._dbSchema=
E={},U=[].slice.call(B.objectStoreNames,0),0!==U.length){var a=B.transaction(wa(U),"readonly");U.forEach(function(b){for(var c,d=a.objectStore(b),e=d.keyPath,f=e&&"string"==typeof e&&-1!==e.indexOf("."),g=new ba(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 ba(c.name,e,!!c.unique,!!c.multiEntry,!1,e&&"string"!=typeof e,f),h.push(c);E[b]=new xa(b,g,h,{})});A([O],r._transPromiseFactory,
Object.keys(E),I,E)}}function ra(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 fa=b&&b.addons||g.addons,na=g.dependencies,ga=na.indexedDB,M=na.IDBKeyRange,oa=na.TypeError,w=na.Error,E=this._dbSchema={},V=[],U=[],O={},va={},B=null,ca=!0,Y=null,ha=!1,I="readwrite",r=this,R=[],
da=!1,ia=!!Ea();this.version=function(a){if(B)throw new w("Cannot add version when database is open");this.verno=Math.max(this.verno,a);var b=V.filter(function(b){return b._cfg.version===a})[0];return b?b:(b=new s(a),V.push(b),V.sort(Ia),b)};d(s.prototype,{stores:function(a){var b,c;return this._cfg.storesSource=this._cfg.storesSource?d(this._cfg.storesSource,a):a,b={},V.forEach(function(a){d(b,a._cfg.storesSource)}),c=this._cfg.dbschema={},this._parseStoresSpec(b,c),E=r._dbSchema=c,ja([O,r,va]),
A([va],Ha,Object.keys(c),I,c),A([O,r,this._cfg.tables],r._transPromiseFactory,Object.keys(c),I,c,!0),U=Object.keys(c),this},upgrade:function(a){var b=this;return y(function(){a(r._createTransaction(I,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=X(a[c]),f=e.shift();if(f.multi)throw new w("Primary key cannot be multi-valued");f.keyPath&&f.auto&&J(d,f.keyPath,0);e.forEach(function(a){if(a.auto)throw new w("Only primary key can be marked as autoIncrement (++)");
if(!a.keyPath)throw new w("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 xa(c,f,e,d)}})}});this._allTables=O;this._tableFactory=function(a,b,c){return"readonly"===a?new W(b.name,c,b,$):new sa(b.name,c,b)};this._createTransaction=function(a,b,c,d){return new ua(a,b,c,d)};this._transPromiseFactory=function(a,b,c){var d,e;return!ca||q.PSD&&q.PSD.letThrough?(e=r._createTransaction(a,b,E),e._promise(a,function(a,b){e.error(function(a){r.on("error").fire(a)});
c(function(b){e.complete(function(){a(b)})},b,e)})):d=new q(function(e,f){R.push({resume:function(){var g=r._transPromiseFactory(a,b,c);d.onuncatched=g.onuncatched;g.then(e,f)}})})};this._whenReady=function(a){return!ca||q.PSD&&q.PSD.letThrough?new q(a):new q(function(b,c){y(function(){new q(function(){a(b,c)})});R.push({resume:function(){a(b,c)}})})};this.verno=0;this.open=function(){return new q(function(b,c){function d(a){try{e.transaction.abort()}catch(b){}ha=!1;Y=a;ca=!1;c(Y);R.forEach(function(a){a.resume()});
R=[]}if(B||ha)throw new w("Database already opened or being opened");var e;try{if(Y=null,ha=!0,0===V.length&&(da=!0),!ga)throw new w("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=da?ga.open(a):ga.open(a,Math.round(10*r.verno));e.onerror=F(d,["opening database",a]);e.onblocked=function(a){r.on("blocked").fire(a)};e.onupgradeneeded=L(function(b){var c,f;da&&!r._allowEmptyDB?(e.onerror=
function(a){a.preventDefault()},e.transaction.abort(),e.result.close(),c=ga.deleteDatabase(a),c.onsuccess=c.onerror=function(){d(new w("Database '"+a+"' doesnt exist"))}):(e.transaction.onerror=F(d),f=b.oldVersion>Math.pow(2,62)?0:b.oldVersion,H(f/10,e.transaction,d,e))},d);e.onsuccess=L(function(){ha=!1;B=e.result;da?Ja():0<B.objectStoreNames.length&&ra(E,B.transaction(wa(B.objectStoreNames),"readonly"));B.onversionchange=r.on("versionchange").fire;ia||ya(function(b){if(-1===b.indexOf(a))return b.push(a)});
q.newPSD(function(){function a(){ca=!1;R.forEach(function(a){a.resume()});R=[];b()}q.PSD.letThrough=!0;try{var c=r.on.ready.fire();c&&"function"==typeof c.then?c.then(a,function(a){B.close();B=null;d(a)}):z(a)}catch(e){d(e)}})},d)}catch(f){d(f)}})};this.close=function(){B&&(B.close(),B=null,ca=!0,Y=null)};this["delete"]=function(){var b=arguments;return new q(function(c,d){function e(){r.close();var b=ga.deleteDatabase(a);b.onsuccess=function(){ia||ya(function(b){var c=b.indexOf(a);if(0<=c)return b.splice(c,
1)});c()};b.onerror=F(d,["deleting",a]);b.onblocked=function(){r.on("blocked").fire()}}if(0<b.length)throw new w("Arguments not allowed in db.delete()");ha?R.push({resume:e}):e()})};this.backendDB=function(){return B};this.isOpen=function(){return null!==B};this.hasFailed=function(){return null!==Y};this.dynamicallyOpened=function(){return da};this.name=a;Object.defineProperty(this,"tables",{get:function(){return Object.keys(O).map(function(a){return O[a]})}});this.on=P(this,"error","populate","blocked",
{ready:[Z,h],versionchange:[u,h]});this.on.ready.subscribe=f(this.on.ready.subscribe,function(a){return function(b,c){function d(){return c||r.on.ready.unsubscribe(d),b.apply(this,arguments)}a.call(this,d);r.isOpen()&&(ca?R.push({resume:d}):d())}});y(function(){r.on("populate").fire(r._createTransaction(I,U,E));r.on("error").fire(new w)});this.transaction=function(a,b,c){function d(b,g){var n=null,s,K,A;try{if(h)throw h;n=r._createTransaction(a,k,E,e);s=k.map(function(a){return n.tables[a]});s.push(n);
A=0;q.newPSD(function(){q.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 q._rootExec(function(){c=a(b);q._tickFinalize(function(){0==--A&&n.active&&(n.active=!1,n.on.complete.fire())})}),c}}return++A,a.call(this,b,function(a,b,d){return c(e(a),e(b),d)},d)}}));n.complete(function(){b(K)});n.error(function(a){n.idbtrans&&(n.idbtrans.onerror=Fa);try{n.abort()}catch(b){}e&&(e.active=!1,e.on.error.fire(a));
var c=g(a);e||c||r.on.error.fire(a)});q._rootExec(function(){K=c.apply(n,s)})});(!n.idbtrans||e&&0===A)&&n._nop()}catch(H){n&&n.idbtrans&&(n.idbtrans.onerror=Fa),n&&n.abort(),e&&e.on.error.fire(H),z(function(){g(H)||r.on("error").fire(H)})}}var e,g;b=[].slice.call(arguments,1,arguments.length-1);c=arguments[arguments.length-1];(e=q.PSD&&q.PSD.trans)&&e.db===r&&-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 W||(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==I?a=I:h=new w("Invalid transaction mode: "+a),e&&(h||(e&&"readonly"===e.mode&&a===I&&(g?e=null:h=h||new w("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 w("Table "+a+" not included in parent transaction. Parent Transaction function: "+e.scopeFunc.toString()))}))),e?e._promise(a,d,"lock"):r._whenReady(d)};this.table=function(a){if(!da&&!O.hasOwnProperty(a))throw new w("Table does not exist");return O[a]};d(W.prototype,function(){function a(){throw new w("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 y(function(){b(c.schema.instanceTemplate)}),this._idbstore("readonly",function(b,d,e){var f=e.get(a);f.onerror=F(d,["getting",a,"from",c.name]);f.onsuccess=function(){b(c.hook.reading.fire(f.result))}}).then(b)},where:function(a){return new aa(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 y(function(){a(b.schema.instanceTemplate)}),this._idbstore("readonly",function(c,d,e){e=e.openCursor();e.onerror=F(d,["calling","Table.each()","on",b.name]);ka(e,null,a,c,d,b.hook.reading.fire)})},toArray:function(a){var b=this;return y(function(){a([b.schema.instanceTemplate])}),this._idbstore("readonly",function(a,c,d){var e=[];d=d.openCursor();d.onerror=F(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 aa(this,a))},toCollection:function(){return new this._collClass(new aa(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:""),Ga(a.prototype,this.schema.primKey.keyPath)),b&&za(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(sa).from(W).extend(function(){return{add:function(a,b){var d=this,e=this.hook.creating.fire;
return this._idbstore(I,function(f,g,D,n){var k={},s,K,A;e!==h&&(s=b||(D.keyPath?S(a,D.keyPath):c),K=e.call(k,s,a,n),s===c&&K!==c&&(D.keyPath?J(a,D.keyPath,K):b=K));A=b?D.add(a,b):D.add(a);A.onerror=F(function(a){if(k.onerror)k.onerror(a);return g(a)},["adding",a,"into",d.name]);A.onsuccess=function(b){var c=D.keyPath;if(c&&J(a,c,b.target.result),k.onsuccess)k.onsuccess(b.target.result);f(A.result)}})},put:function(a,b){var d=this,e=this.hook.updating.fire;return this.hook.creating.fire!==h||e!==
h?this._trans(I,function(e,f,g){var h=b||d.schema.primKey.keyPath&&S(a,d.schema.primKey.keyPath);h===c?g.tables[d.name].add(a).then(e,f):(g._lock(),a=ea(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(I,function(c,e,f){var g=b?f.put(a,b):f.put(a);g.onerror=F(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(I,function(b,c,d){var e=d["delete"](a);e.onerror=F(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(I,function(a,b,c){var d=c.clear();d.onerror=F(b,["clearing",c.name]);d.onsuccess=function(){a(d.result)}})},update:function(a,b){if("object"!=
typeof b||Array.isArray(b))throw new w("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=S(a,this.schema.primKey.keyPath);return d===c&&q.reject(new w("Object does not contain its primary key")),this.where(":id").equals(d).modify(b)}}});d(ua.prototype,{_lock:function(){return++this._reculock,1===this._reculock&&q.PSD&&(q.PSD.lockOwnerFor=
this),this},_unlock:function(){if(0==--this._reculock)for(q.PSD&&(q.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&&(!q.PSD||q.PSD.lockOwnerFor!==this)},_nop:function(a){this.tables[this.storeNames[0]].get(0).then(a)},_promise:function(a,b,c){var d=this;return q.newPSD(function(){var e;return d._locked()?e=new q(function(e,f){d._blockedFuncs.push(function(){d._promise(a,
b,c).then(e,f)})}):(e=d.active?new q(function(e,f){if(!d.idbtrans&&a){if(!B)throw Y?new w("Database not open. Following error in populate, ready or upgrade function made Dexie.open() fail: "+Y):new w("Database not open");var h=d.idbtrans=B.transaction(wa(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(n){g.ignoreTransaction(function(){d.on("error").fire(n)}),d.abort(),f(n)}}):q.reject(Ka(new w("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 w("Transaction Aborted"))}catch(a){}},table:function(a){if(!this.tables.hasOwnProperty(a))throw new w("Table "+a+" not in transaction");return this.tables[a]}});d(aa.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,n=Math.min(a.length,d.length),k=-1,s=0;s<n;++s){if(h=b[s],h!==d[s])return 0>f(a[s],c[s])?a.substr(0,s)+c[s]+c.substr(s+1):0>f(a[s],d[s])?a.substr(0,s)+d[s]+c.substr(s+1):0<=k?a.substr(0,k)+b[k]+c.substr(k+1):null;0>f(a[s],h)&&(k=s)}return n<d.length&&"next"===g?a+c.substr(a.length):n<a.length&&"prev"===g?a.substr(0,c.length):0>k?null:a.substr(0,k)+d[k]+c.substr(k+1)}function f(a,b,g){function h(a){n=
c(a);k=d(a);s="next"===a?la:Ca;K=n(g);A=k(g);H=a}var n,k,s,K,A,H;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=k(f),b(g,A)?(c(function(){a["continue"]()}),!0):(h=e(f,g,K,A,s,H),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 M.only(a)})).limit(0):new this._ctx.collClass(this,function(){return M.bound(a,
b,!c,!d)})},equals:function(a){return new this._ctx.collClass(this,function(){return M.only(a)})},above:function(a){return new this._ctx.collClass(this,function(){return M.lowerBound(a,!0)})},aboveOrEqual:function(a){return new this._ctx.collClass(this,function(){return M.lowerBound(a)})},below:function(a){return new this._ctx.collClass(this,function(){return M.upperBound(a,!0)})},belowOrEqual:function(a){return new this._ctx.collClass(this,function(){return M.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 M.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 w("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 M.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?Da(la):la,g,h;return(e.sort(f),0===e.length)?(new this._ctx.collClass(this,function(){return M.only("")})).limit(0):
(g=new this._ctx.collClass(this,function(){return M.bound(e[0],e[e.length-1])}),g._ondirectionchange=function(a){f="next"===a?la:Ca;d&&(f=Da(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($.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 w("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==++s&&c()}function h(a,c,d){if(!n||n(c,d,e,f)){var g=c.primaryKey.toString();k.hasOwnProperty(g)||(k[g]=!0,b(a,c,d))}}var n=a.filter,k={},s=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(I,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 y(function(){a(f(b))}),this._read(function(c,d,f){e(b,a,c,d,f)})},count:function(a){var b,d,f;return y(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=F(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[n]}function d(a,b){var e=c(a,k),f=c(b,k);return e<f?-g:e>f?g:0}var e=this._ctx,g;y(function(){b([f(e)])});var h=a.split(".").reverse(),n=h[0],k=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 y(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 y(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 y(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 y(function(){c(f(d._ctx))}),a(this._ctx,function(a){return c(a.value)}),b(this._ctx,c),this},or:function(a){return new aa(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 y(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 y(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(ta).from($).extend({modify:function(a){var b=this,c=this._ctx,e=c.table.hook,f=e.updating.fire,g=e.deleting.fire;return y(function(){"function"==typeof a&&a.call({value:c.table.schema.instanceTemplate},c.table.schema.instanceTemplate)}),this._write(function(e,n,k,s){function K(a){return a&&(X.push(a),T.push(r)),
n(new pa("Error modifying one or more objects",X,q,T))}function A(){Ba&&q+X.length===p&&(0<X.length?K():e(q))}var H,l,ja,m;"function"==typeof a?H=f===h&&g===h?a:function(b){var c=ea(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,s),e&&(b=this.value,Object.keys(e).forEach(function(a){J(b,a,e[a])}))):g.call(this,this.primKey,b,s)}:f===h?(l=Object.keys(a),ja=l.length,H=function(b){for(var c,d,e=!1,f=0;f<ja;++f)c=l[f],d=a[c],S(b,
c)!==d&&(J(b,c,d),e=!0);return e}):(m=a,a=Aa(m),H=function(b){var c=!1,e=f.call(this,a,this.primKey,ea(b),s);return e&&d(a,e),Object.keys(a).forEach(function(d){var e=a[d];S(b,d)!==e&&(J(b,d,e),c=!0)}),e&&(a=Aa(m)),c});var p=0,q=0,Ba=!1,X=[],T=[],r=null;b._iterate(function(a,b){var d,e,f;if(r=b.primaryKey,d={primKey:b.primaryKey,value:a},!1!==H.call(d,a))f=(e=!d.hasOwnProperty("value"))?b["delete"]():b.update(d.value),++p,f.onerror=F(function(a){if(X.push(a),T.push(d.primKey),d.onerror)d.onerror(a);
return A(),!0},e?["deleting",a,"from",c.table.name]:["modifying",a,"on",c.table.name]),f.onsuccess=function(){if(d.onsuccess)d.onsuccess(d.value);++q;A()};else if(d.onsuccess)d.onsuccess(d.value)},function(){Ba=!0;A()},K,k)})},"delete":function(){return this.modify(function(){delete this.value})}});d(this,{Collection:$,Table:W,Transaction:ua,Version:s,WhereClause:aa,WriteableCollection:ta,WriteableTable:sa});(function(){r.on("versionchange",function(){r.close();r.on("error").fire(new w("Database version changed by other database connection."))})})();
fa.forEach(function(a){a(r)})}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 p(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 x(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 t(a,b){return a===h?b:function(){return!1===a.apply(this,arguments)?!1:b.apply(this,arguments)}}function u(a,b){return a===
h?b:function(){return!1===b.apply(this,arguments)?!1:a.apply(this,arguments)}}function Q(a,b){return a===h?b:function(){a.apply(this,arguments);b.apply(this,arguments)}}function Z(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 P(b){function c(a,b,f){if(Array.isArray(a))return e(a);if("object"==typeof a)return d(a);b||(b=t);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){z(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 z(b){a.setImmediate?setImmediate(b):setTimeout(b,
0)}function G(a){a=setTimeout(a,1E3);clearTimeout(a)}function L(a,b,c){return function(){var d=q.PSD;q.PSD=c;try{a.apply(this,arguments)}catch(e){b(e)}finally{q.PSD=d}}}function S(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=S(a,b[e]),d.push(g);return d}return(d=b.indexOf("."),-1!==d)?(e=a[b.substr(0,d)],e===c?c:S(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 Ga(a,b){J(a,b,c)}function Aa(a){var b={},c;for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function ea(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(ea(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]=ea(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 za(b,a),b}return a}function za(a,b){Object.keys(b).forEach(function(c){var d=ia(b[c]);a[c]=d})}function F(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 Fa(a){a.preventDefault()}function ya(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 ba(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 xa(a,b,c,d){this.name=a;this.primKey=b||new ba;this.indexes=c||[new ba];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 wa(a){return 1===a.length?a[0]:a}function Ea(){var a=g.dependencies.indexedDB,b=a&&(a.getDatabaseNames||a.webkitGetDatabaseNames);return b&&b.bind(a)}var q=function(){function b(a){y.push([a,
p.call(arguments,1)])}function c(){var b=y,d,e,f;y=[];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?u(g,b,a):g(b,a)},function(a){return c?(u(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=x;x=!1;u=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(H){if(q=g.reject(H),!q&&a.onuncatched)try{a.onuncatched(H)}catch(F){}}finally{if(d.PSD=m,l){do{for(;0<y.length;)c();if(p=z.pop(),p)try{p()}catch(G){}}while(0<z.length||0<y.length);u=t;x=!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,t="undefined"==typeof setImmediate?function(b){var c=arguments;setTimeout(function(){b.apply(a,
p.call(c,1))},0)}:setImmediate,u=t,x=!0,y=[],z=[];return d.on=P(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)):u(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=x,e;x=!1;u=b;try{a()}finally{if(d){do{for(;0<y.length;)c();if(e=z.pop(),e)try{e()}catch(f){}}while(0<z.length||0<y.length);u=t;x=!0}}},d._tickFinalize=function(a){if(x)throw Error("Not in a virtual tick");z.push(a)},d}(),y=function(){},fa;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 q(function(a,b){var c=Ea(),d;c?(d=c(),d.onsuccess=function(b){a([].slice.call(b.target.result,
0))},d.onerror=F(b)):ya(function(b){return a(b),!1})})).then(a)};g.defineClass=function(a){function b(a){a&&d(this,a)}return za(b.prototype,a),b};g.ignoreTransaction=function(a){return q.newPSD(function(){return q.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 q.newPSD(function(){return q.PSD.letThrough=!0,a()})};Object.defineProperty(g,
"currentTransaction",{get:function(){return q.PSD&&q.PSD.trans||null}});g.Promise=q;g.derive=e;g.extend=d;g.override=f;g.events=P;g.getByKeyPath=S;g.setByKeyPath=J;g.delByKeyPath=Ga;g.shallowClone=Aa;g.deepClone=ea;g.addons=[];g.fakeAutoComplete=y;g.asap=z;g.ModifyError=pa;g.MultiModifyError=pa;g.IndexSpec=ba;g.TableSchema=xa;fa=a.idbModules&&a.idbModules.shimIndexedDB?a.idbModules:{};g.dependencies={indexedDB:fa.shimIndexedDB||a.indexedDB||a.mozIndexedDB||a.webkitIndexedDB||a.msIndexedDB,IDBKeyRange:fa.IDBKeyRange||
a.IDBKeyRange||a.webkitIDBKeyRange,IDBTransaction:fa.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);G(function(){y=G})}).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}]);
