<!DOCTYPE html> <!-- Aquila Market Client - one file, for running locally --> <!-- Save this file somewhere convenient, for example on your desktop, --> <!-- and open it in a browser. JavaScript must be enabled, but only --> <!-- for that one file:// URL. By saving the client locally, you take --> <!-- the risk that whoever gave you this file is malicious only once, --> <!-- instead of every time you run it. --> <!-- version=0.1 network=TESTNET t=1455926151 --> <html><head><title>Aquila Market</title><meta charset=utf-8><script>!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){return new Za.prototype.init(a,b,c,d,e) }m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f }var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){function BigInteger(a,b,c){if(!(this instanceof BigInteger))return new BigInteger(a,b,c);if(a!=null){if("number"==typeof a)this.fromNumber(a,b,c);else if(b==null&&"string"!=typeof a)this.fromString(a,256);else this.fromString(a,b)}}var proto=BigInteger.prototype;proto.__bigi=require("../package.json").version;BigInteger.isBigInteger=function(obj,check_ver){return obj&&obj.__bigi&&(!check_ver||obj.__bigi===proto.__bigi)};var dbits;function am1(i,x,w,j,c,n){while(--n>=0){var v=x*this[i++]+w[j]+c;c=Math.floor(v/67108864);w[j++]=v&67108863}return c}function am2(i,x,w,j,c,n){var xl=x&32767,xh=x>>15;while(--n>=0){var l=this[i]&32767;var h=this[i++]>>15;var m=xh*l+h*xl;l=xl*l+((m&32767)<<15)+w[j]+(c&1073741823);c=(l>>>30)+(m>>>15)+xh*h+(c>>>30);w[j++]=l&1073741823}return c}function am3(i,x,w,j,c,n){var xl=x&16383,xh=x>>14;while(--n>=0){var l=this[i]&16383;var h=this[i++]>>14;var m=xh*l+h*xl;l=xl*l+((m&16383)<<14)+w[j]+c;c=(l>>28)+(m>>14)+xh*h;w[j++]=l&268435455}return c}BigInteger.prototype.am=am1;dbits=26;BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<<dbits)-1;var DV=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";var BI_RC=new Array;var rr,vv;rr="0".charCodeAt(0);for(vv=0;vv<=9;++vv)BI_RC[rr++]=vv;rr="a".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr++]=vv;rr="A".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr++]=vv;function int2char(n){return BI_RM.charAt(n)}function intAt(s,i){var c=BI_RC[s.charCodeAt(i)];return c==null?-1:c}function bnpCopyTo(r){for(var i=this.t-1;i>=0;--i)r[i]=this[i];r.t=this.t;r.s=this.s}function bnpFromInt(x){this.t=1;this.s=x<0?-1:0;if(x>0)this[0]=x;else if(x<-1)this[0]=x+DV;else this.t=0}function nbv(i){var r=new BigInteger;r.fromInt(i);return r}function bnpFromString(s,b){var self=this;var k;if(b==16)k=4;else if(b==8)k=3;else if(b==256)k=8;else if(b==2)k=1;else if(b==32)k=5;else if(b==4)k=2;else{self.fromRadix(s,b);return}self.t=0;self.s=0;var i=s.length,mi=false,sh=0;while(--i>=0){var x=k==8?s[i]&255:intAt(s,i);if(x<0){if(s.charAt(i)=="-")mi=true;continue}mi=false;if(sh==0)self[self.t++]=x;else if(sh+k>self.DB){self[self.t-1]|=(x&(1<<self.DB-sh)-1)<<sh;self[self.t++]=x>>self.DB-sh}else self[self.t-1]|=x<<sh;sh+=k;if(sh>=self.DB)sh-=self.DB}if(k==8&&(s[0]&128)!=0){self.s=-1;if(sh>0)self[self.t-1]|=(1<<self.DB-sh)-1<<sh}self.clamp();if(mi)BigInteger.ZERO.subTo(self,self)}function bnpClamp(){var c=this.s&this.DM;while(this.t>0&&this[this.t-1]==c)--this.t}function bnToString(b){var self=this;if(self.s<0)return"-"+self.negate().toString(b);var k;if(b==16)k=4;else if(b==8)k=3;else if(b==2)k=1;else if(b==32)k=5;else if(b==4)k=2;else return self.toRadix(b);var km=(1<<k)-1,d,m=false,r="",i=self.t;var p=self.DB-i*self.DB%k;if(i-->0){if(p<self.DB&&(d=self[i]>>p)>0){m=true;r=int2char(d)}while(i>=0){if(p<k){d=(self[i]&(1<<p)-1)<<k-p;d|=self[--i]>>(p+=self.DB-k)}else{d=self[i]>>(p-=k)&km;if(p<=0){p+=self.DB;--i}}if(d>0)m=true;if(m)r+=int2char(d)}}return m?r:"0"}function bnNegate(){var r=new BigInteger;BigInteger.ZERO.subTo(this,r);return r}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(a){var r=this.s-a.s;if(r!=0)return r;var i=this.t;r=i-a.t;if(r!=0)return this.s<0?-r:r;while(--i>=0)if((r=this[i]-a[i])!=0)return r;return 0}function nbits(x){var r=1,t;if((t=x>>>16)!=0){x=t;r+=16}if((t=x>>8)!=0){x=t;r+=8}if((t=x>>4)!=0){x=t;r+=4}if((t=x>>2)!=0){x=t;r+=2}if((t=x>>1)!=0){x=t;r+=1}return r}function bnBitLength(){if(this.t<=0)return 0;return this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)}function bnByteLength(){return this.bitLength()>>3}function bnpDLShiftTo(n,r){var i;for(i=this.t-1;i>=0;--i)r[i+n]=this[i];for(i=n-1;i>=0;--i)r[i]=0;r.t=this.t+n;r.s=this.s}function bnpDRShiftTo(n,r){for(var i=n;i<this.t;++i)r[i-n]=this[i];r.t=Math.max(this.t-n,0);r.s=this.s}function bnpLShiftTo(n,r){var self=this;var bs=n%self.DB;var cbs=self.DB-bs;var bm=(1<<cbs)-1;var ds=Math.floor(n/self.DB),c=self.s<<bs&self.DM,i;for(i=self.t-1;i>=0;--i){r[i+ds+1]=self[i]>>cbs|c;c=(self[i]&bm)<<bs}for(i=ds-1;i>=0;--i)r[i]=0;r[ds]=c;r.t=self.t+ds+1;r.s=self.s;r.clamp()}function bnpRShiftTo(n,r){var self=this;r.s=self.s;var ds=Math.floor(n/self.DB);if(ds>=self.t){r.t=0;return}var bs=n%self.DB;var cbs=self.DB-bs;var bm=(1<<bs)-1;r[0]=self[ds]>>bs;for(var i=ds+1;i<self.t;++i){r[i-ds-1]|=(self[i]&bm)<<cbs;r[i-ds]=self[i]>>bs}if(bs>0)r[self.t-ds-1]|=(self.s&bm)<<cbs;r.t=self.t-ds;r.clamp()}function bnpSubTo(a,r){var self=this;var i=0,c=0,m=Math.min(a.t,self.t);while(i<m){c+=self[i]-a[i];r[i++]=c&self.DM;c>>=self.DB}if(a.t<self.t){c-=a.s;while(i<self.t){c+=self[i];r[i++]=c&self.DM;c>>=self.DB}c+=self.s}else{c+=self.s;while(i<a.t){c-=a[i];r[i++]=c&self.DM;c>>=self.DB}c-=a.s}r.s=c<0?-1:0;if(c<-1)r[i++]=self.DV+c;else if(c>0)r[i++]=c;r.t=i;r.clamp()}function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs();var i=x.t;r.t=i+y.t;while(--i>=0)r[i]=0;for(i=0;i<y.t;++i)r[i+x.t]=x.am(0,y[i],r,i,0,x.t);r.s=0;r.clamp();if(this.s!=a.s)BigInteger.ZERO.subTo(r,r)}function bnpSquareTo(r){var x=this.abs();var i=r.t=2*x.t;while(--i>=0)r[i]=0;for(i=0;i<x.t-1;++i){var c=x.am(i,x[i],r,2*i,0,1);if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1))>=x.DV){r[i+x.t]-=x.DV;r[i+x.t+1]=1}}if(r.t>0)r[r.t-1]+=x.am(i,x[i],r,2*i,0,1);r.s=0;r.clamp()}function bnpDivRemTo(m,q,r){var self=this;var pm=m.abs();if(pm.t<=0)return;var pt=self.abs();if(pt.t<pm.t){if(q!=null)q.fromInt(0);if(r!=null)self.copyTo(r);return}if(r==null)r=new BigInteger;var y=new BigInteger,ts=self.s,ms=m.s;var nsh=self.DB-nbits(pm[pm.t-1]);if(nsh>0){pm.lShiftTo(nsh,y);pt.lShiftTo(nsh,r)}else{pm.copyTo(y);pt.copyTo(r)}var ys=y.t;var y0=y[ys-1];if(y0==0)return;var yt=y0*(1<<self.F1)+(ys>1?y[ys-2]>>self.F2:0);var d1=self.FV/yt,d2=(1<<self.F1)/yt,e=1<<self.F2;var i=r.t,j=i-ys,t=q==null?new BigInteger:q;y.dlShiftTo(j,t);if(r.compareTo(t)>=0){r[r.t++]=1;r.subTo(t,r)}BigInteger.ONE.dlShiftTo(ys,t);t.subTo(y,y);while(y.t<ys)y[y.t++]=0;while(--j>=0){var qd=r[--i]==y0?self.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);if((r[i]+=y.am(0,qd,r,j,0,ys))<qd){y.dlShiftTo(j,t);r.subTo(t,r);while(r[i]<--qd)r.subTo(t,r)}}if(q!=null){r.drShiftTo(ys,q);if(ts!=ms)BigInteger.ZERO.subTo(q,q)}r.t=ys;r.clamp();if(nsh>0)r.rShiftTo(nsh,r);if(ts<0)BigInteger.ZERO.subTo(r,r)}function bnMod(a){var r=new BigInteger;this.abs().divRemTo(a,null,r);if(this.s<0&&r.compareTo(BigInteger.ZERO)>0)a.subTo(r,r);return r}function Classic(m){this.m=m}function cConvert(x){if(x.s<0||x.compareTo(this.m)>=0)return x.mod(this.m);else return x}function cRevert(x){return x}function cReduce(x){x.divRemTo(this.m,null,x)}function cMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}function cSqrTo(x,r){x.squareTo(r);this.reduce(r)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1)return 0;var x=this[0];if((x&1)==0)return 0;var y=x&3;y=y*(2-(x&15)*y)&15;y=y*(2-(x&255)*y)&255;y=y*(2-((x&65535)*y&65535))&65535;y=y*(2-x*y%this.DV)%this.DV;return y>0?this.DV-y:-y}function Montgomery(m){this.m=m;this.mp=m.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<m.DB-15)-1;this.mt2=2*m.t}function montConvert(x){var r=new BigInteger;x.abs().dlShiftTo(this.m.t,r);r.divRemTo(this.m,null,r);if(x.s<0&&r.compareTo(BigInteger.ZERO)>0)this.m.subTo(r,r);return r}function montRevert(x){var r=new BigInteger;x.copyTo(r);this.reduce(r);return r}function montReduce(x){while(x.t<=this.mt2)x[x.t++]=0;for(var i=0;i<this.m.t;++i){var j=x[i]&32767;var u0=j*this.mpl+((j*this.mph+(x[i]>>15)*this.mpl&this.um)<<15)&x.DM;j=i+this.m.t;x[j]+=this.m.am(0,u0,x,i,0,this.m.t);while(x[j]>=x.DV){x[j]-=x.DV;x[++j]++}}x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function montSqrTo(x,r){x.squareTo(r);this.reduce(r)}function montMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return(this.t>0?this[0]&1:this.s)==0}function bnpExp(e,z){if(e>4294967295||e<1)return BigInteger.ONE;var r=new BigInteger,r2=new BigInteger,g=z.convert(this),i=nbits(e)-1;g.copyTo(r);while(--i>=0){z.sqrTo(r,r2);if((e&1<<i)>0)z.mulTo(r2,g,r);else{var t=r;r=r2;r2=t}}return z.revert(r)}function bnModPowInt(e,m){var z;if(e<256||m.isEven())z=new Classic(m);else z=new Montgomery(m);return this.exp(e,z)}proto.copyTo=bnpCopyTo;proto.fromInt=bnpFromInt;proto.fromString=bnpFromString;proto.clamp=bnpClamp;proto.dlShiftTo=bnpDLShiftTo;proto.drShiftTo=bnpDRShiftTo;proto.lShiftTo=bnpLShiftTo;proto.rShiftTo=bnpRShiftTo;proto.subTo=bnpSubTo;proto.multiplyTo=bnpMultiplyTo;proto.squareTo=bnpSquareTo;proto.divRemTo=bnpDivRemTo;proto.invDigit=bnpInvDigit;proto.isEven=bnpIsEven;proto.exp=bnpExp;proto.toString=bnToString;proto.negate=bnNegate;proto.abs=bnAbs;proto.compareTo=bnCompareTo;proto.bitLength=bnBitLength;proto.byteLength=bnByteLength;proto.mod=bnMod;proto.modPowInt=bnModPowInt;function bnClone(){var r=new BigInteger;this.copyTo(r);return r}function bnIntValue(){if(this.s<0){if(this.t==1)return this[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this[0];else if(this.t==0)return 0;return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]}function bnByteValue(){return this.t==0?this.s:this[0]<<24>>24}function bnShortValue(){return this.t==0?this.s:this[0]<<16>>16}function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function bnSigNum(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this[0]<=0)return 0;else return 1}function bnpToRadix(b){if(b==null)b=10;if(this.signum()==0||b<2||b>36)return"0";var cs=this.chunkSize(b);var a=Math.pow(b,cs);var d=nbv(a),y=new BigInteger,z=new BigInteger,r="";this.divRemTo(d,y,z);while(y.signum()>0){r=(a+z.intValue()).toString(b).substr(1)+r;y.divRemTo(d,y,z)}return z.intValue().toString(b)+r}function bnpFromRadix(s,b){var self=this;self.fromInt(0);if(b==null)b=10;var cs=self.chunkSize(b);var d=Math.pow(b,cs),mi=false,j=0,w=0;for(var i=0;i<s.length;++i){var x=intAt(s,i);if(x<0){if(s.charAt(i)=="-"&&self.signum()==0)mi=true;continue}w=b*w+x;if(++j>=cs){self.dMultiply(d);self.dAddOffset(w,0);j=0;w=0}}if(j>0){self.dMultiply(Math.pow(b,j));self.dAddOffset(w,0)}if(mi)BigInteger.ZERO.subTo(self,self)}function bnpFromNumber(a,b,c){var self=this;if("number"==typeof b){if(a<2)self.fromInt(1);else{self.fromNumber(a,c);if(!self.testBit(a-1))self.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,self);if(self.isEven())self.dAddOffset(1,0);while(!self.isProbablePrime(b)){self.dAddOffset(2,0);if(self.bitLength()>a)self.subTo(BigInteger.ONE.shiftLeft(a-1),self)}}}else{var x=new Array,t=a&7;x.length=(a>>3)+1;b.nextBytes(x);if(t>0)x[0]&=(1<<t)-1;else x[0]=0;self.fromString(x,256)}}function bnToByteArray(){var self=this;var i=self.t,r=new Array;r[0]=self.s;var p=self.DB-i*self.DB%8,d,k=0;if(i-->0){if(p<self.DB&&(d=self[i]>>p)!=(self.s&self.DM)>>p)r[k++]=d|self.s<<self.DB-p;while(i>=0){if(p<8){d=(self[i]&(1<<p)-1)<<8-p;d|=self[--i]>>(p+=self.DB-8)}else{d=self[i]>>(p-=8)&255;if(p<=0){p+=self.DB;--i}}if((d&128)!=0)d|=-256;if(k===0&&(self.s&128)!=(d&128))++k;if(k>0||d!=self.s)r[k++]=d}}return r}function bnEquals(a){return this.compareTo(a)==0}function bnMin(a){return this.compareTo(a)<0?this:a}function bnMax(a){return this.compareTo(a)>0?this:a}function bnpBitwiseTo(a,op,r){var self=this;var i,f,m=Math.min(a.t,self.t);for(i=0;i<m;++i)r[i]=op(self[i],a[i]);if(a.t<self.t){f=a.s&self.DM;for(i=m;i<self.t;++i)r[i]=op(self[i],f);r.t=self.t}else{f=self.s&self.DM;for(i=m;i<a.t;++i)r[i]=op(f,a[i]);r.t=a.t}r.s=op(self.s,a.s);r.clamp()}function op_and(x,y){return x&y}function bnAnd(a){var r=new BigInteger;this.bitwiseTo(a,op_and,r);return r}function op_or(x,y){return x|y}function bnOr(a){var r=new BigInteger;this.bitwiseTo(a,op_or,r);return r}function op_xor(x,y){return x^y}function bnXor(a){var r=new BigInteger;this.bitwiseTo(a,op_xor,r);return r}function op_andnot(x,y){return x&~y}function bnAndNot(a){var r=new BigInteger;this.bitwiseTo(a,op_andnot,r);return r}function bnNot(){var r=new BigInteger;for(var i=0;i<this.t;++i)r[i]=this.DM&~this[i];r.t=this.t;r.s=~this.s;return r}function bnShiftLeft(n){var r=new BigInteger;if(n<0)this.rShiftTo(-n,r);else this.lShiftTo(n,r);return r}function bnShiftRight(n){var r=new BigInteger;if(n<0)this.lShiftTo(-n,r);else this.rShiftTo(n,r);return r}function lbit(x){if(x==0)return-1;var r=0;if((x&65535)==0){x>>=16;r+=16}if((x&255)==0){x>>=8;r+=8}if((x&15)==0){x>>=4;r+=4}if((x&3)==0){x>>=2;r+=2}if((x&1)==0)++r;return r}function bnGetLowestSetBit(){for(var i=0;i<this.t;++i)if(this[i]!=0)return i*this.DB+lbit(this[i]);if(this.s<0)return this.t*this.DB;return-1}function cbit(x){var r=0;while(x!=0){x&=x-1;++r}return r}function bnBitCount(){var r=0,x=this.s&this.DM;for(var i=0;i<this.t;++i)r+=cbit(this[i]^x);return r}function bnTestBit(n){var j=Math.floor(n/this.DB);if(j>=this.t)return this.s!=0;return(this[j]&1<<n%this.DB)!=0}function bnpChangeBit(n,op){var r=BigInteger.ONE.shiftLeft(n);this.bitwiseTo(r,op,r);return r}function bnSetBit(n){return this.changeBit(n,op_or)}function bnClearBit(n){return this.changeBit(n,op_andnot)}function bnFlipBit(n){return this.changeBit(n,op_xor)}function bnpAddTo(a,r){var self=this;var i=0,c=0,m=Math.min(a.t,self.t);while(i<m){c+=self[i]+a[i];r[i++]=c&self.DM;c>>=self.DB}if(a.t<self.t){c+=a.s;while(i<self.t){c+=self[i];r[i++]=c&self.DM;c>>=self.DB}c+=self.s}else{c+=self.s;while(i<a.t){c+=a[i];r[i++]=c&self.DM;c>>=self.DB}c+=a.s}r.s=c<0?-1:0;if(c>0)r[i++]=c;else if(c<-1)r[i++]=self.DV+c;r.t=i;r.clamp()}function bnAdd(a){var r=new BigInteger;this.addTo(a,r);return r}function bnSubtract(a){var r=new BigInteger;this.subTo(a,r);return r}function bnMultiply(a){var r=new BigInteger;this.multiplyTo(a,r);return r}function bnSquare(){var r=new BigInteger;this.squareTo(r);return r}function bnDivide(a){var r=new BigInteger;this.divRemTo(a,r,null);return r}function bnRemainder(a){var r=new BigInteger;this.divRemTo(a,null,r);return r}function bnDivideAndRemainder(a){var q=new BigInteger,r=new BigInteger;this.divRemTo(a,q,r);return new Array(q,r)}function bnpDMultiply(n){this[this.t]=this.am(0,n-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(n,w){if(n==0)return;while(this.t<=w)this[this.t++]=0;this[w]+=n;while(this[w]>=this.DV){this[w]-=this.DV;if(++w>=this.t)this[this.t++]=0;++this[w]}}function NullExp(){}function nNop(x){return x}function nMulTo(x,y,r){x.multiplyTo(y,r)}function nSqrTo(x,r){x.squareTo(r)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(a,n,r){var i=Math.min(this.t+a.t,n);r.s=0;r.t=i;while(i>0)r[--i]=0;var j;for(j=r.t-this.t;i<j;++i)r[i+this.t]=this.am(0,a[i],r,i,0,this.t);for(j=Math.min(a.t,n);i<j;++i)this.am(0,a[i],r,i,0,n-i);r.clamp()}function bnpMultiplyUpperTo(a,n,r){--n;var i=r.t=this.t+a.t-n;r.s=0;while(--i>=0)r[i]=0;for(i=Math.max(n-this.t,0);i<a.t;++i)r[this.t+i-n]=this.am(n-i,a[i],r,0,0,this.t+i-n);r.clamp();r.drShiftTo(1,r)}function Barrett(m){this.r2=new BigInteger;this.q3=new BigInteger;BigInteger.ONE.dlShiftTo(2*m.t,this.r2);this.mu=this.r2.divide(m);this.m=m}function barrettConvert(x){if(x.s<0||x.t>2*this.m.t)return x.mod(this.m);else if(x.compareTo(this.m)<0)return x;else{var r=new BigInteger;x.copyTo(r);this.reduce(r);return r}}function barrettRevert(x){return x}function barrettReduce(x){var self=this;x.drShiftTo(self.m.t-1,self.r2);if(x.t>self.m.t+1){x.t=self.m.t+1;x.clamp()}self.mu.multiplyUpperTo(self.r2,self.m.t+1,self.q3);self.m.multiplyLowerTo(self.q3,self.m.t+1,self.r2);while(x.compareTo(self.r2)<0)x.dAddOffset(1,self.m.t+1);x.subTo(self.r2,x);while(x.compareTo(self.m)>=0)x.subTo(self.m,x)}function barrettSqrTo(x,r){x.squareTo(r);this.reduce(r)}function barrettMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(e,m){var i=e.bitLength(),k,r=nbv(1),z;if(i<=0)return r;else if(i<18)k=1;else if(i<48)k=3;else if(i<144)k=4;else if(i<768)k=5;else k=6;if(i<8)z=new Classic(m);else if(m.isEven())z=new Barrett(m);else z=new Montgomery(m);var g=new Array,n=3,k1=k-1,km=(1<<k)-1;g[1]=z.convert(this);if(k>1){var g2=new BigInteger;z.sqrTo(g[1],g2);while(n<=km){g[n]=new BigInteger;z.mulTo(g2,g[n-2],g[n]);n+=2}}var j=e.t-1,w,is1=true,r2=new BigInteger,t;i=nbits(e[j])-1;while(j>=0){if(i>=k1)w=e[j]>>i-k1&km;else{w=(e[j]&(1<<i+1)-1)<<k1-i;if(j>0)w|=e[j-1]>>this.DB+i-k1}n=k;while((w&1)==0){w>>=1;--n}if((i-=n)<0){i+=this.DB;--j}if(is1){g[w].copyTo(r);is1=false}else{while(n>1){z.sqrTo(r,r2);z.sqrTo(r2,r);n-=2}if(n>0)z.sqrTo(r,r2);else{t=r;r=r2;r2=t}z.mulTo(r2,g[w],r)}while(j>=0&&(e[j]&1<<i)==0){z.sqrTo(r,r2);t=r;r=r2;r2=t;if(--i<0){i=this.DB-1;--j}}}return z.revert(r)}function bnGCD(a){var x=this.s<0?this.negate():this.clone();var y=a.s<0?a.negate():a.clone();if(x.compareTo(y)<0){var t=x;x=y;y=t}var i=x.getLowestSetBit(),g=y.getLowestSetBit();if(g<0)return x;if(i<g)g=i;if(g>0){x.rShiftTo(g,x);y.rShiftTo(g,y)}while(x.signum()>0){if((i=x.getLowestSetBit())>0)x.rShiftTo(i,x);if((i=y.getLowestSetBit())>0)y.rShiftTo(i,y);if(x.compareTo(y)>=0){x.subTo(y,x);x.rShiftTo(1,x)}else{y.subTo(x,y);y.rShiftTo(1,y)}}if(g>0)y.lShiftTo(g,y);return y}function bnpModInt(n){if(n<=0)return 0;var d=this.DV%n,r=this.s<0?n-1:0;if(this.t>0)if(d==0)r=this[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this[i])%n;return r}function bnModInverse(m){var ac=m.isEven();if(this.signum()===0)throw new Error("division by zero");if(this.isEven()&&ac||m.signum()==0)return BigInteger.ZERO;var u=m.clone(),v=this.clone();var a=nbv(1),b=nbv(0),c=nbv(0),d=nbv(1);while(u.signum()!=0){while(u.isEven()){u.rShiftTo(1,u);if(ac){if(!a.isEven()||!b.isEven()){a.addTo(this,a);b.subTo(m,b)}a.rShiftTo(1,a)}else if(!b.isEven())b.subTo(m,b);b.rShiftTo(1,b)}while(v.isEven()){v.rShiftTo(1,v);if(ac){if(!c.isEven()||!d.isEven()){c.addTo(this,c);d.subTo(m,d)}c.rShiftTo(1,c)}else if(!d.isEven())d.subTo(m,d);d.rShiftTo(1,d)}if(u.compareTo(v)>=0){u.subTo(v,u);if(ac)a.subTo(c,a);b.subTo(d,b)}else{v.subTo(u,v);if(ac)c.subTo(a,c);d.subTo(b,d)}}if(v.compareTo(BigInteger.ONE)!=0)return BigInteger.ZERO;if(d.compareTo(m)>=0)return d.subtract(m);if(d.signum()<0)d.addTo(m,d);else return d;if(d.signum()<0)return d.add(m);else return d}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];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(t){var i,x=this.abs();if(x.t==1&&x[0]<=lowprimes[lowprimes.length-1]){for(i=0;i<lowprimes.length;++i)if(x[0]==lowprimes[i])return true;return false}if(x.isEven())return false;i=1;while(i<lowprimes.length){var m=lowprimes[i],j=i+1;while(j<lowprimes.length&&m<lplim)m*=lowprimes[j++];m=x.modInt(m);while(i<j)if(m%lowprimes[i++]==0)return false}return x.millerRabin(t)}function bnpMillerRabin(t){var n1=this.subtract(BigInteger.ONE);var k=n1.getLowestSetBit();if(k<=0)return false;var r=n1.shiftRight(k);t=t+1>>1;if(t>lowprimes.length)t=lowprimes.length;var a=new BigInteger(null);var j,bases=[];for(var i=0;i<t;++i){for(;;){j=lowprimes[Math.floor(Math.random()*lowprimes.length)];if(bases.indexOf(j)==-1)break}bases.push(j);a.fromInt(j);var y=a.modPow(r,this);if(y.compareTo(BigInteger.ONE)!=0&&y.compareTo(n1)!=0){var j=1;while(j++<k&&y.compareTo(n1)!=0){y=y.modPowInt(2,this);if(y.compareTo(BigInteger.ONE)==0)return false}if(y.compareTo(n1)!=0)return false}}return true}proto.chunkSize=bnpChunkSize;proto.toRadix=bnpToRadix;proto.fromRadix=bnpFromRadix;proto.fromNumber=bnpFromNumber;proto.bitwiseTo=bnpBitwiseTo;proto.changeBit=bnpChangeBit;proto.addTo=bnpAddTo;proto.dMultiply=bnpDMultiply;proto.dAddOffset=bnpDAddOffset;proto.multiplyLowerTo=bnpMultiplyLowerTo;proto.multiplyUpperTo=bnpMultiplyUpperTo;proto.modInt=bnpModInt;proto.millerRabin=bnpMillerRabin;proto.clone=bnClone;proto.intValue=bnIntValue;proto.byteValue=bnByteValue;proto.shortValue=bnShortValue;proto.signum=bnSigNum;proto.toByteArray=bnToByteArray;proto.equals=bnEquals;proto.min=bnMin;proto.max=bnMax;proto.and=bnAnd;proto.or=bnOr;proto.xor=bnXor;proto.andNot=bnAndNot;proto.not=bnNot;proto.shiftLeft=bnShiftLeft;proto.shiftRight=bnShiftRight;proto.getLowestSetBit=bnGetLowestSetBit;proto.bitCount=bnBitCount;proto.testBit=bnTestBit;proto.setBit=bnSetBit;proto.clearBit=bnClearBit;proto.flipBit=bnFlipBit;proto.add=bnAdd;proto.subtract=bnSubtract;proto.multiply=bnMultiply;proto.divide=bnDivide;proto.remainder=bnRemainder;proto.divideAndRemainder=bnDivideAndRemainder;proto.modPow=bnModPow;proto.modInverse=bnModInverse;proto.pow=bnPow;proto.gcd=bnGCD;proto.isProbablePrime=bnIsProbablePrime;proto.square=bnSquare;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);BigInteger.valueOf=nbv;module.exports=BigInteger},{"../package.json":3}],2:[function(require,module,exports){(function(Buffer){var assert=require("assert");var BigInteger=require("./bigi");BigInteger.fromByteArrayUnsigned=function(byteArray){if(byteArray[0]&128){return new BigInteger([0].concat(byteArray))}return new BigInteger(byteArray)};BigInteger.prototype.toByteArrayUnsigned=function(){var byteArray=this.toByteArray();return byteArray[0]===0?byteArray.slice(1):byteArray};BigInteger.fromDERInteger=function(byteArray){return new BigInteger(byteArray)};BigInteger.prototype.toDERInteger=BigInteger.prototype.toByteArray;BigInteger.fromBuffer=function(buffer){if(buffer[0]&128){var byteArray=Array.prototype.slice.call(buffer);return new BigInteger([0].concat(byteArray))}return new BigInteger(buffer)};BigInteger.fromHex=function(hex){if(hex==="")return BigInteger.ZERO;assert.equal(hex,hex.match(/^[A-Fa-f0-9]+/),"Invalid hex string");assert.equal(hex.length%2,0,"Incomplete hex");return new BigInteger(hex,16)};BigInteger.prototype.toBuffer=function(size){var byteArray=this.toByteArrayUnsigned();var zeros=[];var padding=size-byteArray.length;while(zeros.length<padding)zeros.push(0);return new Buffer(zeros.concat(byteArray))};BigInteger.prototype.toHex=function(size){return this.toBuffer(size).toString("hex")}}).call(this,require("buffer").Buffer)},{"./bigi":1,assert:49,buffer:"buffer"}],3:[function(require,module,exports){module.exports={name:"bigi",version:"1.4.1",description:"Big integers.",keywords:["cryptography","math","bitcoin","arbitrary","precision","arithmetic","big","integer","int","number","biginteger","bigint","bignumber","decimal","float"],devDependencies:{coveralls:"^2.11.2",istanbul:"^0.3.5",jshint:"^2.5.1",mocha:"^2.1.0",mochify:"^2.1.0"},repository:{url:"git+https://github.com/cryptocoinjs/bigi.git",type:"git"},main:"./lib/index.js",scripts:{"browser-test":"mochify --wd -R spec",test:"_mocha -- test/*.js",jshint:"jshint --config jshint.json lib/*.js ; true",unit:"mocha",coverage:"istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",coveralls:"npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info"},dependencies:{},testling:{files:"test/*.js",harness:"mocha",browsers:["ie/9..latest","firefox/latest","chrome/latest","safari/6.0..latest","iphone/6.0..latest","android-browser/4.2..latest"]},gitHead:"7d034a1b38ca90f68daa9de472dda2fb813836f1",bugs:{url:"https://github.com/cryptocoinjs/bigi/issues"},homepage:"https://github.com/cryptocoinjs/bigi#readme",_id:"bigi@1.4.1",_shasum:"726e8ab08d1fe1dfb8aa6bb6309bffecf93a21b7",_from:"bigi@^1.4.0",_npmVersion:"2.10.1",_nodeVersion:"2.1.0",_npmUser:{name:"jprichardson",email:"jprichardson@gmail.com"},maintainers:[{name:"midnightlightning",email:"boydb@midnightdesign.ws"},{name:"sidazhang",email:"sidazhang89@gmail.com"},{name:"nadav",email:"npm@shesek.info"},{name:"jprichardson",email:"jprichardson@gmail.com"}],dist:{shasum:"726e8ab08d1fe1dfb8aa6bb6309bffecf93a21b7",tarball:"http://registry.npmjs.org/bigi/-/bigi-1.4.1.tgz"},directories:{},_resolved:"https://registry.npmjs.org/bigi/-/bigi-1.4.1.tgz",readme:"ERROR: No README data found!"}},{}],4:[function(require,module,exports){(function(Buffer){function check(buffer){if(buffer.length<8)return false;if(buffer.length>72)return false;if(buffer[0]!==48)return false;if(buffer[1]!==buffer.length-2)return false;if(buffer[2]!==2)return false;var lenR=buffer[3];if(lenR===0)return false;if(5+lenR>=buffer.length)return false;if(buffer[4+lenR]!==2)return false;var lenS=buffer[5+lenR];if(lenS===0)return false;if(6+lenR+lenS!==buffer.length)return false;if(buffer[4]&128)return false;if(lenR>1&&buffer[4]===0&&!(buffer[5]&128))return false;if(buffer[lenR+6]&128)return false;if(lenS>1&&buffer[lenR+6]===0&&!(buffer[lenR+7]&128))return false;return true}function decode(buffer){if(buffer.length<8)throw new Error("DER sequence length is too short");if(buffer.length>72)throw new Error("DER sequence length is too long");if(buffer[0]!==48)throw new Error("Expected DER sequence");if(buffer[1]!==buffer.length-2)throw new Error("DER sequence length is invalid");if(buffer[2]!==2)throw new Error("Expected DER integer");var lenR=buffer[3];if(lenR===0)throw new Error("R length is zero");if(5+lenR>=buffer.length)throw new Error("R length is too long");if(buffer[4+lenR]!==2)throw new Error("Expected DER integer (2)");var lenS=buffer[5+lenR];if(lenS===0)throw new Error("S length is zero");if(6+lenR+lenS!==buffer.length)throw new Error("S length is invalid");if(buffer[4]&128)throw new Error("R value is negative");if(lenR>1&&buffer[4]===0&&!(buffer[5]&128))throw new Error("R value excessively padded");if(buffer[lenR+6]&128)throw new Error("S value is negative");if(lenS>1&&buffer[lenR+6]===0&&!(buffer[lenR+7]&128))throw new Error("S value excessively padded");return{r:buffer.slice(4,4+lenR),s:buffer.slice(6+lenR)}}function encode(r,s){var lenR=r.length;var lenS=s.length;if(lenR===0)throw new Error("R length is zero");if(lenS===0)throw new Error("S length is zero");if(lenR>33)throw new Error("R length is too long");if(lenS>33)throw new Error("S length is too long");if(r[0]&128)throw new Error("R value is negative");if(s[0]&128)throw new Error("S value is negative");if(lenR>1&&r[0]===0&&!(r[1]&128))throw new Error("R value excessively padded");if(lenS>1&&s[0]===0&&!(s[1]&128))throw new Error("S value excessively padded");var signature=new Buffer(6+lenR+lenS);signature[0]=48;signature[1]=signature.length-2;signature[2]=2;signature[3]=r.length;r.copy(signature,4);signature[4+lenR]=2;signature[5+lenR]=s.length;s.copy(signature,6+lenR);return signature}module.exports={check:check,decode:decode,encode:encode}}).call(this,require("buffer").Buffer)},{buffer:"buffer"}],5:[function(require,module,exports){(function(Buffer){"use strict";var base58=require("bs58");var createHash=require("create-hash");function sha256x2(buffer){var tmp=createHash("sha256").update(buffer).digest();return createHash("sha256").update(tmp).digest()}function encode(payload){var checksum=sha256x2(payload);return base58.encode(Buffer.concat([payload,checksum],payload.length+4))}function decode(string){var buffer=new Buffer(base58.decode(string));var payload=buffer.slice(0,-4);var checksum=buffer.slice(-4);var newChecksum=sha256x2(payload);if(checksum[0]^newChecksum[0]|checksum[1]^newChecksum[1]|checksum[2]^newChecksum[2]|checksum[3]^newChecksum[3])throw new Error("Invalid checksum");return payload}module.exports={encode:encode,decode:decode}}).call(this,require("buffer").Buffer)},{bs58:6,buffer:"buffer","create-hash":10}],6:[function(require,module,exports){var ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var ALPHABET_MAP={};for(var i=0;i<ALPHABET.length;i++){ALPHABET_MAP[ALPHABET.charAt(i)]=i}var BASE=58;function encode(buffer){if(buffer.length===0)return"";var i,j,digits=[0];for(i=0;i<buffer.length;i++){for(j=0;j<digits.length;j++)digits[j]<<=8;digits[0]+=buffer[i];var carry=0;for(j=0;j<digits.length;++j){digits[j]+=carry;carry=digits[j]/BASE|0;digits[j]%=BASE}while(carry){digits.push(carry%BASE);carry=carry/BASE|0}}for(i=0;buffer[i]===0&&i<buffer.length-1;i++)digits.push(0);var stringOutput="";for(var i=digits.length-1;i>=0;i--){stringOutput=stringOutput+ALPHABET[digits[i]]}return stringOutput}function decode(string){if(string.length===0)return[];var i,j,bytes=[0];for(i=0;i<string.length;i++){var c=string[i];if(!(c in ALPHABET_MAP))throw new Error("Non-base58 character");for(j=0;j<bytes.length;j++)bytes[j]*=BASE;bytes[0]+=ALPHABET_MAP[c];var carry=0;for(j=0;j<bytes.length;++j){bytes[j]+=carry;carry=bytes[j]>>8;bytes[j]&=255}while(carry){bytes.push(carry&255);carry>>=8}}for(i=0;string[i]==="1"&&i<string.length-1;i++)bytes.push(0);return bytes.reverse()}module.exports={encode:encode,decode:decode}},{}],7:[function(require,module,exports){module.exports=function(a,b){if(typeof a.compare==="function")return a.compare(b);if(a===b)return 0;var x=a.length;var y=b.length;var i=0;var len=Math.min(x,y);while(i<len){if(a[i]!==b[i])break;++i}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0}},{}],8:[function(require,module,exports){(function(Buffer){"use strict";module.exports=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b){return true}if(typeof a.equals==="function"){return a.equals(b)}if(a.length!==b.length){return false}for(var i=0;i<a.length;i++){if(a[i]!==b[i]){return false}}return true}}).call(this,{isBuffer:require("../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":56}],9:[function(require,module,exports){(function(Buffer){module.exports=function reverse(a){var length=a.length;var buffer=new Buffer(length);for(var i=0,j=length-1;i<length;++i,--j){buffer[i]=a[j]}return buffer}}).call(this,require("buffer").Buffer)},{buffer:"buffer"}],10:[function(require,module,exports){(function(Buffer){"use strict";var inherits=require("inherits");var md5=require("./md5");var rmd160=require("ripemd160");var sha=require("sha.js");var Base=require("cipher-base");function HashNoConstructor(hash){Base.call(this,"digest");this._hash=hash;this.buffers=[]}inherits(HashNoConstructor,Base);HashNoConstructor.prototype._update=function(data){this.buffers.push(data)};HashNoConstructor.prototype._final=function(){var buf=Buffer.concat(this.buffers);var r=this._hash(buf);this.buffers=null;return r};function Hash(hash){Base.call(this,"digest");this._hash=hash}inherits(Hash,Base);Hash.prototype._update=function(data){this._hash.update(data)};Hash.prototype._final=function(){return this._hash.digest()};module.exports=function createHash(alg){alg=alg.toLowerCase();if("md5"===alg)return new HashNoConstructor(md5);if("rmd160"===alg||"ripemd160"===alg)return new HashNoConstructor(rmd160);return new Hash(sha(alg)) }}).call(this,require("buffer").Buffer)},{"./md5":12,buffer:"buffer","cipher-base":13,inherits:14,ripemd160:15,"sha.js":17}],11:[function(require,module,exports){(function(Buffer){"use strict";var intSize=4;var zeroBuffer=new Buffer(intSize);zeroBuffer.fill(0);var chrsz=8;function toArray(buf,bigEndian){if(buf.length%intSize!==0){var len=buf.length+(intSize-buf.length%intSize);buf=Buffer.concat([buf,zeroBuffer],len)}var arr=[];var fn=bigEndian?buf.readInt32BE:buf.readInt32LE;for(var i=0;i<buf.length;i+=intSize){arr.push(fn.call(buf,i))}return arr}function toBuffer(arr,size,bigEndian){var buf=new Buffer(size);var fn=bigEndian?buf.writeInt32BE:buf.writeInt32LE;for(var i=0;i<arr.length;i++){fn.call(buf,arr[i],i*4,true)}return buf}function hash(buf,fn,hashSize,bigEndian){if(!Buffer.isBuffer(buf))buf=new Buffer(buf);var arr=fn(toArray(buf,bigEndian),buf.length*chrsz);return toBuffer(arr,hashSize,bigEndian)}exports.hash=hash}).call(this,require("buffer").Buffer)},{buffer:"buffer"}],12:[function(require,module,exports){"use strict";var helpers=require("./helpers");function core_md5(x,len){x[len>>5]|=128<<len%32;x[(len+64>>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i<x.length;i+=16){var olda=a;var oldb=b;var oldc=c;var oldd=d;a=md5_ff(a,b,c,d,x[i+0],7,-680876936);d=md5_ff(d,a,b,c,x[i+1],12,-389564586);c=md5_ff(c,d,a,b,x[i+2],17,606105819);b=md5_ff(b,c,d,a,x[i+3],22,-1044525330);a=md5_ff(a,b,c,d,x[i+4],7,-176418897);d=md5_ff(d,a,b,c,x[i+5],12,1200080426);c=md5_ff(c,d,a,b,x[i+6],17,-1473231341);b=md5_ff(b,c,d,a,x[i+7],22,-45705983);a=md5_ff(a,b,c,d,x[i+8],7,1770035416);d=md5_ff(d,a,b,c,x[i+9],12,-1958414417);c=md5_ff(c,d,a,b,x[i+10],17,-42063);b=md5_ff(b,c,d,a,x[i+11],22,-1990404162);a=md5_ff(a,b,c,d,x[i+12],7,1804603682);d=md5_ff(d,a,b,c,x[i+13],12,-40341101);c=md5_ff(c,d,a,b,x[i+14],17,-1502002290);b=md5_ff(b,c,d,a,x[i+15],22,1236535329);a=md5_gg(a,b,c,d,x[i+1],5,-165796510);d=md5_gg(d,a,b,c,x[i+6],9,-1069501632);c=md5_gg(c,d,a,b,x[i+11],14,643717713);b=md5_gg(b,c,d,a,x[i+0],20,-373897302);a=md5_gg(a,b,c,d,x[i+5],5,-701558691);d=md5_gg(d,a,b,c,x[i+10],9,38016083);c=md5_gg(c,d,a,b,x[i+15],14,-660478335);b=md5_gg(b,c,d,a,x[i+4],20,-405537848);a=md5_gg(a,b,c,d,x[i+9],5,568446438);d=md5_gg(d,a,b,c,x[i+14],9,-1019803690);c=md5_gg(c,d,a,b,x[i+3],14,-187363961);b=md5_gg(b,c,d,a,x[i+8],20,1163531501);a=md5_gg(a,b,c,d,x[i+13],5,-1444681467);d=md5_gg(d,a,b,c,x[i+2],9,-51403784);c=md5_gg(c,d,a,b,x[i+7],14,1735328473);b=md5_gg(b,c,d,a,x[i+12],20,-1926607734);a=md5_hh(a,b,c,d,x[i+5],4,-378558);d=md5_hh(d,a,b,c,x[i+8],11,-2022574463);c=md5_hh(c,d,a,b,x[i+11],16,1839030562);b=md5_hh(b,c,d,a,x[i+14],23,-35309556);a=md5_hh(a,b,c,d,x[i+1],4,-1530992060);d=md5_hh(d,a,b,c,x[i+4],11,1272893353);c=md5_hh(c,d,a,b,x[i+7],16,-155497632);b=md5_hh(b,c,d,a,x[i+10],23,-1094730640);a=md5_hh(a,b,c,d,x[i+13],4,681279174);d=md5_hh(d,a,b,c,x[i+0],11,-358537222);c=md5_hh(c,d,a,b,x[i+3],16,-722521979);b=md5_hh(b,c,d,a,x[i+6],23,76029189);a=md5_hh(a,b,c,d,x[i+9],4,-640364487);d=md5_hh(d,a,b,c,x[i+12],11,-421815835);c=md5_hh(c,d,a,b,x[i+15],16,530742520);b=md5_hh(b,c,d,a,x[i+2],23,-995338651);a=md5_ii(a,b,c,d,x[i+0],6,-198630844);d=md5_ii(d,a,b,c,x[i+7],10,1126891415);c=md5_ii(c,d,a,b,x[i+14],15,-1416354905);b=md5_ii(b,c,d,a,x[i+5],21,-57434055);a=md5_ii(a,b,c,d,x[i+12],6,1700485571);d=md5_ii(d,a,b,c,x[i+3],10,-1894986606);c=md5_ii(c,d,a,b,x[i+10],15,-1051523);b=md5_ii(b,c,d,a,x[i+1],21,-2054922799);a=md5_ii(a,b,c,d,x[i+8],6,1873313359);d=md5_ii(d,a,b,c,x[i+15],10,-30611744);c=md5_ii(c,d,a,b,x[i+6],15,-1560198380);b=md5_ii(b,c,d,a,x[i+13],21,1309151649);a=md5_ii(a,b,c,d,x[i+4],6,-145523070);d=md5_ii(d,a,b,c,x[i+11],10,-1120210379);c=md5_ii(c,d,a,b,x[i+2],15,718787259);b=md5_ii(b,c,d,a,x[i+9],21,-343485551);a=safe_add(a,olda);b=safe_add(b,oldb);c=safe_add(c,oldc);d=safe_add(d,oldd)}return Array(a,b,c,d)}function md5_cmn(q,a,b,x,s,t){return safe_add(bit_rol(safe_add(safe_add(a,q),safe_add(x,t)),s),b)}function md5_ff(a,b,c,d,x,s,t){return md5_cmn(b&c|~b&d,a,b,x,s,t)}function md5_gg(a,b,c,d,x,s,t){return md5_cmn(b&d|c&~d,a,b,x,s,t)}function md5_hh(a,b,c,d,x,s,t){return md5_cmn(b^c^d,a,b,x,s,t)}function md5_ii(a,b,c,d,x,s,t){return md5_cmn(c^(b|~d),a,b,x,s,t)}function safe_add(x,y){var lsw=(x&65535)+(y&65535);var msw=(x>>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<<cnt|num>>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":11}],13:[function(require,module,exports){(function(Buffer){var Transform=require("stream").Transform;var inherits=require("inherits");var StringDecoder=require("string_decoder").StringDecoder;module.exports=CipherBase;inherits(CipherBase,Transform);function CipherBase(hashMode){Transform.call(this);this.hashMode=typeof hashMode==="string";if(this.hashMode){this[hashMode]=this._finalOrDigest}else{this.final=this._finalOrDigest}this._decoder=null;this._encoding=null}CipherBase.prototype.update=function(data,inputEnc,outputEnc){if(typeof data==="string"){data=new Buffer(data,inputEnc)}var outData=this._update(data);if(this.hashMode){return this}if(outputEnc){outData=this._toString(outData,outputEnc)}return outData};CipherBase.prototype.setAutoPadding=function(){};CipherBase.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")};CipherBase.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")};CipherBase.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")};CipherBase.prototype._transform=function(data,_,next){var err;try{if(this.hashMode){this._update(data)}else{this.push(this._update(data))}}catch(e){err=e}finally{next(err)}};CipherBase.prototype._flush=function(done){var err;try{this.push(this._final())}catch(e){err=e}finally{done(err)}};CipherBase.prototype._finalOrDigest=function(outputEnc){var outData=this._final()||new Buffer("");if(outputEnc){outData=this._toString(outData,outputEnc,true)}return outData};CipherBase.prototype._toString=function(value,enc,final){if(!this._decoder){this._decoder=new StringDecoder(enc);this._encoding=enc}if(this._encoding!==enc){throw new Error("can't switch encodings")}var out=this._decoder.write(value);if(final){out+=this._decoder.end()}return out}}).call(this,require("buffer").Buffer)},{buffer:"buffer",inherits:14,stream:72,string_decoder:73}],14:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],15:[function(require,module,exports){(function(Buffer){var zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13];var zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11];var sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6];var sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];var hl=[0,1518500249,1859775393,2400959708,2840853838];var hr=[1352829926,1548603684,1836072691,2053994217,0];function bytesToWords(bytes){var words=[];for(var i=0,b=0;i<bytes.length;i++,b+=8){words[b>>>5]|=bytes[i]<<24-b%32}return words}function wordsToBytes(words){var bytes=[];for(var b=0;b<words.length*32;b+=8){bytes.push(words[b>>>5]>>>24-b%32&255)}return bytes}function processBlock(H,M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t}function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<<n|x>>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof message==="string"){message=new Buffer(message,"utf8")}var m=bytesToWords(message);var nBitsLeft=message.length*8;var nBitsTotal=message.length*8;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;m[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;for(var i=0;i<m.length;i+=16){processBlock(H,m,i)}for(i=0;i<5;i++){var H_i=H[i];H[i]=(H_i<<8|H_i>>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}module.exports=ripemd160}).call(this,require("buffer").Buffer)},{buffer:"buffer"}],16:[function(require,module,exports){(function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0;this._s=0}Hash.prototype.update=function(data,enc){if(typeof data==="string"){enc=enc||"utf8";data=new Buffer(data,enc)}var l=this._len+=data.length;var s=this._s||0;var f=0;var buffer=this._block;while(s<l){var t=Math.min(data.length,f+this._blockSize-s%this._blockSize);var ch=t-f;for(var i=0;i<ch;i++){buffer[s%this._blockSize+i]=data[i+f]}s+=ch;f+=ch;if(s%this._blockSize===0){this._update(buffer)}}this._s=s;return this};Hash.prototype.digest=function(enc){var l=this._len*8;this._block[this._len%this._blockSize]=128;this._block.fill(0,this._len%this._blockSize+1);if(l%(this._blockSize*8)>=this._finalSize*8){this._update(this._block);this._block.fill(0)}this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};module.exports=Hash}).call(this,require("buffer").Buffer)},{buffer:"buffer"}],17:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha");exports.sha1=require("./sha1");exports.sha224=require("./sha224");exports.sha256=require("./sha256");exports.sha384=require("./sha384");exports.sha512=require("./sha512")},{"./sha":18,"./sha1":19,"./sha224":20,"./sha256":21,"./sha384":22,"./sha512":23}],18:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var W=new Array(80);function Sha(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha,Hash);Sha.prototype.init=function(){this._a=1732584193|0;this._b=4023233417|0;this._c=2562383102|0;this._d=271733878|0;this._e=3285377520|0;return this};function rol(num,cnt){return num<<cnt|num>>>32-cnt}Sha.prototype._update=function(M){var W=this._w;var a=this._a;var b=this._b;var c=this._c;var d=this._d;var e=this._e;var j=0;var k;function calcW(){return W[j-3]^W[j-8]^W[j-14]^W[j-16]}function loop(w,f){W[j]=w;var t=rol(a,5)+f+e+w+k;e=d;d=c;c=rol(b,30);b=a;a=t;j++}k=1518500249;while(j<16)loop(M.readInt32BE(j*4),b&c|~b&d);while(j<20)loop(calcW(),b&c|~b&d);k=1859775393;while(j<40)loop(calcW(),b^c^d);k=-1894007588;while(j<60)loop(calcW(),b&c|b&d|c&d);k=-899497514;while(j<80)loop(calcW(),b^c^d);this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha.prototype._hash=function(){var H=new Buffer(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha}).call(this,require("buffer").Buffer)},{"./hash":16,buffer:"buffer",inherits:14}],19:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var W=new Array(80);function Sha1(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha1,Hash);Sha1.prototype.init=function(){this._a=1732584193|0;this._b=4023233417|0;this._c=2562383102|0;this._d=271733878|0;this._e=3285377520|0;return this};function rol(num,cnt){return num<<cnt|num>>>32-cnt}Sha1.prototype._update=function(M){var W=this._w;var a=this._a;var b=this._b;var c=this._c;var d=this._d;var e=this._e;var j=0;var k;function calcW(){return rol(W[j-3]^W[j-8]^W[j-14]^W[j-16],1)}function loop(w,f){W[j]=w;var t=rol(a,5)+f+e+w+k;e=d;d=c;c=rol(b,30);b=a;a=t;j++}k=1518500249;while(j<16)loop(M.readInt32BE(j*4),b&c|~b&d);while(j<20)loop(calcW(),b&c|~b&d);k=1859775393;while(j<40)loop(calcW(),b^c^d);k=-1894007588;while(j<60)loop(calcW(),b&c|b&d|c&d);k=-899497514;while(j<80)loop(calcW(),b^c^d);this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha1.prototype._hash=function(){var H=new Buffer(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha1}).call(this,require("buffer").Buffer)},{"./hash":16,buffer:"buffer",inherits:14}],20:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Sha256=require("./sha256");var Hash=require("./hash");var W=new Array(64);function Sha224(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha224,Sha256);Sha224.prototype.init=function(){this._a=3238371032|0;this._b=914150663|0;this._c=812702999|0;this._d=4144912697|0;this._e=4290775857|0;this._f=1750603025|0;this._g=1694076839|0;this._h=3204075428|0;return this};Sha224.prototype._hash=function(){var H=new Buffer(28);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);return H};module.exports=Sha224}).call(this,require("buffer").Buffer)},{"./hash":16,"./sha256":21,buffer:"buffer",inherits:14}],21:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var W=new Array(64);function Sha256(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha256,Hash);Sha256.prototype.init=function(){this._a=1779033703|0;this._b=3144134277|0;this._c=1013904242|0;this._d=2773480762|0;this._e=1359893119|0;this._f=2600822924|0;this._g=528734635|0;this._h=1541459225|0;return this};function Ch(x,y,z){return z^x&(y^z)}function Maj(x,y,z){return x&y|z&(x|y)}function Sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function Sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function Gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function Gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}Sha256.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;var f=this._f|0;var g=this._g|0;var h=this._h|0;var j=0;function calcW(){return Gamma1(W[j-2])+W[j-7]+Gamma0(W[j-15])+W[j-16]}function loop(w){W[j]=w;var T1=h+Sigma1(e)+Ch(e,f,g)+K[j]+w;var T2=Sigma0(a)+Maj(a,b,c);h=g;g=f;f=e;e=d+T1;d=c;c=b;b=a;a=T1+T2;j++}while(j<16)loop(M.readInt32BE(j*4));while(j<64)loop(calcW());this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0;this._f=f+this._f|0;this._g=g+this._g|0;this._h=h+this._h|0};Sha256.prototype._hash=function(){var H=new Buffer(32);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);H.writeInt32BE(this._h,28);return H};module.exports=Sha256}).call(this,require("buffer").Buffer)},{"./hash":16,buffer:"buffer",inherits:14}],22:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var SHA512=require("./sha512");var Hash=require("./hash");var W=new Array(160);function Sha384(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha384,SHA512);Sha384.prototype.init=function(){this._a=3418070365|0;this._b=1654270250|0;this._c=2438529370|0;this._d=355462360|0;this._e=1731405415|0;this._f=2394180231|0;this._g=3675008525|0;this._h=1203062813|0;this._al=3238371032|0;this._bl=914150663|0;this._cl=812702999|0;this._dl=4144912697|0;this._el=4290775857|0;this._fl=1750603025|0;this._gl=1694076839|0;this._hl=3204075428|0;return this};Sha384.prototype._hash=function(){var H=new Buffer(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._a,this._al,0);writeInt64BE(this._b,this._bl,8);writeInt64BE(this._c,this._cl,16);writeInt64BE(this._d,this._dl,24);writeInt64BE(this._e,this._el,32);writeInt64BE(this._f,this._fl,40);return H};module.exports=Sha384}).call(this,require("buffer").Buffer)},{"./hash":16,"./sha512":23,buffer:"buffer",inherits:14}],23:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];var W=new Array(160);function Sha512(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha512,Hash);Sha512.prototype.init=function(){this._a=1779033703|0;this._b=3144134277|0;this._c=1013904242|0;this._d=2773480762|0;this._e=1359893119|0;this._f=2600822924|0;this._g=528734635|0;this._h=1541459225|0;this._al=4089235720|0;this._bl=2227873595|0;this._cl=4271175723|0;this._dl=1595750129|0;this._el=2917565137|0;this._fl=725511199|0;this._gl=4215389547|0;this._hl=327033209|0;return this};function Ch(x,y,z){return z^x&(y^z)}function Maj(x,y,z){return x&y|z&(x|y)}function Sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function Sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}Sha512.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;var f=this._f|0;var g=this._g|0;var h=this._h|0;var al=this._al|0;var bl=this._bl|0;var cl=this._cl|0;var dl=this._dl|0;var el=this._el|0;var fl=this._fl|0;var gl=this._gl|0;var hl=this._hl|0;var i=0;var j=0;var Wi,Wil;function calcW(){var x=W[j-15*2];var xl=W[j-15*2+1];var gamma0=Gamma0(x,xl);var gamma0l=Gamma0l(xl,x);x=W[j-2*2];xl=W[j-2*2+1];var gamma1=Gamma1(x,xl);var gamma1l=Gamma1l(xl,x);var Wi7=W[j-7*2];var Wi7l=W[j-7*2+1];var Wi16=W[j-16*2];var Wi16l=W[j-16*2+1];Wil=gamma0l+Wi7l;Wi=gamma0+Wi7+(Wil>>>0<gamma0l>>>0?1:0);Wil=Wil+gamma1l;Wi=Wi+gamma1+(Wil>>>0<gamma1l>>>0?1:0);Wil=Wil+Wi16l;Wi=Wi+Wi16+(Wil>>>0<Wi16l>>>0?1:0)}function loop(){W[j]=Wi;W[j+1]=Wil;var maj=Maj(a,b,c);var majl=Maj(al,bl,cl);var sigma0h=Sigma0(a,al);var sigma0l=Sigma0(al,a);var sigma1h=Sigma1(e,el);var sigma1l=Sigma1(el,e);var Ki=K[j];var Kil=K[j+1];var ch=Ch(e,f,g);var chl=Ch(el,fl,gl);var t1l=hl+sigma1l;var t1=h+sigma1h+(t1l>>>0<hl>>>0?1:0);t1l=t1l+chl;t1=t1+ch+(t1l>>>0<chl>>>0?1:0);t1l=t1l+Kil;t1=t1+Ki+(t1l>>>0<Kil>>>0?1:0);t1l=t1l+Wil;t1=t1+Wi+(t1l>>>0<Wil>>>0?1:0);var t2l=sigma0l+majl;var t2=sigma0h+maj+(t2l>>>0<sigma0l>>>0?1:0);h=g;hl=gl;g=f;gl=fl;f=e;fl=el;el=dl+t1l|0;e=d+t1+(el>>>0<dl>>>0?1:0)|0;d=c;dl=cl;c=b;cl=bl;b=a;bl=al;al=t1l+t2l|0;a=t1+t2+(al>>>0<t1l>>>0?1:0)|0;i++;j+=2}while(i<16){Wi=M.readInt32BE(j*4);Wil=M.readInt32BE(j*4+4);loop()}while(i<80){calcW();loop()}this._al=this._al+al|0;this._bl=this._bl+bl|0;this._cl=this._cl+cl|0;this._dl=this._dl+dl|0;this._el=this._el+el|0;this._fl=this._fl+fl|0;this._gl=this._gl+gl|0;this._hl=this._hl+hl|0;this._a=this._a+a+(this._al>>>0<al>>>0?1:0)|0;this._b=this._b+b+(this._bl>>>0<bl>>>0?1:0)|0;this._c=this._c+c+(this._cl>>>0<cl>>>0?1:0)|0;this._d=this._d+d+(this._dl>>>0<dl>>>0?1:0)|0;this._e=this._e+e+(this._el>>>0<el>>>0?1:0)|0;this._f=this._f+f+(this._fl>>>0<fl>>>0?1:0)|0;this._g=this._g+g+(this._gl>>>0<gl>>>0?1:0)|0;this._h=this._h+h+(this._hl>>>0<hl>>>0?1:0)|0};Sha512.prototype._hash=function(){var H=new Buffer(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._a,this._al,0);writeInt64BE(this._b,this._bl,8);writeInt64BE(this._c,this._cl,16);writeInt64BE(this._d,this._dl,24);writeInt64BE(this._e,this._el,32);writeInt64BE(this._f,this._fl,40);writeInt64BE(this._g,this._gl,48);writeInt64BE(this._h,this._hl,56);return H};module.exports=Sha512}).call(this,require("buffer").Buffer)},{"./hash":16,buffer:"buffer",inherits:14}],24:[function(require,module,exports){(function(Buffer){"use strict";var createHash=require("create-hash/browser");var inherits=require("inherits");var Transform=require("stream").Transform;var ZEROS=new Buffer(128);ZEROS.fill(0);function Hmac(alg,key){Transform.call(this);alg=alg.toLowerCase();if(typeof key==="string"){key=new Buffer(key)}var blocksize=alg==="sha512"||alg==="sha384"?128:64;this._alg=alg;this._key=key;if(key.length>blocksize){key=createHash(alg).update(key).digest()}else if(key.length<blocksize){key=Buffer.concat([key,ZEROS],blocksize)}var ipad=this._ipad=new Buffer(blocksize);var opad=this._opad=new Buffer(blocksize);for(var i=0;i<blocksize;i++){ipad[i]=key[i]^54;opad[i]=key[i]^92}this._hash=createHash(alg).update(ipad)}inherits(Hmac,Transform);Hmac.prototype.update=function(data,enc){this._hash.update(data,enc);return this};Hmac.prototype._transform=function(data,_,next){this._hash.update(data);next()};Hmac.prototype._flush=function(next){this.push(this.digest());next()};Hmac.prototype.digest=function(enc){var h=this._hash.digest();return createHash(this._alg).update(this._opad).update(h).digest(enc)};module.exports=function createHmac(alg,key){return new Hmac(alg,key)}}).call(this,require("buffer").Buffer)},{buffer:"buffer","create-hash/browser":10,inherits:25,stream:72}],25:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{dup:14}],26:[function(require,module,exports){var assert=require("assert");var BigInteger=require("bigi");var Point=require("./point");function Curve(p,a,b,Gx,Gy,n,h){this.p=p;this.a=a;this.b=b;this.G=Point.fromAffine(this,Gx,Gy);this.n=n;this.h=h;this.infinity=new Point(this,null,null,BigInteger.ZERO);this.pOverFour=p.add(BigInteger.ONE).shiftRight(2)}Curve.prototype.pointFromX=function(isOdd,x){var alpha=x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p);var beta=alpha.modPow(this.pOverFour,this.p);var y=beta;if(beta.isEven()^!isOdd){y=this.p.subtract(y)}return Point.fromAffine(this,x,y)};Curve.prototype.isInfinity=function(Q){if(Q===this.infinity)return true;return Q.z.signum()===0&&Q.y.signum()!==0};Curve.prototype.isOnCurve=function(Q){if(this.isInfinity(Q))return true;var x=Q.affineX;var y=Q.affineY;var a=this.a;var b=this.b;var p=this.p;if(x.signum()<0||x.compareTo(p)>=0)return false;if(y.signum()<0||y.compareTo(p)>=0)return false;var lhs=y.square().mod(p);var rhs=x.pow(3).add(a.multiply(x)).add(b).mod(p);return lhs.equals(rhs)};Curve.prototype.validate=function(Q){assert(!this.isInfinity(Q),"Point is at infinity");assert(this.isOnCurve(Q),"Point is not on the curve");var nQ=Q.multiply(this.n);assert(this.isInfinity(nQ),"Point is not a scalar multiple of G");return true};module.exports=Curve},{"./point":29,assert:49,bigi:"bigi"}],27:[function(require,module,exports){module.exports={secp128r1:{p:"fffffffdffffffffffffffffffffffff",a:"fffffffdfffffffffffffffffffffffc",b:"e87579c11079f43dd824993c2cee5ed3",n:"fffffffe0000000075a30d1b9038a115",h:"01",Gx:"161ff7528b899b2d0c28607ca52c5b86",Gy:"cf5ac8395bafeb13c02da292dded7a83"},secp160k1:{p:"fffffffffffffffffffffffffffffffeffffac73",a:"00",b:"07",n:"0100000000000000000001b8fa16dfab9aca16b6b3",h:"01",Gx:"3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",Gy:"938cf935318fdced6bc28286531733c3f03c4fee"},secp160r1:{p:"ffffffffffffffffffffffffffffffff7fffffff",a:"ffffffffffffffffffffffffffffffff7ffffffc",b:"1c97befc54bd7a8b65acf89f81d4d4adc565fa45",n:"0100000000000000000001f4c8f927aed3ca752257",h:"01",Gx:"4a96b5688ef573284664698968c38bb913cbfc82",Gy:"23a628553168947d59dcc912042351377ac5fb32"},secp192k1:{p:"fffffffffffffffffffffffffffffffffffffffeffffee37",a:"00",b:"03",n:"fffffffffffffffffffffffe26f2fc170f69466a74defd8d",h:"01",Gx:"db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",Gy:"9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"},secp192r1:{p:"fffffffffffffffffffffffffffffffeffffffffffffffff",a:"fffffffffffffffffffffffffffffffefffffffffffffffc",b:"64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",n:"ffffffffffffffffffffffff99def836146bc9b1b4d22831",h:"01",Gx:"188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",Gy:"07192b95ffc8da78631011ed6b24cdd573f977a11e794811"},secp256k1:{p:"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",a:"00",b:"07",n:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",h:"01",Gx:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",Gy:"483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"},secp256r1:{p:"ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",a:"ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",b:"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",n:"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",h:"01",Gx:"6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",Gy:"4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"}}},{}],28:[function(require,module,exports){var BigInteger=require("bigi");var curves=require("./curves");var Curve=require("./curve");function getCurveByName(name){var curve=curves[name];if(!curve)return null;var p=new BigInteger(curve.p,16);var a=new BigInteger(curve.a,16);var b=new BigInteger(curve.b,16);var n=new BigInteger(curve.n,16);var h=new BigInteger(curve.h,16);var Gx=new BigInteger(curve.Gx,16);var Gy=new BigInteger(curve.Gy,16);return new Curve(p,a,b,Gx,Gy,n,h)}module.exports=getCurveByName},{"./curve":26,"./curves":27,bigi:"bigi"}],29:[function(require,module,exports){(function(Buffer){var assert=require("assert");var BigInteger=require("bigi");var THREE=BigInteger.valueOf(3);function Point(curve,x,y,z){assert.notStrictEqual(z,undefined,"Missing Z coordinate");this.curve=curve;this.x=x;this.y=y;this.z=z;this._zInv=null;this.compressed=true}Object.defineProperty(Point.prototype,"zInv",{get:function(){if(this._zInv===null){this._zInv=this.z.modInverse(this.curve.p)}return this._zInv}});Object.defineProperty(Point.prototype,"affineX",{get:function(){return this.x.multiply(this.zInv).mod(this.curve.p)}});Object.defineProperty(Point.prototype,"affineY",{get:function(){return this.y.multiply(this.zInv).mod(this.curve.p)}});Point.fromAffine=function(curve,x,y){return new Point(curve,x,y,BigInteger.ONE)};Point.prototype.equals=function(other){if(other===this)return true;if(this.curve.isInfinity(this))return this.curve.isInfinity(other);if(this.curve.isInfinity(other))return this.curve.isInfinity(this);var u=other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p);if(u.signum()!==0)return false;var v=other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p);return v.signum()===0};Point.prototype.negate=function(){var y=this.curve.p.subtract(this.y);return new Point(this.curve,this.x,y,this.z)};Point.prototype.add=function(b){if(this.curve.isInfinity(this))return b;if(this.curve.isInfinity(b))return this;var x1=this.x;var y1=this.y;var x2=b.x;var y2=b.y;var u=y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p);var v=x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p);if(v.signum()===0){if(u.signum()===0){return this.twice()}return this.curve.infinity}var v2=v.square();var v3=v2.multiply(v);var x1v2=x1.multiply(v2);var zu2=u.square().multiply(this.z);var x3=zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p);var y3=x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p);var z3=v3.multiply(this.z).multiply(b.z).mod(this.curve.p);return new Point(this.curve,x3,y3,z3)};Point.prototype.twice=function(){if(this.curve.isInfinity(this))return this;if(this.y.signum()===0)return this.curve.infinity;var x1=this.x;var y1=this.y;var y1z1=y1.multiply(this.z);var y1sqz1=y1z1.multiply(y1).mod(this.curve.p);var a=this.curve.a;var w=x1.square().multiply(THREE); if(a.signum()!==0){w=w.add(this.z.square().multiply(a))}w=w.mod(this.curve.p);var x3=w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p);var y3=w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p);var z3=y1z1.pow(3).shiftLeft(3).mod(this.curve.p);return new Point(this.curve,x3,y3,z3)};Point.prototype.multiply=function(k){if(this.curve.isInfinity(this))return this;if(k.signum()===0)return this.curve.infinity;var e=k;var h=e.multiply(THREE);var neg=this.negate();var R=this;for(var i=h.bitLength()-2;i>0;--i){var hBit=h.testBit(i);var eBit=e.testBit(i);R=R.twice();if(hBit!==eBit){R=R.add(hBit?this:neg)}}return R};Point.prototype.multiplyTwo=function(j,x,k){var i=Math.max(j.bitLength(),k.bitLength())-1;var R=this.curve.infinity;var both=this.add(x);while(i>=0){var jBit=j.testBit(i);var kBit=k.testBit(i);R=R.twice();if(jBit){if(kBit){R=R.add(both)}else{R=R.add(this)}}else if(kBit){R=R.add(x)}--i}return R};Point.prototype.getEncoded=function(compressed){if(compressed==undefined)compressed=this.compressed;if(this.curve.isInfinity(this))return new Buffer("00","hex");var x=this.affineX;var y=this.affineY;var buffer;var byteLength=Math.floor((this.curve.p.bitLength()+7)/8);if(compressed){buffer=new Buffer(1+byteLength);buffer.writeUInt8(y.isEven()?2:3,0)}else{buffer=new Buffer(1+byteLength+byteLength);buffer.writeUInt8(4,0);y.toBuffer(byteLength).copy(buffer,1+byteLength)}x.toBuffer(byteLength).copy(buffer,1);return buffer};Point.decodeFrom=function(curve,buffer){var type=buffer.readUInt8(0);var compressed=type!==4;var byteLength=Math.floor((curve.p.bitLength()+7)/8);var x=BigInteger.fromBuffer(buffer.slice(1,1+byteLength));var Q;if(compressed){assert.equal(buffer.length,byteLength+1,"Invalid sequence length");assert(type===2||type===3,"Invalid sequence tag");var isOdd=type===3;Q=curve.pointFromX(isOdd,x)}else{assert.equal(buffer.length,1+byteLength+byteLength,"Invalid sequence length");var y=BigInteger.fromBuffer(buffer.slice(1+byteLength));Q=Point.fromAffine(curve,x,y)}Q.compressed=compressed;return Q};Point.prototype.toString=function(){if(this.curve.isInfinity(this))return"(INFINITY)";return"("+this.affineX.toString()+","+this.affineY.toString()+")"};module.exports=Point}).call(this,require("buffer").Buffer)},{assert:49,bigi:"bigi",buffer:"buffer"}],30:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");function TfTypeError(type,value){this.tfError=Error.call(this);if(arguments.length===1&&typeof type==="string"){this.message=type}else{this.tfType=type;this.tfValue=value;var message;Object.defineProperty(this,"message",{get:function(){if(message)return message;message=tfErrorString(type,value);return message}})}}inherits(TfTypeError,Error);Object.defineProperty(TfTypeError,"stack",{get:function(){return this.tfError.stack}});function TfPropertyTypeError(type,property,value,error){this.tfError=error||Error.call(this);this.tfProperty=property;this.tfType=type;this.tfValue=value;var message;Object.defineProperty(this,"message",{get:function(){if(message)return message;if(type){message=tfPropertyErrorString(type,property,value)}else{message='Unexpected property "'+property+'"'}return message}})}inherits(TfPropertyTypeError,Error);Object.defineProperty(TfPropertyTypeError,"stack",{get:function(){return this.tfError.stack}});TfPropertyTypeError.prototype.asChildOf=function(property){return new TfPropertyTypeError(this.tfType,property+"."+this.tfProperty,this.tfValue,this.tfError)};function getFunctionName(fn){return fn.name||fn.toString().match(/function (.*?)\s*\(/)[1]}function getValueTypeName(value){if(nativeTypes.Null(value))return"";return getFunctionName(value.constructor)}function getValue(value){if(nativeTypes.Function(value))return"";if(nativeTypes.String(value))return JSON.stringify(value);if(value&&nativeTypes.Object(value))return"";return value}function tfJSON(type){if(nativeTypes.Function(type))return type.toJSON?type.toJSON():getFunctionName(type);if(nativeTypes.Array(type))return"Array";if(type&&nativeTypes.Object(type))return"Object";return type||""}function stfJSON(type){type=tfJSON(type);return nativeTypes.Object(type)?JSON.stringify(type):type}function tfErrorString(type,value){var valueTypeName=getValueTypeName(value);var valueValue=getValue(value);return"Expected "+stfJSON(type)+", got"+(valueTypeName!==""?" "+valueTypeName:"")+(valueValue!==""?" "+valueValue:"")}function tfPropertyErrorString(type,name,value){return tfErrorString('property "'+stfJSON(name)+'" of type '+stfJSON(type),value)}var nativeTypes={Array:function(value){return value!==null&&value!==undefined&&value.constructor===Array},Boolean:function(value){return typeof value==="boolean"},Buffer:function(value){return Buffer.isBuffer(value)},Function:function(value){return typeof value==="function"},Null:function(value){return value===undefined||value===null},Number:function(value){return typeof value==="number"},Object:function(value){return typeof value==="object"},String:function(value){return typeof value==="string"},"":function(){return true}};var otherTypes={arrayOf:function arrayOf(type){function arrayOf(value,strict){if(!nativeTypes.Array(value))return false;return value.every(function(x){return typeforce(type,x,strict,arrayOf)})}arrayOf.toJSON=function(){return[tfJSON(type)]};return arrayOf},maybe:function maybe(type){function maybe(value,strict){return nativeTypes.Null(value)||typeforce(type,value,strict,maybe)}maybe.toJSON=function(){return"?"+stfJSON(type)};return maybe},object:function object(type){function object(value,strict){if(!nativeTypes.Object(value))return false;if(nativeTypes.Null(value))return false;var propertyName;try{for(propertyName in type){var propertyType=type[propertyName];var propertyValue=value[propertyName];typeforce(propertyType,propertyValue,strict)}}catch(e){if(e instanceof TfPropertyTypeError){throw e.asChildOf(propertyName)}else if(e instanceof TfTypeError){throw new TfPropertyTypeError(e.tfType,propertyName,e.tfValue,e.tfError)}throw e}if(strict){for(propertyName in value){if(type[propertyName])continue;throw new TfPropertyTypeError(undefined,propertyName)}}return true}object.toJSON=function(){return tfJSON(type)};return object},map:function map(propertyType,propertyKeyType){function map(value,strict){typeforce(nativeTypes.Object,value,strict);if(nativeTypes.Null(value))return false;var propertyName;try{for(propertyName in value){if(propertyKeyType){typeforce(propertyKeyType,propertyName,strict)}var propertyValue=value[propertyName];typeforce(propertyType,propertyValue,strict)}}catch(e){if(e instanceof TfPropertyTypeError){throw e.asChildOf(propertyName)}else if(e instanceof TfTypeError){throw new TfPropertyTypeError(e.tfType,propertyKeyType||propertyName,e.tfValue)}throw e}return true}if(propertyKeyType){map.toJSON=function(){return"{"+stfJSON(propertyKeyType)+": "+stfJSON(propertyType)+"}"}}else{map.toJSON=function(){return"{"+stfJSON(propertyType)+"}"}}return map},oneOf:function oneOf(){var types=[].slice.call(arguments);function oneOf(value,strict){return types.some(function(type){try{return typeforce(type,value,strict)}catch(e){if(e instanceof TfTypeError||e instanceof TfPropertyTypeError)return false;throw e}})}oneOf.toJSON=function(){return types.map(stfJSON).join("|")};return oneOf},quacksLike:function quacksLike(type){function quacksLike(value){return type===getValueTypeName(value)}quacksLike.toJSON=function(){return type};return quacksLike},tuple:function tuple(){var types=[].slice.call(arguments);function tuple(value,strict){return types.every(function(type,i){return typeforce(type,value[i],strict)})}tuple.toJSON=function(){return"("+types.map(stfJSON).join(", ")+")"};return tuple},value:function value(expected){function value(actual){return actual===expected}value.toJSON=function(){return expected};return value}};function compile(type){if(nativeTypes.String(type)){if(type[0]==="?")return otherTypes.maybe(compile(type.slice(1)));return nativeTypes[type]||otherTypes.quacksLike(type)}else if(type&&nativeTypes.Object(type)){if(nativeTypes.Array(type))return otherTypes.arrayOf(compile(type[0]));var compiled={};for(var propertyName in type){compiled[propertyName]=compile(type[propertyName])}return otherTypes.object(compiled)}else if(nativeTypes.Function(type)){return type}return otherTypes.value(type)}function typeforce(type,value,strict,surrogate){if(nativeTypes.Function(type)){if(type(value,strict))return true;throw new TfTypeError(surrogate||type,value)}return typeforce(compile(type),value,strict)}var typeName;Object.keys(nativeTypes).forEach(function(typeName){var nativeType=nativeTypes[typeName];nativeType.toJSON=function(){return typeName};typeforce[typeName]=nativeType});for(typeName in otherTypes){typeforce[typeName]=otherTypes[typeName]}module.exports=typeforce;module.exports.compile=compile;module.exports.TfTypeError=TfTypeError;module.exports.TfPropertyTypeError=TfPropertyTypeError}).call(this,{isBuffer:require("../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":56,inherits:31}],31:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{dup:14}],32:[function(require,module,exports){(function(Buffer){var bs58check=require("bs58check");function decodeRaw(version,buffer){if(buffer[0]!==version)throw new Error("Invalid network version");if(buffer.length===34){if(buffer[33]!==1)throw new Error("Invalid compression flag");return{version:buffer[0],d:buffer.slice(1,-1),compressed:true}}if(buffer.length!==33)throw new Error("Invalid WIF length");return{version:buffer[0],d:buffer.slice(1),compressed:false}}function decode(version,string){return decodeRaw(version,bs58check.decode(string))}function encodeRaw(version,d,compressed){var buffer=new Buffer(compressed?34:33);buffer.writeUInt8(version,0);d.copy(buffer,1);if(compressed){buffer[33]=1}return buffer}function encode(version,d,compressed){return bs58check.encode(encodeRaw(version,d,compressed))}module.exports={decode:decode,decodeRaw:decodeRaw,encode:encode,encodeRaw:encodeRaw}}).call(this,require("buffer").Buffer)},{bs58check:5,buffer:"buffer"}],33:[function(require,module,exports){(function(Buffer){var bs58check=require("bs58check");var bscript=require("./script");var networks=require("./networks");var typeforce=require("typeforce");var types=require("./types");function fromBase58Check(address){var payload=bs58check.decode(address);if(payload.length<21)throw new TypeError(address+" is too short");if(payload.length>21)throw new TypeError(address+" is too long");var version=payload[0];var hash=payload.slice(1);return{hash:hash,version:version}}function fromOutputScript(scriptPubKey,network){network=network||networks.bitcoin;if(bscript.isPubKeyHashOutput(scriptPubKey))return toBase58Check(bscript.compile(scriptPubKey).slice(3,23),network.pubKeyHash);if(bscript.isScriptHashOutput(scriptPubKey))return toBase58Check(bscript.compile(scriptPubKey).slice(2,22),network.scriptHash);throw new Error(bscript.toASM(scriptPubKey)+" has no matching Address")}function toBase58Check(hash,version){typeforce(types.tuple(types.Hash160bit,types.UInt8),arguments);var payload=new Buffer(21);payload.writeUInt8(version,0);hash.copy(payload,1);return bs58check.encode(payload)}function toOutputScript(address,network){network=network||networks.bitcoin;var decode=fromBase58Check(address);if(decode.version===network.pubKeyHash)return bscript.pubKeyHashOutput(decode.hash);if(decode.version===network.scriptHash)return bscript.scriptHashOutput(decode.hash);throw new Error(address+" has no matching Script")}module.exports={fromBase58Check:fromBase58Check,fromOutputScript:fromOutputScript,toBase58Check:toBase58Check,toOutputScript:toOutputScript}}).call(this,require("buffer").Buffer)},{"./networks":42,"./script":44,"./types":48,bs58check:5,buffer:"buffer",typeforce:30}],34:[function(require,module,exports){(function(Buffer){var bufferutils=require("./bufferutils");var bcrypto=require("./crypto");var compare=require("buffer-compare");var Transaction=require("./transaction");function Block(){this.version=1;this.prevHash=null;this.merkleRoot=null;this.timestamp=0;this.bits=0;this.nonce=0}Block.fromBuffer=function(buffer){if(buffer.length<80)throw new Error("Buffer too small (< 80 bytes)");var offset=0;function readSlice(n){offset+=n;return buffer.slice(offset-n,offset)}function readUInt32(){var i=buffer.readUInt32LE(offset);offset+=4;return i}var block=new Block;block.version=readUInt32();block.prevHash=readSlice(32);block.merkleRoot=readSlice(32);block.timestamp=readUInt32();block.bits=readUInt32();block.nonce=readUInt32();if(buffer.length===80)return block;function readVarInt(){var vi=bufferutils.readVarInt(buffer,offset);offset+=vi.size;return vi.number}function readTransaction(){var tx=Transaction.fromBuffer(buffer.slice(offset),true);offset+=tx.byteLength();return tx}var nTransactions=readVarInt();block.transactions=[];for(var i=0;i<nTransactions;++i){var tx=readTransaction();block.transactions.push(tx)}return block};Block.fromHex=function(hex){return Block.fromBuffer(new Buffer(hex,"hex"))};Block.prototype.getHash=function(){return bcrypto.hash256(this.toBuffer(true))};Block.prototype.getId=function(){return[].reverse.call(this.getHash()).toString("hex")};Block.prototype.getUTCDate=function(){var date=new Date(0);date.setUTCSeconds(this.timestamp);return date};Block.prototype.toBuffer=function(headersOnly){var buffer=new Buffer(80);var offset=0;function writeSlice(slice){slice.copy(buffer,offset);offset+=slice.length}function writeUInt32(i){buffer.writeUInt32LE(i,offset);offset+=4}writeUInt32(this.version);writeSlice(this.prevHash);writeSlice(this.merkleRoot);writeUInt32(this.timestamp);writeUInt32(this.bits);writeUInt32(this.nonce);if(headersOnly||!this.transactions)return buffer;var txLenBuffer=bufferutils.varIntBuffer(this.transactions.length);var txBuffers=this.transactions.map(function(tx){return tx.toBuffer()});return Buffer.concat([buffer,txLenBuffer].concat(txBuffers))};Block.prototype.toHex=function(headersOnly){return this.toBuffer(headersOnly).toString("hex")};Block.calculateTarget=function(bits){var exponent=((bits&4278190080)>>24)-3;var mantissa=bits&8388607;var i=31-exponent;var target=new Buffer(32);target.fill(0);target[i]=mantissa&255;target[i-1]=mantissa>>8;target[i-2]=mantissa>>16;target[i-3]=mantissa>>24;return target};Block.prototype.checkProofOfWork=function(){var hash=[].reverse.call(this.getHash());var target=Block.calculateTarget(this.bits);return compare(hash,target)<=0};module.exports=Block}).call(this,require("buffer").Buffer)},{"./bufferutils":35,"./crypto":36,"./transaction":46,buffer:"buffer","buffer-compare":7}],35:[function(require,module,exports){(function(Buffer){var opcodes=require("./opcodes");function verifuint(value,max){if(typeof value!=="number")throw new Error("cannot write a non-number as a number");if(value<0)throw new Error("specified a negative value for writing an unsigned value");if(value>max)throw new Error("value is larger than maximum value for type");if(Math.floor(value)!==value)throw new Error("value has a fractional component")}function pushDataSize(i){return i<opcodes.OP_PUSHDATA1?1:i<255?2:i<65535?3:5}function readPushDataInt(buffer,offset){var opcode=buffer.readUInt8(offset);var number,size;if(opcode<opcodes.OP_PUSHDATA1){number=opcode;size=1}else if(opcode===opcodes.OP_PUSHDATA1){if(offset+2>buffer.length)return null;number=buffer.readUInt8(offset+1);size=2}else if(opcode===opcodes.OP_PUSHDATA2){if(offset+3>buffer.length)return null;number=buffer.readUInt16LE(offset+1);size=3}else{if(offset+5>buffer.length)return null;if(opcode!==opcodes.OP_PUSHDATA4)throw new Error("Unexpected opcode");number=buffer.readUInt32LE(offset+1);size=5}return{opcode:opcode,number:number,size:size}}function readUInt64LE(buffer,offset){var a=buffer.readUInt32LE(offset);var b=buffer.readUInt32LE(offset+4);b*=4294967296;verifuint(b+a,9007199254740991);return b+a}function readVarInt(buffer,offset){var t=buffer.readUInt8(offset);var number,size;if(t<253){number=t;size=1}else if(t<254){number=buffer.readUInt16LE(offset+1);size=3}else if(t<255){number=buffer.readUInt32LE(offset+1);size=5}else{number=readUInt64LE(buffer,offset+1);size=9}return{number:number,size:size}}function writePushDataInt(buffer,number,offset){var size=pushDataSize(number);if(size===1){buffer.writeUInt8(number,offset)}else if(size===2){buffer.writeUInt8(opcodes.OP_PUSHDATA1,offset);buffer.writeUInt8(number,offset+1)}else if(size===3){buffer.writeUInt8(opcodes.OP_PUSHDATA2,offset);buffer.writeUInt16LE(number,offset+1)}else{buffer.writeUInt8(opcodes.OP_PUSHDATA4,offset);buffer.writeUInt32LE(number,offset+1)}return size}function writeUInt64LE(buffer,value,offset){verifuint(value,9007199254740991);buffer.writeInt32LE(value&-1,offset);buffer.writeUInt32LE(Math.floor(value/4294967296),offset+4)}function varIntSize(i){return i<253?1:i<65536?3:i<4294967296?5:9}function writeVarInt(buffer,number,offset){var size=varIntSize(number);if(size===1){buffer.writeUInt8(number,offset)}else if(size===3){buffer.writeUInt8(253,offset);buffer.writeUInt16LE(number,offset+1)}else if(size===5){buffer.writeUInt8(254,offset);buffer.writeUInt32LE(number,offset+1)}else{buffer.writeUInt8(255,offset);writeUInt64LE(buffer,number,offset+1)}return size}function varIntBuffer(i){var size=varIntSize(i);var buffer=new Buffer(size);writeVarInt(buffer,i,0);return buffer}module.exports={equal:require("buffer-equals"),pushDataSize:pushDataSize,readPushDataInt:readPushDataInt,readUInt64LE:readUInt64LE,readVarInt:readVarInt,reverse:require("buffer-reverse"),varIntBuffer:varIntBuffer,varIntSize:varIntSize,writePushDataInt:writePushDataInt,writeUInt64LE:writeUInt64LE,writeVarInt:writeVarInt}}).call(this,require("buffer").Buffer)},{"./opcodes":43,buffer:"buffer","buffer-equals":8,"buffer-reverse":9}],36:[function(require,module,exports){var createHash=require("create-hash");function hash160(buffer){return ripemd160(sha256(buffer))}function hash256(buffer){return sha256(sha256(buffer))}function ripemd160(buffer){return createHash("rmd160").update(buffer).digest()}function sha1(buffer){return createHash("sha1").update(buffer).digest()}function sha256(buffer){return createHash("sha256").update(buffer).digest()}module.exports={hash160:hash160,hash256:hash256,ripemd160:ripemd160,sha1:sha1,sha256:sha256}},{"create-hash":10}],37:[function(require,module,exports){(function(Buffer){var createHmac=require("create-hmac");var typeforce=require("typeforce");var types=require("./types");var BigInteger=require("bigi");var ECSignature=require("./ecsignature");var ZERO=new Buffer([0]);var ONE=new Buffer([1]);var ecurve=require("ecurve");var secp256k1=ecurve.getCurveByName("secp256k1");function deterministicGenerateK(hash,x,checkSig){typeforce(types.tuple(types.Hash256bit,types.Buffer256bit,types.Function),arguments);var k=new Buffer(32);var v=new Buffer(32);v.fill(1);k.fill(0);k=createHmac("sha256",k).update(v).update(ZERO).update(x).update(hash).digest();v=createHmac("sha256",k).update(v).digest();k=createHmac("sha256",k).update(v).update(ONE).update(x).update(hash).digest();v=createHmac("sha256",k).update(v).digest();v=createHmac("sha256",k).update(v).digest();var T=BigInteger.fromBuffer(v);while(T.signum()<=0||T.compareTo(secp256k1.n)>=0||!checkSig(T)){k=createHmac("sha256",k).update(v).update(ZERO).digest();v=createHmac("sha256",k).update(v).digest();v=createHmac("sha256",k).update(v).digest();T=BigInteger.fromBuffer(v)}return T}var N_OVER_TWO=secp256k1.n.shiftRight(1);function sign(hash,d){typeforce(types.tuple(types.Hash256bit,types.BigInt),arguments);var x=d.toBuffer(32);var e=BigInteger.fromBuffer(hash);var n=secp256k1.n;var G=secp256k1.G;var r,s;deterministicGenerateK(hash,x,function(k){var Q=G.multiply(k);if(secp256k1.isInfinity(Q))return false;r=Q.affineX.mod(n);if(r.signum()===0)return false;s=k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n);if(s.signum()===0)return false;return true});if(s.compareTo(N_OVER_TWO)>0){s=n.subtract(s)}return new ECSignature(r,s)}function verify(hash,signature,Q){typeforce(types.tuple(types.Hash256bit,types.ECSignature,types.ECPoint),arguments);var n=secp256k1.n;var G=secp256k1.G;var r=signature.r;var s=signature.s;if(r.signum()<=0||r.compareTo(n)>=0)return false;if(s.signum()<=0||s.compareTo(n)>=0)return false;var e=BigInteger.fromBuffer(hash);var sInv=s.modInverse(n);var u1=e.multiply(sInv).mod(n);var u2=r.multiply(sInv).mod(n);var R=G.multiplyTwo(u1,Q,u2);if(secp256k1.isInfinity(R))return false;var xR=R.affineX;var v=xR.mod(n);return v.equals(r)}function recoverPubKey(e,signature,i){typeforce(types.tuple(types.BigInt,types.ECSignature,types.UInt2),arguments);var n=secp256k1.n;var G=secp256k1.G;var r=signature.r;var s=signature.s;if(r.signum()<=0||r.compareTo(n)>=0)throw new Error("Invalid r value");if(s.signum()<=0||s.compareTo(n)>=0)throw new Error("Invalid s value");var isYOdd=i&1;var isSecondKey=i>>1;var x=isSecondKey?r.add(n):r;var R=secp256k1.pointFromX(isYOdd,x);var nR=R.multiply(n);if(!secp256k1.isInfinity(nR))throw new Error("nR is not a valid curve point");var rInv=r.modInverse(n);var eNeg=e.negate().mod(n);var Q=R.multiplyTwo(s,G,eNeg).multiply(rInv);secp256k1.validate(Q);return Q}function calcPubKeyRecoveryParam(e,signature,Q){typeforce(types.tuple(types.BigInt,types.ECSignature,types.ECPoint),arguments);for(var i=0;i<4;i++){var Qprime=recoverPubKey(e,signature,i);if(Qprime.equals(Q)){return i}}throw new Error("Unable to find valid recovery factor")}module.exports={calcPubKeyRecoveryParam:calcPubKeyRecoveryParam,deterministicGenerateK:deterministicGenerateK,recoverPubKey:recoverPubKey,sign:sign,verify:verify,__curve:secp256k1}}).call(this,require("buffer").Buffer)},{"./ecsignature":39,"./types":48,bigi:"bigi",buffer:"buffer","create-hmac":24,ecurve:"ecurve",typeforce:30}],38:[function(require,module,exports){(function(Buffer){var bcrypto=require("./crypto");var bs58check=require("bs58check");var ecdsa=require("./ecdsa");var randomBytes=require("randombytes");var typeforce=require("typeforce");var types=require("./types");var wif=require("wif");var NETWORKS=require("./networks");var BigInteger=require("bigi");var ecurve=require("ecurve");var secp256k1=ecdsa.__curve;function ECPair(d,Q,options){if(options){typeforce({compressed:types.maybe(types.Boolean),network:types.maybe(types.Network)},options)}options=options||{};if(d){if(d.signum()<=0)throw new Error("Private key must be greater than 0");if(d.compareTo(secp256k1.n)>=0)throw new Error("Private key must be less than the curve order");if(Q)throw new TypeError("Unexpected publicKey parameter");this.d=d}else{typeforce(types.ECPoint,Q);this.__Q=Q}this.compressed=options.compressed===undefined?true:options.compressed;this.network=options.network||NETWORKS.bitcoin}Object.defineProperty(ECPair.prototype,"Q",{get:function(){if(!this.__Q&&this.d){this.__Q=secp256k1.G.multiply(this.d)}return this.__Q}});ECPair.fromPublicKeyBuffer=function(buffer,network){var Q=ecurve.Point.decodeFrom(secp256k1,buffer);return new ECPair(null,Q,{compressed:Q.compressed,network:network})};ECPair.fromWIF=function(string,network){network=network||NETWORKS.bitcoin;var buffer=bs58check.decode(string);if(types.Array(network)){var version=buffer[0];network=network.filter(function(network){return version===network.wif}).pop()||{}}var decoded=wif.decodeRaw(network.wif,buffer);var d=BigInteger.fromBuffer(decoded.d);return new ECPair(d,null,{compressed:decoded.compressed,network:network})};ECPair.makeRandom=function(options){options=options||{};var rng=options.rng||randomBytes;var d;do{var buffer=rng(32);typeforce(types.Buffer256bit,buffer);d=BigInteger.fromBuffer(buffer)}while(d.signum()<=0||d.compareTo(secp256k1.n)>=0);return new ECPair(d,null,options)};ECPair.prototype.getAddress=function(){var pubKey=this.getPublicKeyBuffer();var pubKeyHash=bcrypto.hash160(pubKey);var payload=new Buffer(21);payload.writeUInt8(this.network.pubKeyHash,0);pubKeyHash.copy(payload,1);return bs58check.encode(payload)};ECPair.prototype.getNetwork=function(){return this.network};ECPair.prototype.getPublicKeyBuffer=function(){return this.Q.getEncoded(this.compressed)};ECPair.prototype.sign=function(hash){if(!this.d)throw new Error("Missing private key");return ecdsa.sign(hash,this.d)};ECPair.prototype.toWIF=function(){if(!this.d)throw new Error("Missing private key");return wif.encode(this.network.wif,this.d.toBuffer(32),this.compressed)};ECPair.prototype.verify=function(hash,signature){return ecdsa.verify(hash,signature,this.Q)};module.exports=ECPair}).call(this,require("buffer").Buffer)},{"./crypto":36,"./ecdsa":37,"./networks":42,"./types":48,bigi:"bigi",bs58check:5,buffer:"buffer",ecurve:"ecurve",randombytes:"randombytes",typeforce:30,wif:32}],39:[function(require,module,exports){(function(Buffer){var bip66=require("bip66");var typeforce=require("typeforce");var types=require("./types");var BigInteger=require("bigi");function ECSignature(r,s){typeforce(types.tuple(types.BigInt,types.BigInt),arguments);this.r=r;this.s=s}ECSignature.parseCompact=function(buffer){if(buffer.length!==65)throw new Error("Invalid signature length");var flagByte=buffer.readUInt8(0)-27;if(flagByte!==(flagByte&7))throw new Error("Invalid signature parameter");var compressed=!!(flagByte&4);var recoveryParam=flagByte&3;var r=BigInteger.fromBuffer(buffer.slice(1,33));var s=BigInteger.fromBuffer(buffer.slice(33));return{compressed:compressed,i:recoveryParam,signature:new ECSignature(r,s)}};ECSignature.fromDER=function(buffer){var decode=bip66.decode(buffer);var r=BigInteger.fromDERInteger(decode.r);var s=BigInteger.fromDERInteger(decode.s);return new ECSignature(r,s)};ECSignature.parseScriptSignature=function(buffer){var hashType=buffer.readUInt8(buffer.length-1);var hashTypeMod=hashType&~128;if(hashTypeMod<=0||hashTypeMod>=4)throw new Error("Invalid hashType "+hashType);return{signature:ECSignature.fromDER(buffer.slice(0,-1)),hashType:hashType}};ECSignature.prototype.toCompact=function(i,compressed){if(compressed){i+=4}i+=27;var buffer=new Buffer(65);buffer.writeUInt8(i,0);this.r.toBuffer(32).copy(buffer,1);this.s.toBuffer(32).copy(buffer,33);return buffer};ECSignature.prototype.toDER=function(){var r=new Buffer(this.r.toDERInteger());var s=new Buffer(this.s.toDERInteger());return bip66.encode(r,s)};ECSignature.prototype.toScriptSignature=function(hashType){var hashTypeMod=hashType&~128;if(hashTypeMod<=0||hashTypeMod>=4)throw new Error("Invalid hashType "+hashType);var hashTypeBuffer=new Buffer(1);hashTypeBuffer.writeUInt8(hashType,0);return Buffer.concat([this.toDER(),hashTypeBuffer])};module.exports=ECSignature}).call(this,require("buffer").Buffer)},{"./types":48,bigi:"bigi",bip66:4,buffer:"buffer",typeforce:30}],40:[function(require,module,exports){(function(Buffer){var base58check=require("bs58check");var bcrypto=require("./crypto");var createHmac=require("create-hmac");var typeforce=require("typeforce");var types=require("./types");var NETWORKS=require("./networks");var BigInteger=require("bigi");var ECPair=require("./ecpair");var ecurve=require("ecurve");var curve=ecurve.getCurveByName("secp256k1");function HDNode(keyPair,chainCode){typeforce(types.tuple("ECPair",types.Buffer256bit),arguments);if(!keyPair.compressed)throw new TypeError("BIP32 only allows compressed keyPairs");this.keyPair=keyPair;this.chainCode=chainCode;this.depth=0;this.index=0;this.parentFingerprint=0}HDNode.HIGHEST_BIT=2147483648;HDNode.LENGTH=78;HDNode.MASTER_SECRET=new Buffer("Bitcoin seed");HDNode.fromSeedBuffer=function(seed,network){typeforce(types.tuple(types.Buffer,types.maybe(types.Network)),arguments);if(seed.length<16)throw new TypeError("Seed should be at least 128 bits");if(seed.length>64)throw new TypeError("Seed should be at most 512 bits");var I=createHmac("sha512",HDNode.MASTER_SECRET).update(seed).digest();var IL=I.slice(0,32);var IR=I.slice(32);var pIL=BigInteger.fromBuffer(IL);var keyPair=new ECPair(pIL,null,{network:network});return new HDNode(keyPair,IR)};HDNode.fromSeedHex=function(hex,network){return HDNode.fromSeedBuffer(new Buffer(hex,"hex"),network)};HDNode.fromBase58=function(string,networks){var buffer=base58check.decode(string);if(buffer.length!==78)throw new Error("Invalid buffer length");var version=buffer.readUInt32BE(0);var network;if(Array.isArray(networks)){network=networks.filter(function(network){return version===network.bip32.private||version===network.bip32.public}).pop()||{}}else{network=networks||NETWORKS.bitcoin}if(version!==network.bip32.private&&version!==network.bip32.public)throw new Error("Invalid network");var depth=buffer[4];var parentFingerprint=buffer.readUInt32BE(5);if(depth===0){if(parentFingerprint!==0)throw new Error("Invalid parent fingerprint")}var index=buffer.readUInt32BE(9);if(depth===0&&index!==0)throw new Error("Invalid index");var chainCode=buffer.slice(13,45);var keyPair;if(version===network.bip32.private){if(buffer.readUInt8(45)!==0)throw new Error("Invalid private key");var d=BigInteger.fromBuffer(buffer.slice(46,78));keyPair=new ECPair(d,null,{network:network})}else{var Q=ecurve.Point.decodeFrom(curve,buffer.slice(45,78));if(!Q.compressed)throw new Error("Invalid public key");curve.validate(Q);keyPair=new ECPair(null,Q,{network:network})}var hd=new HDNode(keyPair,chainCode);hd.depth=depth;hd.index=index;hd.parentFingerprint=parentFingerprint;return hd};HDNode.prototype.getAddress=function(){return this.keyPair.getAddress()};HDNode.prototype.getIdentifier=function(){return bcrypto.hash160(this.keyPair.getPublicKeyBuffer())};HDNode.prototype.getFingerprint=function(){return this.getIdentifier().slice(0,4)};HDNode.prototype.getNetwork=function(){return this.keyPair.getNetwork()};HDNode.prototype.getPublicKeyBuffer=function(){return this.keyPair.getPublicKeyBuffer()};HDNode.prototype.neutered=function(){var neuteredKeyPair=new ECPair(null,this.keyPair.Q,{network:this.keyPair.network});var neutered=new HDNode(neuteredKeyPair,this.chainCode);neutered.depth=this.depth;neutered.index=this.index;neutered.parentFingerprint=this.parentFingerprint;return neutered};HDNode.prototype.sign=function(hash){return this.keyPair.sign(hash)};HDNode.prototype.verify=function(hash,signature){return this.keyPair.verify(hash,signature)};HDNode.prototype.toBase58=function(__isPrivate){if(__isPrivate!==undefined)throw new TypeError("Unsupported argument in 2.0.0");var network=this.keyPair.network;var version=this.keyPair.d?network.bip32.private:network.bip32.public;var buffer=new Buffer(78);buffer.writeUInt32BE(version,0);buffer.writeUInt8(this.depth,4);buffer.writeUInt32BE(this.parentFingerprint,5);buffer.writeUInt32BE(this.index,9);this.chainCode.copy(buffer,13);if(this.keyPair.d){buffer.writeUInt8(0,45);this.keyPair.d.toBuffer(32).copy(buffer,46)}else{this.keyPair.getPublicKeyBuffer().copy(buffer,45)}return base58check.encode(buffer)};HDNode.prototype.derive=function(index){var isHardened=index>=HDNode.HIGHEST_BIT;var data=new Buffer(37);if(isHardened){if(!this.keyPair.d)throw new TypeError("Could not derive hardened child key");data[0]=0;this.keyPair.d.toBuffer(32).copy(data,1);data.writeUInt32BE(index,33)}else{this.keyPair.getPublicKeyBuffer().copy(data,0);data.writeUInt32BE(index,33)}var I=createHmac("sha512",this.chainCode).update(data).digest();var IL=I.slice(0,32);var IR=I.slice(32);var pIL=BigInteger.fromBuffer(IL);if(pIL.compareTo(curve.n)>=0){return this.derive(index+1)}var derivedKeyPair;if(this.keyPair.d){var ki=pIL.add(this.keyPair.d).mod(curve.n);if(ki.signum()===0){return this.derive(index+1)}derivedKeyPair=new ECPair(ki,null,{network:this.keyPair.network})}else{var Ki=curve.G.multiply(pIL).add(this.keyPair.Q);if(curve.isInfinity(Ki)){return this.derive(index+1) }derivedKeyPair=new ECPair(null,Ki,{network:this.keyPair.network})}var hd=new HDNode(derivedKeyPair,IR);hd.depth=this.depth+1;hd.index=index;hd.parentFingerprint=this.getFingerprint().readUInt32BE(0);return hd};HDNode.prototype.deriveHardened=function(index){return this.derive(index+HDNode.HIGHEST_BIT)};HDNode.prototype.toString=HDNode.prototype.toBase58;module.exports=HDNode}).call(this,require("buffer").Buffer)},{"./crypto":36,"./ecpair":38,"./networks":42,"./types":48,bigi:"bigi",bs58check:5,buffer:"buffer","create-hmac":24,ecurve:"ecurve",typeforce:30}],41:[function(require,module,exports){(function(Buffer){var bufferutils=require("./bufferutils");var bcrypto=require("./crypto");var ecdsa=require("./ecdsa");var networks=require("./networks");var BigInteger=require("bigi");var ECPair=require("./ecpair");var ECSignature=require("./ecsignature");function magicHash(message,network){var messagePrefix=new Buffer(network.messagePrefix);var messageBuffer=new Buffer(message);var lengthBuffer=bufferutils.varIntBuffer(messageBuffer.length);var buffer=Buffer.concat([messagePrefix,lengthBuffer,messageBuffer]);return bcrypto.hash256(buffer)}function sign(keyPair,message,network){network=network||networks.bitcoin;var hash=magicHash(message,network);var signature=keyPair.sign(hash);var e=BigInteger.fromBuffer(hash);var i=ecdsa.calcPubKeyRecoveryParam(e,signature,keyPair.Q);return signature.toCompact(i,keyPair.compressed)}function verify(address,signature,message,network){if(!Buffer.isBuffer(signature)){signature=new Buffer(signature,"base64")}network=network||networks.bitcoin;var hash=magicHash(message,network);var parsed=ECSignature.parseCompact(signature);var e=BigInteger.fromBuffer(hash);var Q=ecdsa.recoverPubKey(e,parsed.signature,parsed.i);var keyPair=new ECPair(null,Q,{compressed:parsed.compressed,network:network});return keyPair.getAddress()===address}module.exports={magicHash:magicHash,sign:sign,verify:verify}}).call(this,require("buffer").Buffer)},{"./bufferutils":35,"./crypto":36,"./ecdsa":37,"./ecpair":38,"./ecsignature":39,"./networks":42,bigi:"bigi",buffer:"buffer"}],42:[function(require,module,exports){module.exports={bitcoin:{messagePrefix:"Bitcoin Signed Message:\n",bip32:{"public":76067358,"private":76066276},pubKeyHash:0,scriptHash:5,wif:128,dustThreshold:546},testnet:{messagePrefix:"Bitcoin Signed Message:\n",bip32:{"public":70617039,"private":70615956},pubKeyHash:111,scriptHash:196,wif:239,dustThreshold:546},litecoin:{messagePrefix:"Litecoin Signed Message:\n",bip32:{"public":27108450,"private":27106558},pubKeyHash:48,scriptHash:5,wif:176,dustThreshold:0},dogecoin:{messagePrefix:"Dogecoin Signed Message:\n",bip32:{"public":49990397,"private":49988504},pubKeyHash:30,scriptHash:22,wif:158,dustThreshold:0}}},{}],43:[function(require,module,exports){module.exports={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_1:81,OP_TRUE:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255}},{}],44:[function(require,module,exports){(function(Buffer){var bip66=require("bip66");var bufferutils=require("./bufferutils");var typeforce=require("typeforce");var types=require("./types");var OPS=require("./opcodes");var REVERSE_OPS=function(){var result={};for(var op in OPS){var code=OPS[op];result[code]=op}return result}();var OP_INT_BASE=OPS.OP_RESERVED;function toASM(chunks){if(Buffer.isBuffer(chunks)){chunks=decompile(chunks)}return chunks.map(function(chunk){if(Buffer.isBuffer(chunk))return chunk.toString("hex");return REVERSE_OPS[chunk]}).join(" ")}function fromASM(asm){typeforce(types.String,asm);return compile(asm.split(" ").map(function(chunkStr){if(OPS[chunkStr]!==undefined)return OPS[chunkStr];return new Buffer(chunkStr,"hex")}))}function compile(chunks){if(Buffer.isBuffer(chunks))return chunks;typeforce(types.Array,chunks);var bufferSize=chunks.reduce(function(accum,chunk){if(Buffer.isBuffer(chunk)){return accum+bufferutils.pushDataSize(chunk.length)+chunk.length}return accum+1},0);var buffer=new Buffer(bufferSize);var offset=0;chunks.forEach(function(chunk){if(Buffer.isBuffer(chunk)){offset+=bufferutils.writePushDataInt(buffer,chunk.length,offset);chunk.copy(buffer,offset);offset+=chunk.length}else{buffer.writeUInt8(chunk,offset);offset+=1}});if(offset!==buffer.length)throw new Error("Could not decode chunks");return buffer}function decompile(buffer){if(types.Array(buffer))return buffer;typeforce(types.Buffer,buffer);var chunks=[];var i=0;while(i<buffer.length){var opcode=buffer[i];if(opcode>OPS.OP_0&&opcode<=OPS.OP_PUSHDATA4){var d=bufferutils.readPushDataInt(buffer,i);if(d===null)return[];i+=d.size;if(i+d.number>buffer.length)return[];var data=buffer.slice(i,i+d.number);i+=d.number;chunks.push(data)}else{chunks.push(opcode);i+=1}}return chunks}function isCanonicalPubKey(buffer){if(!Buffer.isBuffer(buffer))return false;if(buffer.length<33)return false;switch(buffer[0]){case 2:case 3:return buffer.length===33;case 4:return buffer.length===65}return false}function isCanonicalSignature(buffer){if(!Buffer.isBuffer(buffer))return false;if(!isDefinedHashType(buffer[buffer.length-1]))return false;return bip66.check(buffer.slice(0,-1))}function isDefinedHashType(hashType){var hashTypeMod=hashType&~128;return hashTypeMod>0&&hashTypeMod<4}function isPubKeyHashInput(script){var chunks=decompile(script);return chunks.length===2&&isCanonicalSignature(chunks[0])&&isCanonicalPubKey(chunks[1])}function isPubKeyHashOutput(script){var buffer=compile(script);return buffer.length===25&&buffer[0]===OPS.OP_DUP&&buffer[1]===OPS.OP_HASH160&&buffer[2]===20&&buffer[23]===OPS.OP_EQUALVERIFY&&buffer[24]===OPS.OP_CHECKSIG}function isPubKeyInput(script){var chunks=decompile(script);return chunks.length===1&&isCanonicalSignature(chunks[0])}function isPubKeyOutput(script){var chunks=decompile(script);return chunks.length===2&&isCanonicalPubKey(chunks[0])&&chunks[1]===OPS.OP_CHECKSIG}function isScriptHashInput(script,allowIncomplete){var chunks=decompile(script);if(chunks.length<2)return false;var lastChunk=chunks[chunks.length-1];if(!Buffer.isBuffer(lastChunk))return false;var scriptSigChunks=chunks.slice(0,-1);var redeemScriptChunks=decompile(lastChunk);if(redeemScriptChunks.length===0)return false;return classifyInput(scriptSigChunks,allowIncomplete)===classifyOutput(redeemScriptChunks)}function isScriptHashOutput(script){var buffer=compile(script);return buffer.length===23&&buffer[0]===OPS.OP_HASH160&&buffer[1]===20&&buffer[22]===OPS.OP_EQUAL}function isMultisigInput(script,allowIncomplete){var chunks=decompile(script);if(chunks.length<2)return false;if(chunks[0]!==OPS.OP_0)return false;if(allowIncomplete){return chunks.slice(1).every(function(chunk){return chunk===OPS.OP_0||isCanonicalSignature(chunk)})}return chunks.slice(1).every(isCanonicalSignature)}function isMultisigOutput(script){var chunks=decompile(script);if(chunks.length<4)return false;if(chunks[chunks.length-1]!==OPS.OP_CHECKMULTISIG)return false;var mOp=chunks[0];var nOp=chunks[chunks.length-2];if(!types.Number(mOp))return false;if(!types.Number(nOp))return false;var m=mOp-OP_INT_BASE;var n=nOp-OP_INT_BASE;if(m<=0)return false;if(m>n)return false;if(n>16)return false;if(n!==chunks.length-3)return false;return chunks.slice(1,-2).every(isCanonicalPubKey)}function isNullDataOutput(script){var chunks=decompile(script);return chunks[0]===OPS.OP_RETURN}function classifyOutput(script){var chunks=decompile(script);if(isPubKeyHashOutput(chunks)){return"pubkeyhash"}else if(isScriptHashOutput(chunks)){return"scripthash"}else if(isMultisigOutput(chunks)){return"multisig"}else if(isPubKeyOutput(chunks)){return"pubkey"}else if(isNullDataOutput(chunks)){return"nulldata"}return"nonstandard"}function classifyInput(script,allowIncomplete){var chunks=decompile(script);if(isPubKeyHashInput(chunks)){return"pubkeyhash"}else if(isMultisigInput(chunks,allowIncomplete)){return"multisig"}else if(isScriptHashInput(chunks,allowIncomplete)){return"scripthash"}else if(isPubKeyInput(chunks)){return"pubkey"}return"nonstandard"}function pubKeyOutput(pubKey){return compile([pubKey,OPS.OP_CHECKSIG])}function pubKeyHashOutput(pubKeyHash){typeforce(types.Hash160bit,pubKeyHash);return compile([OPS.OP_DUP,OPS.OP_HASH160,pubKeyHash,OPS.OP_EQUALVERIFY,OPS.OP_CHECKSIG])}function scriptHashOutput(scriptHash){typeforce(types.Hash160bit,scriptHash);return compile([OPS.OP_HASH160,scriptHash,OPS.OP_EQUAL])}function multisigOutput(m,pubKeys){typeforce(types.tuple(types.Number,[types.Buffer]),arguments);var n=pubKeys.length;if(n<m)throw new Error("Not enough pubKeys provided");return compile([].concat(OP_INT_BASE+m,pubKeys,OP_INT_BASE+n,OPS.OP_CHECKMULTISIG))}function pubKeyInput(signature){typeforce(types.Buffer,signature);return compile([signature])}function pubKeyHashInput(signature,pubKey){typeforce(types.tuple(types.Buffer,types.Buffer),arguments);return compile([signature,pubKey])}function scriptHashInput(scriptSig,scriptPubKey){var scriptSigChunks=decompile(scriptSig);var serializedScriptPubKey=compile(scriptPubKey);return compile([].concat(scriptSigChunks,serializedScriptPubKey))}function multisigInput(signatures,scriptPubKey){if(scriptPubKey){var chunks=decompile(scriptPubKey);if(!isMultisigOutput(chunks))throw new Error("Expected multisig scriptPubKey");var mOp=chunks[0];var nOp=chunks[chunks.length-2];var m=mOp-OP_INT_BASE;var n=nOp-OP_INT_BASE;if(signatures.length<m)throw new Error("Not enough signatures provided");if(signatures.length>n)throw new Error("Too many signatures provided")}return compile([].concat(OPS.OP_0,signatures))}function nullDataOutput(data){return compile([OPS.OP_RETURN,data])}module.exports={compile:compile,decompile:decompile,fromASM:fromASM,toASM:toASM,number:require("./script_number"),isCanonicalPubKey:isCanonicalPubKey,isCanonicalSignature:isCanonicalSignature,isDefinedHashType:isDefinedHashType,isPubKeyHashInput:isPubKeyHashInput,isPubKeyHashOutput:isPubKeyHashOutput,isPubKeyInput:isPubKeyInput,isPubKeyOutput:isPubKeyOutput,isScriptHashInput:isScriptHashInput,isScriptHashOutput:isScriptHashOutput,isMultisigInput:isMultisigInput,isMultisigOutput:isMultisigOutput,isNullDataOutput:isNullDataOutput,classifyOutput:classifyOutput,classifyInput:classifyInput,pubKeyOutput:pubKeyOutput,pubKeyHashOutput:pubKeyHashOutput,scriptHashOutput:scriptHashOutput,multisigOutput:multisigOutput,pubKeyInput:pubKeyInput,pubKeyHashInput:pubKeyHashInput,scriptHashInput:scriptHashInput,multisigInput:multisigInput,nullDataOutput:nullDataOutput}}).call(this,require("buffer").Buffer)},{"./bufferutils":35,"./opcodes":43,"./script_number":45,"./types":48,bip66:4,buffer:"buffer",typeforce:30}],45:[function(require,module,exports){(function(Buffer){function decode(buffer,maxLength,minimal){maxLength=maxLength||4;minimal=minimal===undefined?true:minimal;var length=buffer.length;if(length===0)return 0;if(length>maxLength)throw new TypeError("Script number overflow");if(minimal){if((buffer[length-1]&127)===0){if(length<=1||(buffer[length-2]&128)===0)throw new Error("Non-minimally encoded script number")}}if(length===5){var a=buffer.readUInt32LE(0);var b=buffer.readUInt8(4);if(b&128)return-((b&~128)*4294967296+a);return b*4294967296+a}var result=0;for(var i=0;i<length;++i){result|=buffer[i]<<8*i}if(buffer[length-1]&128)return-(result&~(128<<8*(length-1)));return result}function scriptNumSize(i){return i>2147483647?5:i>8388607?4:i>32767?3:i>127?2:i>0?1:0}function encode(number){var value=Math.abs(number);var size=scriptNumSize(value);var buffer=new Buffer(size);var negative=number<0;for(var i=0;i<size;++i){buffer.writeUInt8(value&255,i);value>>=8}if(buffer[size-1]&128){buffer.writeUInt8(negative?128:0,size-1)}else if(negative){buffer[size-1]|=128}return buffer}module.exports={decode:decode,encode:encode}}).call(this,require("buffer").Buffer)},{buffer:"buffer"}],46:[function(require,module,exports){(function(Buffer){var bcrypto=require("./crypto");var bscript=require("./script");var bufferutils=require("./bufferutils");var opcodes=require("./opcodes");var typeforce=require("typeforce");var types=require("./types");function Transaction(){this.version=1;this.locktime=0;this.ins=[];this.outs=[]}Transaction.DEFAULT_SEQUENCE=4294967295;Transaction.SIGHASH_ALL=1;Transaction.SIGHASH_NONE=2;Transaction.SIGHASH_SINGLE=3;Transaction.SIGHASH_ANYONECANPAY=128;Transaction.fromBuffer=function(buffer,__noStrict){var offset=0;function readSlice(n){offset+=n;return buffer.slice(offset-n,offset)}function readUInt32(){var i=buffer.readUInt32LE(offset);offset+=4;return i}function readUInt64(){var i=bufferutils.readUInt64LE(buffer,offset);offset+=8;return i}function readVarInt(){var vi=bufferutils.readVarInt(buffer,offset);offset+=vi.size;return vi.number}function readScript(){return readSlice(readVarInt())}var tx=new Transaction;tx.version=readUInt32();var vinLen=readVarInt();for(var i=0;i<vinLen;++i){tx.ins.push({hash:readSlice(32),index:readUInt32(),script:readScript(),sequence:readUInt32()})}var voutLen=readVarInt();for(i=0;i<voutLen;++i){tx.outs.push({value:readUInt64(),script:readScript()})}tx.locktime=readUInt32();if(__noStrict)return tx;if(offset!==buffer.length)throw new Error("Transaction has unexpected data");return tx};Transaction.fromHex=function(hex){return Transaction.fromBuffer(new Buffer(hex,"hex"))};Transaction.isCoinbaseHash=function(buffer){return Array.prototype.every.call(buffer,function(x){return x===0})};var EMPTY_SCRIPT=new Buffer(0);Transaction.prototype.addInput=function(hash,index,sequence,scriptSig){typeforce(types.tuple(types.Hash256bit,types.UInt32,types.maybe(types.UInt32),types.maybe(types.Buffer)),arguments);if(types.Null(sequence)){sequence=Transaction.DEFAULT_SEQUENCE}return this.ins.push({hash:hash,index:index,script:scriptSig||EMPTY_SCRIPT,sequence:sequence})-1};Transaction.prototype.addOutput=function(scriptPubKey,value){typeforce(types.tuple(types.Buffer,types.UInt53),arguments);return this.outs.push({script:scriptPubKey,value:value})-1};Transaction.prototype.byteLength=function(){function scriptSize(someScript){var length=someScript.length;return bufferutils.varIntSize(length)+length}return 8+bufferutils.varIntSize(this.ins.length)+bufferutils.varIntSize(this.outs.length)+this.ins.reduce(function(sum,input){return sum+40+scriptSize(input.script)},0)+this.outs.reduce(function(sum,output){return sum+8+scriptSize(output.script)},0)};Transaction.prototype.clone=function(){var newTx=new Transaction;newTx.version=this.version;newTx.locktime=this.locktime;newTx.ins=this.ins.map(function(txIn){return{hash:txIn.hash,index:txIn.index,script:txIn.script,sequence:txIn.sequence}});newTx.outs=this.outs.map(function(txOut){return{script:txOut.script,value:txOut.value}});return newTx};var ONE=new Buffer("0000000000000000000000000000000000000000000000000000000000000001","hex");var VALUE_UINT64_MAX=new Buffer("ffffffffffffffff","hex");Transaction.prototype.hashForSignature=function(inIndex,prevOutScript,hashType){typeforce(types.tuple(types.UInt32,types.Buffer,types.Number),arguments);if(inIndex>=this.ins.length)return ONE;var txTmp=this.clone();var hashScript=bscript.compile(bscript.decompile(prevOutScript).filter(function(x){return x!==opcodes.OP_CODESEPARATOR}));var i;txTmp.ins.forEach(function(input){input.script=EMPTY_SCRIPT});txTmp.ins[inIndex].script=hashScript;if((hashType&31)===Transaction.SIGHASH_NONE){txTmp.outs=[];txTmp.ins.forEach(function(input,i){if(i!==inIndex){input.sequence=0}})}else if((hashType&31)===Transaction.SIGHASH_SINGLE){var nOut=inIndex;if(nOut>=this.outs.length)return ONE;txTmp.outs=txTmp.outs.slice(0,nOut+1);var stubOut={script:EMPTY_SCRIPT,valueBuffer:VALUE_UINT64_MAX};for(i=0;i<nOut;i++){txTmp.outs[i]=stubOut}txTmp.ins.forEach(function(input,i){if(i!==inIndex){input.sequence=0}})}if(hashType&Transaction.SIGHASH_ANYONECANPAY){txTmp.ins[0]=txTmp.ins[inIndex];txTmp.ins=txTmp.ins.slice(0,1)}var buffer=new Buffer(txTmp.byteLength()+4);buffer.writeInt32LE(hashType,buffer.length-4);txTmp.toBuffer().copy(buffer,0);return bcrypto.hash256(buffer)};Transaction.prototype.getHash=function(){return bcrypto.hash256(this.toBuffer())};Transaction.prototype.getId=function(){return[].reverse.call(this.getHash()).toString("hex")};Transaction.prototype.toBuffer=function(){var buffer=new Buffer(this.byteLength());var offset=0;function writeSlice(slice){slice.copy(buffer,offset);offset+=slice.length}function writeUInt32(i){buffer.writeUInt32LE(i,offset);offset+=4}function writeUInt64(i){bufferutils.writeUInt64LE(buffer,i,offset);offset+=8}function writeVarInt(i){var n=bufferutils.writeVarInt(buffer,i,offset);offset+=n}writeUInt32(this.version);writeVarInt(this.ins.length);this.ins.forEach(function(txIn){writeSlice(txIn.hash);writeUInt32(txIn.index);writeVarInt(txIn.script.length);writeSlice(txIn.script);writeUInt32(txIn.sequence)});writeVarInt(this.outs.length);this.outs.forEach(function(txOut){if(!txOut.valueBuffer){writeUInt64(txOut.value)}else{writeSlice(txOut.valueBuffer)}writeVarInt(txOut.script.length);writeSlice(txOut.script)});writeUInt32(this.locktime);return buffer};Transaction.prototype.toHex=function(){return this.toBuffer().toString("hex")};Transaction.prototype.setInputScript=function(index,scriptSig){typeforce(types.tuple(types.Number,types.Buffer),arguments);this.ins[index].script=scriptSig};module.exports=Transaction}).call(this,require("buffer").Buffer)},{"./bufferutils":35,"./crypto":36,"./opcodes":43,"./script":44,"./types":48,buffer:"buffer",typeforce:30}],47:[function(require,module,exports){(function(Buffer){var baddress=require("./address");var bcrypto=require("./crypto");var bscript=require("./script");var bufferEquals=require("buffer-equals");var networks=require("./networks");var ops=require("./opcodes");var typeforce=require("typeforce");var types=require("./types");var ECPair=require("./ecpair");var ECSignature=require("./ecsignature");var Transaction=require("./transaction");function fixMSSignatures(transaction,vin,pubKeys,signatures,prevOutScript,hashType,skipPubKey){var unmatched=signatures.slice();var cache={};return pubKeys.map(function(pubKey){if(skipPubKey&&bufferEquals(skipPubKey,pubKey))return undefined;var matched;var keyPair2=ECPair.fromPublicKeyBuffer(pubKey);unmatched.some(function(signature,i){if(!signature)return false;var signatureHash=cache[hashType]=cache[hashType]||transaction.hashForSignature(vin,prevOutScript,hashType);if(!keyPair2.verify(signatureHash,signature))return false;unmatched[i]=undefined;matched=signature;return true});return matched||undefined})}function extractInput(transaction,txIn,vin){var redeemScript;var scriptSig=txIn.script;var scriptSigChunks=bscript.decompile(scriptSig);var prevOutScript;var prevOutType=bscript.classifyInput(scriptSig,true);var scriptType;if(prevOutType==="scripthash"){redeemScript=scriptSigChunks.slice(-1)[0];prevOutScript=bscript.scriptHashOutput(bcrypto.hash160(redeemScript));scriptSig=bscript.compile(scriptSigChunks.slice(0,-1));scriptSigChunks=scriptSigChunks.slice(0,-1);scriptType=bscript.classifyInput(scriptSig,true)}else{scriptType=prevOutType}var redeemScriptChunks;if(redeemScript){redeemScriptChunks=bscript.decompile(redeemScript)}var hashType,parsed,pubKeys,signatures;switch(scriptType){case"pubkeyhash":parsed=ECSignature.parseScriptSignature(scriptSigChunks[0]);hashType=parsed.hashType;pubKeys=scriptSigChunks.slice(1);signatures=[parsed.signature];prevOutScript=bscript.pubKeyHashOutput(bcrypto.hash160(pubKeys[0]));break;case"pubkey":parsed=ECSignature.parseScriptSignature(scriptSigChunks[0]);hashType=parsed.hashType;signatures=[parsed.signature];if(redeemScript){pubKeys=redeemScriptChunks.slice(0,1)}break;case"multisig":signatures=scriptSigChunks.slice(1).map(function(chunk){if(chunk===ops.OP_0)return undefined;var parsed=ECSignature.parseScriptSignature(chunk);hashType=parsed.hashType;return parsed.signature});if(redeemScript){pubKeys=redeemScriptChunks.slice(1,-2);if(pubKeys.length!==signatures.length){signatures=fixMSSignatures(transaction,vin,pubKeys,signatures,redeemScript,hashType,redeemScript)}}break}return{hashType:hashType,prevOutScript:prevOutScript,prevOutType:prevOutType,pubKeys:pubKeys,redeemScript:redeemScript,scriptType:scriptType,signatures:signatures}}function TransactionBuilder(network){this.prevTxMap={};this.prevOutScripts={};this.prevOutTypes={};this.network=network||networks.bitcoin;this.inputs=[];this.tx=new Transaction}TransactionBuilder.prototype.setLockTime=function(locktime){typeforce(types.UInt32,locktime);if(this.inputs.some(function(input){if(!input.signatures)return false;return input.signatures.some(function(s){return s})})){throw new Error("No, this would invalidate signatures")}this.tx.locktime=locktime};TransactionBuilder.fromTransaction=function(transaction,network){var txb=new TransactionBuilder(network);txb.tx.version=transaction.version;txb.tx.locktime=transaction.locktime;transaction.ins.forEach(function(txIn){txb.addInput(txIn.hash,txIn.index,txIn.sequence)});transaction.outs.forEach(function(txOut){txb.addOutput(txOut.script,txOut.value)});txb.inputs=transaction.ins.map(function(txIn,vin){if(Transaction.isCoinbaseHash(txIn.hash)){throw new Error("coinbase inputs not supported")}if(txIn.script.length===0)return{};return extractInput(transaction,txIn,vin)});return txb};TransactionBuilder.prototype.addInput=function(txHash,vout,sequence,prevOutScript){if(typeof txHash==="string"){txHash=[].reverse.call(new Buffer(txHash,"hex"))}else if(txHash instanceof Transaction){prevOutScript=txHash.outs[vout].script;txHash=txHash.getHash()}var input={};if(prevOutScript){var prevOutScriptChunks=bscript.decompile(prevOutScript);var prevOutType=bscript.classifyOutput(prevOutScriptChunks);switch(prevOutType){case"multisig":input.pubKeys=prevOutScriptChunks.slice(1,-2);input.signatures=input.pubKeys.map(function(){return undefined});break;case"pubkey":input.pubKeys=prevOutScriptChunks.slice(0,1);input.signatures=[undefined];break}if(prevOutType!=="scripthash"){input.scriptType=prevOutType}input.prevOutScript=prevOutScript;input.prevOutType=prevOutType}if(!this.inputs.every(function(otherInput){if(otherInput.hashType===undefined)return true;return otherInput.hashType&Transaction.SIGHASH_ANYONECANPAY})){throw new Error("No, this would invalidate signatures")}var prevOut=txHash.toString("hex")+":"+vout;if(this.prevTxMap[prevOut])throw new Error("Transaction is already an input");var vin=this.tx.addInput(txHash,vout,sequence);this.inputs[vin]=input;this.prevTxMap[prevOut]=vin;return vin};TransactionBuilder.prototype.addOutput=function(scriptPubKey,value){var nOutputs=this.tx.outs.length;if(!this.inputs.every(function(input,index){if(input.hashType===undefined)return true;var hashTypeMod=input.hashType&31;if(hashTypeMod===Transaction.SIGHASH_NONE)return true;if(hashTypeMod===Transaction.SIGHASH_SINGLE){return index<nOutputs}return false})){throw new Error("No, this would invalidate signatures")}if(typeof scriptPubKey==="string"){scriptPubKey=baddress.toOutputScript(scriptPubKey,this.network)}return this.tx.addOutput(scriptPubKey,value)};TransactionBuilder.prototype.build=function(){return this.__build(false)};TransactionBuilder.prototype.buildIncomplete=function(){return this.__build(true)};var canBuildTypes={multisig:true,pubkey:true,pubkeyhash:true};TransactionBuilder.prototype.__build=function(allowIncomplete){if(!allowIncomplete){if(!this.tx.ins.length)throw new Error("Transaction has no inputs");if(!this.tx.outs.length)throw new Error("Transaction has no outputs")}var tx=this.tx.clone();this.inputs.forEach(function(input,index){var scriptType=input.scriptType;var scriptSig;if(!allowIncomplete){if(!scriptType)throw new Error("Transaction is not complete");if(!canBuildTypes[scriptType])throw new Error(scriptType+" not supported");if(!input.signatures)throw new Error("Transaction is missing signatures")}if(input.signatures){switch(scriptType){case"pubkeyhash":var pkhSignature=input.signatures[0].toScriptSignature(input.hashType);scriptSig=bscript.pubKeyHashInput(pkhSignature,input.pubKeys[0]);break;case"multisig":var msSignatures=input.signatures.map(function(signature){return signature&&signature.toScriptSignature(input.hashType)});if(allowIncomplete){for(var i=0;i<msSignatures.length;++i){msSignatures[i]=msSignatures[i]||ops.OP_0}}else{msSignatures=msSignatures.filter(function(x){return x})}var redeemScript=allowIncomplete?undefined:input.redeemScript;scriptSig=bscript.multisigInput(msSignatures,redeemScript);break;case"pubkey":var pkSignature=input.signatures[0].toScriptSignature(input.hashType);scriptSig=bscript.pubKeyInput(pkSignature);break}}if(scriptSig){if(input.prevOutType==="scripthash"){scriptSig=bscript.scriptHashInput(scriptSig,input.redeemScript)}tx.setInputScript(index,scriptSig)}});return tx};TransactionBuilder.prototype.sign=function(index,keyPair,redeemScript,hashType){if(keyPair.network!==this.network)throw new Error("Inconsistent network");if(!this.inputs[index])throw new Error("No input at index: "+index);hashType=hashType||Transaction.SIGHASH_ALL;var input=this.inputs[index];var canSign=input.hashType&&input.prevOutScript&&input.prevOutType&&input.pubKeys&&input.scriptType&&input.signatures&&input.signatures.length===input.pubKeys.length;var kpPubKey=keyPair.getPublicKeyBuffer();if(canSign){if(redeemScript){if(!bufferEquals(input.redeemScript,redeemScript))throw new Error("Inconsistent redeemScript")}if(input.hashType!==hashType)throw new Error("Inconsistent hashType")}else{if(redeemScript){if(input.prevOutScript){if(input.prevOutType!=="scripthash")throw new Error("PrevOutScript must be P2SH");var scriptHash=bscript.decompile(input.prevOutScript)[1];if(!bufferEquals(scriptHash,bcrypto.hash160(redeemScript)))throw new Error("RedeemScript does not match "+scriptHash.toString("hex"))}var scriptType=bscript.classifyOutput(redeemScript);var redeemScriptChunks=bscript.decompile(redeemScript);var pubKeys;switch(scriptType){case"multisig":pubKeys=redeemScriptChunks.slice(1,-2);break;case"pubkeyhash":var pkh1=redeemScriptChunks[2];var pkh2=bcrypto.hash160(keyPair.getPublicKeyBuffer());if(!bufferEquals(pkh1,pkh2))throw new Error("privateKey cannot sign for this input");pubKeys=[kpPubKey];break;case"pubkey":pubKeys=redeemScriptChunks.slice(0,1);break;default:throw new Error("RedeemScript not supported ("+scriptType+")")}if(!input.prevOutScript){input.prevOutScript=bscript.scriptHashOutput(bcrypto.hash160(redeemScript));input.prevOutType="scripthash"}input.pubKeys=pubKeys;input.redeemScript=redeemScript;input.scriptType=scriptType;input.signatures=pubKeys.map(function(){return undefined})}else{if(input.prevOutType==="scripthash")throw new Error("PrevOutScript is P2SH, missing redeemScript");if(!input.scriptType){input.prevOutScript=bscript.pubKeyHashOutput(bcrypto.hash160(keyPair.getPublicKeyBuffer()));input.prevOutType="pubkeyhash";input.pubKeys=[kpPubKey];input.scriptType=input.prevOutType;input.signatures=[undefined]}else{if(!input.pubKeys||!input.signatures)throw new Error(input.scriptType+" not supported")}}input.hashType=hashType}var signatureScript=input.redeemScript||input.prevOutScript;var signatureHash=this.tx.hashForSignature(index,signatureScript,hashType);var valid=input.pubKeys.some(function(pubKey,i){if(!bufferEquals(kpPubKey,pubKey))return false;if(input.signatures[i])throw new Error("Signature already exists");var signature=keyPair.sign(signatureHash);input.signatures[i]=signature;return true});if(!valid)throw new Error("Key pair cannot sign for this input")};module.exports=TransactionBuilder}).call(this,require("buffer").Buffer)},{"./address":33,"./crypto":36,"./ecpair":38,"./ecsignature":39,"./networks":42,"./opcodes":43,"./script":44,"./transaction":46,"./types":48,buffer:"buffer","buffer-equals":8,typeforce:30}],48:[function(require,module,exports){var typeforce=require("typeforce");function nBuffer(value,n){typeforce(types.Buffer,value);if(value.length!==n)throw new typeforce.TfTypeError("Expected "+n*8+"-bit Buffer, got "+value.length*8+"-bit Buffer");return true}function Hash160bit(value){return nBuffer(value,20)}function Hash256bit(value){return nBuffer(value,32)}function Buffer256bit(value){return nBuffer(value,32)}var UINT53_MAX=Math.pow(2,53)-1;function UInt2(value){return(value&3)===value}function UInt8(value){return(value&255)===value}function UInt32(value){return value>>>0===value}function UInt53(value){return typeforce.Number(value)&&value>=0&&value<=UINT53_MAX&&Math.floor(value)===value}var BigInt=typeforce.quacksLike("BigInteger");var ECPoint=typeforce.quacksLike("Point");var ECSignature=typeforce.compile({r:BigInt,s:BigInt});var Network=typeforce.compile({messagePrefix:typeforce.oneOf(typeforce.Buffer,typeforce.String),bip32:{"public":UInt32,"private":UInt32},pubKeyHash:UInt8,scriptHash:UInt8,wif:UInt8,dustThreshold:UInt53});var types={BigInt:BigInt,Buffer256bit:Buffer256bit,ECPoint:ECPoint,ECSignature:ECSignature,Hash160bit:Hash160bit,Hash256bit:Hash256bit,Network:Network,UInt2:UInt2,UInt8:UInt8,UInt32:UInt32,UInt53:UInt53};for(var typeName in typeforce){types[typeName]=typeforce[typeName]}module.exports=types},{typeforce:30}],49:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&!isFinite(value)){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction}) }assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(util.isPrimitive(a)||util.isPrimitive(b)){return a===b}var aIsArgs=isArguments(a),bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return false;if(aIsArgs){a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}var ka=objectKeys(a),kb=objectKeys(b),key,i;if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":75}],50:[function(require,module,exports){},{}],51:[function(require,module,exports){(function(exports){"use strict";var i;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var lookup=[];for(i=0;i<code.length;i++){lookup[i]=code[i]}var revLookup=[];for(i=0;i<code.length;++i){revLookup[code.charCodeAt(i)]=i}revLookup["-".charCodeAt(0)]=62;revLookup["_".charCodeAt(0)]=63;var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;function decode(elt){var v=revLookup[elt.charCodeAt(0)];return v!==undefined?v:-1}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders=b64.charAt(len-2)==="="?2:b64.charAt(len-1)==="="?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function encode(num){return lookup[num]}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}function encodeChunk(uint8,start,end){var temp;var output=[];for(var i=start;i<end;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output.push(tripletToBase64(temp))}return output.join("")}function uint8ToBase64(uint8){var i;var extraBytes=uint8.length%3;var output="";var parts=[];var temp,length;var maxChunkLength=16383;for(i=0,length=uint8.length-extraBytes;i<length;i+=maxChunkLength){parts.push(encodeChunk(uint8,i,i+maxChunkLength>length?length:i+maxChunkLength))}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break;default:break}parts.push(output);return parts.join("")}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],52:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],53:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],54:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],55:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{dup:14}],56:[function(require,module,exports){module.exports=function(obj){return!!(obj!=null&&(obj._isBuffer||obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)))}},{}],57:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],58:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=setTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;clearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){setTimeout(drainQueue,0)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],59:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":60}],60:[function(require,module,exports){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var processNextTick=require("process-nextick-args");var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v<keys.length;v++){var method=keys[v];if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]}function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;processNextTick(onEndNT,this)}function onEndNT(self){self.end()}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}},{"./_stream_readable":62,"./_stream_writable":64,"core-util-is":65,inherits:55,"process-nextick-args":66}],61:[function(require,module,exports){"use strict";module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":63,"core-util-is":65,inherits:55}],62:[function(require,module,exports){(function(process){"use strict";module.exports=Readable;var processNextTick=require("process-nextick-args");var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events");var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var util=require("core-util-is");util.inherits=require("inherits");var debugUtil=require("util");var debug;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var StringDecoder;util.inherits(Readable,Stream);var Duplex;function ReadableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}var Duplex;function Readable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);if(!addToFront)state.reading=false;if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc;return this};var MAX_HWM=8388608;function computeNewHighWaterMark(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else{return state.length}}return n}Readable.prototype.read=function(n){debug("read",n);var state=this._readableState;var nOrig=n;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n<state.highWaterMark){doRead=true;debug("length less than watermark",doRead)}if(state.ended||state.reading){doRead=false;debug("reading or ended",doRead)}if(doRead){debug("do read");state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);var ret;if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended&&state.length===0)endReadable(this);if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){debug("maybeReadMore read 0");stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)processNextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){debug("onunpipe");if(readable===src){cleanup()}}function onend(){debug("onend");dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=false;function cleanup(){debug("cleanup");dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);src.removeListener("data",ondata);cleanedUp=true;if(state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain))ondrain()}src.on("data",ondata);function ondata(chunk){debug("ondata");var ret=dest.write(chunk);if(false===ret){if(state.pipesCount===1&&state.pipes[0]===dest&&src.listenerCount("data")===1&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&false!==this._readableState.flowing){this.resume()}if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){processNextTick(nReadingNextTick,this)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;function nReadingNextTick(self){debug("readable nexttick read 0");self.read(0)}Readable.prototype.resume=function(){var state=this._readableState;if(!state.flowing){debug("resume");state.flowing=true;resume(this,state)}return this};function resume(stream,state){if(!state.resumeScheduled){state.resumeScheduled=true;processNextTick(resume_,stream,state)}}function resume_(stream,state){if(!state.reading){debug("resume read 0");stream.read(0)}state.resumeScheduled=false;stream.emit("resume");flow(stream);if(state.flowing&&!state.reading)stream.read(0)}Readable.prototype.pause=function(){debug("call pause flowing=%j",this._readableState.flowing);if(false!==this._readableState.flowing){debug("pause");this._readableState.flowing=false;this.emit("pause")}return this};function flow(stream){var state=stream._readableState;debug("flow",state.flowing);if(state.flowing){do{var chunk=stream.read()}while(null!==chunk&&state.flowing)}}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){debug("wrapped end");if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){debug("wrapped data");if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(this[i]===undefined&&typeof stream[i]==="function"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){debug("wrapped _read",n);if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else if(list.length===1)ret=list[0];else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{"./_stream_duplex":60,_process:58,buffer:"buffer","core-util-is":65,events:54,inherits:55,isarray:57,"process-nextick-args":66,"string_decoder/":73,util:50}],63:[function(require,module,exports){"use strict";module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);this._transformState=new TransformState(this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;if(options){if(typeof options.transform==="function")this._transform=options.transform;if(typeof options.flush==="function")this._flush=options.flush}this.once("prefinish",function(){if(typeof this._flush==="function")this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform) }else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":60,"core-util-is":65,inherits:55}],64:[function(require,module,exports){"use strict";module.exports=Writable;var processNextTick=require("process-nextick-args");var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}var Duplex;function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false}WritableState.prototype.getBuffer=function writableStateGetBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.")})}catch(_){}})();var Duplex;function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest=new WriteReq(chunk,encoding,cb);if(last){last.next=state.lastBufferedRequest}else{state.bufferedRequest=state.lastBufferedRequest}}else{doWrite(stream,state,false,len,chunk,encoding,cb)}return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;if(writev)stream._writev(chunk,state.onwrite);else stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){--state.pendingcb;if(sync)processNextTick(cb,er);else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state);if(!finished&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest){clearBuffer(stream,state)}if(sync){processNextTick(afterWrite,stream,state,finished,cb)}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);state.pendingcb--;cb();finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var buffer=[];var cbs=[];while(entry){cbs.push(entry.callback);buffer.push(entry);entry=entry.next}state.pendingcb++;state.lastBufferedRequest=null;doWrite(stream,state,true,state.length,buffer,"",function(err){for(var i=0;i<cbs.length;i++){state.pendingcb--;cbs[i](err)}})}else{while(entry){var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,false,len,chunk,encoding,cb);entry=entry.next;if(state.writing){break}}if(entry===null)state.lastBufferedRequest=null}state.bufferedRequest=entry;state.bufferProcessing=false}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype._writev=null;Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(chunk!==null&&chunk!==undefined)this.write(chunk,encoding);if(state.corked){state.corked=1;this.uncork()}if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(state){return state.ending&&state.length===0&&state.bufferedRequest===null&&!state.finished&&!state.writing}function prefinish(stream,state){if(!state.prefinished){state.prefinished=true;stream.emit("prefinish")}}function finishMaybe(stream,state){var need=needFinish(state);if(need){if(state.pendingcb===0){prefinish(stream,state);state.finished=true;stream.emit("finish")}else{prefinish(stream,state)}}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)processNextTick(cb);else stream.once("finish",cb)}state.ended=true}},{"./_stream_duplex":60,buffer:"buffer","core-util-is":65,events:54,inherits:55,"process-nextick-args":66,"util-deprecate":67}],65:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":56}],66:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn){var args=new Array(arguments.length-1);var i=0;while(i<args.length){args[i++]=arguments[i]}process.nextTick(function afterTick(){fn.apply(null,args)})}}).call(this,require("_process"))},{_process:58}],67:[function(require,module,exports){(function(global){module.exports=deprecate;function deprecate(fn,msg){if(config("noDeprecation")){return fn}var warned=false;function deprecated(){if(!warned){if(config("throwDeprecation")){throw new Error(msg)}else if(config("traceDeprecation")){console.trace(msg)}else{console.warn(msg)}warned=true}return fn.apply(this,arguments)}return deprecated}function config(name){try{if(!global.localStorage)return false}catch(_){return false}var val=global.localStorage[name];if(null==val)return false;return String(val).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],68:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":61}],69:[function(require,module,exports){var Stream=function(){try{return require("st"+"ream")}catch(_){}}();exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream||exports;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":60,"./lib/_stream_passthrough.js":61,"./lib/_stream_readable.js":62,"./lib/_stream_transform.js":63,"./lib/_stream_writable.js":64}],70:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":63}],71:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":64}],72:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:54,inherits:55,"readable-stream/duplex.js":59,"readable-stream/passthrough.js":68,"readable-stream/readable.js":69,"readable-stream/transform.js":70,"readable-stream/writable.js":71}],73:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:"buffer"}],74:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],75:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":74,_process:58,inherits:55}],aes:[function(require,module,exports){module.exports=AES;function AES(key){if(!this._tables[0][0][0])this._precompute();var tmp,encKey,decKey;var sbox=this._tables[0][4];var decTable=this._tables[1];var keyLen=key.length;var rcon=1;if(keyLen!==4&&keyLen!==6&&keyLen!==8){throw new Error("invalid aes key size")}this._key=[encKey=key.slice(0),decKey=[]];for(var i=keyLen;i<4*keyLen+28;i++){tmp=encKey[i-1];if(i%keyLen===0||keyLen===8&&i%keyLen===4){tmp=sbox[tmp>>>24]<<24^sbox[tmp>>16&255]<<16^sbox[tmp>>8&255]<<8^sbox[tmp&255];if(i%keyLen===0){tmp=tmp<<8^tmp>>>24^rcon<<24;rcon=rcon<<1^(rcon>>7)*283}}encKey[i]=encKey[i-keyLen]^tmp}for(var j=0;i;j++,i--){tmp=encKey[j&3?i:i-4];if(i<=4||j<4){decKey[j]=tmp}else{decKey[j]=decTable[0][sbox[tmp>>>24]]^decTable[1][sbox[tmp>>16&255]]^decTable[2][sbox[tmp>>8&255]]^decTable[3][sbox[tmp&255]]}}}AES.prototype={encrypt:function(data){return this._crypt(data,0)},decrypt:function(data){return this._crypt(data,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){var encTable=this._tables[0],decTable=this._tables[1],sbox=encTable[4],sboxInv=decTable[4],i,x,xInv,d=new Uint8Array(256),th=new Uint8Array(256),x2,x4,x8,s,tEnc,tDec;for(i=0;i<256;i++){th[(d[i]=i<<1^(i>>7)*283)^i]=i}for(x=xInv=0;!sbox[x];x^=x2||1,xInv=th[xInv]||1){s=xInv^xInv<<1^xInv<<2^xInv<<3^xInv<<4;s=s>>8^s&255^99;sbox[x]=s;sboxInv[s]=x;x8=d[x4=d[x2=d[x]]];tDec=x8*16843009^x4*65537^x2*257^x*16843008;tEnc=d[s]*257^s*16843008;for(i=0;i<4;i++){encTable[i][x]=tEnc=tEnc<<24^tEnc>>>8;decTable[i][s]=tDec=tDec<<24^tDec>>>8}}},_crypt:function(input,dir){if(input.length!==4){throw new Error("invalid aes block size")}var key=this._key[dir],a=input[0]^key[0],b=input[dir?3:1]^key[1],c=input[2]^key[2],d=input[dir?1:3]^key[3],a2,b2,c2,nInnerRounds=key.length/4-2,i,kIndex=4,out=new Uint32Array(4),table=this._tables[dir],t0=table[0],t1=table[1],t2=table[2],t3=table[3],sbox=table[4];for(i=0;i<nInnerRounds;i++){a2=t0[a>>>24]^t1[b>>16&255]^t2[c>>8&255]^t3[d&255]^key[kIndex];b2=t0[b>>>24]^t1[c>>16&255]^t2[d>>8&255]^t3[a&255]^key[kIndex+1];c2=t0[c>>>24]^t1[d>>16&255]^t2[a>>8&255]^t3[b&255]^key[kIndex+2];d=t0[d>>>24]^t1[a>>16&255]^t2[b>>8&255]^t3[c&255]^key[kIndex+3];kIndex+=4;a=a2;b=b2;c=c2}for(i=0;i<4;i++){out[dir?3&-i:i]=sbox[a>>>24]<<24^sbox[b>>16&255]<<16^sbox[c>>8&255]<<8^sbox[d&255]^key[kIndex++];a2=a;a=b;b=c;c=d;d=a2}return out}}},{}],bigi:[function(require,module,exports){var BigInteger=require("./bigi");require("./convert");module.exports=BigInteger},{"./bigi":1,"./convert":2}],"bitcoinjs-lib":[function(require,module,exports){module.exports={Block:require("./block"),ECPair:require("./ecpair"),ECSignature:require("./ecsignature"),HDNode:require("./hdnode"),Transaction:require("./transaction"),TransactionBuilder:require("./transaction_builder"),address:require("./address"),bufferutils:require("./bufferutils"),crypto:require("./crypto"),message:require("./message"),networks:require("./networks"),opcodes:require("./opcodes"),script:require("./script")}},{"./address":33,"./block":34,"./bufferutils":35,"./crypto":36,"./ecpair":38,"./ecsignature":39,"./hdnode":40,"./message":41,"./networks":42,"./opcodes":43,"./script":44,"./transaction":46,"./transaction_builder":47}],buffer:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var rootParent={};Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.foo=function(){return 42};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Buffer(arg){if(!(this instanceof Buffer)){if(arguments.length>1)return new Buffer(arg,arguments[1]);return new Buffer(arg)}if(!Buffer.TYPED_ARRAY_SUPPORT){this.length=0;this.parent=undefined}if(typeof arg==="number"){return fromNumber(this,arg)}if(typeof arg==="string"){return fromString(this,arg,arguments.length>1?arguments[1]:"utf8")}return fromObject(this,arg)}Buffer._augment=function(arr){arr.__proto__=Buffer.prototype;return arr};function fromNumber(that,length){that=allocate(that,length<0?0:checked(length)|0);if(!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<length;i++){that[i]=0}}return that}function fromString(that,string,encoding){if(typeof encoding!=="string"||encoding==="")encoding="utf8";var length=byteLength(string,encoding)|0;that=allocate(that,length);that.write(string,encoding);return that}function fromObject(that,object){if(Buffer.isBuffer(object))return fromBuffer(that,object);if(isArray(object))return fromArray(that,object);if(object==null){throw new TypeError("must start with number, buffer, array or string")}if(typeof ArrayBuffer!=="undefined"){if(object.buffer instanceof ArrayBuffer){return fromTypedArray(that,object)}if(object instanceof ArrayBuffer){return fromArrayBuffer(that,object)}}if(object.length)return fromArrayLike(that,object);return fromJsonObject(that,object)}function fromBuffer(that,buffer){var length=checked(buffer.length)|0;that=allocate(that,length);buffer.copy(that,0,0,length);return that}function fromArray(that,array){var length=checked(array.length)|0; that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromTypedArray(that,array){var length=checked(array.length)|0;that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromArrayBuffer(that,array){array.byteLength;if(Buffer.TYPED_ARRAY_SUPPORT){that=new Uint8Array(array);that.__proto__=Buffer.prototype}else{that=fromTypedArray(that,new Uint8Array(array))}return that}function fromArrayLike(that,array){var length=checked(array.length)|0;that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromJsonObject(that,object){var array;var length=0;if(object.type==="Buffer"&&isArray(object.data)){array=object.data;length=checked(array.length)|0}that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}if(Buffer.TYPED_ARRAY_SUPPORT){Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true})}}else{Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined}function allocate(that,length){if(Buffer.TYPED_ARRAY_SUPPORT){that=new Uint8Array(length);that.__proto__=Buffer.prototype}else{that.length=length}var fromPool=length!==0&&length<=Buffer.poolSize>>>1;if(fromPool)that.parent=rootParent;return that}function checked(length){if(length>=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(subject,encoding){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding);var buf=new Buffer(subject,encoding);delete buf.parent;return buf}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;var i=0;var len=Math.min(x,y);while(i<len){if(a[i]!==b[i])break;++i}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!isArray(list))throw new TypeError("list argument must be an Array of Buffers.");if(list.length===0){return new Buffer(0)}var i;if(length===undefined){length=0;for(i=0;i<list.length;i++){length+=list[i].length}}var buf=new Buffer(length);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};function byteLength(string,encoding){if(typeof string!=="string")string=""+string;var len=string.length;if(len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"binary":case"raw":case"raws":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;start=start|0;end=end===undefined||end===Infinity?this.length:end|0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;Buffer.prototype.toString=function toString(){var length=this.length|0;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function compare(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return 0;return Buffer.compare(this,b)};Buffer.prototype.indexOf=function indexOf(val,byteOffset){if(byteOffset>2147483647)byteOffset=2147483647;else if(byteOffset<-2147483648)byteOffset=-2147483648;byteOffset>>=0;if(this.length===0)return-1;if(byteOffset>=this.length)return-1;if(byteOffset<0)byteOffset=Math.max(this.length+byteOffset,0);if(typeof val==="string"){if(val.length===0)return-1;return String.prototype.indexOf.call(this,val,byteOffset)}if(Buffer.isBuffer(val)){return arrayIndexOf(this,val,byteOffset)}if(typeof val==="number"){if(Buffer.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,val,byteOffset)}return arrayIndexOf(this,[val],byteOffset)}function arrayIndexOf(arr,val,byteOffset){var foundIndex=-1;for(var i=0;byteOffset+i<arr.length;i++){if(arr[byteOffset+i]===val[foundIndex===-1?0:i-foundIndex]){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===val.length)return byteOffset+foundIndex}else{foundIndex=-1}}return-1}throw new TypeError("val must be string, number or Buffer")};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var parsed=parseInt(string.substr(i*2,2),16);if(isNaN(parsed))throw new Error("Invalid hex string");buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}else if(isFinite(offset)){offset=offset|0;if(isFinite(length)){length=length|0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length|0;length=swap}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"binary":return binaryWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i<end){var firstByte=buf[i];var codePoint=null;var bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(i<len){res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH))}return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i]&127)}return ret}function binarySlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=this.subarray(start,end);newBuf.__proto__=Buffer.prototype}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}}if(newBuf.length)newBuf.parent=this.parent||this;return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}return val};Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("index out of range");if(offset<0)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||this.length===0)return 0;if(targetStart<0){throw new RangeError("targetStart out of bounds")}if(start<0||start>=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart<end-start){end=target.length-targetStart+start}var len=end-start;var i;if(this===target&&start<targetStart&&targetStart<end){for(i=len-1;i>=0;i--){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i<len;i++){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,start+len),targetStart)}return len};Buffer.prototype.fill=function fill(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new RangeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new RangeError("start out of bounds");if(end<0||end>this.length)throw new RangeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;i++){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":51,ieee754:52,isarray:53}],ecurve:[function(require,module,exports){var Point=require("./point");var Curve=require("./curve");var getCurveByName=require("./names");module.exports={Curve:Curve,Point:Point,getCurveByName:getCurveByName}},{"./curve":26,"./names":28,"./point":29}],randombytes:[function(require,module,exports){(function(process,global,Buffer){"use strict";function oldBrowser(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var crypto=global.crypto||global.msCrypto;if(crypto&&crypto.getRandomValues){module.exports=randomBytes}else{module.exports=oldBrowser}function randomBytes(size,cb){if(size>65536)throw new Error("requested too many random bytes");var rawBytes=new global.Uint8Array(size);crypto.getRandomValues(rawBytes);var bytes=new Buffer(rawBytes.buffer);if(typeof cb==="function"){return process.nextTick(function(){cb(null,bytes)})}return bytes}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{_process:58,buffer:"buffer"}]},{},[]);bitcoin=require("bitcoinjs-lib");ecurve=require("ecurve");bigi=require("bigi");Buffer=require("buffer").Buffer;AES=require("aes");randomBytes=require("randombytes");function searchParam(key){var val=undefined,str=location.search.substring(1);str.split("&").forEach(function(pair){var parens;if((parens=pair.match(/^([-A-Za-z0-9_]+)=(.*)/))&&parens[1]===key){val=decodeURI(parens[2])}});return val}function isStr(a){return typeof a==="string"}function isNum(a){return typeof a==="number"&&a===a}function isInt(a){return isNum(a)&&Math.floor(a)===a}function isObj(a){return a&&typeof a==="object"}function isArray(a){return a&&typeof a==="object"&&a instanceof Array}function getUnixTime(){return Math.floor(Date.now()/1e3)}function timeToUnits(dt){if(dt<60){return Math.floor(dt)+"s"}else if(dt<60*60){return Math.floor(dt/60)+"m"}else if(dt<60*60*24){return Math.floor(dt/(60*60))+"h"}else{return Math.floor(dt/(60*60*24))+"d"}}function timeAgo(t){if(t===0)return"--";return timeToUnits(getUnixTime()-t)}function timePlusMinus(t){var dt=t-getUnixTime();if(dt>0){return"+"+timeToUnits(dt)}else{return"-"+timeToUnits(-dt)}}function timeFromUserInput(tin){if(tin.substr(0,1)==="+"){return getUnixTime()+tin.substr(1)*24*60*60}else if(tin.substr(0,1)==="-"){return getUnixTime()-tin.substr(1)*24*60*60}else{return tin|0}}aq={page:{},rpc:{}};aq.getStorage=function(key){var r=window.localStorage.getItem("aquila."+conf.network+"."+key);try{return r?JSON.parse(r):r}catch(e){return}};aq.setStorage=function(key,value){try{window.localStorage.setItem("aquila."+conf.network+"."+key,JSON.stringify(value))}catch(e){ui.log("*** FAILED, window.localStorage.setItem(): "+e);ui.log("increase storage quota for this domain in browser settings?");ui.showPopup("log")}};aq.isAlreadyRead=function(m){return m.hash in aq.alreadyRead.hashes};aq.markAlreadyRead=function(m,yes){var aah=aq.alreadyRead.hashes;if(yes){aah[m.hash]=m.timeReal;if(Object.keys(aah).length>1e3){var h,hOldest,tOldest=getUnixTime();for(h in aah){if(aah[h]<tOldest){tOldest=aah[h];hOldest=h}}delete aah[hOldest];aq.alreadyRead.omitsBefore=tOldest}}else{delete aah[m.hash]}aq.setStorage("alreadyRead",aq.alreadyRead)};aq.clearAlreadyRead=function(){aq.setStorage("alreadyRead",null)};aq.init=function(){ui.log("This is Aquila client version "+conf.version);if(searchParam("a")==="servers"){aq.loadPage();return}aq.alreadyRead=aq.getStorage("alreadyRead")||{hashes:{},omitsBefore:0};var now=getUnixTime(),mc=aq.getStorage("marketControl"),ticker=aq.getStorage("ticker");if(!(isObj(mc)&&isObj(mc.msg)&&isInt(mc.receivedAt)&&now-mc.receivedAt<conf.marketControlCheckInterval)){ui.showPopup("log");aq.getMarketControl();return}ui.log("keeping marketControl (received "+timeAgo(mc.receivedAt)+" ago), with");ui.log(" hash="+mc.msg.hash);if(!(isObj(ticker)&&isInt(ticker.receivedAt)&&now-ticker.receivedAt<conf.tickerInterval)){ui.showPopup("log");aq.getTicker();return}ui.log("keeping ticker info (received "+timeAgo(ticker.receivedAt)+" ago)");aq.loadPage()};aq.setUpCategories=function(mc){$("#categories").html("");var spc="";if(searchParam("a")==="search")spc=searchParam("category")||"";function showCategory(cat,now){if(!(isStr(cat)&&isStr(now)))return false;cat=cat.split(";");now=now.split(";");return cat.length<=now.length+1&&cat.slice(0,cat.length-1).join(";")===now.slice(0,cat.length-1).join(";")}mc.categories.forEach(function(c){var link=c;if(showCategory(c,spc)){c=c.replace(/[^;]*;/g," ")}else{return}$("<a/>",{text:c,href:"?a=search&category="+encodeURI(link),"class":"leftitem"}).appendTo("#categories")})};aq.showToolbarItemsForRole=function(){var ani=aq.getStorage("approveNewIdentity"),keys=aq.getStorage("keys"),mc=aq.getStorage("marketControl").msg;if(isObj(ani)&&ani.allowed){if(ani.maySell){$("#for-sellers").css("display","block")}else{$("#for-buyers").css("display","block")}}if(isObj(keys)&&keys.primary===mc.adminPkh[0]){$("#for-admins").css("display","block")}var owners=aq.getStorage("owners");if(isObj(owners)&&isObj(keys)){var pkhId;for(pkhId in keys.secretKeys){if(pkhId in owners)$("#for-owners").css("display","block")}}};aq.loadPage=function(){ui.hidePopup();var ani=aq.getStorage("approveNewIdentity"),keys=aq.getStorage("keys"),mc=aq.getStorage("marketControl").msg;aq.setUpCategories(mc);aq.showToolbarItemsForRole();var nag;if(!window.location.toString().match(/^file:\/\//)){nag="it's best to save client locally"}if($.grep(mc.clientVersion,function(v){return v===conf.version}).length===0){nag="new client version available"}if(nag){$("#nagbar").css("display","block");$("#nagbar-link").text(nag)}var a=searchParam("a");if(a in aq.page){if(!aq.page[a].needKeys||isObj(keys)&&Object.keys(keys).length>0&&isObj(ani)){ui.hidePopup();aq.page[a].init()}else{ui.navTo("keys")}}else{ui.log("nothing for page "+a)}};aq.getTicker=function(){var done=false;function gotOne(r){if(done)return;if(!(isObj(r)&&isObj(r.result)))return;var m=r.result;if(!aq.verifyMsgSignatures(m)){ui.log("*** SIGNATURE FAIL FOR ticker");return}if(Math.abs(getUnixTime()-m.timeReal)>60*60){ui.log("*** TICKER IS OLD: "+timePlusMinus(m.timeReal));return}var mc=aq.getStorage("marketControl").msg;if(!mc.adminTicker.some(function(a){return a===m.sigFrom})){ui.log("*** TICKER NOT SIGNED BY adminTicker");return}ui.log("got ticker information:");m.receivedAt=getUnixTime();ui.log(" time = "+m.time);ui.log(" timeHash = "+m.timeHash);ui.log(" timeReal = "+m.timeReal+" ("+timePlusMinus(m.timeReal)+")");aq.setStorage("ticker",m);ui.log("\ndone, loading page");done=true;window.setTimeout(aq.loadPage,.5*1e3) }function gotAll(){if(!done){ui.log("*** NO TICKER INFO RECEIVED");ui.log("Can't proceed, reload or check network settings?");ui.log("Markets using .onion servers require Tor.");ui.showPopup("log");return}}ui.log("\ngetting ticker information (exchange rates, time)");aq.rpc.toServers("ticker",{},gotOne,gotAll)};aq.imageDataUrl=function(dataUrl){try{var jpeg="data:image/jpeg;base64,",png="data:image/png;base64,",base64,type;if(dataUrl.substr(0,jpeg.length)===jpeg){base64=dataUrl.substr(jpeg.length);type="jpeg"}else if(dataUrl.substr(0,png.length)===png){base64=dataUrl.substr(png.length);type="png"}else{throw"bad type"}var d=new Buffer(base64,"base64");return"image/"+type+";base64,"+d.toString("base64")}catch(e){return""}};aq.showCaptcha=function(r,captchaBad){var img=$("#captcha-img");img.attr("src","data:"+aq.imageDataUrl(r.result.img));img.css("height","100px");img.css("width","240px");$("#captcha-bad").css("display",captchaBad?"block":"none");$("#captcha-text")[0].value="";ui.showPopup("captcha")};aq.sendMsgWithCaptcha=function(m,success,captchaBad){ui.showPopup("log");aq.rpc.toOneServer("captcha",{},function(r,server){var captchaTag=r.result.tag;aq.showCaptcha(r,captchaBad);$("#captcha-another").off("click");$("#captcha-another").on("click",function(){aq.sendMsgWithCaptcha(m,success,false)});$("#captcha-broadcast").off("click");$("#captcha-broadcast").on("click",function(){function fs(r){if(r&&r.error&&r.error==="bad captcha"){aq.sendMsgWithCaptcha(m,success,true)}else if(r&&r.result&&r.result==="ok"){ui.showPopup("notify","The message has been sent. It may take a few "+"minutes to propagate to the full network.");if(success){$("#popup-notify-button").off("click");$("#popup-notify-button").on("click",function(){success(m)})}}else{ui.log("unknown response: "+JSON.stringify(r))}}aq.rpc.toServer(server,"sendMsg",{captchaTag:captchaTag,captchaText:$("#captcha-text")[0].value,msg:m},fs);ui.showPopup("log")})})};aq.finishAndSendMsg=function(m,success){try{var keys=aq.getStorage("keys");m.sigFrom=keys.primary;m.sig=msg.notYetSigned;msg.fillTime(m);m=msg.fromUntrusted(m,"compute");msg.fillSignatures(m);m=JSON.stringify(m);aq.sendMsgWithCaptcha([m],success)}catch(e){ui.showPopup("notify","Message format bad: "+e)}};aq.sigTotal=0;aq.sigDone=0;aq.verifyMsgSignatures=function(m,async){var ok;try{if(m.type==="marketControl"){for(var i=0;i<m.ownerSig.length;i++){var osf=m.ownerSigFrom[i],os=m.ownerSig[i];if(!bitcoin.message.verify(osf,os,m.hash,conf.btcNet)){throw"bad sig"}}}else{var sf=m.sigFrom,s=m.sig;if(!bitcoin.message.verify(sf,s,m.hash,conf.btcNet)){throw"bad sig"}}ok=true}catch(e){ok=false}if(!async)aq.sigTotal++;aq.sigDone++;$("#sigs-count").text(aq.sigDone+"/"+aq.sigTotal);return ok};aq.asyncBacklog=[];aq.asyncVerifyMsgSignatures=function(m,cb){var dt=55;function checkOneSignature(){var a=aq.asyncBacklog.shift(),m=a[0],cb=a[1],ok=aq.verifyMsgSignatures(JSON.parse(m),true);if(typeof cb==="function"){cb(ok)}else{if(!ok){cb.css("background","red");cb.css("padding","10px");cb.css("display","block");cb.css("font-weight","bold");cb.text("SIGNATURE FAILED")}}if(aq.asyncBacklog.length>0){window.setTimeout(checkOneSignature,dt)}}if(aq.asyncBacklog.length===0){window.setTimeout(checkOneSignature,dt)}aq.sigTotal++;aq.asyncBacklog.push([JSON.stringify(m),cb])};aq.getMsgByHash=function(hash,cb){var done=false;aq.rpc.toServers("searchMsg",{hashInclude:[hash],deletedOk:true,resultsAs:"msg"},function(r){if(done)return;if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;if(r.result.msgs.length!==1)return;var m=r.result.msgs[0];if(m.hash!==hash)return;if(!aq.verifyMsgSignatures(m))return;done=true;cb(r.result.msgs[0])},function(){if(done)return;ui.log("*** FAILED TO GET MSG WITH hash="+hash)});ui.showPopup("log")};aq.getMsgsBySearch=function(params,cb){params.resultsAs="msg";var have={},first=true;aq.rpc.toServers("searchMsg",params,function(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;r=r.result;var out=[];r.msgs.forEach(function(m){if(have[m.hash])return;have[m.hash]=true;out.push(m)});var page={skipped:r.skipped,inPage:r.msgs.length,total:r.n};if(out.length>0||first)cb(out,page);first=false},function(){if(first)ui.log("*** NO RESPONSES IN getMsgsBySearch")});ui.showPopup("log")};aq.getMsgBySearch=function(params,cb){params.resultsAs="msg";params.limitResults=1;var first=true,have=false;aq.rpc.toServers("searchMsg",params,function(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;r=r.result;if(r.msgs.length>1)return;if(r.msgs.length>0){if(!have)cb(r.msgs[0]);have=true}else if(first){cb(null)}first=false},function(){if(first)ui.log("*** NO RESPONSES IN getMsgBySearch")});ui.showPopup("log")};aq.currencyToBtc=function(value,currency,ticker){ticker=ticker||aq.getStorage("ticker");for(var i=0;i<ticker.currencies.length;i++){if(ticker.currencies[i]===currency){return value/ticker.exchangeRates[i]}}};aq.getTransactionInfo=function(txHex){var tx=bitcoin.Transaction.fromHex(txHex),txb=bitcoin.TransactionBuilder.fromTransaction(tx,conf.btcNet),n=undefined,addr;if(txb.inputs.length<1)throw"no inputs";txb.inputs.forEach(function(input){if(input.signatures.length!==3)throw"inputs are not x/3 multisig";var nt=0;for(var i=0;i<3;i++){if(input.signatures[i])nt++}if(n===undefined){n=nt}else if(n!==nt){throw"all inputs should have same number of signers"}});if(n===0)throw"no sigs";if(n>2)throw"too many sigs";if(tx.outs.length!==1)throw"not 1 output";var addr=bitcoin.address.fromOutputScript(tx.outs[0].script,conf.btcNet);return{tx:tx,txb:txb,txHex:txHex,addr:addr,value:cutil.satoshisToBtc(tx.outs[0].value),n:n}};aq.gotOneMarketControl=function(data,state){if(!data.result)return;var blocks={},b,bn;for(bn in data.result.blocks){b=data.result.blocks[bn];var buf=new Buffer(b,"hex");var hash=cutil.reverseBuffer(cutil.sha256Twice(buf)).toString("hex");blocks[bn]={prev:cutil.reverseBuffer(buf.slice(4,4+32)).toString("hex"),hash:hash,work:cutil.workFromHash(hash),merkle:cutil.reverseBuffer(buf.slice(4+32,4+32+32)).toString("hex")}}for(var i=0;i<data.result.txs.length;i++){var tx=data.result.txs[i];var b=blocks[tx.blockNumber];if(!b){ui.log("block for proof-of-work not provided, ignoring server");return}var merkle=tx.txid;tx.proof.forEach(function(p){if(p[0]){merkle=cutil.merkleHash(p[1],merkle)}else{merkle=cutil.merkleHash(merkle,p[1])}});if(merkle!==b.merkle){ui.log("merkle proof for transaction incorrect, ignoring server");return}var txid=cutil.sha256Twice(new Buffer(tx.hex,"hex"));txid=cutil.reverseBuffer(txid).toString("hex");if(!txid===tx.txid){ui.log("txid is wrong, ignoring server");return}var b0=tx.blockNumber,needWork=conf.workPerShare*tx.sharesOut,prevHash=null;for(var j=b0;;j++){var bj=blocks[j];if(typeof bj==="undefined"){ui.log("block missing for proof of work, ignoring server");return}if(!(j===b0||bj.prev===prevHash)){ui.log("chain has wrong prev hash, ignoring server");return}if(bj.work>=needWork){bj.work-=needWork;break}else{needWork-=bj.work;bj.work=0;prevHash=bj.hash}}}if(!data.result.delegations.every(function(dpv){if(dpv.sigFrom in state.delegators&&dpv.timeReal<=state.delegators[dpv.sigFrom].timeReal){return true}if(dpv.type!=="delegateProxyVote"){ui.log("msg is not delegateProxyVote, bad");return false}if(!aq.verifyMsgSignatures(dpv)){ui.log("msg signature fails, bad");return false}state.delegators[dpv.sigFrom]=dpv;return true})){ui.log("bad delegateProxyVote, ignoring server");return}ui.log("marketControl response looks valid, adding to candidates");var mc=data.result.marketControl;var h2=cutil.sha256(JSON.stringify(mc)).toString("hex");state.msgs[h2]=mc;data.result.txs.forEach(function(tx){if(tx.txid in state.txs){if(tx.sharesOut>state.txs[tx.txid].sharesOut){state.txs[tx.txid].sharesOut=tx.sharesOut}state.txs[tx.txid].timesReceived++}else{state.txs[tx.txid]={hex:tx.hex,sharesOut:tx.sharesOut,timesReceived:1}}})};aq.verifyTransaction=function(txHex){try{var tx=bitcoin.Transaction.fromHex(txHex);if(!isObj(tx)){throw"bitcoin.Transaction return bad"}for(var i=0;i<tx.ins.length;i++){var txin=tx.ins[i];if(!bitcoin.script.isPubKeyHashInput(txin.script)){throw"all inputs should be P2PKH"}var scriptSig=bitcoin.script.decompile(txin.script);if(!(isArray(scriptSig)&&scriptSig.length==2)){throw"scriptSig should have two chunks"}var sig=scriptSig[0],pubKey=scriptSig[1];if(!(sig instanceof Buffer&&pubKey instanceof Buffer)){throw"sig and pubKey should be Buffer"}var pubKeyHash=bitcoin.crypto.hash160(pubKey);var scriptPubKey=bitcoin.script.compile([bitcoin.opcodes.OP_DUP,bitcoin.opcodes.OP_HASH160,pubKeyHash,bitcoin.opcodes.OP_EQUALVERIFY,bitcoin.opcodes.OP_CHECKSIG]);var hfs=tx.hashForSignature(i,scriptPubKey,bitcoin.Transaction.SIGHASH_ALL);var ecp=bitcoin.ECPair.fromPublicKeyBuffer(pubKey);var ecs=bitcoin.ECSignature.fromDER(sig.slice(0,-1));if(!ecMath.verifyEcdsa(hfs,ecs,ecp.Q)){throw"verify signature failed"}}return tx}catch(e){ui.log(" DISCARDED: "+e.toString());return null}};aq.computeOwnership=function(txs){var colored={},txidThatSpends={},txFromTxid={},addr={};ui.log("\nCOMPUTING CAP TABLE FOR MARKET:\n");conf.genesisTxo.forEach(function(txo){var key=txo[0]+","+txo[1];colored[key]=true;addr[key]="genesis"});txs.forEach(function(tx){txFromTxid[tx.txid]=tx;for(var i=0;i<tx.tx.outs.length;i++){var txo=tx.tx.outs[i];if(cutil.valueIsColoredSatoshis(txo.value)){colored[tx.txid+","+i]=true}}});txs.forEach(function(tx){tx.tx.ins.forEach(function(txi){var txo=cutil.txoStringKey(txi);if(txo in txidThatSpends){ui.log(" *** DOUBLE-SPEND DETECTED");ui.log(" picking the tx we received from more servers");var txExisting=txFromTxid[txidThatSpends[txo]];if(tx.timesReceived>txExisting.timesReceived){txidThatSpends[txo]=tx.txid}}else{txidThatSpends[txo]=tx.txid}})});var cap={},process={};conf.genesisTxo.forEach(function(txo){var key=txo[0]+","+txo[1];if(key in txidThatSpends){process[txidThatSpends[key]]=true}cap[key]=txo[2]});function fmtNum(i){var str=i.toString();while(str.length<7)str=" "+str;return str}for(;;){var processNext={},pl=Object.keys(process);if(pl.length===0)break;pl.forEach(function(txid){var tx=txFromTxid[txid];var canApply=true;tx.tx.ins.forEach(function(txi){var key=cutil.txoStringKey(txi);if(colored[key]&&!(key in cap)){canApply=false}});if(!canApply)return;ui.log("for txn "+tx.txid);ui.log(" inputs");var inShares=0;tx.tx.ins.forEach(function(txi){var key=cutil.txoStringKey(txi);if(key in cap){ui.log(" "+fmtNum(cap[key])+" "+key);inShares+=cap[key];delete cap[key]}});var outUnrounded=inShares-conf.destroyPerTransfer;if(outUnrounded>0){var totalValue=0;for(var i=0;i<tx.tx.outs.length;i++){var value=tx.tx.outs[i].value;if(cutil.valueIsColoredSatoshis(value)){totalValue+=value}}ui.log(" outputs");for(var i=0;i<tx.tx.outs.length;i++){var value=tx.tx.outs[i].value,txo=tx.txid+","+i;if(cutil.valueIsColoredSatoshis(value)){var sharesOut=Math.floor(outUnrounded*(value/totalValue));cap[txo]=sharesOut;ui.log(" "+fmtNum(cap[txo])+" "+txo);addr[txo]=bitcoin.address.fromOutputScript(tx.tx.outs[i].script,conf.btcNet);if(txo in txidThatSpends){processNext[txidThatSpends[txo]]=true}}}}else{ui.log(" no outputs, all shares destroyed")}ui.log("")});process=processNext}var utxos=Object.keys(cap);var capByAddr={};utxos.sort(function(a,b){return cap[b]-cap[a]});ui.log("FINAL MARKET OWNERSHIP BY ADDRESS:");utxos.forEach(function(utxo){ui.log(" "+fmtNum(cap[utxo])+" "+addr[utxo]);var ad=addr[utxo];if(!(ad in capByAddr)||ad in capByAddr&&capByAddr[ad]<cap[utxo]){capByAddr[addr[utxo]]=cap[utxo]}});return capByAddr};aq.gotAllMarketControl=function(state){var txs=[];ui.log("\nall marketControl requests have returned or failed now");ui.log("checking signatures on transactions with txid");var txid;for(txid in state.txs){var tx=aq.verifyTransaction(state.txs[txid].hex);if(tx){ui.log(" "+txid+" ok");txs.push({txid:txid,hex:state.txs[txid].hex,tx:tx,timesReceived:state.txs[txid].timesReceived})}}ui.log("checking signatures on marketControl msgs with hash");var h;for(h in state.msgs){var mc=state.msgs[h];ui.log(" "+mc.hash+", sigs="+mc.ownerSig.length);if(!aq.verifyMsgSignatures(mc)){ui.log(" FAIL");delete state.msgs[h]}}ui.log("done checking signatures");var cap=aq.computeOwnership(txs);var delegates={},pkh;for(pkh in state.delegators){var to=state.delegators[pkh].proxy;if(to in delegates){delegates[to].push(pkh)}else{delegates[to]=[pkh]}}ui.log("");ui.log("DELEGATED PROXY VOTING:");for(pkh in delegates){ui.log(" "+pkh+" also votes on behalf of:");delegates[pkh].forEach(function(v){ui.log(" "+v)})}var bestPower={aged:-1e10},bestMsg=null,now=getUnixTime();for(h in state.msgs){var power=msg.marketControlVotingPower(state.msgs[h],now,conf.voteAgingFactor,cap,delegates);if(power.aged>bestPower.aged){bestPower=power;bestMsg=state.msgs[h]}}if(!bestMsg){ui.log("*** NO marketControl MESSAGE RECEIVED");ui.log("Can't proceed without that, reload or check network settings?");ui.log("Markets using .onion servers require Tor.");ui.showPopup("log");return}ui.log("\nselected best marketControl message");ui.log(" net voting power = "+bestPower.aged);ui.log(" hash = "+bestMsg.hash);aq.setStorage("marketControl",{msg:bestMsg,votingPower:bestPower.unaged,receivedAt:getUnixTime()});aq.setStorage("owners",cap);aq.setStorage("delegates",delegates);ui.log("\ndone, getting ticker");window.setTimeout(aq.getTicker,.5*1e3)};aq.getMarketControl=function(servers){ui.log("marketControl message is out of date, getting from network");var hash,votingPower,servers,mc=aq.getStorage("marketControl");if(isObj(mc)&&isObj(mc.msg)){ui.log("old msg.hash = "+mc.msg.hash);hash=mc.msg.hash;votingPower=mc.votingPower}else{ui.log("no existing message, bootstrapping");hash=conf.block0Hash;votingPower=-1e10}ui.log("waiting for "+conf.serverTimeout/1e3+" s, or until all servers respond");var state={msgs:{},txs:{},delegators:{}};aq.rpc.toServers("marketControl",{haveHash:hash,haveVotingPower:votingPower,haveTxids:[],workPerShare:conf.workPerShare},aq.gotOneMarketControl,aq.gotAllMarketControl,state)};var confTest={version:"0.1",network:"TESTNET",block0:702e3,block0Hash:"00000000000088687174912347c38e879d8d559679aef56eac8e053efb77a3e5",genesisTxo:[["da921b15c9fcfddc53cf2810e491239f81a4c7aaf119881a8296fff735836121",0,1e6]],destroyPerTransfer:500,voteAgingFactor:7e-4,workPerShare:1e9,marketControlCheckInterval:2*60*60,tickerInterval:10*60,serverUris:["http://aqla3nr4g3kxr2wm.onion","http://aqla6wqpnyplun5z.onion","http://aqla5tj5a4zjnhun.onion"],serverTimeout:15*1e3,btcExplorer:"https://test-insight.bitpay.com/address/",btcNet:bitcoin.networks.testnet,msgsPerPage:10,postsPerPage:10,listingsPerPage:25,ordersPerPage:10,trustsPerPage:25};var conf=confTest;aq.rpc.sequence=0;aq.rpc.resultFromUntrusted=function(method,rIn){var ck=cutil.checker;if(!isObj(rIn))return;if(isStr(rIn.error)){return{error:rIn.error}}if(method==="sendMsg"||method==="newBuyerIdentity"){if(isStr(rIn.result)){return{result:rIn.result}}else{throw"bad sendMsg / newBuyerIdentity response"}}if(!isObj(rIn.result))return;rIn=rIn.result;if(method==="marketControl"){var marketControl=msg.fromUntrusted(rIn.marketControl,"check");if(!marketControl)return;var delegations=[];if(!isArray(rIn.delegations))"throw delegations not array";rIn.delegations.forEach(function(dpv){dpv=msg.fromUntrusted(dpv,"check");if(!dpv)throw"bad delegateProxyVote";if(dpv.type!=="delegateProxyVote")throw"not delegateProxyVote";delegations.push(dpv)});var bh,blocks={};if(!isObj(rIn.blocks))return;for(bn in rIn.blocks){var b=rIn.blocks[bn];if(isStr(bn)&&bn.match(/^[0-9]+$/)&&bn>conf.block0&&isStr(b)&&b.match(/^[0-9a-f]{160}$/)){blocks[bn]=b}else{return}}var txid,txs=[];if(!isArray(rIn.txs))return;for(var i=0;i<rIn.txs.length;i++){var txIn=rIn.txs[i];var txOut={};if(isStr(txIn.txid)&&txIn.txid.match(/^[0-9a-f]{64}$/)&&isStr(txIn.hex)&&txIn.hex.match(/^[0-9a-f]+$/)&&isInt(txIn.blockNumber)&&isInt(txIn.sharesOut)&&isArray(txIn.proof)){txOut.txid=txIn.txid;txOut.hex=txIn.hex;txOut.blockNumber=txIn.blockNumber;txOut.sharesOut=txIn.sharesOut;txOut.proof=[];for(var j=0;j<txIn.proof.length;j++){var ll=txIn.proof[j];if(ll.length===2&&(ll[0]===0||ll[0]===1)&&(isStr(ll[1])&&ll[1].match(/^[0-9a-f]{64}$/))){txOut.proof.push([ll[0],ll[1]])}else{return}}txs.push(txOut)}else{return}}return{result:{marketControl:marketControl,delegations:delegations,txs:txs,blocks:blocks}}}else if(method==="searchMsg"){var out=[];if(!isInt(rIn.n))throw"n is not an integer";if(!isInt(rIn.skipped))throw"skipped is not an integer";var outh={n:rIn.n,skipped:rIn.skipped};if(isArray(rIn.hashes)){rIn.hashes.forEach(function(h){if(!ck.hex256b(h))throw"not a valid hex hash";out.push(h)});outh.hashes=out;return{result:outh}}else if(isArray(rIn.msgs)){rIn.msgs.forEach(function(m){m=msg.fromUntrusted(m,"check");out.push(m)});outh.msgs=out;if(isArray(rIn.chain)){var chout=[];rIn.chain.forEach(function(m){m=msg.fromUntrusted(m,"check");chout.push(m)});outh.chain=chout}return{result:outh}}else if(isArray(rIn.thumbs)){rIn.thumbs.forEach(function(m){if(!ck.imageDataUrl(m.thumb))throw"not a valid img data url";if(!ck.hex256b(m.hash))throw"not a valid hash";out.push({thumb:m.thumb,hash:m.hash})});outh.thumbs=out;return{result:outh}}else if(isArray(rIn.listings)){rIn.listings.forEach(function(m){if(!ck.hex256b(m.hash))throw"not a valid hash";if(!ck.string(m.subject))throw"not a valid subject";if(!ck.integer(m.timeReal))throw"not a valid time";if(!ck.array(ck.hex256b)(m.images))throw"not valid images";out.push({subject:m.subject,hash:m.hash,timeReal:m.timeReal,images:m.images})});outh.listings=out;return{result:outh}}throw"not implemented"}else if(method==="txos"){var out=[];if(!isArray(rIn))throw"not array";rIn.forEach(function(txo){if(!(ck.hex256b(txo.txid)&&ck.integer(txo.vout)&&ck.number(txo.value)&&ck.btcAddr(txo.addr))){throw"bad txo"}out.push({txid:txo.txid,vout:txo.vout,value:txo.value,addr:txo.addr})});return{result:out}}else if(method==="ticker"){var t=msg.fromUntrusted(rIn,"check");if(!t)throw"bad msg";if(t.type!=="ticker")throw"not ticker";return{result:t}}else{var formatCheck={captcha:{tag:ck.stringMaxLen(30),img:ck.imageDataUrl}};if(!(method in formatCheck))throw"unknown method";var fmt=formatCheck[method];var rOut=ck.check(rIn,fmt);return{result:rOut}}};aq.rpc.toServerUnchecked=function(server,method,params,cbSucceed,cbErr){if(!server.match(/^(http|https):\/\//))return;ui.log(">>> rpc to "+server+", "+method);var countdown=$("<div/>",{"class":"countdown"});countdown.appendTo("#popup-log-countdown");var t0=new Date;function count(){if(!countdown)return;var dt=conf.serverTimeout-(new Date-t0);var str=Math.round(dt/1e3)+"";if(str.length===1)str=" "+str;countdown.text(str);dt-=1e3*Math.floor(dt/1e3);window.setTimeout(count,dt)}count();var rpc={method:method,params:params};$.ajax({type:"POST",url:server+"/rpc",data:JSON.stringify(rpc),success:function(){countdown.remove();countdown=null;cbSucceed.apply(this,arguments)},dataType:"json",error:function(){countdown.remove();countdown=null;cbErr.apply(this,arguments)},timeout:conf.serverTimeout})};aq.rpc.updateGoodness=function(uri,action,dt){var servers=aq.getStorage("servers");if(!servers)servers={};var su;if(!servers[uri]){servers[uri]={goodness:0,receivedAt:getUnixTime(),dtAverage:action==="data"?dt:conf.serverTimeout/1e3}}su=servers[uri];var u,dtAvg=0,dtN=0;for(u in servers){if(u!==uri&&getUnixTime()-servers[u].receivedAt<10*60){dtAvg+=servers[u].dtAverage;dtN++}}dtAvg=dtN===0?conf.serverTimeout/2:dtAvg/dtN;switch(action){case"data":var w=.1;su.dtAverage=(1-w)*su.dtAverage+w*dt;su.receivedAt=getUnixTime();if(su.dtAverage<dtAvg){su.goodness+=200}else{su.goodness+=100}break;case"netFail":case"checkFail":su.goodness-=1e3;break}su.goodness=Math.max(Math.min(su.goodness,3e3),-3e3);for(u in servers){servers[u].goodness*=.95;if(getUnixTime()-servers[u].receivedAt>100*24*60*60){delete servers[u]}}aq.setStorage("servers",servers)};aq.rpc.getServerList=function(method){var serversForce=aq.getStorage("serversForce");if(serversForce){return serversForce}var sc={};var mc=aq.getStorage("marketControl");if(isObj(mc)&&isObj(mc.msg)){mc.msg.serverUris.forEach(function(u){sc[u]=true})}var servers=aq.getStorage("servers");if(method==="marketControl"){conf.serverUris.forEach(function(u){sc[u]=true});return Object.keys(sc)}else{if(!isObj(servers))servers={};var l=Object.keys(sc);function goodness(a){return a in servers?servers[a].goodness:0}l.sort(function(a,b){return goodness(b)-goodness(a)});var best=l.slice(0,2),rest=l.slice(2);if(rest.length>0){var i=Math.floor(rest.length*Math.random());best.push(rest[i])}return best}};aq.rpc.toServers=function(method,params,cbOne,cbAll,state){var servers=aq.rpc.getServerList(method);var total=servers.length,succeeded=0;$("#servers-count").text("0/"+total);$("#servers-dt").text("");var seq=++aq.rpc.sequence;var pending={};servers.forEach(function(server){var t0=new Date;var fs=function(data){var dt=(new Date-t0)/1e3;ui.log("<<< rpc data from "+server+", "+method+" dt="+dt.toFixed(3)+" s");var r;try{r=aq.rpc.resultFromUntrusted(method,data)}catch(e){ui.log("RPC result format bad (rpc.toServers): "+e)}if(r&&cbOne)cbOne(r,state);succeeded++;aq.rpc.updateGoodness(server,r?"data":"checkFail",dt);if(seq===aq.rpc.sequence){$("#servers-count").text(succeeded+"/"+total);if(succeeded<=3){var sdt=$("#servers-dt");sdt.text(sdt.text()+" "+dt.toFixed(1)+"s")}}delete pending[server];if(Object.keys(pending).length===0&&cbAll)cbAll(state)};var fe=function(xhr,textStatus){var dt=(new Date-t0)/1e3;ui.log("<<< rpc failure from "+server+", "+method+" dt="+dt.toFixed(3)+" s");aq.rpc.updateGoodness(server,"netFail",dt);delete pending[server];if(Object.keys(pending).length===0){if(succeeded===0){ui.log("*** ALL REQUESTS FAILED");ui.log("will retry marketControl next time");var mc=aq.getStorage("marketControl");if(isObj(mc)){mc.receivedAt=0;aq.setStorage("marketControl",mc)}}if(cbAll)cbAll(state)}};pending[server]=true;aq.rpc.toServerUnchecked(server,method,params,fs,fe)})};aq.rpc.toOneServer=function(method,params,cb,n){n=n|0;var servers=aq.rpc.getServerList(method),server=servers[0];function fs(data){try{var r=aq.rpc.resultFromUntrusted(method,data);cb(r,server)}catch(e){ui.log("RPC result format bad (rpc.toOneServer): "+e)}}function fe(){aq.rpc.updateGoodness(server,"netFail",conf.serverTimeout);if(n<5){ui.log("aq.rpc.toOneServer failed, retrying");aq.rpc.toOneServer(method,params,cb,n+1)}else{ui.log("*** TRIED FIVE TIMES, GIVING UP")}}aq.rpc.toServerUnchecked(server,method,params,fs,fe)};aq.rpc.toServer=function(server,method,params,cb){aq.rpc.toServerUnchecked(server,method,params,function(data){try{var r=aq.rpc.resultFromUntrusted(method,data);cb(r,server)}catch(e){ui.log("RPC result format bad (rpc.toServer): "+e)}},function(){ui.log("rpc.toServer: failed")})};ui={init:function(){var a,p,page;$("#logosub").text(conf.network);if(!((a=searchParam("a"))&&(p=a.match(/^[-a-zA-Z0-9_]+$/))&&(page=$("#page-"+p[0]))&&page.length===1)){ui.navTo("index");return}page.css("display","block");$("#page-default").css("display","none");$("input.btcaddr").each(function(t,obj){$(obj)[0].placeholder="1xxx59kuE"});$("input.hash").each(function(t,obj){var h="0123456789abcdef";$(obj)[0].placeholder=h+h+h+h});$("#log-text")[0].value="";this.attachClickHandlers();aq.init()},log:function(text){var lt=$("#log-text")[0];lt.value=lt.value+text+"\n";lt.scrollTop=lt.scrollHeight},attachClickHandlers:function(){$("div").each(function(i,obj){var o=$(obj);if(o.data("click")){o.off("click");o.on("click",ui.clickHandler)}if(o.data("address")){o.off("click");o.on("click",ui.addressBookHandler)}});$("span.tab").each(function(t,obj){var o=$(obj);if(o.data("tab")){o.off("click");o.on("click",ui.tabHandler)}})},clickHandler:function(e){var dest=$(e.target).data("click");var f,a=searchParam("a");if(a in aq.page&&dest in aq.page[a]){aq.page[a][dest]()}else if(dest in aq){aq[dest]()}},tabHandler:function(e){$("div.tab-content").each(function(i,obj){$(obj).css("display","none")});$("span.tab").each(function(i,obj){$(obj).removeClass("tab-sel");$(obj).addClass("tab-unsel")});$(e.target).removeClass("tab-unsel");$(e.target).addClass("tab-sel");$("#"+$(e.target).data("tab")).css("display","block")},addressBookHandler:function(e){var dest=$(e.target).data("address");var mc=aq.getStorage("marketControl").msg,ac=mc.adminContact[0];var ab=aq.getStorage("addressBook");if(!ab)ab={};delete ab[ac];var pkhs=Object.keys(ab);pkhs.sort(function(a,b){if(a===b)return 0;return a>b?1:-1});pkhs=[ac].concat(pkhs);ab[ac]="adminContact";var tb=$("#addressBook-popup-body");tb.html("");pkhs.forEach(function(pkh){var tr=$("<tr/>",{"class":"hoverhl"}),tda=$("<td/>",{text:pkh,"class":"mono"}),tdn=$("<td/>",{text:ab[pkh]});if(pkh===ac)tdn.addClass("admin");tda.appendTo(tr);tdn.appendTo(tr);tr.appendTo(tb);tr.on("click",function(){$("#"+dest)[0].value=pkh;ui.hidePopup()})});ui.showPopup("addressBook")},showPopup:function(popup,p){this.hidePopup();$("#popup-"+popup).css("display","block");this.popupShown=popup;$("#dimmer").css("display","block");window.scrollTo(0,0);switch(popup){case"notify":$("#popup-notify-text").text(p);break}},hidePopup:function(){if(this.popupShown){$("#popup-"+this.popupShown).css("display","none");this.popupShown=undefined;$("#dimmer").css("display","none")}},navTo:function(a,extra){var p,str="?a="+encodeURI(a);for(p in extra){str+="&"+encodeURI(p)+"="+encodeURI(extra[p])}window.location=str},navReload:function(){window.location.reload()},pageWithSkip:function(skip,paramsToCopy){var obj={skip:Math.max(0,skip)};paramsToCopy.forEach(function(p){var spp=searchParam(p);if(spp)obj[p]=spp});ui.navTo(searchParam("a"),obj)},pageControls:function(dest,copy,things,skipped,nPage,nTotal,mpp){var dcnt=$(dest+"-count");if(nPage>0&&nTotal>0){dcnt.text(things+(skipped+1)+"-"+(skipped+nPage)+" of "+nTotal)}else if(nTotal>0){dcnt.text("skipped too far?")}else{dcnt.text("no "+things)}var dnew=$(dest+"-newer"),dold=$(dest+"-older");dnew.css("display",skipped>0?"inline":"none");dold.css("display",skipped+nPage<nTotal?"inline":"none");dnew.off("click");dold.off("click");dnew.on("click",function(){ui.pageWithSkip(skipped-mpp,copy)});dold.on("click",function(){ui.pageWithSkip(skipped+mpp,copy)})},hashLink:function(h,page){if(!h.match(/^[0-9a-f]{64}$/))throw"not hash";var a=$("<a/>",{text:h,"class":"wrap mono",href:"?a="+(page||"msg")+"&hash="+encodeURI(h)});return a},hashTableCell:function(h,page){var a=ui.hashLink(h,page),td=$("<td/>",{"class":"wrap"});a.appendTo(td);return td},btcLink:function(btc){return $("<a/>",{text:btc,href:conf.btcExplorer+encodeURI(btc),target:"_blank","class":"payaddr"})},formatBtc:function(btc){return ui.formatBtcBare(btc)+" "+"BTC"},formatBtcBare:function(btc){return isNum(btc)?btc.toFixed(6):"???"},wrapTd:function(e){var td=$("<td/>");e.appendTo(td);return td},addressDiv:function(pkh,oneLine){var raw=$("<a/>",{text:pkh,href:"?a=user&pkh="+encodeURI(pkh),"class":"mono"});raw.css("display","block");raw.css("line-height","130%");raw.css("margin-bottom","2px");raw.css("color","inherit");raw.addClass("wrap");if(!oneLine)raw.css("width","130px");var mc=aq.getStorage("marketControl").msg,adminType=undefined;for(var i=0;i<mc.adminContact.length;i++){if(mc.adminContact[i]===pkh){adminType="adminContact";break}}for(var i=0;i<mc.adminPkh.length;i++){if(mc.adminPkh[i]===pkh&&mc.adminType[i]==="adminSuper"){adminType="adminSuper";break}}var ab=aq.getStorage("addressBook");if(!ab)ab={};var a=$("<a/>",{href:"?a=addressBook&pkh="+encodeURI(pkh)});if(pkh in ab){a.text(ab[pkh])}else if(adminType){a.text(adminType)}else{var keys=aq.getStorage("keys");if(keys&&pkh in keys.secretKeys){a.text("me");a.addClass("me")}else{a.text("new user");a.css("font-style","italic")}}a.css("font-size","14px");a.css("display","block");if(adminType){a.addClass("admin")}var out=$("<div/>");out.css("display","inline-block");if(oneLine){raw.css("display","inline");a.css("display","inline");raw.appendTo(out);$("<span/>",{text:", "}).appendTo(out);a.appendTo(out)}else{raw.appendTo(out);a.appendTo(out)}return out},commentTable:function(m,params){if(!params)params={};var table=$("<table/>",{"class":"borders comment"});var tr0=$("<tr/>"),tr1=$("<tr/>"),fa,s,b;fa=$("<td/>",{rowspan:2});var ft=params.showToNotFrom?"TO:":"FROM:",addr=params.showToNotFrom?m.cipherTo[0]:m.sigFrom;$("<div/>",{text:ft,"class":"fromto"}).appendTo(fa);ui.addressDiv(addr).appendTo(fa);var da=$("<div/>",{text:timeAgo(m.timeReal)+" ago"});da.css("margin","7px 0 10px 0");da.css("font-size","14px");da.appendTo(fa);if(params.replyButton){var b=$("<div/>",{"class":"button-small likereply",text:"Reply"});b.appendTo(fa);$("<br/>").appendTo(fa);var keys=aq.getStorage("keys"),sendReplyTo,replySubject;if(m.sigFrom===keys.primary){sendReplyTo=m.cipherTo[0]}else{sendReplyTo=m.sigFrom}replySubject=m.subject;if(!replySubject.match(/^Re: /))replySubject="Re: "+replySubject;b.on("click",function(){ui.navTo("compose",{to:sendReplyTo,subject:replySubject})})}var alreadyRead=aq.isAlreadyRead(m);if(params.markReadButton){var b=$("<div/>",{"class":"button-small likereply",text:alreadyRead?"Mark Unread":"Mark Read"});b.appendTo(fa);b.on("click",function(){aq.markAlreadyRead(m,!alreadyRead);ui.navReload()})}s=$("<td/>");if(m.ref&&m.type==="privateComment"&&!params.noOrderLink){var subject=m.subject.replace(/^ORDER:/,"");s.text(subject);$("<a/>",{text:"ORDER:",href:"?a=order&hash="+encodeURI(m.ref)}).prependTo(s)}else{s.text(m.subject)}b=$("<td/>");if(m.body)b.text(m.body+"\n\n");if(m.ref&&m.state&&m.type==="privateComment"){var st=$("<div/>",{text:m.state,"class":"state"});$("<b/>",{text:"STATE CHANGED TO: "}).prependTo(st);st.appendTo(b)}if(m.tx&&m.ref){var str;try{var info=aq.getTransactionInfo(m.tx);if(info.n==1)str="proposed, 1/3 ";if(info.n==2)str="accepted, 2/3 ";var txd=$("<div/>",{text:str,"class":"state"});$("<b/>",{text:"ESCROW RELEASE: "}).prependTo(txd);if(info.n===1){var but=$("<div/>",{text:"View Proposal","class":"button-small"});but.on("click",function(){ui.navTo("release",{order:m.ref,tx:m.tx,to:m.sigFrom})});but.appendTo(txd)}else{var but=$("<div/>",{text:"View Transaction","class":"button-small"});but.on("click",function(){$("#viewTx-tx")[0].value=m.tx;$("#viewTx-n").text(2);ui.showPopup("viewTx")});but.appendTo(txd)}txd.appendTo(b)}catch(e){str="bad tx"}}fa.css("width","120px");s.css("height","15px");table.css("width",params.narrower?"640px":"690px");table.css("margin","15px 0 10px 0");table.css("margin-left",params.isReply?"20px":"0");s.css("font-weight","bold");if(alreadyRead)table.addClass("msg-read");[fa,s].forEach(function(e){if(alreadyRead){e.addClass("bg-read")}else if(params.isReply){e.addClass("bg-reply")}else{e.addClass("bg-top")}});[fa,s,b].forEach(function(e){e.css("vertical-align","top")});b.css("white-space","pre-wrap");s.css("padding-top","3px");s.css("padding-bottom","3px");fa.appendTo(tr0);s.appendTo(tr0);b.appendTo(tr1);tr0.appendTo(table);tr1.appendTo(table);return table},countryList:["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","IS","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","ZA","ZM","ZW"],countryEuList:["AT","BE","BG","HR","CY","CZ","DK","EE","FI","FR","DE","GR","HU","IE","IT","LV","LT","LU","MT","NL","PL","PT","RO","SK","SI","ES","SE","GB"],countryAll:function(out){ui.countryList.forEach(function(c){out[c]=true })},countryEu:function(out){ui.countryEuList.forEach(function(c){out[c]=true})},countryValid:function(c){var valid=false;ui.countryList.forEach(function(ct){if(c===ct)valid=true});return valid},countryShow:function(l){var h={},prefix=[];l.forEach(function(c){h[c]=true});function collapse(l2,to){var haveAll=true;l2.forEach(function(c){if(!h[c])haveAll=false});if(haveAll){l2.forEach(function(c){delete h[c]});prefix.push(to)}}collapse(ui.countryList,"ANY");collapse(ui.countryEuList,"EU");return prefix.concat(Object.keys(h)).join(", ")}};window.addEventListener("load",function(){ui.init()});aq.page.index={needKeys:false,init:function(){var latest=0,mc=aq.getStorage("marketControl").msg;function gotOne(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;if(r.result.msgs.length!==1)return;var pc=r.result.msgs[0];if(!(pc.type==="publicComment"&&pc.ref==="userInfo"&&pc.sigFrom===mc.adminPkh[0])){return}if(pc.timeReal<=latest)return;latest=pc.timeReal;if(!aq.verifyMsgSignatures(pc))return;ui.hidePopup();var ct=ui.commentTable(pc);ct.appendTo("#index-info")}function gotAll(){if(latest===0){ui.log("*** the admins have not published market info, odd")}}aq.rpc.toServers("searchMsg",{type:"publicComment",ref:"userInfo",sigFrom:[mc.adminPkh[0]],resultsAs:"msg",limitResults:1},gotOne,gotAll);ui.showPopup("log")}};aq.page.client={needKeys:false,init:function(){var mc=aq.getStorage("marketControl").msg;if(!mc.clientUri.match(/^(http|https):\/\//))return;$("#client-me").text(conf.version);$("#client-version").text(mc.clientVersion.join(", "));var a=$("<a/>",{text:mc.clientUri,href:mc.clientUri});a.appendTo("#client-url");$("#client-hash").text(mc.clientHash)}};aq.page.keys={needKeys:false,allSavedState:["keys","servers","marketControl","txs","addressBook","alreadyRead","serverForce","approveNewIdentity"],pkhCryptsSortedByDate:function(skCrypt){var list=Object.keys(skCrypt);list.sort(function(a,b){return skCrypt[b].created-skCrypt[a].created});return list},publicKeyFromWif:function(wif){var ecp=bitcoin.ECPair.fromWIF(wif,conf.btcNet);return ecp.getPublicKeyBuffer().toString("hex")},getPublicKeys:function(){var keys=aq.getStorage("keys");var kp=keys.secretKeys[keys.primary];var list=aq.page.keys.pkhCryptsSortedByDate(kp.skCrypt);return{btc:aq.page.keys.publicKeyFromWif(kp.skBtc),crypt:aq.page.keys.publicKeyFromWif(kp.skCrypt[list[0]].sk)}},showKeysInTable:function(){function row(){var classes=["mono wrap","","mono wrap","mono wrap"];var tr=$("<tr/>");for(var i=0;i<arguments.length;i++){var td=$("<td/>",{text:arguments[i],"class":classes[i]});if(i===0&&!arguments[1].match(/id/)){td.css("padding-left","25px")}td.appendTo(tr)}var td=$("<td/>");if(arguments[1].match(/id/)){if(arguments[1].match(/primary/)){tr.addClass("hl")}else{var makePrimary=$("<div/>",{text:"Make Primary","class":"button-small"});makePrimary.appendTo(td);var pkh=arguments[0];makePrimary.on("click",function(){var keys=aq.getStorage("keys");if(pkh in keys.secretKeys){keys.primary=pkh;aq.setStorage("keys",keys);ui.navReload()}});var deleteId=$("<div/>",{text:"Delete","class":"button-small"});$("<br/>").appendTo(td);td.css("line-height","30px");deleteId.appendTo(td);deleteId.on("click",function(){ui.navTo("deleteKey",{pkhId:pkh})})}}if(arguments[1].match(/crypt/)&&!arguments[1].match(/newest/)){var pkh=arguments[0];var deleteCrypt=$("<div/>",{text:"Delete","class":"button-small"});deleteCrypt.on("click",function(){ui.navTo("deleteKey",{pkhCrypt:pkh})});deleteCrypt.appendTo(td)}td.appendTo(tr);tr.appendTo("#keys-list")}var keys=aq.getStorage("keys");var makePk=aq.page.keys.publicKeyFromWif;Object.keys(keys.secretKeys).reverse().forEach(function(pkhId){var h=keys.secretKeys[pkhId];var type="identity";if(pkhId===keys.primary)type+=" (primary)";row(pkhId,type,h.skId,makePk(h.skId),timeAgo(h.created));var pkhCrypts=aq.page.keys.pkhCryptsSortedByDate(h.skCrypt);for(var i=0;i<pkhCrypts.length;i++){var pkhCrypt=pkhCrypts[i],str="crypt";if(i===0)str+=" (newest)";var sk=h.skCrypt[pkhCrypt].sk;row(pkhCrypt,str,sk,makePk(sk),timeAgo(h.skCrypt[pkhCrypt].created))}row("not used","btc",h.skBtc,makePk(h.skBtc),timeAgo(h.created))})},checkKeysForIdentity:function(){function gotOne(r){if(gotOk)return;if(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)&&r.result.msgs.length===1){var m=r.result.msgs[0];if(m.pkBtc===pkBtc&&m.pkCrypt===pkCrypt){ui.hidePopup();gotOk=true;ui.log("GOOD keysForIdentity, public keys match")}else{ui.log("BAD keysForIdentity with hash "+m.hash);ui.log(" their pkCrypt = "+m.pkCrypt);ui.log(" our pkCrypt = "+pkCrypt);ui.log(" their pkBtc = "+m.pkBtc);ui.log(" our pkBtc = "+pkBtc)}}else{ui.log("bad or empty result")}}function gotAll(){if(!gotOk)ui.showPopup("keysForIdentity")}var pks=aq.page.keys.getPublicKeys(),pkBtc=pks.btc;pkCrypt=pks.crypt,gotOk=false,keys=aq.getStorage("keys");aq.rpc.toServers("searchMsg",{type:"keysForIdentity",sigFrom:[keys.primary],limitResults:1,resultsAs:"msg"},gotOne,gotAll);ui.showPopup("log")},checkApproveNewIdentity:function(){function gotOne(r){if(gotOk)return;if(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)&&r.result.msgs.length===1){var m=r.result.msgs[0],mc=aq.getStorage("marketControl").msg;if(m.type==="approveNewIdentity"&&m.pkhId===keys.primary&&msg.signedWithAuthorizedAdminKey(m,mc)){gotOk=true;ui.log("GOOD approveNewIdentity, ours");aq.setStorage("approveNewIdentity",m);aq.showToolbarItemsForRole();aq.page.keys.checkKeysForIdentity()}else{ui.log("BAD approveNewIdentity with hash "+m.hash)}}else{ui.log("bad or empty result")}}function gotAll(){if(!gotOk)aq.page.keys.requestNewBuyerApproval()}var gotOk=false,keys=aq.getStorage("keys");ui.log("seek approveNewIdentity for pkhId = "+keys.primary);aq.rpc.toServers("searchMsg",{type:"approveNewIdentity",pkhId:keys.primary,limitResults:1,resultsAs:"msg"},gotOne,gotAll);ui.showPopup("log")},init:function(){var keys=aq.getStorage("keys");if(!isObj(keys)){ui.showPopup("keys");return}if(!aq.getStorage("keysExported")){ui.showPopup("exportKeys");return}aq.page.keys.showKeysInTable();aq.page.keys.checkApproveNewIdentity()},deleteAll:function(){if($("#keys-delete-confirm")[0].value==="DELETE ALL"){aq.page.keys.allSavedState.forEach(function(p){aq.setStorage(p,null)});ui.navTo("keys")}else{ui.showPopup("notify",'Must type "DELETE ALL".')}},requestNewBuyerApproval:function(){var keys=aq.getStorage("keys"),pks=aq.page.keys.getPublicKeys();var kfi={type:"keysForIdentity",pkCrypt:pks.crypt,pkBtc:pks.btc,sigFrom:keys.primary,sig:msg.notYetSigned};msg.fillTime(kfi);kfi=msg.fromUntrusted(kfi,"compute");msg.fillSignatures(kfi);kfi=JSON.stringify(kfi);var path="/approve?&msg="+new Buffer(kfi).toString("base64");var pal=$("#popup-approveNewIdentity-list");var mc=aq.getStorage("marketControl").msg;mc.newBuyerUris.forEach(function(uri){if(!uri.match(/^(http|https):\/\//))return;var li=$("<li/>",{"class":"mono"}),a=$("<a/>",{text:uri+"/approve",href:uri+path,target:"_blank"});a.appendTo(li);li.appendTo(pal)});ui.showPopup("approveNewIdentity")},newRandom:function(ecpId){if(!ecpId){ecpId=bitcoin.ECPair.makeRandom({network:conf.btcNet})}var ecpCrypt=bitcoin.ECPair.makeRandom({network:conf.btcNet}),ecpBtc=bitcoin.ECPair.makeRandom({network:conf.btcNet});var pkhId=ecpId.getAddress(),keys={};keys[pkhId]={skId:ecpId.toWIF(),skCrypt:{},skBtc:ecpBtc.toWIF(),created:getUnixTime()};keys[pkhId].skCrypt[ecpCrypt.getAddress()]={sk:ecpCrypt.toWIF(),created:getUnixTime()};aq.setStorage("keys",{secretKeys:keys,primary:pkhId});aq.setStorage("keysExported",false);ui.navTo("keys")},importWif:function(){try{var wif=$("#keys-wif")[0].value,ecpId=bitcoin.ECPair.fromWIF(wif,conf.btcNet);if(!ecpId)throw"ec pair null"}catch(e){alert("Failed to parse WIF.");return}aq.page.keys.newRandom(ecpId)},advanced:function(){var b=$("#keys-advanced"),d=$("#keys-import-wif");if(d.css("display")==="none"){d.css("display","block");b.text("Hide Advanced")}else{d.css("display","none");b.text("Show Advanced")}},"export":function(){var keys=aq.getStorage("keys");var obj={what:"saved user state for Aquila market client",network:conf.network,version:conf.version,savedAt:(new Date).toISOString()};aq.page.keys.allSavedState.forEach(function(p){obj[p]=aq.getStorage(p)});var str=JSON.stringify(obj,null," ");var a=document.createElement("a");a.href="data:text/json,"+encodeURI(str);a.target="_blank";a.download="aquila-keys-"+keys.primary+".json";a.style.display="none";document.body.appendChild(a);a.click();document.body.removeChild(a);aq.setStorage("keysExported",true);ui.navReload()},"import":function(){var input=$(document.createElement("input"));input.attr("type","file");input.attr("accept",".json");input.on("change",function(e){var fl=input[0].files;if(fl.length!==1)return;var f=fl[0],fr=new FileReader;fr.onload=function(e){try{var str=e.target.result,obj=JSON.parse(str);if(obj.what!=="saved user state for Aquila market client"){throw"not aquila keys? (wrong .what)"}if(obj.network!==conf.network)throw"wrong network";aq.page.keys.allSavedState.forEach(function(p){aq.setStorage(p,obj[p])});aq.setStorage("keysExported",true);ui.navTo("keys")}catch(ex){alert("Load JSON failed: "+ex)}};fr.readAsText(f)});input.trigger("click")},rotateEncryptionKey:function(){var ecp=bitcoin.ECPair.makeRandom({network:conf.btcNet});var keys=aq.getStorage("keys"),pri=keys.secretKeys[keys.primary].skCrypt;pri[ecp.getAddress()]={created:getUnixTime(),sk:ecp.toWIF()};aq.setStorage("keys",keys);aq.setStorage("keysExported",false);ui.navTo("keys")},newBuyerIdentity:function(){var ecp={},params={};["id","btc","crypt"].forEach(function(p){ecp[p]=bitcoin.ECPair.makeRandom({network:conf.btcNet})});var kfi={type:"keysForIdentity",pkCrypt:ecp.crypt.getPublicKeyBuffer().toString("hex"),pkBtc:ecp.btc.getPublicKeyBuffer().toString("hex"),sigFrom:ecp.id.getAddress(),sig:msg.notYetSigned};msg.fillTime(kfi);kfi=msg.fromUntrusted(kfi,"compute");var sig=bitcoin.message.sign(ecp.id,kfi.hash,conf.btcNet);kfi.sig=sig.toString("base64");kfi=JSON.stringify(kfi);params={msg:kfi,sig:[],sigFrom:[]};var keys=aq.getStorage("keys"),sk=keys.secretKeys,pkhsOld;pkhsOld=Object.keys(sk);pkhsOld=pkhsOld.reverse().slice(0,3);pkhsOld.forEach(function(pkhId){var ecpOldId=bitcoin.ECPair.fromWIF(sk[pkhId].skId,conf.btcNet),sig=bitcoin.message.sign(ecpOldId,kfi,conf.btcNet);params.sigFrom.push(pkhId);params.sig.push(sig.toString("base64"))});var mc=aq.getStorage("marketControl").msg;var pnl=$("#popup-newBuyerIdentity-list");pnl.text("");mc.newBuyerUris.forEach(function(url){if(!url.match(/^(http|https):\/\//))return;var li=$("<li/>"),a=$("<a/>",{text:url,href:"#","class":"mono"});a.appendTo(li);li.appendTo(pnl);a.on("click",function(){aq.page.keys.newBuyerIdentityWithServer(url,ecp,params);return false})});ui.showPopup("newBuyerIdentity")},newBuyerIdentityWithServer:function(server,ecp,params,captchaBad){ui.showPopup("log");aq.rpc.toServer(server,"captcha",{},function(r){var captchaTag=r.result.tag;aq.showCaptcha(r,captchaBad);$("#captcha-another").off("click");$("#captcha-another").on("click",function(){aq.page.keys.newBuyerIdentityWithServer(server,ecp,params,false)});$("#captcha-broadcast").text("New Pseudonym");$("#captcha-broadcast").off("click");$("#captcha-broadcast").on("click",function(){params.captchaTag=captchaTag;params.captchaText=$("#captcha-text")[0].value;aq.rpc.toServer(server,"newBuyerIdentity",params,function(r){if(isObj(r)&&r.error==="bad captcha"){aq.page.keys.newBuyerIdentityWithServer(server,ecp,params,true)}else if(isObj(r)&&r.result==="ok"){aq.page.keys.finishNewBuyerIdentity(ecp)}else{ui.log("unknown response: "+JSON.stringify(r))}},function(){ui.log("timeout or other failure")});ui.showPopup("log")})})},finishNewBuyerIdentity:function(ecp){var keys=aq.getStorage("keys"),sk=keys.secretKeys;var pkhId=ecp.id.getAddress();sk[pkhId]={skId:ecp.id.toWIF(),skCrypt:{},skBtc:ecp.btc.toWIF(),created:getUnixTime()};sk[pkhId].skCrypt[ecp.crypt.getAddress()]={sk:ecp.crypt.toWIF(),created:getUnixTime()};keys.primary=pkhId;aq.setStorage("keys",keys);aq.setStorage("keysExported",false);ui.navTo("keys")},broadcastKeysForIdentity:function(){var keys=aq.getStorage("keys");var pks=aq.page.keys.getPublicKeys();var m={type:"keysForIdentity",pkCrypt:pks.crypt,pkBtc:pks.btc,sigFrom:keys.primary,sig:msg.notYetSigned};msg.fillTime(m);m=msg.fromUntrusted(m,"compute");msg.fillSignatures(m);m=JSON.stringify(m);aq.sendMsgWithCaptcha([m])}};aq.page.deleteKey={needKeys:true,init:function(){ui.showPopup("log");var query={limitResults:10};var pkhCrypt=searchParam("pkhCrypt"),pkhId=searchParam("pkhId");if(pkhCrypt){query.cipherPkhCrypt=[pkhCrypt];$("#deleteKey-crypt").css("display","block")}else if(pkhId){query.cipherToAny=[pkhId];$("#deleteKey-id").css("display","block")}else{ui.log("*** NEITHER pkhCrypt NOR pkhId GIVEN");return}aq.getMsgsBySearch(query,function(ms,paging){ms.forEach(function(m){var tr=$("<tr/>");$("<td/>",{text:m.type}).appendTo(tr);ui.hashTableCell(m.hash).appendTo(tr);$("<td/>",{text:timeAgo(m.timeReal)}).appendTo(tr);tr.appendTo("#deleteKey-msgs")});var n=paging.total-paging.inPage;$("#deleteKey-count").text("(and "+n+" older)");ui.hidePopup()})},"delete":function(){if($("#deleteKey-confirm")[0].value!=="DELETE"){ui.showPopup("notify",'Must type "DELETE".');return}var keys=aq.getStorage("keys");var pkhCrypt=searchParam("pkhCrypt"),pkhId=searchParam("pkhId");if(pkhCrypt){var pkh,sk=keys.secretKeys;for(pkh in sk){delete sk[pkh].skCrypt[pkhCrypt]}}else if(pkhId){if(keys.primary===pkhId)return;delete keys.secretKeys[pkhId]}else{return}aq.setStorage("keys",keys);ui.navTo("keys")}};aq.page.addressBook={needKeys:true,init:function(){var ab=aq.getStorage("addressBook"),pkhShow=searchParam("pkh");if(!ab)ab={};if(pkhShow){$("#addressBook-new-addr")[0].value=pkhShow;$("#addressBook-new-nickname")[0].value=pkhShow in ab?ab[pkhShow]:""}var pkhs=Object.keys(ab),cbs=[];pkhs.sort(function(a,b){if(a===b)return 0;if(a===pkhShow)return-1;if(b===pkhShow)return 1;return ab[a]>ab[b]?1:-1});pkhs.forEach(function(pkh){var tr=$("<tr/>");var td=$("<td/>"),a=$("<a/>",{text:pkh,"class":"mono",href:"?a=user&pkh="+encodeURI(pkh)});a.css("color","inherit");a.appendTo(td);td.appendTo(tr);$("<td/>",{text:ab[pkh]}).appendTo(tr);var td=$("<td/>"),cb=$("<input/>",{type:"checkbox"});cb.appendTo(td);td.appendTo(tr);tr.appendTo("#addressBook-body");if(pkh===pkhShow){tr.addClass("hl")}cbs.push([cb,pkh])});if(pkhs.length===0){var tr=$("<tr/>");$("<td/>",{text:"no nicknames yet",colspan:3}).appendTo(tr);tr.appendTo("#addressBook-body")}$("#addressBook-delete").on("click",function(){var ab=aq.getStorage("addressBook");if(!ab)ab={};var deleted=false;cbs.forEach(function(cb){if(cb[0][0].checked){delete ab[cb[1]];deleted=true}});if(deleted){aq.setStorage("addressBook",ab);ui.navTo("addressBook")}else{ui.showPopup("notify","No nicknames selected to delete.")}})},add:function(){var pkh=$("#addressBook-new-addr")[0].value,nick=$("#addressBook-new-nickname")[0].value;if(!cutil.checker.btcAddr(pkh)){ui.showPopup("notify","Not a Bitcoin address.");return}if(nick.length===0){ui.showPopup("notify","Nickname must not be empty.");return}var ab=aq.getStorage("addressBook");if(!ab)ab={};ab[pkh]=nick;aq.setStorage("addressBook",ab);ui.navTo("addressBook")}};aq.page.owner={needKeys:false,init:function(){var keys=aq.getStorage("keys");if(!(isObj(keys)&&Object.keys(keys).length>0)){ui.navTo("keys");return}var mc=aq.getStorage("marketControl").msg,mcHash=mc.hash;var l=["type","genesisTxid","genesisVout","time","timeHash","timeReal","hash","ownerSig","ownerSigFrom"];l.forEach(function(p){mc[p]="(press 'Check' button to fill)"});mc=JSON.stringify(mc,null," ");$("#owner-market-control")[0].value=mc;var owners=aq.getStorage("owners"),sk=keys.secretKeys,pkh,shares=0,totalShares=0;for(pkh in owners){totalShares+=owners[pkh];if(pkh in sk){shares+=owners[pkh]}}var percent=(100*(shares/totalShares)).toFixed(2);$("#owner-stake").text("stake = "+shares+" shares, "+percent+"%");var now=getUnixTime(),owners=aq.getStorage("owners"),delegates=aq.getStorage("delegates"),have={};function gotMsgs(r){if(!(r&&r.result&&isArray(r.result.msgs)))return;r=r.result.msgs;ui.hidePopup();r.forEach(function(mc){var vp=msg.marketControlVotingPower(mc,now,conf.voteAgingFactor,owners,delegates);var mh=cutil.sha256(JSON.stringify(mc)).toString("hex");if(have[mh])return;var tr=$("<tr/>");ui.hashTableCell(mc.hash).appendTo(tr);var pkh=mc.adminPkh.length>0?mc.adminPkh[0]:"-";$("<td/>",{text:pkh,"class":"mono wrap"}).appendTo(tr);$("<td/>",{text:timeAgo(mc.timeReal)}).appendTo(tr);var vpp=(100*(vp.aged/totalShares)).toFixed(2)+"%";$("<td/>",{text:vpp}).appendTo(tr);var td=$("<td/>"),rd=$("<input/>",{type:"radio",name:"owner-rad"});rd.appendTo(td);td.appendTo(tr);if(mc.hash===mcHash)tr.addClass("hl");have[mh]={marketControl:mc,radio:rd};tr.appendTo("#owner-votables")})}$("#owner-vote-button").on("click",function(){var mh;for(mh in have){if(have[mh].radio[0].checked){aq.page.owner.voteFor(have[mh].marketControl);return}}ui.showPopup("notify","No message selected.")});aq.rpc.toServers("searchMsg",{type:"marketControl",limitResults:30,resultsAs:"msg",sortBy:"votingPower"},gotMsgs,null);ui.showPopup("log");var radios={};for(pkh in sk){if(!(pkh in owners))continue;var tr=$("<tr/>");$("<td/>",{"class":"mono",text:pkh}).appendTo(tr);$("<td/>",{"class":"mono",text:owners[pkh]}).appendTo(tr);radios[pkh]=$("<input/>",{type:"radio",name:"owner-pkhs"});ui.wrapTd(radios[pkh]).appendTo(tr);tr.appendTo("#owner-pkhs")}function delegate(to){try{var pkh,from;for(pkh in radios){if(radios[pkh][0].checked)from=pkh}if(!from)throw"Must select a key.";to=to||from;if(!owners[to])throw"Delegate must be an owner.";var dpv={type:"delegateProxyVote",proxy:to,sigFrom:from,sig:msg.notYetSigned};msg.fillTime(dpv);dpv=msg.fromUntrusted(dpv,"compute");msg.fillSignatures(dpv);dpv=JSON.stringify(dpv);aq.sendMsgWithCaptcha([dpv])}catch(e){ui.showPopup("notify","Failed: "+e)}}$("#owner-delegate").on("click",function(){delegate($("#owner-proxy-addr")[0].value)});$("#owner-rescind").on("click",function(){delegate()})},checkMarketControl:function(silent){var mc;try{var ta=$("#owner-market-control")[0];mc=JSON.parse(ta.value);mc.type="marketControl";msg.fillTime(mc);mc.ownerSigFrom=[];mc.ownerSig=[];mc=msg.fromUntrusted(mc,"compute");ta.value=JSON.stringify(mc,null," ")}catch(e){if(!silent){ui.showPopup("notify","Message format bad: "+e.toString())}return}if(!silent){ui.showPopup("notify","Message format okay. The time, hash, and signatures will "+"be filled upon broadcast.")}return mc},fillOwnerSignatures:function(mc){var i,have={};for(i=0;i<mc.ownerSig.length;i++){have[mc.ownerSigFrom[i]]=true}var owners=aq.getStorage("owners"),keys=aq.getStorage("keys"),pkh;for(pkh in keys.secretKeys){if(owners[pkh]&&!have[pkh]){mc.ownerSigFrom.push(pkh);mc.ownerSig.push(msg.notYetSigned)}}},broadcastMarketControl:function(){var mc=aq.page.owner.checkMarketControl(true);if(!mc){ui.showPopup("notify","Format bad, use check button to debug.");return}aq.page.owner.fillOwnerSignatures(mc);if(mc.ownerSigFrom.length===0){ui.showPopup("notify","Need owner keys to send marketControl.");return}msg.fillSignatures(mc);aq.sendMsgWithCaptcha([JSON.stringify(mc)])},voteFor:function(mcIn){var mc=JSON.parse(JSON.stringify(mcIn));var before=mc.ownerSig.length;aq.page.owner.fillOwnerSignatures(mc);if(mc.ownerSig.length===before){ui.showPopup("notify","Already signed, or no owner keys loaded.");return}msg.fillSignatures(mc);aq.sendMsgWithCaptcha([JSON.stringify(mc)])}};aq.page.admin={needKeys:false,init:function(){var keys=aq.getStorage("keys");if(!isObj(keys))ui.navTo("keys")},approveNewIdentity:function(){var ani={type:"approveNewIdentity",allowed:!$("#admin-approve-ban")[0].checked,maySell:$("#admin-approve-sell")[0].checked,pkhId:$("#admin-approve-pkhId")[0].value,validFrom:timeFromUserInput($("#admin-approve-validFrom")[0].value),validTo:timeFromUserInput($("#admin-approve-validTo")[0].value),kbPerDay:$("#admin-approve-kbPerDay")[0].value|0,comment:$("#admin-approve-comment")[0].value};aq.finishAndSendMsg(ani)},"delete":function(){var dm={type:"deleteMessage",toDelete:$("#admin-delete-hash")[0].value,comment:$("#admin-delete-comment")[0].value};aq.finishAndSendMsg(dm)},requestFeePayment:function(){try{var rfp={type:"requestFeePayment",feeFrom:[],feeTo:[],feeAmount:[],comment:$("#admin-fee-comment")[0].value};var t=$("#admin-fee-text")[0].value;var lc=0;t.split("\n").forEach(function(line){lc++;if(line==="")throw"empty line";var sp=line.split(",");if(sp.length!==3){throw"bad field count, want=3 have="+sp.length}if(!cutil.checker.btcAddr(sp[0]))throw"sender address bad";if(!cutil.checker.btcAddr(sp[1]))throw"recipient address bad";sp[2]=Number(sp[2]);if(sp[2]<0||sp[2]>100)throw"bad value";rfp.feeFrom.push(sp[0]);rfp.feeTo.push(sp[1]);rfp.feeAmount.push(sp[2])})}catch(e){ui.showPopup("notify","Bad fee request: "+e+": around line "+lc);return}aq.finishAndSendMsg(rfp)}};aq.page.servers={needKeys:false,init:function(){var inMc={},inBootstrap={};var mc=aq.getStorage("marketControl");if(isObj(mc)){mc=mc.msg;mc.serverUris.forEach(function(uri){inMc[uri]=true})}conf.serverUris.forEach(function(uri){inBootstrap[uri]=true});var uris,servers=aq.getStorage("servers");if(servers){uris=Object.keys(servers);uris.sort(function(a,b){return servers[b].goodness-servers[a].goodness})}else{uris=[]}function yes(v){return v?"✓":""}uris.forEach(function(uri){var tr=$("<tr/>");$("<td/>",{text:uri,"class":"mono"}).appendTo(tr);$("<td/>",{text:servers[uri].goodness.toFixed(0)}).appendTo(tr);$("<td/>",{text:servers[uri].dtAverage.toFixed(3)}).appendTo(tr);$("<td/>",{text:timeAgo(servers[uri].receivedAt)}).appendTo(tr);$("<td/>",{text:yes(inMc[uri]),"class":"center"}).appendTo(tr);$("<td/>",{text:yes(inBootstrap[uri]),"class":"center"}).appendTo(tr);tr.appendTo("#servers-working")});for(var i=0;i<3;i++){var sm=$("#servers-manual-"+i);sm[0].placeholder="http://xxx.onion";sm[0].value="";sm.on("input",function(){$("#servers-manual")[0].checked=true})}var serversForce=aq.getStorage("serversForce");if(serversForce){$("#servers-manual")[0].checked=true;for(var i=0;i<Math.min(3,serversForce.length);i++){$("#servers-manual-"+i)[0].value=serversForce[i]}}else{$("#servers-auto")[0].checked=true}},save:function(){var sf=[];if($("#servers-manual")[0].checked){for(var i=0;i<3;i++){var s=$("#servers-manual-"+i)[0].value;if(s.match(/^http/))sf.push(s)}}aq.setStorage("serversForce",sf.length>0?sf:null);ui.navReload()}};aq.page.msg={needKeys:false,searchParams:["type","minTime","maxTime","sigFrom","cipherTo","skipResults","custom-key","custom-value"],init:function(){var gotStuff=false,have={};function gotMessage(r){if(gotStuff)return;if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;if(r.result.msgs.length!==1)return;r=r.result.msgs[0];gotStuff=true;if(!aq.verifyMsgSignatures(r))return;ui.hidePopup();$("#msg-json").css("display","block");var append="";if("cipherTo"in r){try{var sk=aq.getStorage("keys").secretKeys;te=msg.extractCiphered(r,sk),m2={};["cipherText","cipherEphem","cipherIv","cipherPkhCrypt","cipherSessionKey"].forEach(function(p){m2[p]=r[p];delete r[p]});append+="decrypted = "+JSON.stringify(te,null," ");append+="\nciphered = "+JSON.stringify(m2,null," ")}catch(e){append+="// could not decrypt: "+e+"\n"}}var str=JSON.stringify(r,null," "),out="";str.split("\n").forEach(function(line){["timeReal","validFrom","validTo"].forEach(function(p){var prefix=' "'+p+'"';if(line.substr(0,prefix.length)===prefix){line+=" // "+timePlusMinus(r[p])}});out+=line+"\n"});out+=append;$("#msg-json")[0].value="msg = "+out}function gotHashes(r){if(!(r&&r.result))return;r=r.result;if(!(isArray(r.hashes)&&r.hashes.length>0))return;gotStuff=true;r.hashes.forEach(function(h){if(have[h])return;have[h]=true;var tr=$("<tr/>");ui.hashTableCell(h).appendTo(tr);tr.appendTo("#msg-hashes")});ui.hidePopup();$("#msg-table-many").css("display","block");$("#msg-count").css("display","block");$("#msg-count").text("total matching = "+r.n)}function gotAll(){if(!gotStuff){ui.log("*** ALL REQUESTS TIMED OUT OR RETURNED NO MSGS")}}var h=searchParam("hash");if(h&&h.length===64){aq.rpc.toServers("searchMsg",{hashInclude:[h],deletedOk:true,resultsAs:"msg"},gotMessage,gotAll);$("#msg-search").css("display","none")}else{var params={limitResults:20,skipResults:0,resultsAs:"hash"};aq.page.msg.searchParams.forEach(function(p){var v=searchParam(p);if(v&&v.length>0){$("#msg-"+p)[0].value=v;if(p==="maxTime"||p==="minTime"){v=timeFromUserInput(v)}else if(p==="sigFrom"||p==="cipherTo"){v=[v]}else if(p==="skipResults"){v=v|0}else if(p==="custom-value"){p=searchParam("custom-key")}params[p]=v}});if(searchParam("deletedOk")){$("#msg-deletedOk")[0].checked=true;params.deletedOk=true}aq.rpc.toServers("searchMsg",params,gotHashes,gotAll)}ui.showPopup("log")},get:function(){var params={};aq.page.msg.searchParams.concat(["hash"]).forEach(function(p){var v=$("#msg-"+p)[0].value;if(v&&v.length>0){params[p]=v}});if($("#msg-deletedOk")[0].checked)params.deletedOk="true";ui.navTo("msg",params)},getAll:function(){ui.navTo("msg")}};aq.page.marketControl={needKeys:false,init:function(){var mc=aq.getStorage("marketControl").msg,owners=aq.getStorage("owners"),delegates=aq.getStorage("delegates"),ticker=aq.getStorage("ticker");mc.ownerSig="(not shown here)";ticker.sig="(not shown here)";$("#marketControl-marketControl").text(JSON.stringify(mc,null," "));$("#marketControl-owners").text(JSON.stringify(owners,null," "));$("#marketControl-delegates").text(JSON.stringify(delegates,null," "));$("#marketControl-ticker").text(JSON.stringify(ticker,null," "))},refresh:function(){aq.setStorage("ticker",null);aq.setStorage("marketControl",null);ui.navReload()}};aq.page.forumList={needKeys:false,init:function(){var mc=aq.getStorage("marketControl").msg;var fb=$("#forumList-body");mc.forums.forEach(function(f){var tr=$("<tr/>"),td=$("<td/>"),a=$("<a/>",{text:f,href:"?a=forum&f="+encodeURI(f)});a.appendTo(td);td.appendTo(tr);tr.appendTo(fb)})}};aq.page.forum={needKeys:false,init:function(){var f=searchParam("f"),ref=searchParam("ref"),topLevel;if(ref){$("#forum-postings").css("display","none");$("#forum-post").text("Broadcast New Forum Reply");topLevel=false}else{$("#forum-replies").css("display","none");$("#forum-parent").css("display","none");$("#forum-post").text("Broadcast New Forum Post");ref=f;topLevel=true}$("#forum-title").text(f);$("#forum-postings").css("width","700px");$("#forum-subject")[0].value="";$("#forum-body")[0].value="";if(!topLevel){$("#forum-compose").css("padding-left","30px")}function trForPostSummary(m,uri){var tr=$("<tr/>");var a=$("<td/>",{text:timeAgo(m.timeReal)});a.appendTo(tr);a.css("width","40px");var f=$("<td/>");ui.addressDiv(m.sigFrom).appendTo(f);f.appendTo(tr);f.css("width","120px");var sa=$("<a/>",{text:m.subject,href:uri}),std=$("<td/>");sa.appendTo(std);std.appendTo(tr);return tr}function tableForCompletePost(m,reply){return ui.commentTable(m,{isReply:reply})}var have={},haveParent=false;if(!topLevel){aq.rpc.toServers("searchMsg",{hashInclude:[ref],resultsAs:"msg"},function(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;if(r.result.msgs.length!==1)return;var m=r.result.msgs[0];if(haveParent||m.hash!==ref)return;haveParent=true;var table=tableForCompletePost(m);table.appendTo("#forum-parent");aq.asyncVerifyMsgSignatures(m,table);$("#forum-subject")[0].value=m.subject;$("#forum-body")[0].value=""},null)}aq.rpc.toServers("searchMsg",{type:"publicComment",ref:ref,skipResults:searchParam("skip")|0,limitResults:conf.postsPerPage,resultsAs:"msg",sortBy:topLevel?"timeForum":"timeReal"},function(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;var fpb=$("#forum-postings-body");r.result.msgs.forEach(function(m){if(have[m.hash])return;have[m.hash]=true;var elem;if(topLevel){var uri="?a=forum&f="+encodeURI(f)+"&ref="+encodeURI(m.hash);elem=trForPostSummary(m,uri);elem.appendTo("#forum-postings")}else{elem=tableForCompletePost(m,true);elem.appendTo("#forum-replies")}aq.asyncVerifyMsgSignatures(m,elem)});if(Object.keys(have).length===0){have["empty-forum"]=true;if(topLevel){var tr=$("<tr/>");$("<td/>",{text:"no posts yet in this forum",colspan:3}).appendTo(tr);tr.appendTo(fpb)}}var copy=["f","ref"];ui.pageControls("#forum",copy,topLevel?"posts ":"replies ",r.result.skipped,r.result.msgs.length,r.result.n,conf.postsPerPage);ui.hidePopup()},null);ui.showPopup("log")},post:function(){var keys=aq.getStorage("keys");if(!keys){ui.navTo("keys");return}var subject=$("#forum-subject")[0].value,body=$("#forum-body")[0].value,ref=searchParam("ref")||searchParam("f");if(subject.length<10||body.length<10){ui.showPopup("notify","Subject or body too short.");return}var pc={type:"publicComment",subject:subject,body:body,ref:ref};aq.finishAndSendMsg(pc,function(){ui.navReload()})}};aq.page.compose={needKeys:true,init:function(){var keys=aq.getStorage("keys");$("#compose-from").text(keys.primary);$("#compose-subject")[0].value=searchParam("subject")||"";$("#compose-to")[0].value=searchParam("to")||"";if(searchParam("order")){$("#compose-order").css("display","table-row");$("#compose-state")[0].disabled=!searchParam("isSeller");if(searchParam("escrowReleased")){$("#compose-state")[0].value="escrow released"}$("#compose-to")[0].readOnly=true;$("#compose-subject")[0].readOnly=true;$("#compose-addrBook").css("display","none")}if(searchParam("tx")){try{var obj=aq.getTransactionInfo(searchParam("tx"));$("#compose-nsigs").text(obj.n);ui.btcLink(obj.addr).appendTo("#compose-outAddr");$("#compose-tx").css("display","table-row");$("#compose-viewTx").on("click",function(){$("#viewTx-tx")[0].value=searchParam("tx");$("#viewTx-n").text(obj.n);ui.showPopup("viewTx")})}catch(e){}}},viewOrder:function(){ui.navTo("order",{hash:searchParam("order")})},send:function(){var order=searchParam("order"),state=$("#compose-state")[0].value;var s=$("#compose-subject")[0].value,b=$("#compose-body")[0].value,t=$("#compose-to")[0].value;try{if(s.length<1)throw"subject is blank";if(b.length<1&&!state)throw"body is blank";if(!cutil.checker.btcAddr(t))throw"to: format bad"}catch(e){ui.showPopup("notify","Failed to send: "+e);return}var keys=aq.getStorage("keys"),pks=aq.page.keys.getPublicKeys();var toPubKey={};toPubKey[t]=null;if($("#compose-me")[0].checked){toPubKey[keys.primary]=pks.crypt}if($("#compose-admins")[0].checked){var mc=aq.getStorage("marketControl").msg;toPubKey[mc.adminContact[0]]=null}function send(){var pkh,cipherTo=[],pks=[];for(pkh in toPubKey){cipherTo.push(pkh);pks.push(toPubKey[pkh])}var pc={type:"privateComment",ref:order?order:"",state:order?state:"",cipherTo:cipherTo};var toEncrypt={subject:s,body:b};if(searchParam("tx"))toEncrypt.tx=searchParam("tx");try{msg.fillCiphered(pc,toEncrypt,pks);pc.sigFrom=keys.primary;pc.sig=msg.notYetSigned;msg.fillTime(pc);pc=msg.fromUntrusted(pc,"compute");msg.fillSignatures(pc);pc=JSON.stringify(pc);var list=[pc];if(toEncrypt.tx){try{var info=aq.getTransactionInfo(toEncrypt.tx);if(info.n===2){list.push(JSON.stringify({type:"broadcastBtcTx",tx:toEncrypt.tx}))}}catch(e){}}aq.sendMsgWithCaptcha(list,function(){if(order){ui.navTo("order",{hash:order})}else{ui.navTo("sent")}})}catch(e){ui.showPopup("notify","Failed to cipher and send")}}var gotKeys=false;function gotOne(r){if(gotKeys)return;if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;if(r.result.msgs.length!==1){ui.log("*** MISSING keysForIdentity");return}var kfi=r.result.msgs[0];if(!(kfi.type==="keysForIdentity"&&kfi.sigFrom in toPubKey&&aq.verifyMsgSignatures(kfi))){ui.log("*** BAD keysForIdentity");return}ui.log("got keysForIdentity for "+kfi.sigFrom+":");ui.log(" pkCrypt = "+kfi.pkCrypt);ui.log(" timeReal = "+kfi.timeReal);toPubKey[kfi.sigFrom]=kfi.pkCrypt;var pkh;for(pkh in toPubKey){if(!toPubKey[pkh])return}gotKeys=true;send()}var pkh;for(pkh in toPubKey){if(toPubKey[pkh])continue;aq.rpc.toServers("searchMsg",{type:"keysForIdentity",sigFrom:[pkh],limitResults:1,resultsAs:"msg"},gotOne,null) }ui.showPopup("log")}};aq.privateMsg={};aq.privateMsg.gotOne=function(r,have,dest){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;r=r.result;r.msgs.forEach(function(m){if(have[m.hash])return;have[m.hash]=true;msg.extractCipheredPrivateComment(m);var t=ui.commentTable(m,{showToNotFrom:dest==="#sent",replyButton:true,markReadButton:dest!=="#sent"});t.appendTo(dest+"-msgs");aq.asyncVerifyMsgSignatures(m,t)});var copy=["to","from","unreadOnly"];ui.pageControls(dest,copy,"msgs ",r.skipped,r.msgs.length,r.n,conf.msgsPerPage);ui.hidePopup()};aq.page.inbox={needKeys:true,init:function(){var spf=searchParam("from"),spu=searchParam("unreadOnly");$("#inbox-from")[0].value=spf||"";$("#inbox-unread")[0].checked=spu;var keys=aq.getStorage("keys");var have={},p={type:"privateComment",cipherTo:[keys.primary],skipResults:searchParam("skip")|0,limitResults:conf.msgsPerPage,resultsAs:"msg"};if(spf)p.sigFrom=[spf];if(spu){p.hashExclude=Object.keys(aq.alreadyRead.hashes);p.minTime=aq.alreadyRead.omitsBefore+1;if(aq.alreadyRead.omitsBefore!==0){$("#inbox-warning-age").text(timeAgo(aq.alreadyRead.omitsBefore));$("#inbox-warning").css("display","block")}}aq.rpc.toServers("searchMsg",p,function(r){aq.privateMsg.gotOne(r,have,"#inbox")},null);ui.showPopup("log")},clearFilter:function(){ui.navTo("inbox")},filter:function(){var p={},from=$("#inbox-from")[0].value;if(from!==""){if(!cutil.checker.btcAddr(from)){ui.showPopup("notify","Bad format for from: address");return}p.from=from}if($("#inbox-unread")[0].checked)p.unreadOnly=true;ui.navTo("inbox",p)}};aq.page.sent={needKeys:true,init:function(){var spt=searchParam("to");$("#sent-to")[0].value=spt||"";var keys=aq.getStorage("keys");var have={},p={type:"privateComment",sigFrom:[keys.primary],skipResults:searchParam("skip")|0,limitResults:conf.msgsPerPage,resultsAs:"msg"};if(spt)p.cipherTo=[spt];aq.rpc.toServers("searchMsg",p,function(r){aq.privateMsg.gotOne(r,have,"#sent")},null);ui.showPopup("log")},clearFilter:function(){ui.navTo("sent")},filter:function(){var p={},to=$("#sent-to")[0].value;if(to!==""){if(!cutil.checker.btcAddr(to)){ui.showPopup("notify","Bad format for to: address");return}p.to=to}ui.navTo("sent",p)}};aq.page.uploadImgs={needKeys:true,init:function(){var keys=aq.getStorage("keys");var have={};function gotOne(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.thumbs)))return;r.result.thumbs.forEach(function(thumb){if(have[thumb.hash])return;var div=$("<div/>"),label=$("<label/>");$("<img/>",{src:"data:"+aq.imageDataUrl(thumb.thumb)}).appendTo(label);var radio=$("<input/>",{type:"radio",name:"uploadImgs-del"});radio.appendTo(label);label.appendTo(div);div.appendTo("#uploadImgs-existing");have[thumb.hash]=radio});if(Object.keys(have).length===0){$("#uploadImgs-existing").text(" (no images have been uploaded yet)");$("#uploadImgs-delete").css("display","none")}else{$("#uploadImgs-delete").css("display","inline")}ui.hidePopup("log")}$("#uploadImgs-delete").on("click",function(){var hash;for(hash in have){if(have[hash][0].checked){var dm={type:"deleteMessage",toDelete:hash,comment:"by poster from client"};aq.finishAndSendMsg(dm,function(){ui.navReload()});return}}ui.showPopup("notify","No image to delete selected.")});aq.rpc.toServers("searchMsg",{type:"image",sigFrom:[keys.primary],resultsAs:"thumb"},gotOne,null);ui.showPopup("log")},previewFinish:function(blob){createImageBitmap(blob).then(function(img){function scaleToCanvas(img,dest,scale){var w=scale*img.width,h=scale*img.height;var ci=$(dest)[0],cic=ci.getContext("2d");ci.height=h;ci.width=w;cic.drawImage(img,0,0,w,h)}var whMax=Math.max(img.width,img.height),scaleImage=Math.min(1,330/whMax),scaleThumb=110/whMax;scaleToCanvas(img,"#uploadImgs-image",scaleImage);scaleToCanvas(img,"#uploadImgs-thumb",scaleThumb);$("#uploadImgs-preview").css("display","block");$("#uploadImgs-upload").css("display","inline")})},preview:function(){var input=$(document.createElement("input"));input.attr("type","file");input.attr("accept",".jpeg,.jpg");input.on("change",function(e){var fl=input[0].files;if(fl.length!==1)return;aq.page.uploadImgs.previewFinish(fl[0])});input.trigger("click")},upload:function(){function getDatUrl(id,maxLen){var c=$(id)[0],quality=.8;for(;;){var url=c.toDataURL("image/jpeg",quality);if(url.length<maxLen){return url}else if(quality>.1){quality-=.1}else{alert("Could not export JPEG within size limit.");return}}}var image=getDatUrl("#uploadImgs-image",90*1e3),thumb=getDatUrl("#uploadImgs-thumb",9*1e3);var m={type:"image",image:image,thumb:thumb};aq.finishAndSendMsg(m,function(){ui.navReload()})}};aq.page.listingNew={needKeys:true,init:function(){var mc=aq.getStorage("marketControl").msg;mc.categories.forEach(function(cat){var l=cat.replace(/;/g,": ");opt=$("<option/>",{text:l,value:cat});opt.appendTo("#listingNew-category")});var ticker=aq.getStorage("ticker");ticker.currencies.forEach(function(code){var opt=$("<option/>",{text:code,value:code});opt.appendTo("#listingNew-currency")});function addItemRow(){var tr=$("<tr/>"),td=[];for(var i=0;i<4;i++){td[i]=$("<td/>");td[i].appendTo(tr)}var desc=$("<input/>");desc.css("width","300px");desc.appendTo(td[0]);var price=$("<input/>");price.css("width","70px");price.appendTo(td[1]);var group=$("<select/>");group.appendTo(td[2]);$("<option/>",{text:"main",value:"main"}).appendTo(group);$("<option/>",{text:"shipping",value:"shipping"}).appendTo(group);var del=$("<div/>",{"class":"button-small",text:"Delete Row"});del.appendTo(td[3]);del.on("click",function(){if($("#listingNew-items").children().length>2)tr.remove()});$("#listingNew-items-add-row").before(tr)}$("#listingNew-items-add").on("click",function(){addItemRow()});addItemRow();var haveThumb={};function gotThumb(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.thumbs)))return;r.result.thumbs.forEach(function(thumb){if(haveThumb[thumb.hash])return;var div=$("<div/>"),label=$("<label/>");$("<img/>",{src:"data:"+aq.imageDataUrl(thumb.thumb)}).appendTo(label);var check=$("<input/>",{type:"checkbox"});check.appendTo(label);label.appendTo(div);div.appendTo("#listingNew-images");haveThumb[thumb.hash]=check});if(Object.keys(haveThumb).length===0){$("#listingNew-images").text(" (no images have been uploaded yet)")}ui.hidePopup("log")}$("#listingNew-create").on("click",function(){aq.page.listingNew.create(haveThumb)});var keys=aq.getStorage("keys");aq.rpc.toServers("searchMsg",{type:"image",sigFrom:[keys.primary],resultsAs:"thumb"},gotThumb,null);ui.showPopup("log")},create:function(imgs){function countryList(id){var csv=$(id)[0].value;csv=csv.toUpperCase().replace("[^A-Za-z,]","");var out={};csv.split(",").forEach(function(c){if(c==="ANY"){ui.countryAll(out)}else if(c==="EU"){ui.countryEu(out)}else if(ui.countryValid(c)){out[c]=true}else{throw"country code not valid, "+c+", valid codes are ISO 3166-1 alpha-2"}});return Object.keys(out)}try{var m={type:"listing",subject:$("#listingNew-subject")[0].value,body:$("#listingNew-body")[0].value,images:[],category:$("#listingNew-category")[0].value,shipFrom:countryList("#listingNew-from"),shipTo:countryList("#listingNew-to"),currency:$("#listingNew-currency")[0].value,itemPrice:[],itemDesc:[],itemGroup:[]};var hash;for(hash in imgs){if(imgs[hash][0].checked){m.images.push(hash)}}var rows=$("#listingNew-items").children();for(var i=0;i<rows.length-1;i++){var row=rows[i],desc=row.children[0].children[0].value,price=row.children[1].children[0].value,group=row.children[2].children[0].value;if(desc.length<1)throw"description is blank";price=price*1;if(!(price>=0))throw"price is not a number";m.itemPrice.push(price);m.itemDesc.push(desc);m.itemGroup.push(group)}aq.finishAndSendMsg(m,function(m){try{var mp=JSON.parse(m[0]);ui.navTo("listing",{hash:mp.hash})}catch(e){}})}catch(e){ui.showPopup("notify","Bad format: "+e)}}};aq.page.listings={needKeys:true,init:function(){var haveListing={};function gotListing(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.listings)))return;r.result.listings.forEach(function(lst){if(haveListing[lst.hash])return;var tr=$("<tr/>"),td=$("<td/>");var a=$("<a/>",{text:lst.subject,href:"?a=listing&hash="+encodeURI(lst.hash)});a.appendTo(td);td.appendTo(tr);$("<td/>",{text:timeAgo(lst.timeReal)}).appendTo(tr);var check=$("<input/>",{type:"radio",name:"listings-delete"});td=$("<td/>");check.appendTo(td);td.appendTo(tr);tr.appendTo("#listings-existing");haveListing[lst.hash]=check});ui.hidePopup("log")}$("#listings-delete").on("click",function(){var hash;for(hash in haveListing){if(haveListing[hash][0].checked){var dm={type:"deleteMessage",toDelete:hash,comment:"by poster from client"};aq.finishAndSendMsg(dm,function(){ui.navReload()});return}}ui.showPopup("notify","No listing to delete selected.")});var keys=aq.getStorage("keys");aq.rpc.toServers("searchMsg",{type:"listing",sigFrom:[keys.primary],resultsAs:"listing"},gotListing,null);ui.showPopup("log")}};aq.page.listing={needKeys:false,init:function(){var qtys=[];var listing,kfi;var mc=aq.getStorage("marketControl").msg;function getQtys(){if(!listing)return;var out=[];for(var i=0;i<listing.itemPrice.length;i++){var input=qtys[i][0];if(input.type==="radio"){out.push(input.checked?1:0)}else{out.push(input.value*1)}}return out}function updateTotal(){if(!listing)return;var q=getQtys(),total=0;for(var i=0;i<q.length;i++){total+=q[i]*listing.itemPrice[i]}var str;if(total>0){str="for total cost "+total+" "+listing.currency;if(listing.currency!=="BTC"){str+=" = ";str+=ui.formatBtc(aq.currencyToBtc(total,listing.currency))}}else{str="bad quantities"}$("#listing-total").text(str)}var wantImage={};function gotImage(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;r.result.msgs.forEach(function(img){if(!wantImage[img.hash])return;if(!aq.verifyMsgSignatures(img))return;delete wantImage[img.hash];var div=$("<div/>");$("<img/>",{src:"data:"+aq.imageDataUrl(img.image)}).appendTo(div);div.appendTo("#listing-images")})}var haveListing=false;function gotListing(r){if(haveListing)return;if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;if(r.result.msgs.length!=1)return;var m=r.result.msgs[0];if(m.hash!==searchParam("hash"))return;if(m.type!=="listing")return;if(!aq.verifyMsgSignatures(m))return;if(!isArray(r.result.chain))return;var maySell=false;r.result.chain.forEach(function(chm){if(chm.type==="approveNewIdentity"&&chm.pkhId===m.sigFrom){if(!aq.verifyMsgSignatures(chm))return;if(!msg.signedWithAuthorizedAdminKey(chm,mc)){ui.log("*** LISTING CREATOR approveNewIdentity SIGNER BAD");return}if(chm.maySell)maySell=true}if(chm.type==="keysForIdentity"&&chm.sigFrom===m.sigFrom){if(!aq.verifyMsgSignatures(chm))return;kfi=chm}});if(!maySell){ui.log("*** LISTING CREATOR maySell is false");return}if(!kfi)return;haveListing=true;listing=m;$("#listing-subject").text(m.subject);$("#listing-from").text(ui.countryShow(m.shipFrom));$("#listing-to").text(ui.countryShow(m.shipTo));$("#listing-category").text(m.category.replace(/;/g,": "));ui.commentTable(m).appendTo("#listing-body");var i,nMain=0;for(i=0;i<m.itemGroup.length;i++){if(m.itemGroup[i]!=="main")continue;var tr=$("<tr/>");$("<td/>",{text:m.itemDesc[i]}).appendTo(tr);$("<td/>",{text:m.itemPrice[i]+" "+m.currency}).appendTo(tr);var qty=$("<input/>",{value:nMain===0?"1":"0"});qty.on("input",updateTotal);qty.css("width","40px");qtys[i]=qty;var td=$("<td/>");qty.appendTo(td);td.appendTo(tr);tr.appendTo("#listing-items");nMain++}var nShip=0;for(i=0;i<m.itemGroup.length;i++){if(m.itemGroup[i]!=="shipping")continue;if(nShip===0){var tr=$("<tr/>");$("<th/>",{text:"Shipping"}).appendTo(tr);$("<th/>",{text:"Price"}).appendTo(tr);$("<th/>",{text:""}).appendTo(tr);tr.appendTo("#listing-items")}var tr=$("<tr/>");$("<td/>",{text:m.itemDesc[i]}).appendTo(tr);$("<td/>",{text:m.itemPrice[i]+" "+m.currency}).appendTo(tr);var sel=$("<input/>",{type:"radio",name:"listing-shipping-method",checked:nShip===0,id:"listing-qty-"+i});sel.on("change",updateTotal);var td=$("<td/>");sel.appendTo(td);qtys[i]=sel;td.appendTo(tr);tr.appendTo("#listing-items");nShip++}if(m.images.length>0){aq.rpc.toServers("searchMsg",{hashInclude:m.images,resultsAs:"msg"},gotImage,null);m.images.forEach(function(hash){wantImage[hash]=true})}aq.getMsgBySearch({type:"deleteMessage",toDelete:m.hash},function(dm){if(!(dm&&aq.verifyMsgSignatures(dm)&&dm.type==="deleteMessage"&&dm.toDelete===m.hash&&(msg.signedWithAuthorizedAdminKey(dm,mc)||dm.sigFrom===m.sigFrom))){return}$("#page-listing").addClass("deleted");$("#listing-deleted").css("display","block");$("#listing-order").off("click")});updateTotal();ui.hidePopup()}$("#listing-order").on("click",function(){if(listing&&kfi){aq.page.listing.order(listing,kfi,getQtys())}});aq.rpc.toServers("searchMsg",{hashInclude:[searchParam("hash")],resultsAs:"msg",chainOfTrust:true,deletedOk:true},gotListing,null);ui.showPopup("log")},order:function(listing,kfiSeller,qtys){ui.showPopup("wait");var keys=aq.getStorage("keys");if(!keys){ui.navTo("keys");return}var mc=aq.getStorage("marketControl").msg;function makeMessages(kfiAdmin){try{var keys=aq.getStorage("keys"),myPks=aq.page.keys.getPublicKeys(),orderHash,ticker=aq.getStorage("ticker");ticker=msg.fromUntrusted(ticker,"check");if(!ticker)throw"bad ticker";ticker=JSON.stringify(ticker);do{var poTe={stealth:randomBytes(32).toString("hex")};var po={type:"placeOrder",listing:listing.hash,subject:listing.subject,qty:qtys,ticker:ticker,pkBuyer:myPks.btc,pkSeller:kfiSeller.pkBtc,pkAdmin:mc.adminBtc[0],cipherTo:[listing.sigFrom,keys.primary,mc.adminContact[0]],sigFrom:keys.primary,sig:msg.notYetSigned};msg.fillCiphered(po,poTe,[kfiSeller.pkCrypt,myPks.crypt,kfiAdmin.pkCrypt]);msg.fillTime(po);po=msg.fromUntrusted(po,"compute")}while(!ecMath.validOrderHash(po.hash,poTe.stealth));msg.fillSignatures(po);orderHash=po.hash;po=JSON.stringify(po);var body=$("#listing-compose")[0].value;if(body.length<10)throw"address missing or too short";var pcTe={subject:"ORDER: "+listing.subject,body:body};var pc={type:"privateComment",ref:orderHash,state:"new",cipherTo:[listing.sigFrom],sigFrom:keys.primary,sig:msg.notYetSigned};msg.fillCiphered(pc,pcTe,[kfiSeller.pkCrypt]);msg.fillTime(pc);pc=msg.fromUntrusted(pc,"compute");msg.fillSignatures(pc);pc=JSON.stringify(pc);aq.sendMsgWithCaptcha([po,pc],function(){ui.navTo("order",{hash:orderHash})})}catch(e){ui.showPopup("notify","Failed: "+e)}}var gotAdminKfi=false;function gotOne(r){if(gotAdminKfi)return;if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;if(r.result.msgs.length!==1)return;var kfi=r.result.msgs[0];if(kfi.sigFrom!==mc.adminContact[0])return;if(!aq.verifyMsgSignatures(kfi))return;if(kfi.type!=="keysForIdentity")return;gotAdminKfi=true;makeMessages(kfi)}aq.rpc.toServers("searchMsg",{type:"keysForIdentity",sigFrom:[mc.adminContact[0]],resultsAs:"msg",limitResults:1},gotOne,null)}};aq.page.search={needKeys:false,init:function(){var haveListing={},wantThumb={};function gotThumb(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.thumbs)))return;r.result.thumbs.forEach(function(thumb){if(!(thumb.hash in wantThumb))return;wantThumb[thumb.hash].forEach(function(a){var img=$("<img/>",{src:"data:"+aq.imageDataUrl(thumb.thumb)});$("<br/>").prependTo(a);img.prependTo(a)});delete wantThumb[thumb.hash]})}function gotListing(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.listings)))return;var wantMoreThumbs=false;r.result.listings.forEach(function(lst){var h=cutil.sha256(JSON.stringify(lst)).toString("hex");if(haveListing[h])return;haveListing[h]=true;var a=$("<a/>",{href:"?a=listing&hash="+encodeURI(lst.hash),"class":"result"}),div=$("<div/>",{"class":"vcent"});div.text(lst.subject);div.appendTo(a);a.appendTo("#search-results");if(lst.images.length>0){var ih=lst.images[0];if(ih in wantThumb){wantThumb[ih].push(div)}else{wantThumb[ih]=[div]}wantMoreThumbs=true}});if(wantMoreThumbs){aq.rpc.toServers("searchMsg",{hashInclude:Object.keys(wantThumb),resultsAs:"thumb"},gotThumb,null)}if(Object.keys(haveListing).length===0){$("#search-results").text("no results")}ui.hidePopup("log")}var query={type:"listing",resultsAs:"listing",sortBy:"trust",limitResults:conf.listingsPerPage};function maybeAdd(inSp,inQuery,noForm){if(!inQuery)inQuery=inSp;var sp=searchParam(inSp);if(sp)query[inQuery]=sp;if(!noForm)$("#search-"+inSp)[0].value=sp||""}maybeAdd("category",null,true);maybeAdd("shipFrom");maybeAdd("shipTo");maybeAdd("seller","sigFrom");var c=searchParam("category");if(c)c=c.replace(/;/g,": ");$("#search-category").text(c||"everything");if(query.sigFrom)query.sigFrom=[query.sigFrom];aq.rpc.toServers("searchMsg",query,gotListing,null);ui.showPopup("log")},search:function(){var nav={},cat=searchParam("category");if(cat)nav.category=cat;function maybeAdd(inSp,uc){var f=$("#search-"+inSp)[0].value;if(f)nav[inSp]=uc?f.toUpperCase():f}maybeAdd("shipFrom",true);maybeAdd("shipTo",true);maybeAdd("seller",false);ui.navTo("search",nav)}};aq.page.orders={needKeys:true,init:function(){var have={};function gotOne(r){if(!(isObj(r)&&isObj(r.result)&&isArray(r.result.msgs)))return;var r=r.result;r.msgs.forEach(function(po){if(have[po.hash])return;have[po.hash]=true;var tr=$("<tr/>");var td=$("<td/>",{"class":"mono wrap"}),a=$("<a/>",{text:po.hash,href:"?a=order&hash="+encodeURI(po.hash)});a.appendTo(td);td.appendTo(tr);$("<td/>",{text:timeAgo(po.timeReal)}).appendTo(tr);$("<td/>",{text:po.subject}).appendTo(tr);ui.wrapTd(ui.addressDiv(po.sigFrom)).appendTo(tr);ui.wrapTd(ui.addressDiv(po.cipherTo[0])).appendTo(tr);tr.appendTo("#orders-list")});var copy=["to","from"];ui.pageControls("#orders",copy,"orders ",r.skipped,r.msgs.length,r.n,conf.ordersPerPage);ui.hidePopup("log")}var params={type:"placeOrder",limitResults:conf.ordersPerPage,skipResults:searchParam("skip")|0,resultsAs:"msg"};var to=searchParam("to"),from=searchParam("from"),keys=aq.getStorage("keys");if(to==="me"){params.cipherTo=[keys.primary];$("#orders-title").text("My Received Orders");$("#orders-table").addClass("hide5")}else if(to){params.cipherTo=[to]}else if(from==="me"){params.sigFrom=[keys.primary];$("#orders-title").text("My Placed Orders");$("#orders-table").addClass("hide4")}else if(from){params.sigFrom=[from]}else{return}aq.rpc.toServers("searchMsg",params,gotOne,null);ui.showPopup("log")}};aq.page.order={needKeys:true,init:function(){var listing,order,comments=[];function gotListing(m){listing=m;try{var mc=aq.getStorage("marketControl").msg,keys=aq.getStorage("keys"),sk=keys.secretKeys,te=msg.extractCiphered(order,sk),myPks=aq.page.keys.getPublicKeys();if(!(order.sigFrom===keys.primary&&order.pkBuyer===myPks.btc||order.cipherTo[0]===keys.primary&&order.pkSeller===myPks.btc||mc.adminPkh[0]===keys.primary)){throw"neither buyer nor seller nor admin"}if($.grep(mc.adminBtc,function(v){return v===order.pkAdmin}).length===0){throw"admin btc key not valid"}if(order.cipherTo[0]!==listing.sigFrom)throw"not to seller";if(order.qty.length!==listing.itemGroup.length)throw"item counts do not match";ui.hidePopup("log");showCommentsIfDone();aq.page.order.show(listing,order,te)}catch(e){ui.log("*** failed to decrypt: "+e)}}function gotOrder(m){order=m;aq.getMsgByHash(m.listing,gotListing)}function gotPrivateMessages(ms,paging){comments=comments.concat(ms);showCommentsIfDone()}function showCommentsIfDone(){if(!(order&&listing))return;var keys=aq.getStorage("keys");comments.forEach(function(m){if(!(m.type==="privateComment"&&m.ref===hash))return;if(!(m.sigFrom===order.sigFrom||m.sigFrom===listing.sigFrom)){return}msg.extractCipheredPrivateComment(m);var ct=ui.commentTable(m,{isReply:m.sigFrom===keys.primary,narrower:true,noOrderLink:true,markReadButton:m.sigFrom!==keys.primary});ct.appendTo("#order-msgs");aq.asyncVerifyMsgSignatures(m,ct);if(m.state==="escrow released"){$("#order-trust").css("display","inline")}if(m.tx){$("#order-propose-upper").css("display","none");$("#order-propose-lower").css("display","inline")}});comments=[]}var hash=searchParam("hash");aq.getMsgByHash(hash,gotOrder);aq.getMsgsBySearch({type:"privateComment",ref:hash},gotPrivateMessages)},show:function(listing,order,te){var address=ecMath.getMultisigAddress(order,te);var ticker;try{ticker=JSON.parse(order.ticker);ticker=msg.fromUntrusted(ticker,"check");if(ticker.type!=="ticker")throw"bad type";if(!aq.verifyMsgSignatures(ticker))throw"bad sig";var dt=Math.abs(order.timeReal-ticker.timeReal);if(dt>2*60*60)throw"bad ticker time: "+dt+" s";var mc=aq.getStorage("marketControl").msg;if(!mc.adminTicker.some(function(a){return a===ticker.sigFrom})){throw"not signed by adminTicker"}}catch(e){ui.log("**** BAD ticker IN ORDER FOR RATE LOCK: "+e);ui.showPopup("log");return}var keys=aq.getStorage("keys");if(order.cipherTo[0]===keys.primary){$("#order-title").text("View Received Order")}else if(order.sigFrom===keys.primary){$("#order-title").text("View Placed Order")}$("#order-hash").text(order.hash);$("<a/>",{text:listing.subject,href:"?a=listing&hash="+encodeURI(listing.hash)}).appendTo("#order-listing");ui.addressDiv(listing.sigFrom,true).appendTo("#order-seller");ui.addressDiv(order.sigFrom,true).appendTo("#order-buyer");$("#order-age").text(timeAgo(order.timeReal));ui.btcLink(address).appendTo("#order-addr");var cur=listing.currency,total=0;for(var i=0;i<order.qty.length;i++){if(order.qty[i]===0)continue;var subtotal=listing.itemPrice[i]*order.qty[i];total+=subtotal;var tr=$("<tr/>");$("<td/>",{text:listing.itemDesc[i]}).appendTo(tr);$("<td/>",{text:order.qty[i]}).appendTo(tr);$("<td/>",{text:listing.itemPrice[i]+" "+cur}).appendTo(tr);$("<td/>",{text:subtotal+" "+cur}).appendTo(tr);tr.appendTo("#order-items")}var tr=$("<tr/>");$("<td/>",{"class":"noborder",colspan:3}).appendTo(tr);var str=total+" "+cur;if(cur!=="BTC"){str+=" = ";str+=ui.formatBtc(aq.currencyToBtc(total,cur,ticker))}$("<td/>",{text:str,"class":"total"}).appendTo(tr);tr.appendTo("#order-items");var to;if(order.sigFrom===keys.primary){to=order.cipherTo[0]}else if(order.cipherTo[0]===keys.primary){to=order.sigFrom}else{return}$("#order-trust").on("click",function(){ui.navTo("trustNew",{to:to,order:order.hash})});var composeParams={to:to,subject:"ORDER: "+listing.subject,order:order.hash,isSeller:order.cipherTo[0]===keys.primary?"true":""};$("#order-compose").on("click",function(){ui.navTo("compose",composeParams)});var txos={};$("#order-propose-upper,#order-propose-lower").on("click",function(){ui.log("\nGETTING ALL UTXOs SENT TO ADDRESS "+address);ui.showPopup("log");aq.rpc.toServers("txos",{address:address},function(r){if(!(isObj(r)&&isArray(r.result)))return;r.result.forEach(function(txo){var key=txo.txid+","+txo.vout;if(key in txos)return;txos[key]=txo;var tr=$("<tr/>");$("<td/>",{"class":"mono wrap",text:txo.txid}).appendTo(tr);$("<td/>",{text:txo.vout}).appendTo(tr);$("<td/>",{text:ui.formatBtc(txo.value)}).appendTo(tr);tr.appendTo("#escrow-txos")});if(Object.keys(txos).length>0){ui.showPopup("escrow")}},function(){if(Object.keys(txos).length===0){ui.showPopup("notify","Escrowed funds not yet found in blockchain.")}})});$("#escrow-compose").on("click",function(){try{var keys=aq.getStorage("keys"),skBase=keys.secretKeys[keys.primary].skBtc,sk=ecMath.getStealthSecretKey(order,te,skBase),pks=ecMath.getStealthPublicKeys(order,te),redeemScript=bitcoin.script.multisigOutput(2,pks);var txb=new bitcoin.TransactionBuilder(conf.btcNet),key,total=0,i,n=0;for(key in txos){txb.addInput(txos[key].txid,txos[key].vout);n++;total+=txos[key].value}var fee=$("#escrow-fee")[0].value*1;if(!isNum(fee)||fee<0||fee>.002)throw"fee unreasonable";var satoshis=cutil.btcToSatoshis(total-fee);var outAddr=$("#escrow-addr")[0].value;if(!cutil.checker.btcAddr(outAddr))throw"bad output address";txb.addOutput(outAddr,satoshis);var ecp=bitcoin.ECPair.fromWIF(sk,conf.btcNet);for(i=0;i<n;i++){txb.sign(i,ecp,redeemScript)}var tx=txb.buildIncomplete().toHex();composeParams.tx=tx;ui.navTo("compose",composeParams)}catch(e){ui.showPopup("notify","Failed: "+e)}})}};aq.page.release={needKeys:true,init:function(){var keys=aq.getStorage("keys"),sk=keys.secretKeys;var orderHash=searchParam("order"),to=searchParam("to"),txHex=searchParam("tx"),payFrom,payTo,valueIn,valueOut,order,te,tx,txb;$("<a/>",{text:orderHash,href:"?a=order&hash="+encodeURI(orderHash),"class":"mono"}).appendTo("#release-order");try{var info=aq.getTransactionInfo(txHex);payTo=info.addr;valueOut=info.value;tx=info.tx;txb=info.txb}catch(e){ui.log("*** BAD TRANSACTION");ui.showPopup("log");return}function signAndFinish(){try{var skBase=keys.secretKeys[keys.primary].skBtc,sk=ecMath.getStealthSecretKey(order,te,skBase),ecp=bitcoin.ECPair.fromWIF(sk,conf.btcNet),pks=ecMath.getStealthPublicKeys(order,te),redeemScript=bitcoin.script.multisigOutput(2,pks);for(var i=0;i<txb.inputs.length;i++){txb.sign(i,ecp,redeemScript)}var hex=txb.build().toHex();ui.navTo("compose",{to:to,subject:"ORDER: "+order.subject,order:orderHash,tx:hex,escrowReleased:true})}catch(e){ui.showPopup("notify","failed to sign: "+e)}}aq.getMsgByHash(orderHash,function(m){order=m;te=msg.extractCiphered(order,sk);ui.addressDiv(order.cipherTo[0],true).appendTo("#release-seller");ui.addressDiv(order.sigFrom,true).appendTo("#release-buyer");payFrom=ecMath.getMultisigAddress(order,te);ui.btcLink(payFrom).appendTo("#release-payFrom");ui.btcLink(payTo).appendTo("#release-payTo");$("#release-valueOut").text(ui.formatBtc(valueOut));var txos={},done=false;aq.rpc.toServers("txos",{address:payFrom},function(r){if(done)return;if(!(isObj(r)&&isArray(r.result)))return;r.result.forEach(function(txo){txos[txo.txid+","+txo.vout]=txo});var total=0;if(!tx.ins.every(function(txi){var rb=cutil.reverseBuffer(txi.hash),p=rb.toString("hex")+","+txi.index;if(!(p in txos))return false;total+=txos[p].value;return true}))return;done=true;valueIn=total;$("#release-valueIn").text(ui.formatBtc(valueIn));$("#release-fee").text(ui.formatBtc(valueIn-valueOut));$("#release-go").on("click",signAndFinish);ui.hidePopup()})})},viewTx:function(){try{var info=aq.getTransactionInfo(searchParam("tx"));$("#viewTx-tx")[0].value=info.txHex;$("#viewTx-n").text(info.n);ui.showPopup("viewTx")}catch(e){}}};aq.page.userInfo={needKeys:true,init:function(){var keys=aq.getStorage("keys"),latest=0;aq.getMsgsBySearch({type:"publicComment",ref:"userInfo",sigFrom:[keys.primary],limitResults:1},function(r){if(r.length===0){ui.hidePopup("log");return}if(r.length!==1)return;var m=r[0];if(!(m.type==="publicComment"&&m.sigFrom===keys.primary&&m.ref==="userInfo"&&aq.verifyMsgSignatures(m))){return}if(m.timeReal>latest){$("#userInfo-body")[0].value=m.body;$("#userInfo-subject")[0].value=m.subject;latest=m.timeReal}ui.hidePopup("log")})},post:function(){var pc={type:"publicComment",subject:$("#userInfo-subject")[0].value,body:$("#userInfo-body")[0].value,ref:"userInfo"};aq.finishAndSendMsg(pc,function(){ui.navReload()})},user:function(){var keys=aq.getStorage("keys");ui.navTo("user",{pkh:keys.primary})}};aq.page.user={needKeys:false,init:function(){var mc=aq.getStorage("marketControl").msg,owners=aq.getStorage("owners");var pkh=searchParam("pkh");$("#user-pkh")[0].value=pkh;ui.showPopup("log");aq.getMsgBySearch({type:"publicComment",ref:"userInfo",sigFrom:[pkh]},function(m){if(!(m&&aq.verifyMsgSignatures(m)&&m.type==="publicComment"&&m.ref==="userInfo"&&m.sigFrom===pkh)){return}$("#user-info").text("");ui.commentTable(m).appendTo("#user-info")});aq.getMsgBySearch({sigFrom:[pkh]},function(m){if(!(m&&aq.verifyMsgSignatures(m)&&m.sigFrom===pkh))return;$("#user-ago").text(timeAgo(m.timeReal)+" ago")});aq.getMsgBySearch({pkhId:pkh,approveNewIdentity:1},function(m){if(!(m&&aq.verifyMsgSignatures(m)&&m.type==="approveNewIdentity"&&m.pkhId===pkh&&msg.signedWithAuthorizedAdminKey(m,mc))){return}if(m.pkhId in owners){$("#user-owner").css("display","block")}else{if(m.allowed){if(m.maySell){$("#user-seller").css("display","block")}else{if(mc.adminContact.some(function(a){return a===pkh})||mc.adminPkh.some(function(a){return a===pkh})){$("#user-admin").css("display","block")}else{$("#user-buyer").css("display","block")}}}else{$("#user-banned").css("display","block")}}$("#user-valid").text("from "+timePlusMinus(m.validFrom)+" to "+timePlusMinus(m.validTo));ui.hidePopup()})},search:function(){ui.navTo("user",{pkh:$("#user-pkh")[0].value})},listings:function(){ui.navTo("search",{seller:searchParam("pkh")})},ordersTo:function(){ui.navTo("orders",{to:searchParam("pkh")})},ordersFrom:function(){ui.navTo("orders",{from:searchParam("pkh")})},trustFrom:function(){ui.navTo("trust",{from:searchParam("pkh")})},trustTo:function(){ui.navTo("trust",{to:searchParam("pkh")})},compose:function(){ui.navTo("compose",{to:searchParam("pkh")})}};aq.page.trust={needKeys:true,init:function(){var keys=aq.getStorage("keys");var to=searchParam("to"),from=searchParam("from");if(to==="me"){to=keys.primary;$("#trust-title").text("View Feedback Received For Me")}else if(from==="me"){$("#trust-title").text("View Feedback Left By Me");from=keys.primary}$("#trust-from")[0].value=from||"";$("#trust-to")[0].value=to||"";var p={type:"trust",limitResults:conf.trustsPerPage,skipResults:searchParam("skip")|0};if(to)p.to=to;if(from)p.sigFrom=[from];aq.getMsgsBySearch(p,function(r,page){r.forEach(function(m){if(to&&m.to!==to)return;if(from&&m.sigFrom!==from)return;if(m.type!=="trust")return;var tr=$("<tr/>");$("<td/>",{text:timeAgo(m.timeReal)}).appendTo(tr);ui.wrapTd(ui.addressDiv(m.sigFrom)).appendTo(tr);ui.wrapTd(ui.addressDiv(m.to)).appendTo(tr);var tdc=$("<td/>"),divc=$("<div/>",{text:m.comment});divc.css("max-width","160px");divc.css("overflow","hidden");divc.appendTo(tdc);tdc.appendTo(tr);var score=m.score.toFixed(1);if(m.score>0)score="+"+score;$("<td/>",{text:score}).appendTo(tr);var ol=$("<a/>",{"class":"mono wrap",text:m.order,href:"?a=order&hash="+encodeURI(m.order)}),otd=$("<td/>",{"class":"mono wrap"});ol.appendTo(otd);otd.appendTo(tr);tr.appendTo("#trust-msgs");aq.asyncVerifyMsgSignatures(m,tr)});var copy=["to","from"];ui.pageControls("#trust",copy,"feedbacks ",page.skipped,page.inPage,page.total,conf.trustsPerPage);ui.hidePopup()})},search:function(){ui.navTo("trust",{from:$("#trust-from")[0].value,to:$("#trust-to")[0].value})}};aq.page.trustNew={needKeys:true,init:function(){var keys=aq.getStorage("keys");$("#trustNew-from").text(keys.primary);var order=searchParam("order"),to=searchParam("to");if(order&&to){var io=$("#trustNew-order")[0],it=$("#trustNew-to")[0];io.value=order;it.value=to;io.readOnly=true;it.readOnly=true;aq.getMsgBySearch({type:"trust",to:to,sigFrom:[keys.primary]},function(r){if(!r)return;ui.showPopup("trustDel");$("#trustDel-delete").on("click",function(){var m={type:"deleteMessage",toDelete:r.hash,comment:"delete trust before replacing"};aq.finishAndSendMsg(m,function(){ui.hidePopup()})})});ui.hidePopup()}},post:function(){var m={type:"trust",score:$("#trustNew-score")[0].value*1,to:$("#trustNew-to")[0].value,order:$("#trustNew-order")[0].value,comment:$("#trustNew-comment")[0].value};aq.finishAndSendMsg(m,function(){var keys=aq.getStorage("keys");ui.navTo("trust",{from:keys.primary})})}};aq.page.feeRequests={needKeys:true,init:function(){var keys=aq.getStorage("keys");var from=searchParam("from"),to=searchParam("to");if(from==="me")from=keys.primary;if(to==="me")to=keys.primary;$("#feeRequests-from")[0].value=from||"";$("#feeRequests-to")[0].value=to||"";var query={type:"requestFeePayment",resultsAs:"msg"};if(from)query.feeFrom=from;if(to)query.feeTo=to;aq.getMsgsBySearch(query,function(ms){ms.forEach(function(rfp){var tr=$("<tr/>");ui.hashTableCell(rfp.hash,"feeRequest").appendTo(tr);$("<td/>",{text:timeAgo(rfp.timeReal)}).appendTo(tr);ui.wrapTd(ui.addressDiv(rfp.sigFrom)).appendTo(tr);$("<td/>",{text:rfp.comment}).appendTo(tr);tr.appendTo("#feeRequests-lines")});ui.hidePopup()})},search:function(){ui.navTo("feeRequests",{from:$("#feeRequests-from")[0].value,to:$("#feeRequests-to")[0].value})}};aq.page.feeRequest={needKeys:true,init:function(){var keys=aq.getStorage("keys"),mc=aq.getStorage("marketControl").msg,h=searchParam("hash");aq.getMsgByHash(h,function(rfp){if(!aq.verifyMsgSignatures(rfp)||rfp.hash!==h){ui.showPopup("*** BAD SIGNATURE"); return}ui.hidePopup();$("#feeRequest-hash").text(rfp.hash);$("#feeRequest-age").text(timeAgo(rfp.timeReal));ui.addressDiv(rfp.sigFrom,true).appendTo("#feeRequest-adminSuper");$("#feeRequest-comment").text(rfp.comment);var rows=[];for(var i=0;i<rfp.feeFrom.length;i++){rows.push({from:rfp.feeFrom[i],to:rfp.feeTo[i],amount:rfp.feeAmount[i],i:i})}var kp=keys.primary;rows.sort(function(a,b){if(a.from===kp&&b.from!==kp)return-1;if(a.from!==kp&&b.from===kp)return 1;return a.i-b.i});rows.forEach(function(row){var tr=$("<tr/>");$("<td/>",{text:row.from,"class":"mono wrap"}).appendTo(tr);$("<td/>",{text:row.to,"class":"mono wrap"}).appendTo(tr);$("<td/>",{text:ui.formatBtcBare(row.amount)}).appendTo(tr);var td=$("<td/>");if(row.from===keys.primary){tr.addClass("hl");var pay=$("<div/>",{"class":"button-blue",text:"Pay"});td.css("padding","12px 5px");pay.appendTo(td);pay.on("click",function(){getCryptKeys(row.to,row.amount)})}td.appendTo(tr);tr.appendTo("#feeRequest-lines")})});function getCryptKeys(to,value){var pkCryptAdmin,pkCryptTo,pkBtcTo,done=false;function got(kfi){if(!(kfi&&kfi.type==="keysForIdentity"&&aq.verifyMsgSignatures(kfi))){ui.log("*** BAD OR MISSING ENCRYPTION KEY");return}if(kfi.sigFrom===to){pkCryptTo=kfi.pkCrypt;pkBtcTo=kfi.pkBtc;ui.log("got pkCrypt for recipient: "+pkCryptTo);ui.log("got pkBtc for recipient: "+pkBtcTo)}if(kfi.sigFrom===mc.adminContact[0]){pkCryptAdmin=kfi.pkCrypt;ui.log("got pkCrypt for admin: "+pkCryptAdmin)}if(pkCryptTo&&pkCryptAdmin&&pkBtcTo&&!done){done=true;paidFee(to,value,pkCryptTo,pkCryptAdmin,pkBtcTo)}}ui.log("getting pkCrypt for recipient and admin");aq.getMsgBySearch({type:"keysForIdentity",sigFrom:[mc.adminContact[0]]},got);aq.getMsgBySearch({type:"keysForIdentity",sigFrom:[to]},got)}function paidFee(to,value,pkCryptTo,pkCryptAdmin,pkBtcTo){var myPks=aq.page.keys.getPublicKeys();do{var pfTe={stealth:randomBytes(32).toString("hex")};var pf={type:"paidFee",pkBtc:pkBtcTo,request:h,feeAmount:value,cipherTo:[to,keys.primary,mc.adminContact[0]],sigFrom:keys.primary,sig:msg.notYetSigned};msg.fillCiphered(pf,pfTe,[pkCryptTo,myPks.crypt,pkCryptAdmin]);msg.fillTime(pf);pf=msg.fromUntrusted(pf,"compute")}while(!ecMath.validOrderHash(pf.hash,pfTe.stealth));msg.fillSignatures(pf);aq.sendMsgWithCaptcha([JSON.stringify(pf)],function(){ui.navTo("feePayment",{hash:pf.hash})})}}};aq.page.feePayments={needKeys:true,init:function(){var keys=aq.getStorage("keys");var from=searchParam("from"),to=searchParam("to");if(from==="me")from=keys.primary;if(to==="me")to=keys.primary;$("#feePayments-from")[0].value=from||"";$("#feePayments-to")[0].value=to||"";var query={type:"paidFee",resultsAs:"msg"};if(from)query.sigFrom=[from];if(to)query.cipherTo=[to];aq.getMsgsBySearch(query,function(ms){ms.forEach(function(pf){var tr=$("<tr/>");ui.hashTableCell(pf.hash,"feePayment").appendTo(tr);$("<td/>",{text:timeAgo(pf.timeReal)}).appendTo(tr);ui.wrapTd(ui.addressDiv(pf.sigFrom)).appendTo(tr);ui.wrapTd(ui.addressDiv(pf.cipherTo[0])).appendTo(tr);$("<td/>",{text:ui.formatBtcBare(pf.feeAmount)}).appendTo(tr);tr.appendTo("#feePayments-lines")});ui.hidePopup()})},search:function(){ui.navTo("feePayments",{from:$("#feePayments-from")[0].value,to:$("#feePayments-to")[0].value})}};aq.page.feePayment={needKeys:true,init:function(){var h=searchParam("hash");aq.getMsgByHash(h,function(pf){if(!(pf&&aq.verifyMsgSignatures(pf)&&pf.type==="paidFee")){ui.log("*** BAD paidFee MESSAGE");return}$("#feePayment-hash").text(pf.hash);$("#feePayment-age").text(timeAgo(pf.timeReal));ui.addressDiv(pf.sigFrom,true).appendTo("#feePayment-from");ui.addressDiv(pf.cipherTo[0],true).appendTo("#feePayment-to");$("#feePayment-amount").text(ui.formatBtc(pf.feeAmount));ui.hashLink(pf.request,"feeRequest").appendTo("#feePayment-request");try{var keys=aq.getStorage("keys"),pkh,sk=keys.secretKeys,te=msg.extractCiphered(pf,sk),addr=ecMath.getFeeAddress(pf,te);ui.btcLink(addr).appendTo("#feePayment-address");for(pkh in sk){if(pkh===pf.cipherTo[0]){var wif=ecMath.getStealthSecretKey(pf,te,sk[pkh].skBtc);var ecp=bitcoin.ECPair.fromWIF(wif,conf.btcNet);if(ecp.getAddress()!==addr){ui.log("*** ADDRESS FROM SK DOES NOT MATCH");throw"bad stealth from sk"}$("#feePayment-wif-row").css("display","table-row");$("#feePayment-wif").text(wif)}}}catch(e){console.log(e);$("#feePayment-address").text("cannot decrypt")}ui.hidePopup()})}};var crypto=typeof module==="object"?require("crypto"):undefined;var cutil={};cutil.checker={number:function(v){return typeof v==="number"&&v===v},integer:function(v){return typeof v==="number"&&v===Math.floor(v)},bool:function(v){return typeof v==="boolean"},stringEnum:function(options){var okay={};options.forEach(function(o){okay[o]=true});return function(v){return okay[v]}},stringMaxLen:function(maxLen){return function(v){return typeof v==="string"&&v.length<=maxLen}},string:function(v){return cutil.checker.stringMaxLen(500)(v)},imageDataUrl:function(v){return typeof v==="string"&&v.length<100*1e3&&v.match(/^data:image\/(jpeg|png);base64,[0-9A-Za-z+\/]*=*$/)},uri:function(v){return typeof v==="string"&&v.length<300&&v.match(/^(http|https):\/\//)},hex256b:function(v){return typeof v==="string"&&v.match(/^[0-9a-f]{64}$/)},hex128b:function(v){return typeof v==="string"&&v.match(/^[0-9a-f]{32}$/)},btcAddr:function(v){return typeof v==="string"&&v.match(/^[0-9a-zA-Z]{26,35}$/)},btcPubKey:function(v){return typeof v==="string"&&v.match(/^(02|03)([0-9a-f][0-9a-f]){10,100}$/)},btcSignature:function(v){return typeof v==="string"&&v.match(/^[0-9a-zA-Z+\/]{10,300}=*$/)},btcTx:function(v){return typeof v==="string"&&v.match(/^([0-9a-f]{2}){50,1000}$/)},btcSecretKey:function(v){return typeof v==="string"&&v.match(/^[0-9a-zA-Z]+$/)},cipherText:function(v){return typeof v==="string"&&v.length<10*1e3&&v.match(/^[A-Za-z0-9+\/]+=*$/)},array:function(f){return function(v){if(typeof v!=="object")return false;if(!(v instanceof Array))return false;var okay=true;v.forEach(function(vv){if(!f(vv))okay=false});return okay}},optional:function(f){return function(v){if(typeof v==="undefined")return true;return f(v)}},check:function(objIn,fmt){var objOut={};for(var field in fmt){if(!fmt[field](objIn[field])){throw"bad property: "+field}objOut[field]=objIn[field]}return objOut}};cutil.btcToSatoshis=function(btc){return Math.round(btc*1e8)};cutil.satoshisToBtc=function(satoshis){return satoshis/1e8};cutil.valueIsColoredSatoshis=function(satoshis){return satoshis%2==0};cutil.valueIsColoredBtc=function(btc){return cutil.valueIsColoredSatoshis(cutil.btcToSatoshis(btc))};cutil.workFromHash=function(hash){var work=1,buf=new Buffer(hash,"hex");if(buf.length!==32)throw"bad hash len";for(var i=0;i<buf.length;i++){if(buf[i]===0){work*=256}else{for(var j=7;j>=0;j--){if(buf[i]&1<<j){return work}else{work*=2}}}}throw"hash not plausible"};cutil.sha256=function(v){if(typeof v==="string")v=new Buffer(v);if(typeof bitcoin==="object"){return bitcoin.crypto.sha256(v)}else{var ss=crypto.createHash("sha256");ss.update(v);return ss.digest()}};cutil.sha256Twice=function(v){return cutil.sha256(cutil.sha256(v))};cutil.reverseBuffer=function(bufIn){var n=bufIn.length,bufOut=new Buffer(n);for(var i=0;i<n;i++){bufOut[n-1-i]=bufIn[i]}return bufOut};cutil.merkleHash=function(a,b){a=cutil.reverseBuffer(new Buffer(a,"hex"));b=cutil.reverseBuffer(new Buffer(b,"hex"));var ab=cutil.sha256Twice(Buffer.concat([a,b]));ab=cutil.reverseBuffer(ab).toString("hex");return ab};cutil.txoStringKey=function(txi){return cutil.reverseBuffer(txi.hash).toString("hex")+","+txi.index};if(typeof module==="object")module.exports=cutil;if(typeof module==="object"){cutil=require("./cutil.js");conf=require("../server/conf.js")}msg={};msg.notYetSigned="000000000000000000000000000000000000000000000000";msg.fromUntrusted=function(msgIn,howHash){var ck=cutil.checker;var formatCheck={ticker:{currencies:ck.array(ck.stringMaxLen(3)),exchangeRates:ck.array(ck.number)},marketControl:{clientVersion:ck.array(ck.string),clientUri:ck.uri,clientHash:ck.hex256b,newBuyerUris:ck.array(ck.uri),serverUris:ck.array(ck.uri),categories:ck.array(ck.string),forums:ck.array(ck.string),adminPkh:ck.array(ck.btcAddr),adminValidFrom:ck.array(ck.integer),adminValidTo:ck.array(ck.integer),adminType:ck.array(ck.stringEnum(["adminNewBuyer","adminSuper"])),adminBtc:ck.array(ck.btcPubKey),adminContact:ck.array(ck.btcAddr),adminTicker:ck.array(ck.btcAddr)},delegateProxyVote:{proxy:ck.btcAddr},approveNewIdentity:{allowed:ck.bool,maySell:ck.bool,pkhId:ck.btcAddr,validFrom:ck.integer,validTo:ck.integer,kbPerDay:ck.integer,comment:ck.string},keysForIdentity:{pkCrypt:ck.btcPubKey,pkBtc:ck.btcPubKey},publicComment:{subject:ck.string,body:ck.stringMaxLen(40*1e3),ref:ck.string},privateComment:{cipherText:ck.cipherText,ref:ck.string,state:ck.string},image:{image:ck.imageDataUrl,thumb:ck.imageDataUrl},listing:{subject:ck.string,body:ck.stringMaxLen(30*1e3),images:ck.array(ck.hex256b),category:ck.string,shipFrom:ck.array(ck.stringMaxLen(2)),shipTo:ck.array(ck.stringMaxLen(2)),currency:ck.stringMaxLen(3),itemPrice:ck.array(ck.number),itemDesc:ck.array(ck.string),itemGroup:ck.array(ck.stringEnum(["main","shipping"]))},deleteMessage:{toDelete:ck.hex256b,comment:ck.string},placeOrder:{cipherText:ck.cipherText,listing:ck.hex256b,subject:ck.string,qty:ck.array(ck.integer),ticker:ck.stringMaxLen(1e3),pkBuyer:ck.btcPubKey,pkSeller:ck.btcPubKey,pkAdmin:ck.btcPubKey},trust:{score:ck.number,to:ck.btcAddr,order:ck.hex256b,comment:ck.stringMaxLen(100)},requestFeePayment:{feeFrom:ck.array(ck.btcAddr),feeTo:ck.array(ck.btcAddr),feeAmount:ck.array(ck.number),comment:ck.string},paidFee:{cipherText:ck.cipherText,pkBtc:ck.btcPubKey,request:ck.hex256b,feeAmount:ck.number}};for(var type in formatCheck){var fco={},fci=formatCheck[type];fco.type=ck.string;fco.genesisTxid=ck.hex256b;fco.genesisVout=ck.integer;fco.time=ck.integer;fco.timeHash=ck.hex256b;fco.timeReal=ck.integer;for(var p in fci){fco[p]=fci[p];if(p==="cipherText"){fco.cipherTo=ck.array(ck.btcAddr);fco.cipherEphem=ck.btcPubKey;fco.cipherIv=ck.hex128b;fco.cipherPkhCrypt=ck.array(ck.btcAddr);fco.cipherSessionKey=ck.array(ck.hex256b)}}if(type!=="marketControl"){fco.sigFrom=ck.btcAddr}formatCheck[type]=fco}if(!msgIn)throw"msg is null";if(typeof msgIn!=="object")throw"msg not object";if(typeof msgIn.type!=="string")throw"msg.type not string";var fc=formatCheck[msgIn.type];if(!fc)throw"msg.type not recognized";var msgOut=ck.check(msgIn,fc);if(!msgOut)throw"msg format check failed";if(msgIn.genesisTxid!==conf.genesisTxo[0][0]||msgIn.genesisVout!==conf.genesisTxo[0][1]){throw"not for this market, wrong genesis TXO"}if(fc.cipherText){if(!(msgIn.cipherTo.length===msgIn.cipherPkhCrypt.length)&&msgIn.cipherTo.length===msgIn.cipherSessionKey.length){throw"cipherXXX lengths should match"}if(!(msgIn.cipherTo.length>=1&&msgIn.cipherTo.length<=3)){throw"cipherXXX length should be 1, 2, or 3"}}switch(msgOut.type){case"ticker":if(!(msgIn.currencies.length===msgIn.exchangeRates.length)){throw"currencies and exchangeRates lengths should match"}break;case"marketControl":if(!(msgIn.adminPkh.length===msgIn.adminValidFrom.length&&msgIn.adminPkh.length===msgIn.adminValidTo.length&&msgIn.adminPkh.length===msgIn.adminType.length)){throw"adminXXX lengths should match"}if(msgIn.adminPkh.length<1){throw"adminPkh length must be at least one"}if(msgIn.adminType[0]!="adminSuper"){throw"adminType[0] must be adminSuper"}if(msgIn.adminContact.length<1){throw"adminContact length must be at least one"}if(msgIn.adminBtc.length<1){throw"adminBtc length must be at least one"}if(msgIn.adminTicker.length<1){throw"adminTicker length must be at least one"}break;case"listing":if(!(msgIn.itemPrice.length===msgIn.itemDesc.length&&msgIn.itemPrice.length===msgIn.itemGroup.length)){throw"itemXXX lengths should match"}break;case"requestFeePayment":if(!(msgIn.feeFrom.length===msgIn.feeTo.length&&msgIn.feeFrom.length===msgIn.feeAmount.length)){throw"feeXXX lengths should match"}break}var hashOut=cutil.sha256(JSON.stringify(msgOut)).toString("hex");if(howHash==="compute"){msgOut.hash=hashOut}else if(howHash==="check"){if(msgIn.hash===hashOut){msgOut.hash=hashOut}else{throw"msg.hash is incorrect"}}else{throw"bad howHash, compute or check"}if(msgOut.type==="marketControl"){if(ck.array(ck.btcAddr)(msgIn.ownerSigFrom)&&ck.array(ck.btcSignature)(msgIn.ownerSig)&&msgIn.ownerSigFrom.length===msgIn.ownerSig.length){msgOut.ownerSigFrom=msgIn.ownerSigFrom;msgOut.ownerSig=msgIn.ownerSig}else{throw"ownerSigXXX format wrong"}}else{if(ck.btcSignature(msgIn.sig)){msgOut.sig=msgIn.sig}else{throw"msg.sig format wrong"}}return msgOut};msg.fillTime=function(msg){msg.genesisTxid=conf.genesisTxo[0][0];msg.genesisVout=conf.genesisTxo[0][1];var ticker=aq.getStorage("ticker");msg.time=ticker.time;msg.timeHash=ticker.timeHash;msg.timeReal=getUnixTime()};msg.fillOneSignature=function(pkh,hash){var sk=aq.getStorage("keys").secretKeys;if(!(pkh in sk))throw"no secret key for "+pkh;var ecpId=bitcoin.ECPair.fromWIF(sk[pkh].skId,conf.btcNet),sig=bitcoin.message.sign(ecpId,hash,conf.btcNet);return sig.toString("base64")};msg.fillSignatures=function(m){if(m.type==="marketControl"){if(m.ownerSigFrom.length!==m.ownerSig.length)throw"lengths bad";for(var i=0;i<m.ownerSigFrom.length;i++){if(m.ownerSig[i]!==msg.notYetSigned)continue;m.ownerSig[i]=msg.fillOneSignature(m.ownerSigFrom[i],m.hash)}}else{if(m.sig!==msg.notYetSigned)throw"missing placeholder";m.sig=msg.fillOneSignature(m.sigFrom,m.hash)}};msg.signedWithAuthorizedAdminKey=function(m,mc){var i;for(i=0;i<mc.adminPkh.length;i++){if(mc.adminPkh[i]===m.sigFrom)break}if(i>=mc.adminPkh.length){return false}if(m.timeReal<mc.adminValidFrom[i]||m.timeReal>mc.adminValidTo[i]){return false}if(mc.adminType[i]==="adminNewBuyer"&&!(m.type==="approveNewIdentity"&&m.maySell===false)){return false}switch(m.type){case"approveNewIdentity":case"keysForIdentity":case"publicComment":case"trust":case"deleteMessage":case"requestFeePayment":return true}return false};msg.marketControlVotingPower=function(mc,t,agingFactor,owners,delegates){if(mc.type!=="marketControl")return-1e10;var votingPower=0,alreadySignedBy={};for(var i=0;i<mc.ownerSig.length;i++){var os=mc.ownerSig[i],osf=mc.ownerSigFrom[i];var voters=[osf];if(osf in delegates){voters=voters.concat(delegates[osf])}voters.forEach(function(voter){if(!alreadySignedBy[voter]&&voter in owners){votingPower+=owners[voter];alreadySignedBy[voter]=true}})}var dt=t-mc.timeReal;if(dt<0)dt=0;var aging=Math.pow(dt*agingFactor,1.5);return{aged:Math.floor(votingPower-aging),unaged:votingPower}};msg.fillCiphered=function(m,toEncrypt,pks){var tes=JSON.stringify(toEncrypt),ee=ecMath.encrypt(tes,pks),p;for(p in ee){m[p]=ee[p]}};msg.extractCiphered=function(m,sk){var i;for(i=0;i<m.cipherTo.length;i++){if(m.cipherTo[i]in sk)break}if(i>=m.cipherTo.length)throw"to unknown pkhId";sk=sk[m.cipherTo[i]].skCrypt;if(!(m.cipherPkhCrypt[i]in sk))throw"to unknown pkhCrypt";sk=sk[m.cipherPkhCrypt[i]].sk;var dc=ecMath.decrypt(m,sk),json=dc.text,teIn=JSON.parse(json);var ck=cutil.checker;var fc={privateComment:{subject:ck.string,body:ck.stringMaxLen(40*1e3),tx:ck.optional(ck.btcTx)},placeOrder:{stealth:ck.hex256b},paidFee:{stealth:ck.hex256b}};if(!(m.type in fc))throw"unknown message type";var te=ck.check(teIn,fc[m.type]);if(!te)throw"check failed";te._aesKey=dc.aesKey;return te};msg.extractCipheredPrivateComment=function(m){var s="",b="",tx;try{var sk=aq.getStorage("keys").secretKeys;te=msg.extractCiphered(m,sk);s=te.subject;b=te.body;tx=te.tx}catch(e){s="<only recipient can decrypt this, not you>"}m.subject=s;m.body=b;if(tx)m.tx=tx};if(typeof module==="object")module.exports=msg;var ecMath={};ecMath.curve=ecurve.getCurveByName("secp256k1");ecMath.stealthPublicKeyInt=function(basePubKey,adder){var adderEcp=new bitcoin.ECPair(adder,null,{network:conf.btcNet});basePubKey=new Buffer(basePubKey,"hex");var basePt=ecurve.Point.decodeFrom(ecMath.curve,basePubKey),adderPt=adderEcp.Q,sumPt=basePt.add(adderPt);var sumEcp=new bitcoin.ECPair(null,sumPt,{network:conf.btcNet});return sumEcp.getPublicKeyBuffer().toString("hex")};ecMath.stealthSecretKeyInt=function(base,adder){var baseEcp=bitcoin.ECPair.fromWIF(base,conf.btcNet),adderEcp=new bitcoin.ECPair(adder,null,{network:conf.btcNet});var sum=baseEcp.d.add(adderEcp.d);if(sum.compareTo(ecMath.curve.n)>=0){sum=sum.subtract(ecMath.curve.n)}var sumEcp=new bitcoin.ECPair(sum,null,{network:conf.btcNet});return sumEcp.toWIF()};ecMath.multisigAddress=function(pks){var script=bitcoin.script.multisigOutput(2,pks),sho=bitcoin.script.scriptHashOutput(bitcoin.crypto.hash160(script)),addr=bitcoin.address.fromOutputScript(sho,conf.btcNet).toString();return addr};ecMath.getStealthPublicKeys=function(order,te){var pks=[];var adderi=ecMath.adderFromMessage(order.hash,te.stealth);["Buyer","Seller","Admin"].forEach(function(role){var pk=ecMath.stealthPublicKeyInt(order["pk"+role],adderi);pks.push(new Buffer(pk,"hex"))});return pks};ecMath.getStealthSecretKey=function(m,te,skBase){var adderi=ecMath.adderFromMessage(m.hash,te.stealth);return ecMath.stealthSecretKeyInt(skBase,adderi)};ecMath.getMultisigAddress=function(order,te){return ecMath.multisigAddress(ecMath.getStealthPublicKeys(order,te))};ecMath.getFeeAddress=function(pf,te){var adderi=ecMath.adderFromMessage(pf.hash,te.stealth),pk=ecMath.stealthPublicKeyInt(pf.pkBtc,adderi);pk=new Buffer(pk,"hex");var ecp=bitcoin.ECPair.fromPublicKeyBuffer(pk,conf.btcNet);return ecp.getAddress()};ecMath.adderFromMessage=function(orderHash,stealth){var a=new Buffer(orderHash,"hex"),b=new Buffer(stealth,"hex"),ab=Buffer.concat([a,b]);if(a.length!==32||b.length!==32||ab.length!==64)throw"bad len";return bigi.fromBuffer(bitcoin.crypto.sha256(ab))};ecMath.validOrderHash=function(orderHash,stealth){var ei=ecMath.adderFromMessage(orderHash,stealth);return ei.signum()>0&&ei.compareTo(ecMath.curve.n)<0};AES.bufferTo32=function(buf,i){return buf[i+0]<<0|buf[i+1]<<8|buf[i+2]<<16|buf[i+3]<<24};AES.bufferToArray32=function(buf,i,n){var out=[];for(var j=0;j<n;j++){out.push(AES.bufferTo32(buf,i+j*4))}return out};AES.array32Xor=function(a,b){if(a.length!=b.length)throw"lengths should match";var out=[];for(var i=0;i<a.length;i++){out.push(a[i]^b[i])}return out};AES.array32ToBuffer=function(array,buf,i){array.forEach(function(v){buf[i++]=v>>0&255;buf[i++]=v>>8&255;buf[i++]=v>>16&255;buf[i++]=v>>24&255})};ecMath.encrypt=function(plainText,destPubKeys){var iv=randomBytes(16),aesKey=randomBytes(32);var ephemEcp=bitcoin.ECPair.makeRandom({network:conf.btcNet}),cipherEphem=ephemEcp.getPublicKeyBuffer().toString("hex");var aes=new AES(AES.bufferToArray32(aesKey,0,8));while(Buffer.byteLength(plainText)%16!==0){plainText+=" "}var plainTextBuf=new Buffer(plainText);plainTextBuf=Buffer.concat([plainTextBuf,bitcoin.crypto.sha256(plainTextBuf)]);var cipherTextBuf=new Buffer(plainTextBuf.length),pt,ct;ct=AES.bufferToArray32(iv,0,4);for(var i=0;i<plainTextBuf.length;i+=16){pt=AES.array32Xor(ct,AES.bufferToArray32(plainTextBuf,i,4));ct=aes.encrypt(pt);AES.array32ToBuffer(ct,cipherTextBuf,i)}var cipherSessionKey=[],cipherPkhCrypt=[];destPubKeys.forEach(function(destPubKey){var dpkbuf=new Buffer(destPubKey,"hex"),destEcp=bitcoin.ECPair.fromPublicKeyBuffer(dpkbuf,conf.btcNet);cipherPkhCrypt.push(destEcp.getAddress());var ecdh=destEcp.Q.multiply(ephemEcp.d),secret=bitcoin.crypto.sha256(ecdh.affineX.toBuffer());var xor=new Buffer(32);for(var i=0;i<32;i++){xor[i]=secret[i]^aesKey[i]}cipherSessionKey.push(xor.toString("hex"))});return{cipherEphem:cipherEphem,cipherIv:iv.toString("hex"),cipherPkhCrypt:cipherPkhCrypt,cipherSessionKey:cipherSessionKey,cipherText:cipherTextBuf.toString("base64")}};ecMath.decrypt=function(msg,privKey){var privEcp=bitcoin.ECPair.fromWIF(privKey,conf.btcNet);var privAddr=privEcp.getAddress();for(var i=0;i<msg.cipherPkhCrypt.length;i++){if(msg.cipherPkhCrypt[i]===privAddr){break}}if(i>=msg.cipherPkhCrypt.length){return}var ephemPubKey=new Buffer(msg.cipherEphem,"hex"),ephemPt=ecurve.Point.decodeFrom(ecMath.curve,ephemPubKey);var ecdh=ephemPt.multiply(privEcp.d),secret=bitcoin.crypto.sha256(ecdh.affineX.toBuffer());var session=new Buffer(msg.cipherSessionKey[i],"hex"),aesKey=new Buffer(32);for(var j=0;j<32;j++){aesKey[j]=secret[j]^session[j]}var aes=new AES(AES.bufferToArray32(aesKey,0,8));var cipherTextBuf=new Buffer(msg.cipherText,"base64");if(cipherTextBuf.length%16!==0){return}var plainTextBuf=new Buffer(cipherTextBuf.length);var iv=AES.bufferToArray32(new Buffer(msg.cipherIv,"hex"),0,4),pt,ct;for(var j=0;j<cipherTextBuf.length;j+=16){ct=AES.bufferToArray32(cipherTextBuf,j,4);pt=AES.array32Xor(aes.decrypt(ct),iv);AES.array32ToBuffer(pt,plainTextBuf,j);iv=ct}var mac1=plainTextBuf.slice(-32),plainTextBuf=plainTextBuf.slice(0,-32),mac2=bitcoin.crypto.sha256(plainTextBuf);for(var j=0;j<32;j++){if(mac1[j]!==mac2[j])return}return{text:plainTextBuf.toString(),aesKey:aesKey.toString("hex")}};ecMath.verifyEcdsa=function(hash,signature,Q){var secp256k1=ecMath.curve;var n=secp256k1.n;var G=secp256k1.G;var r=signature.r;var s=signature.s;if(r.signum()<=0||r.compareTo(n)>=0)return false;if(s.signum()<=0||s.compareTo(n)>=0)return false;var e=bigi.fromBuffer(hash);var sInv=s.modInverse(n);var u1=e.multiply(sInv).mod(n);var u2=r.multiply(sInv).mod(n);var R=G.multiplyTwo(u1,Q,u2);if(secp256k1.isInfinity(R))return false;var xR=R.affineX;var v=xR.mod(n);return v.equals(r)};ecMath.test=function(){var order={},ecp={},te={};["pkBuyer","pkSeller","pkAdmin"].forEach(function(p){ecp[p]=bitcoin.ECPair.makeRandom({network:conf.btcNet});order[p]=ecp[p].getPublicKeyBuffer().toString("hex")});do{order.hash=randomBytes(32).toString("hex");te.stealth=randomBytes(32).toString("hex")}while(!ecMath.validOrderHash(order.hash,te.stealth));var pks=ecMath.getStealthPublicKeys(order,te);["pkBuyer","pkSeller","pkAdmin"].forEach(function(p){var pk=pks.shift().toString("hex");var sk=ecMath.getStealthSecretKey(order,te,ecp[p].toWIF());var ecp2=bitcoin.ECPair.fromWIF(sk,conf.btcNet),pk2=ecp2.getPublicKeyBuffer().toString("hex");console.log("from pk: "+pk);console.log("from sk: "+pk2);if(pk!==pk2)console.log(" *** FAIL, NOT MATCHING");else console.log(" ok, match")});var recipient=bitcoin.ECPair.makeRandom({network:conf.btcNet}),recipientPubKey=recipient.getPublicKeyBuffer().toString("hex");var ct=ecMath.encrypt("{ hello, world, padding }",[recipientPubKey]);console.log("sender encrypts to "+JSON.stringify(ct,null," "));var pt=ecMath.decrypt(ct,recipient.toWIF());console.log("recipient decrypts to "+JSON.stringify(pt,null," "))};</script><style>.mono,.small{font-size:12px}.spacer,body{background:#333}#leftbar,#outer2,div.popup{position:absolute}.nh,div.popup{display:none}.center,div.likereply{text-align:center}#logomain,.admin,.fromto,.leftsep,.me,.payaddr,h1,h2,table.props td:nth-child(1){font-weight:700}.indent{padding-left:20px}.mono{font-family:monospace}.wrap{word-break:break-all}body{font-family:Arial,Helvetica,sans-serif;font-size:17px;padding:0;margin:0;overflow-y:scroll}p{margin-right:45px}a{text-decoration:none}a:hover{text-decoration:underline}.leftitem,.leftitem:hover,.link:hover,.logolink:hover{text-decoration:none}.spacer{width:100%;height:8px;clear:both}#outer,#outer2{padding:0;min-height:100%;width:950px;background:#fff}#outer{top:0;margin:0 auto}#outer2{margin:0}#dimmer{position:fixed;width:100%;height:100%;background:rgba(100,100,100,.85);top:0;left:0;z-index:100}div.popup{border:1px solid #000;top:100px;left:100px;width:600px;height:305px;background:#fff;padding:10px;box-shadow:7px 7px 7px 0 #888;z-index:200;overflow-y:auto}#leftbar,#nagbar,#topbar{background:#ccc;border:1px solid #888}#leftbar,#logo{box-shadow:2px 2px 5px 0 #333}.logolink{color:inherit}#logo{background:#000;padding:5px 10px 5px 5px;height:30px;float:left}#logomain{color:red;font-size:26px;padding-left:5px}#logosub{color:#aaa;font-size:21px;padding-left:10px}#nagbar,#topbar{height:18px;padding:0 9px 2px;border-top:none;box-shadow:-1px 2px 5px 0 #333;float:right}#nagbar{margin-left:30px;margin-right:20px;float:left;box-shadow:1px 2px 5px 0 #333}#topbar{border-right:none}.topelem{padding:0 5px}#servers-count,#servers-dt{display:inline-block}#leftbar{bottom:0;top:44px;margin:25px 0 0;width:158px;border-left:none;padding:0 0 10px 2px}.leftsep{padding:2px 3px 2px 7px;margin:13px 0 0;color:#111;font-size:17px}.leftitem{padding:1px 2px 1px 14px;display:block;color:#000;font-size:16px}.leftitem:hover,.link:hover{cursor:pointer;background:#111;color:#fff}h1,h2{font-size:25px;margin:5px 0 6px;padding:0}h2{font-size:20px;margin:12px 0 5px}div.page{float:left;margin:30px 0 60px 190px;width:750px;display:none;min-height:400px}.button,.button-blue,.button-small{cursor:default;display:inline;border:1px solid #888;border-radius:3px;background:linear-gradient(160deg,#bbb,#ccc);padding:6px 10px 4px;box-shadow:inset 3px 3px 3px 0 #fff,2px 2px 3px 0 #000;white-space:nowrap}.button-blue:active,.button-small:active,.button:active{position:relative;top:1px;left:1px;box-shadow:inset -3px -3px 3px 0 #fff,-1px -1px 2px 0 #000}.button-blue{border:1px solid #66a;background:linear-gradient(160deg,#77f,#99f);box-shadow:inset 3px 3px 3px 0 #bbf,2px 2px 3px 0 #004}.button-blue:active{box-shadow:inset -3px -3px 3px 0 #aaf,-1px -1px 2px 0 #000}.button-small{padding:3px 3px 1px;font-size:14px;border-radius:2px}div.likereply{display:inline-block;margin:0 0 8px;color:#000}div.state{font-size:14px;margin-bottom:3px}.fromto{font-size:11px;padding-top:3px}.admin,.me{font-size:15px;margin:4px 0 4px -3px;padding:1px 3px}.me{color:#000;background:inherit}.admin{color:#0a2}.msgcount{margin-top:20px;margin-right:40px}.msgcount .button{margin-right:15px}table{border-collapse:collapse;border-spacing:0}table.props td:nth-child(1){text-align:right}table.comment{background:#fafafa;box-shadow:2px 2px 5px 0 #666;border:1px solid #888}table.hide4 td:nth-child(4),table.hide4 th:nth-child(4),table.hide5 td:nth-child(5),table.hide5 th:nth-child(5){display:none}table.borders td{background:#f6f6f6}table.comment td{background:0}table.msg-read{color:#999}table.borders td.bg-read{background:#eef}table.borders td.bg-reply{background:#eee}table.borders td.bg-top{background:#ccf}table.borders td,table.borders th{border:1px solid #888;border-spacing:0;padding:2px 10px}table.borders th{background:#ddd}table.borders td.action-button{text-align:right;padding:14px 0;border:none;background:#fff}table.borders{margin-right:30px}table.escrow td:nth-child(3){padding:10px 5px}table.borders td.noborder{border:none;background:#fff}table.borders td.total{background:#ccf}.payaddr{font-family:monospace;color:#a70;font-size:95%;border:1px dashed #a0a;padding:1px 5px}input.compose,textarea.compose{font-size:16px;font-family:Arial,Helvetica,sans-serif}textarea{overflow-y:scroll;resize:none}textarea.compose{width:500px;height:200px;margin:10px 0 15px}input.compose{width:400px}div.compose{padding:30px 0 0}#forum-postings{margin:20px 0 10px}tr.hoverhl:hover{cursor:pointer;background:#ccf}tr.hoverhl{background:#fafafa}tr.hoverhl td{background:inherit}tr.hl td{background:#ccf}div.tabs{border-bottom:1px solid #888;margin-right:40px;margin-top:20px;padding-left:10px;position:relative}a.tab,span.tab{display:inline-block;border:1px solid #888;border-bottom:none;margin:0 5px;padding:1px 5px;color:#000;height:20px;position:relative;top:1px}a.tab-unsel:hover,span.tab-unsel:hover{background:#000;color:#fff;cursor:pointer;text-decoration:none;border-color:#000}a.tab-sel,span.tab-sel{position:relative;background:#fff}.tab-content{padding-left:10px;display:none}table.twocol td:nth-child(1){text-align:right;padding:7px 7px 7px 20px;white-space:nowrap}table.twocol{margin-bottom:27px}table.noedit td:nth-child(1){font-weight:700;padding:6px 7px 6px 20px}table.noedit{margin-top:9px}input.btcaddr,input.hash{font-family:monospace;font-size:13px;width:320px}input.hash{width:520px}div.imgs{padding-right:20px}a.result,div.imgs div{display:inline-block;margin:10px 20px 10px 0;border:1px solid #888;padding:3px;vertical-align:top}div.imgs a.result{width:140px;overflow:hidden;height:180px;font-size:15px;box-shadow:2px 2px 5px 0 #666;background:#f6f6f6}div.countdown,div.mktcm{font-family:monospace;font-size:12px;white-space:pre}div.imgs div.vcent{position:relative;top:50%;transform:translateY(-50%);width:100%;text-align:center;margin:0;padding:0;border:none}div.imgs div.vcent:hover{text-decoration:underline}div.mktcm{background:#eee;padding:5px;margin:0 70px 0 20px}div.countdown{float:right;margin:0 3px;border:1px solid #888;padding:1px 3px}.deleted,.deleted a,.deleted div{color:#999}#listing-deleted{color:#000}div.nv,span.nv{display:block}div.nh,span.nh{display:none} </style><body><div id=outer><div id=outer2><div class=spacer></div><div id=logo><a href=? class=logolink><span id=logomain>AQUILA</span> <span id=logosub></span></a></div><div id=topbar><span class=topelem style=border-style:none;box-shadow:none><span class=link onclick=ui.navTo("servers")>servers: <span id=servers-count> / </span> <span id=servers-dt class=small></span></span>,</span> <span class=topelem>sigs: <span id=sigs-count> / </span>,</span> <span class=topelem><span id=log-show class=link onclick=ui.showPopup("log")>show log</span></span></div><div id=nagbar class=nh><span class=link onclick=ui.navTo("client") id=nagbar-link></span></div><div style=clear:both></div><div id=leftbar><div style=padding-top:8px id=categories><a class=leftitem style=font-size:12px>Loading Categories....</a></div><div class=leftsep>GENERAL</div><a class=leftitem href="?a=inbox">Private Messages</a> <a class=leftitem href="?a=forumList">Public Forums</a> <a class=leftitem href="?a=userInfo">My User Info</a> <a class=leftitem href="?a=keys">Manage Keys</a> <a class=leftitem href="?a=addressBook">Address Book</a><div id=for-buyers class=nh><div class=leftsep>BUYER TOOLS</div><a class=leftitem href="?a=orders&from=me">Orders Placed</a> <a class=leftitem href="?a=trust&from=me">Feedback By Me</a></div><div id=for-sellers class=nh><div class=leftsep>SELLER TOOLS</div><a class=leftitem href="?a=listings">My Listings</a> <a class=leftitem href="?a=uploadImgs">Upload Images</a> <a class=leftitem href="?a=orders&to=me">Orders Received</a> <a class=leftitem href="?a=trust&to=me">Feedback For Me</a> <a class=leftitem href="?a=fees">Market Fees</a></div><div class=leftsep>ADVANCED</div><a class=leftitem href="?a=msg">Msg Explorer</a> <a class=leftitem href="?a=marketControl">Market Control</a><div id=for-owners class=nh><a class=leftitem href="?a=owner">Owner Tools</a> <a class=leftitem href="?a=fees">Market Fees</a></div><div id=for-admins class=nh><a class=leftitem href="?a=admin">Admin Tools</a></div><a class=leftitem href="?a=client">Client Version</a></div><div id=page-default class="page nv"><h1>Loading...</h1><noscript><p>JavaScript is disabled in your browser.</p><p>Aquila uses client-side cryptography to avoid trusting a single remote server. This requires JavaScript in your browser. To minimize the associated risk, we recommend that you save this web page on your local computer (for example, on your desktop), and always open the local copy of the market software.</p><p>This isn't strictly necessary, but it limits your exposure to malicious code to the initial download. Later upgrades should be performed through the market, and the market will check their signatures.</p></noscript></div><div id=page-index class=page><h1>Market Home</h1><div id=index-info></div></div><div id=page-client class=page><h1>Client Software Version</h1><p>Aquila uses client-side cryptography to resist theft of funds or disclosure of secret information, even if its servers are compromised. For full security, the Aquila client <b>must be installed locally</b>. If you don't install the client, then its security is no better than for a standard web application.</p><p>The client is a single HTML file, with no other dependencies. To install, right-click to download the file below, and save it to local media. Then open the file with your web browser.</p><table class="borders props"><tr><th colspan=2>You Are Running<tr><td>Version:<td id=client-me class=mono><tr><th colspan=2>The Market Recommends<tr><td>Version:<td id=client-version class=mono><tr><td>Download Link:<td id=client-url class=mono><tr><td>File sha256 Hash:<td id=client-hash class=mono></table><p>The recommended software version is obtained from a message signed and broadcast by the market owners, and will change from time to time.</p><p>The client is distributed as a single HTML file instead of a browser extension because:</p><ul style=margin-right:80px><li>JavaScript in an ordinary web page is more sandboxed than JavaScript in a browser extension, reducing the attack surface if this client turns out to be malicious or flawed.</li><li>Installation of browser extensions is inconvenient on many operating systems designed to run from read-only media.</li></ul><p>The client that you are running now is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.</p><p>Copyright 2016 Aquila Developers</p></div><div id=page-inbox class=page><h1>Private Messages</h1><div class=tabs><span class="tab tab-sel">Inbox</span> <a class="tab tab-unsel" href="?a=sent">Sent Items</a> <a class="tab tab-unsel" href="?a=compose">Compose</a></div><table style="margin:20px 10px"><tr><td>From: <td><input class=btcaddr id=inbox-from><td><div class=button-small data-address=inbox-from>Address Book</div><td> <div class=button data-click=filter>Filter</div><td> <div class=button data-click=clearFilter>Clear</div><tr><td colspan=3 style=padding-top:3px;padding-bottom:5px> <label><input type=checkbox id=inbox-unread> unread messages only</label></table><div id=inbox-msgs></div><div class=msgcount><div style=float:right><div class=button id=inbox-newer>Newer</div><div class=button id=inbox-older>Older</div><span id=inbox-count></span></div></div><div style=clear:both></div><p id=inbox-warning class=nh>Messages older than <span id=inbox-warning-age></span> are not shown, even if they're unread.</p></div><div id=page-sent class=page><h1>Private Messages</h1><div class=tabs><a class="tab tab-unsel" href="?a=inbox">Inbox</a> <span class="tab tab-sel">Sent Items</span> <a class="tab tab-unsel" href="?a=compose">Compose</a></div><table style="margin:20px 10px"><tr><td>To: <td><input class=btcaddr id=sent-to><td><div class=button-small data-address=sent-to>Address Book</div><td> <div class=button data-click=filter>Filter</div><td> <div class=button data-click=clearFilter>Clear</div></table><div id=sent-msgs></div><div class=msgcount><div style=float:right><div class=button id=sent-newer>Newer</div><div class=button id=sent-older>Older</div><span id=sent-count></span></div></div></div><div id=page-compose class=page><h1>Private Messages</h1><div class=tabs><a class="tab tab-unsel" href="?a=inbox">Inbox</a> <a class="tab tab-unsel" href="?a=sent">Sent Items</a> <span class="tab tab-sel">Compose</span></div><p><table class=twocol><tr><td>From:<td class=mono id=compose-from><tr><td>To:<td><input class=btcaddr id=compose-to><div class=button-small data-address=compose-to id=compose-addrBook>Address Book</div><tr><td>Subject:<td><input id=compose-subject class=compose style=width:500px><tr id=compose-tx class=nh><td>Bitcoin Tx:<td>pays to <span id=compose-outAddr style=font-size:14px></span>  <div class=button-small id=compose-viewTx>View Transaction</div><tr id=compose-order class=nh><td>State:<td><select id=compose-state><option value="">(no change)<option value=new>new<option value="order received">order received<option value="items shipped">shipped<option value="order cancelled">cancelled<option value="escrow released">escrow released</select> <div class=button-small data-click=viewOrder>View Order</div><tr><td colspan=3 style=text-align:left>make msg also readable by  <label><input type=checkbox id=compose-me checked> sender (me)</label> <label><input type=checkbox id=compose-admins checked> market admins</label><tr><td colspan=2 style=text-align:left><textarea style=margin:0;width:600px class=compose id=compose-body></textarea><tr><td colspan=2 style=text-align:left;padding-top:12px><div class=button-blue data-click=send>Broadcast Private Message</div>  (plain text, no markup)</table></p></div><div id=page-uploadImgs class=page><h1>Upload Images</h1><p>Uploaded images can be attached to listings. Existing images appear below.</p><div id=uploadImgs-existing class=imgs></div><div style=clear:both></div><div style="padding:10px 0 50px 0"><div class=button-blue data-click=delete id=uploadImgs-delete>Broadcast Delete Selected Image</div></div><p><div class=button data-click=preview>Select Image and Preview Upload</div> <div class="button-blue nh" data-click=upload id=uploadImgs-upload>Broadcast Upload Previewed Image</div></p><table class="borders nh" id=uploadImgs-preview><thead><tr><th>Image<th>Thumbnail<tbody><tr><td><canvas id=uploadImgs-image></canvas><td><canvas id=uploadImgs-thumb></canvas></table></div><div id=page-search class=page><h1>Search Listings</h1><div class=indent><table class=twocol><tr><td><b>Category:</b><td><span id=search-category></span><tr><td><b>Ship From:</b><td><input id=search-shipFrom size=2>   <b>Ship To:</b> <input id=search-shipTo size=2><tr><td><b>Seller:</b><td colspan=3><input id=search-seller class=btcaddr><td> <div class=button data-click=search>Filter</div></table></div><div class=imgs id=search-results></div></div><div id=page-addressBook class=page><h1>Address Book</h1><p>Users on the market are identified by Bitcoin-style addresses (coded hashes of public keys). To keep track of people more conveniently, you can assign arbitrary nicknames to addresses.</p><p>Only you will see these nicknames. For security reasons, the market does not try to provide a global address book.</p><p><table class=twocol><tr><td>Address:<td><input class=btcaddr id=addressBook-new-addr><td rowspan=2 style=padding-left:20px><div class=button data-click=add>Add / Edit</div><tr><td>Nickname:<td><input id=addressBook-new-nickname size=30></table></p><table id=addressBook class=borders><thead><tr><th>Address (PK Hash)<th>Nickname<th><tbody id=addressBook-body><tfoot><td colspan=3 class=action-button><div class=button id=addressBook-delete>Delete</div></table></div><div id=page-forumList class=page><h1>Forum List</h1><p><table class=borders><thead><tr><th>Name<tbody id=forumList-body></table></p></div><div id=page-forum class=page><h1 id=forum-title></h1><table id=forum-postings class=borders><thead><tr><th>Age<th>From<th>Subject<tbody id=forum-postings-body></table><div id=forum-parent></div><div id=forum-replies></div><div class=msgcount style=margin-bottom:40px;margin-right:15px><div style=float:right><div class=button id=forum-newer>Newer</div><div class=button id=forum-older>Older</div><span id=forum-count></span></div></div><div class=compose id=forum-compose>Subject: <input id=forum-subject class=compose><br><textarea class=compose id=forum-body></textarea><br><div id=forum-post class=button-blue data-click=post>Broadcast New Forum Post</div>  (plain text, no markup)</div></div><div id=page-keys class=page><h1>Manage Keys</h1><p>All users identify themselves to the market using cryptographic key pairs. The browser may store these key pairs persistently (across exit and reboot), but you should also back them up by exporting them to a file and saving it locally.</p><p><div class=button data-click=export>Export Keys To File</div></p><p>To import from a backup file, delete all keys below. You will then be prompted to import.</p><table class=borders><thead><tr><th>PK Hash<th>Type<th>Secret Key (WIF)<th>Public Key (hex)<th>Age<th>Action<tbody id=keys-list></table><table style="margin:20px 0 20px 0"><tr><td><div class=button data-click=rotateEncryptionKey>Rotate Encryption Key</div>   <td><div class=button data-click=newBuyerIdentity>Generate New Buyer Pseudonym</div></table><table style=margin-top:35px><tr><td><div class=button data-click=deleteAll>Delete All Keys</div><td>  <input id=keys-delete-confirm size=11><td>  (type "DELETE ALL" in box to confirm)</table><p>If you delete all keys, then you will lose the ability to decrypt messages sent to you, or to release escrowed funds. Do not rely on any delete button here to securely delete keys. Use encrypted volumes, and wipe or physically destroy media at end of life.</p></div><div id=page-deleteKey class=page><div id=deleteKey-crypt class=nh><h1>Delete Old Encryption Key</h1><p>By deleting this key, you will make all messages encrypted with it permanently unreadable. These messages are:</p></div><div id=deleteKey-id class=nh><h1>Delete Old Pseudonym</h1><p>By deleting this pseudonym, you will lose the ability to send new messages under this identity, or to release any escrowed funds. You will also lose access to any encrypted messages sent to this pseudonym. These messages are:</p></div><table class=borders><thead><tr><th>Type<th>Hash<th>Age<tbody id=deleteKey-msgs></table><p id=deleteKey-count></p><table style=margin-top:25px><tr><td><div class=button data-click=delete>Delete</div><td>  <input id=deleteKey-confirm size=9><td>  (type "DELETE" in box to confirm)</table></div><div id=page-listingNew class=page><h1>Create New Listing</h1><div class=compose><table class=twocol style="margin:-20px 0 -4px 0"><tr><td>Currency:<td><select id=listingNew-currency></select><tr><td>Ship From:<td><input id=listingNew-from size=12> <span style=position:relative;top:13px> (like "DE", "FR,GB", "EU,CH", "ANY", etc.)</span><tr><td>Ship To:<td><input id=listingNew-to size=12><tr><td>Category:<td><select id=listingNew-category></select><tr><td>Title:<td><input id=listingNew-subject class=compose></table><textarea class=compose id=listingNew-body style=margin-bottom:3px;width:600px></textarea><br>  (plain text, no markup)</div><p>Select images from the list below to attach to this listing. Images must already have been uploaded.</p><div id=listingNew-images class=imgs></div><div style=clear:both></div><p>From the table below, the buyer must choose one line from the "main" group, and one line from the "shipping" group if it's present.</p><table class=borders><thead><tr><th>Item Description<th>Price Each<th>Group<th><tbody id=listingNew-items><tr id=listingNew-items-add-row><td colspan=3 style=border:none;background:#fff><td style=border:none;padding-top:5px;background:#fff><div class=button-small id=listingNew-items-add>Add Row</div></table><p><div class=button-blue id=listingNew-create>Broadcast New Listing</div></p></div><div id=page-listings class=page><h1>My Current Listings</h1><p><table class=borders><thead><tr><th>Title<th>Age<th><tbody id=listings-existing><tfoot><td colspan=3 class=action-button><div class=button id=listings-delete>Delete</div></table></p><p><div class=button onclick=ui.navTo("listingNew")>Create New Listing</div></p></div><div id=page-listing class=page><h1 id=listing-subject></h1><p class=nh id=listing-deleted><b>This listing has been deleted.</b></p><div class=imgs><div><b>Category:</b> <span id=listing-category></span></div><div><b>Ship From:</b> <span id=listing-from></span></div><div><b>Ship To:</b> <span id=listing-to></span></div></div><div style=clear:both></div><div id=listing-body></div><div id=listing-images class=imgs></div><div style=clear:both></div><p><table class=borders><thead><th>Item<th>Price<th>Qty<tbody id=listing-items></table></p><p>Shipping address, and notes to seller:<br><textarea style=margin:0;width:400px;height:100px class=compose id=listing-compose></textarea></p><p style=margin-top:30px><div class=button-blue id=listing-order>Broadcast Place New Order</div>  <b id=listing-total></b></p><p>The multisig payment address will be generated after you broadcast the order, and exchange rates will be locked. Your order may be cancelled if you don't send payment within thirty minutes.</p></div><div id=page-orders class=page><h1 id=orders-title>Orders</h1><table class=borders style=width:700px id=orders-table><thead><tr><th>Hash<th>Age<th>Title<th>Buyer<th>Seller<tbody id=orders-list></table><div class=msgcount><div style=float:right><div class=button id=orders-newer>Newer</div><div class=button id=orders-older>Older</div><span id=orders-count></span></div></div></div><div id=page-order class=page><h1 id=order-title>View Existing Order</h1><table class="twocol noedit" style=margin-bottom:-5px;margin-top:10px><tr><td>Hash:<td id=order-hash class=mono><tr><td>Listing:<td id=order-listing><tr><td>Seller:<td id=order-seller><tr><td>Buyer:<td id=order-buyer><tr><td>Age:<td id=order-age><tr><td>Pay To:<td id=order-addr></table><p>The buyer must send payment in the given amount to the Bitcoin address above. The seller will confirm that payment has been received, by clicking the address to view it in a blockchain explorer.</p><div class=indent><table class=borders><thead><tr><th>Item<th>Qty<th>Price (Each)<th>Price (Total)<tbody id=order-items></table></div><br><p>The following private messages have been sent regarding this order:</p><div class=indent style=padding-top:2px;padding-bottom:5px><div class=button id=order-compose>New Private Message</div> <div class=button id=order-propose-upper>Propose Escrow Release</div> <div class="button nh" id=order-trust>Leave Feedback</div></div><div class=indent><div id=order-msgs></div></div><br><div class="button nh" id=order-propose-lower>Propose Different Escrow Release</div></div><div id=page-release class=page><h1>Order Escrow Release</h1><table class="twocol noedit"><tr><td>Order:<td id=release-order><tr><td>Seller:<td id=release-seller><tr><td>Buyer:<td id=release-buyer><tr><td>Pay From:<td id=release-payFrom><tr><td>Value In:<td id=release-valueIn><tr><td>Pay To:<td id=release-payTo><tr><td>Value Out:<td id=release-valueOut><tr><td>Fee:<td id=release-fee><tr><td>Transaction:<td><div class=button-small data-click=viewTx>View As Hex</div></table><p><div class=button id=release-go>Compose Message Accepting Escrow Release</div></p></div><div id=page-msg class=page><h1>Msg Explorer</h1><div id=msg-search><p><table class=twocol><tr><td>Hash:<td><input id=msg-hash class=hash><tr><td>Type:<td><input id=msg-type list=msg-types><datalist id=msg-types><option value=marketControl><option value=delegateProxyVote><option value=approveNewIdentity><option value=keysForIdentity><option value=publicComment><option value=privateComment><option value=trust><option value=image><option value=listing><option value=deleteMessage><option value=placeOrder><option value=requestFeePayment><option value=paidFee></datalist><tr><td>Time:<td><input id=msg-minTime size=5> to <input id=msg-maxTime size=5> (Unix time, or -x for x days ago)<tr><td>sigFrom:<td><input id=msg-sigFrom class=btcaddr> (sender)<tr><td>cipherTo[0]:<td><input id=msg-cipherTo class=btcaddr> (intended recipient)<tr><td><input id=msg-custom-key list=msg-customs size=5>:<datalist id=msg-customs><option value=pkhId><option value=ref><option value=category><option value=shipFrom><option value=shipTo><option value=to></datalist><td><input id=msg-custom-value><tr><td>Skip first:<td><input id=msg-skipResults size=5 placeholder=0> results  <label><input type=checkbox id=msg-deletedOk> include deleted</label></table></p><p><div class=button data-click=get>Search Messages</div> <div class=button data-click=getAll>Clear Filters</div></p></div><textarea class="mono nh" cols=100 rows=30 id=msg-json style=overflow-x:scroll;margin-top:30px wrap=off spellcheck readonly></textarea><table class="borders nh" id=msg-table-many style=margin-top:30px><thead><tr><th>Hash<tbody id=msg-hashes></table><p class=nh id=msg-count></p></div><div id=page-marketControl class=page><h1>Market Control</h1><p>Control of the market (i.e., the ability to allow or ban users, or moderate a forum, or release escrow to resolve a buyer-seller dispute) is determined by a vote of many owners, with ownership tracked in the Bitcoin blockchain.</p><p><div class=indent><div class=button data-click=refresh>Refresh ticker/marketControl</div></div></p><p>The current elected admins are:</p><div id=marketControl-marketControl class=mktcm></div><p>The owners are:</p><div id=marketControl-owners class=mktcm></div><p>The owners have delegated voting power (<span class=mono>agent : [ principal0, ... ]</span>) as follows:</p><div id=marketControl-delegates class=mktcm></div><p>The ticker, which contains frequently-changing information needed by the client, is:</p><div id=marketControl-ticker class=mktcm></div></div><div id=page-owner class=page><h1>Owner Tools <span id=owner-stake style=font-size:16px;font-weight:400></span></h1><div class=tabs><span class="tab tab-sel" data-tab=owner-vote>Vote For Admins</span> <span class="tab tab-unsel" data-tab=owner-nominate>Nominate Myself</span> <span class="tab tab-unsel" data-tab=owner-proxy>Proxy Vote</span></div><div class="nv tab-content" id=owner-vote><p>This is a list of marketControl messages. Only one is effective, but many can be broadcast and awaiting votes. The message with greatest total voting power becomes effective after a delay, typically a few minutes.</p><table class=borders><thead><tr><th>Hash<th>adminPkh[0]<th>Age<th>Voting Power<th><tbody id=owner-votables><tfoot><td colspan=5 class=action-button><div class=button-blue id=owner-vote-button>Vote</div></table></div><div class=tab-content id=owner-nominate><p>Compose and broadcast a marketControl message. All owner's keys that you control will vote for this message. In most cases, more votes from other users will be required before it becomes effective.</p><p><textarea class=mono cols=80 rows=20 id=owner-market-control style=overflow-x:scroll wrap=off spellcheck></textarea></p><p><div class=button data-click=checkMarketControl>Check Format</div> <div class=button-blue data-click=broadcastMarketControl>Broadcast Nomination</div></p></div><div class=tab-content id=owner-proxy><p>If you broadcast a proxy message, then the person that you specify can vote on your behalf on marketControl messages. Select an owner's key, and delegate or rescind proxy voting power:</p><p><table class=borders><thead><tr><th>pkhId<th>Shares<th><tbody id=owner-pkhs></table></p><p><table><tr><td><input id=owner-proxy-addr class=btcaddr><td> <div class=button-blue id=owner-delegate>Broadcast Delegate To Proxy</div></table></p><p style=margin-top:25px>If you rescind the proxy, then they lose that authority.</p><p><div class=button-blue id=owner-rescind>Broadcast Rescind Proxy</div></p></div></div><div id=page-admin class=page><h1>Admin Tools</h1><div class=tabs><span class="tab tab-sel" data-tab=admin-approve>Approve or Ban User</span> <span class="tab tab-unsel" data-tab=admin-delete>Delete Message</span> <span class="tab tab-unsel" data-tab=admin-fee>Request Fee</span></div><div class="nv tab-content" id=admin-approve><p><table class=twocol><tr><td>Approve As:<td><label><input type=radio name=admin-approve id=admin-approve-buy checked> buyer</label><label><input type=radio name=admin-approve id=admin-approve-sell> seller</label><label><input type=radio name=admin-approve id=admin-approve-ban> ban</label><tr><td>Address:<td><input id=admin-approve-pkhId class=btcaddr><tr><td>Valid From:<td><input id=admin-approve-validFrom size=10> <span style=position:relative;top:16px>  (Unix time, or +/-x for x days in future/past)</span><tr><td>Valid To:<td><input id=admin-approve-validTo size=10><tr><td>kB Per Day:<td><input id=admin-approve-kbPerDay size=5><tr><td>Comment:<td><input id=admin-approve-comment size=40></table></p><p><div class=button-blue data-click=approveNewIdentity>Broadcast Approve (or Ban) Identity</div></p></div><div class=tab-content id=admin-delete><p><table class=twocol><tr><td>Hash:<td><input id=admin-delete-hash class=hash><tr><td>Comment:<td><input id=admin-delete-comment size=40></table></p><p><div class=button-blue data-click=delete>Broadcast Delete Message</div></p></div><div class=tab-content id=admin-fee><p>CSV format, one row per payment, "from,to,amount", amount in BTC.</p><p><textarea rows=15 cols=80 id=admin-fee-text placeholder=1SenderXXX,1RecipientXXX,0.32></textarea></p><div style=margin-top:-10px;margin-bottom:22px>Comment: <input size=45 id=admin-fee-comment></div><p><div class=button-blue data-click=requestFeePayment>Broadcast Request Fee</div></p></div></div><div id=page-userInfo class=page><h1>My User Information</h1><p>This page contains public information about you. For example, a seller might post general policies here, or off-market contact information. Other users will see this page when they click your address.</p><div class=indent><div class=compose style=margin-top:0;padding-top:0>Title: <input id=userInfo-subject class=compose><br><textarea class=compose id=userInfo-body></textarea><br><div class=button-blue data-click=post>Broadcast New User Info</div>  (plain text, no markup)</div><p style=margin-top:35px><div class=button data-click=user>View My User Information As Others Will See It</div></p></div></div><div id=page-user class=page><h1>User Information</h1><table class="twocol noedit"><tr><td>User:<td><input class=btcaddr id=user-pkh> <div class=button data-click=search>Get User Info</div><tr><td>Last Seen:<td id=user-ago><tr><td>Private Msg:<td><div class=button-small data-click=compose>Compose To User</div><tr><td>Role:<td><div id=user-seller class=nh>seller  <div class=button-small data-click=listings>View Listings</div> <div class=button-small data-click=ordersTo>View Orders</div></div><div id=user-buyer class=nh>buyer  <div class=button-small data-click=ordersFrom>View Orders</div></div><div id=user-admin class=nh>admin</div><div id=user-owner class=nh>owner</div><div id=user-banned class=nh>BANNED</div><tr><td>Effective:<td id=user-valid><tr><td>Feedback:<td><div class=button-small data-click=trustFrom>Left By User</div> <div class=button-small data-click=trustTo>Received For User</div></table><div id=user-info>no user info</div></div><div id=page-trustNew class=page><h1>Provide Feedback</h1><p>Leave a score of +1 after an entirely successful transaction, or -1 if you got scammed. A score of zero has the same effect as no feedback at all.</p><table class=twocol><tr><td>Left By:<td id=trustNew-from class=mono><tr><td>For User:<td><input class=btcaddr id=trustNew-to><tr><td>Order:<td><input class=hash id=trustNew-order><tr><td>Score:<td><input id=trustNew-score value=+1 size=5><tr><td>Comment:<td><input id=trustNew-comment size=40 maxlength=100></table><p><div class=button-blue data-click=post>Broadcast Feedback</div></p></div><div id=page-trust class=page><h1 id=trust-title>View Feedback</h1><table class=twocol><tr><td>Left By:<td><input class=btcaddr id=trust-from><tr><td>For User:<td><input class=btcaddr id=trust-to>  <div class=button data-click=search>Search</div></table><table class=borders><thead><tr><th>Age<th>Left By<th>For<th>Comment<th>Score<th>Order<tbody id=trust-msgs></table><div class=msgcount><div style=float:right><div class=button id=trust-newer>Newer</div><div class=button id=trust-older>Older</div><span id=trust-count></span></div></div></div><div id=page-fees class=page><h1>Market Fees</h1><p>Market fees are generally paid from sellers to owners, but may be used for other purposes too (e.g., to refund a bond posted by a seller). They are totally independent of payment for items bought and sold on the market.</p><p style=margin-top:20px><b>Requests</b> from the market admins to pay fees:</p><div class=indent><p><div class=button onclick=ui.navTo("feeRequests",{from:"me"})>Fees That I Pay</div> <div class=button onclick=ui.navTo("feeRequests",{to:"me"})>Fees That I Receive</div> <div class=button onclick=ui.navTo("feeRequests")>All Fees</div> </p></div><p style=margin-top:30px><b>Confirmations</b> from users claiming to have paid fees:</p><div class=indent><p><div class=button onclick=ui.navTo("feePayments",{from:"me"})>Fees That I Pay</div> <div class=button onclick=ui.navTo("feePayments",{to:"me"})>Fees That I Receive</div> <div class=button onclick=ui.navTo("feePayments")>All Fees</div> </p></div><p>Stealth-style payment is used, so the fee recipient needs this confirmation to find the payment in the blockchain.</p></div><div id=page-feeRequests class=page><h1>Requested Fee Payments</h1><p>The admins have requested that users make payments as follows:</p><table class=twocol><tr><td>From:<td><input class=btcaddr id=feeRequests-from><tr><td>To:<td><input class=btcaddr id=feeRequests-to>  <div class=button data-click=search>Search</div></table><table class=borders><thead><tr><th>Hash<th>Age<th>By Admin<th>Comment<tbody id=feeRequests-lines></table></div><div id=page-feeRequest class=page><h1>Requested Fee Payment</h1><p>In one specific payment request:</p><table class="twocol noedit"><tr><td>Hash:<td id=feeRequest-hash class=mono><tr><td>Age:<td id=feeRequest-age><tr><td>By Admin:<td id=feeRequest-adminSuper><tr><td>Comment:<td id=feeRequest-comment></table><table class=borders><thead><tr><th>From<th>To<th>Value<br>(BTC)<th><tbody id=feeRequest-lines></table></div><div id=page-feePayments class=page><h1>Completed Fee Payments</h1><p>Users claim to have made payments as follows:</p><table class=twocol><tr><td>From:<td><input class=btcaddr id=feePayments-from><tr><td>To:<td><input class=btcaddr id=feePayments-to>  <div class=button data-click=search>Search</div></table><table class=borders><thead><tr><th>Hash<th>Age<th>From<th>To<th>Value<br>(BTC)<tbody id=feePayments-lines></table></div><div id=page-feePayment class=page><h1>Completed Fee Payment</h1><p>A user claims to have made the following payment:</p><table class="twocol noedit"><tr><td>Hash:<td id=feePayment-hash class=mono><tr><td>Age:<td id=feePayment-age><tr><td>From:<td id=feePayment-from><tr><td>To:<td id=feePayment-to><tr><td>Amount:<td id=feePayment-amount><tr><td>Request:<td id=feePayment-request><tr><td>Pay To:<td id=feePayment-address><tr id=feePayment-wif-row class=nh><td>WIF:<td id=feePayment-wif class=mono></table><p>The sender must pay Bitcoin to the address given above, in the given amount.</p><p>The recipient may import this address as WIF to another wallet, and spend the payment from there.</p></div><div id=page-servers class=page><h1>Server List</h1><p>The table shows the server URI, goodness metric, average response time, last seen time, whether it appears in marketControl, and whether it appears in the hard-coded bootstrap list.</p><table class=borders><thead><tr><th>URI<th>Gdns<th>resp (s)<th>ago<th>mktC?<th>btstrp?<tbody id=servers-working></table><br><p>Choose servers</p><div class=indent style=margin-top:-8px><label><input type=radio name=servers-how id=servers-auto> automatically (recommended)</label></div><div class=indent><label><input type=radio name=servers-how id=servers-manual> manually, always using:</label><div style=margin-top:5px;margin-left:50px><input class=mono id=servers-manual-0 size=60><br><input class=mono id=servers-manual-1 size=60><br><input class=mono id=servers-manual-2 size=60><br></div></div><p><div class=button data-click=save>Save Changes</div></p></div><div id=popup-captcha class=popup><h1>CAPTCHA Required</h1><p id=captcha-bad>Last CAPTCHA wrong, please retry.</p><p><img src="" id=captcha-img><br><input size=10 id=captcha-text></p><p><div class=button-blue id=captcha-broadcast>Broadcast Message</div> <div class=button id=captcha-another>Get Different CAPTCHA</div> <div class=button onclick=ui.hidePopup()>Dismiss Window</div></p></div><div id=popup-keys class=popup><h1>No Keys in Browser Local Storage</h1><p>No cryptographic key pairs were found in browser local storage. All market buyers, sellers, owners, and admins need key pairs to identify themselves to the market.</p><div class=indent style=margin-top:25px;margin-bottom:30px><div class=button data-click=newRandom>Make New Identity</div> <div class=button data-click=import>Import From File</div> <div class=button onclick=ui.navTo("index")>Remain As Guest</div></div><div class=button-small id=keys-advanced data-click=advanced>Show Advanced</div><div id=keys-import-wif class=nh style=margin-top:30px><p>When you create a new identity, the address that other users will see is usually generated randomly. You can instead import that address as WIF (e.g., from vanitygen).</p><div class=indent style=margin-top:12px><p style=margin-bottom:23px>WIF: <input class=mono size=60 id=keys-wif><br></p><p><div class=button data-click=importWif>Make New Identity Using Imported skId</div></p><br></div></div></div><div id=popup-approveNewIdentity class=popup><h1>Identity Not Yet Approved</h1><p>Your identity has not yet been approved by the market admins. You can request this at the following web pages:</p><ul id=popup-approveNewIdentity-list></ul><p>The identity appears in your list of keys immediately, but can't be used to send messages on the market until it's approved.</p><div class=button onclick=ui.navReload()>Confirm Approval</div> <div class=button onclick=ui.hidePopup()>Not Now</div></div><div id=popup-keysForIdentity class=popup><h1>Keys Not Yet Broadcast To Market</h1><p>The market may not have your latest encryption or Bitcoin escrow release keys. This means that other users might send encrypted messages or funds using older keys that you plan to retire soon.</p><p>This loses the benefit of key rotation. To fix this, broadcast your latest public keys now.</p><div class=button-blue data-click=broadcastKeysForIdentity>Broadcast Latest Crypt/BTC Public Keys</div> <div class=button onclick=ui.hidePopup()>Dismiss Window</div></div><div id=popup-exportKeys class=popup><h1>Export Cryptographic Keys</h1><p>You have generated new cryptographic keys, and you haven't yet exported them. The keys are stored in browser local storage, but you should also export them to a file, and save the file on a local encrypted volume.</p><p>If you lose your keys, then you will lose your account's reputation from feedback, access to all encrypted messages, and all escrowed funds.</p><div class=button data-click=export>Export Keys</div></div><div id=popup-newBuyerIdentity class=popup><h1>New Buyer Pseudonym</h1><p>You can create a new buyer pseudonym. This hides the fact that the same person placed multiple orders from the general public. Choose a server from the list below:</p><ul id=popup-newBuyerIdentity-list></ul><p>It's best to always use the same server if possible, since the admin of that server can learn the link between your pseudonyms.</p><div class=button onclick=ui.hidePopup()>Dismiss Window</div></div><div id=popup-addressBook class=popup><h1>Address Book</h1><table class=borders><thead><tr><th>Address<th>Nickname<tbody id=addressBook-popup-body></table><p><div class=button onclick=ui.hidePopup()>Dismiss Window</div></p></div><div id=popup-escrow class=popup><h1>Propose Escrow Release</h1><p><div class=indent><table class=borders><thead><tr><th>TXID<th>vout<th>Value<tbody id=escrow-txos></table></div></p><p>Propose that all funds above be released to:</p><table class=twocol><tr><td>Address:<td><input class=btcaddr id=escrow-addr><tr><td>Transaction Fee:<td><input id=escrow-fee value=0.0001 size=5> BTC</table><p><div class=button id=escrow-compose>Compose Message Proposing Escrow Release</div> <div class=button onclick=ui.hidePopup()>Dismiss Window</div></p></div><div id=popup-viewTx class=popup><h1>View Transaction As Hex</h1><textarea class=mono rows=13 cols=80 readonly id=viewTx-tx></textarea><p><div class=button onclick=ui.hidePopup()>Dismiss Window</div>  signed by <span id=viewTx-n></span>/3 parties</p></div><div id=popup-trustDel class=popup><h1>Feedback Already Exists</h1><p>You have already left feedback for this user. To leave new feedback, delete the old feedback first.</p><div class=button-blue id=trustDel-delete>Broadcast Delete Old Feedback</div></div><div id=popup-wait class=popup><h1>Performing EC Math...</h1></div><div id=popup-notify class=popup><h1>Notification</h1><p id=popup-notify-text></p><div class=button onclick=ui.hidePopup() id=popup-notify-button>Dismiss Window</div></div><div id=popup-log class=popup><h1>Network Activity Log</h1><textarea rows=13 cols=80 readonly class=mono id=log-text wrap=off></textarea><p><div style=float:left><div class=button id=popup-log-dismiss onclick=ui.hidePopup()>Dismiss Window</div></div><div style=float:right id=popup-log-countdown></div></p></div><div class=spacer style=position:absolute;bottom:0></div></div><div id=dimmer class=nh></div></div>