diff --git a/src/css/keyboard.css b/src/css/keyboard.css new file mode 100644 index 0000000..906e8c2 --- /dev/null +++ b/src/css/keyboard.css @@ -0,0 +1,329 @@ +/* keyboard - jQuery UI Widget */ +.ui-keyboard { + text-align: center; + padding: .3em; + position: absolute; + left: 0; + top: 0; + z-index: 16000; + /* see issue #484 */ + -ms-touch-action: manipulation; + touch-action: manipulation; +} +.ui-keyboard-has-focus { + z-index: 16001; +} +.ui-keyboard div { + font-size: 1.1em; +} +.ui-keyboard-button { + height: 2em; + min-width: 2em; + margin: .1em; + cursor: pointer; + overflow: hidden; + line-height: 2em; + -moz-user-focus: ignore; +} +.ui-keyboard-button span { + padding: 0; + margin: 0; + white-space: nowrap; + display: inline-block; +} +.ui-keyboard-button-endrow { + clear: left; +} +.ui-keyboard-space { + width: 15em; +} +/* see http://nicolasgallagher.com/another-css-image-replacement-technique/ */ +.ui-keyboard-space span, .ui-keyboard-empty span { + font: 0/0 a; + text-shadow: none; + color: transparent; +} +.ui-keyboard-preview-wrapper { + text-align: center; + position: relative; + overflow: hidden; +} +/* width is calculated in IE, since 99% = 99% full browser width =( */ +.ui-keyboard-preview { + text-align: left; + margin: 0 0 3px 0; + display: inline; + width: 99%; +} +.ui-keyboard-keyset { + text-align: center; + white-space: nowrap; +} +.ui-keyboard-input { + text-align: left; +} +.ui-keyboard-input-current { + -moz-box-shadow: 0 0 5px #4d90fe; + -webkit-box-shadow: 0 0 5px #4d90fe; + box-shadow: 0 0 5px #4d90fe; +} +.ui-keyboard-placeholder { + color: #888; +} +/* disabled or readonly inputs, or use + input[disabled='disabled'] { color: #f00; } */ +.ui-keyboard-nokeyboard { + color: #888; + border-color: #888; +} +.ui-keyboard-spacer { + display: inline-block; + width: 1px; + height: 0; + cursor: default; +} + +.ui-keyboard-NBSP span, .ui-keyboard-ZWSP span, .ui-keyboard-ZWNJ span, +.ui-keyboard-ZWJ span, .ui-keyboard-LRM span, .ui-keyboard-RLM span { + font-size: 0.5em; + line-height: 1.5em; + white-space: normal; +} + +/* combo key styling - toggles diacritics on/off */ +.ui-keyboard-button.ui-keyboard-combo.ui-state-default { + border-color: #ffaf0f; +} + +/* (in)valid inputs */ +button.ui-keyboard-accept.ui-keyboard-valid-input { + border-color: #0c0; + background: #080; + color: #fff; +} +button.ui-keyboard-accept.ui-keyboard-valid-input:not([disabled]):hover { + background: #0a0; +} +button.ui-keyboard-accept.ui-keyboard-invalid-input { + border-color: #c00; + background: #800; + color: #fff; + opacity: 0.5; + filter: alpha(opacity=50); +} +button.ui-keyboard-accept.ui-keyboard-invalid-input:not([disabled]):hover { + background: #a00; +} + +/*** Caret extension definition ***/ +/* margin-top => is added to the caret height (top & bottom) */ +.ui-keyboard-caret { + background: #c00; + width: 1px; + margin-top: 3px; +} + +/*** jQuery Mobile definitions ***/ +/* jQuery Mobile styles - need wider buttons because of font size and + text-overflow:ellipsis */ +div.ui-body.ui-keyboard button.ui-keyboard-button.ui-btn { + padding: 0.5em 1em; + border-color: transparent; +} +.ui-body .ui-keyboard-button { + width: 3em; + height: 3em; + display: inline-block; +} +.ui-body .ui-keyboard-widekey { + width: 5.5em; +} +.ui-body .ui-keyboard-space { + width: 15em; +} +.ui-body .ui-keyboard-space span { + visibility: hidden; /* hides the ellipsis */ +} +.ui-body .ui-keyboard-keyset { + line-height: 0.5em; +} +.ui-body input.ui-input-text, .ui-body textarea.ui-input-text { + width: 95%; +} + +/* over-ride padding set by mobile ui theme - needed because the mobile script + wraps button text with several more spans */ +.ui-body .ui-btn-inner { + height: 2em; + padding: 0.2em 0; + margin: 0; +} +.ui-body .ui-btn { + margin: 0; + font-size: 13px; /* mobile default size is 13px */ +} + +/* override Bootstrap excessive button padding */ +button.ui-keyboard-button.btn { + padding: 1px 6px; +} + +/* enable/disable icons */ +button.ui-keyboard-toggle span { + width: .8em; + height: .8em; + display: inline-block; + background-repeat: no-repeat; + background-position: center center; + background-size: contain; +} +/* unlocked icon (keyboard enabled) */ +button.ui-keyboard-toggle span { + /* light theme unlocked icon - fill: #111 */ + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgZmlsbD0iIzExMSI+PHBhdGggZD0iTTguNyw0LjRINy41SDUuMHYtMS45YzAtMS40LTEuMS0yLjUtMi41LTIuNWMtMS40LDAtMi41LDEuMS0yLjUsMi41djEuOWgxLjIgdi0xLjljMC0wLjcsMC42LTEuMiwxLjItMS4yczEuMiwwLjYsMS4yLDEuMnYxLjljLTAuNywwLTEuMiwwLjYtMS4yLDEuMlY4LjggYzAsMC43LDAuNiwxLjIsMS4yLDEuMmg1LjBDOS40LDEwLDEwLDkuNCwxMCw4LjhWNS42QzEwLDUuMCw5LjQsNC40LDguOCw0LjR6IE02LjYsNy40djEuMCBjMCwwLjItMC4xLDAuMy0wLjMsMC4zUzYuMCw4LjYsNi4wLDguNFY3LjRjLTAuMi0wLjEtMC4zLTAuMy0wLjMtMC41YzAtMC4zLDAuMy0wLjYsMC42LTAuNiBTNi45LDYuNiw2LjksNi45QzYuOSw3LjEsNi44LDcuMyw2LjYsNy40eiIvPjwvc3ZnPg==); +} +.ui-keyboard-dark-theme button.ui-keyboard-toggle span { + /* dark theme unlocked icon - fill: #eee */ + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgZmlsbD0iI2VlZSI+PHBhdGggZD0iTTguNyw0LjRINy41SDUuMHYtMS45YzAtMS40LTEuMS0yLjUtMi41LTIuNWMtMS40LDAtMi41LDEuMS0yLjUsMi41djEuOWgxLjIgdi0xLjljMC0wLjcsMC42LTEuMiwxLjItMS4yczEuMiwwLjYsMS4yLDEuMnYxLjljLTAuNywwLTEuMiwwLjYtMS4yLDEuMlY4LjggYzAsMC43LDAuNiwxLjIsMS4yLDEuMmg1LjBDOS40LDEwLDEwLDkuNCwxMCw4LjhWNS42QzEwLDUuMCw5LjQsNC40LDguOCw0LjR6IE02LjYsNy40djEuMCBjMCwwLjItMC4xLDAuMy0wLjMsMC4zUzYuMCw4LjYsNi4wLDguNFY3LjRjLTAuMi0wLjEtMC4zLTAuMy0wLjMtMC41YzAtMC4zLDAuMy0wLjYsMC42LTAuNiBTNi45LDYuNiw2LjksNi45QzYuOSw3LjEsNi44LDcuMyw2LjYsNy40eiIvPjwvc3ZnPg==); +} + +/* locked icon (keyboard disabled) */ +button.ui-keyboard-toggle.ui-keyboard-disabled span { + /* light theme locked icon - fill: #111 */ + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgZmlsbD0iIzExMSI+PHBhdGggZD0iTTcuNCA0LjRWMi41YzAtMS40LTEuMS0yLjUtMi41LTIuNWMtMS40IDAtMi41IDEuMS0yLjUgMi41djEuOSBjLTAuNyAwLTEuMiAwLjUtMS4yIDEuMnYzLjFDMS4zIDkuNCAxLjggMTAgMi41IDEwaDQuOWMwLjcgMCAxLjItMC42IDEuMi0xLjJWNS42IEM4LjcgNC45IDguMSA0LjQgNy40IDQuNHogTTUuMyA3LjR2MS4wYzAgMC4yLTAuMSAwLjMtMC4zIDAuM2MtMC4yIDAtMC4zLTAuMS0wLjMtMC4zVjcuNCBjLTAuMi0wLjEtMC4zLTAuMy0wLjMtMC41YzAtMC4zIDAuMy0wLjYgMC42LTAuNmMwLjMgMCAwLjYgMC4zIDAuNiAwLjYgQzUuNiA3LjEgNS41IDcuMyA1LjMgNy40eiBNNi4yIDQuNEgzLjdWMi41YzAtMC43IDAuNS0xLjIgMS4yLTEuMmMwLjcgMCAxLjIgMC42IDEuMiAxLjIgVjQuNHoiLz48L3N2Zz4=); +} +.ui-keyboard-dark-theme button.ui-keyboard-toggle.ui-keyboard-disabled span { + /* dark theme locked icon - fill: #eee */ + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgZmlsbD0iI2VlZSI+PHBhdGggZD0iTTcuNCA0LjRWMi41YzAtMS40LTEuMS0yLjUtMi41LTIuNWMtMS40IDAtMi41IDEuMS0yLjUgMi41djEuOSBjLTAuNyAwLTEuMiAwLjUtMS4yIDEuMnYzLjFDMS4zIDkuNCAxLjggMTAgMi41IDEwaDQuOWMwLjcgMCAxLjItMC42IDEuMi0xLjJWNS42IEM4LjcgNC45IDguMSA0LjQgNy40IDQuNHogTTUuMyA3LjR2MS4wYzAgMC4yLTAuMSAwLjMtMC4zIDAuM2MtMC4yIDAtMC4zLTAuMS0wLjMtMC4zVjcuNCBjLTAuMi0wLjEtMC4zLTAuMy0wLjMtMC41YzAtMC4zIDAuMy0wLjYgMC42LTAuNmMwLjMgMCAwLjYgMC4zIDAuNiAwLjYgQzUuNiA3LjEgNS41IDcuMyA1LjMgNy40eiBNNi4yIDQuNEgzLjdWMi41YzAtMC43IDAuNS0xLjIgMS4yLTEuMmMwLjcgMCAxLjIgMC42IDEuMiAxLjIgVjQuNHoiLz48L3N2Zz4=); +} + +.ui-keyboard.ui-keyboard-disabled button:not(.ui-keyboard-toggle), +.ui-keyboard.ui-keyboard-disabled input { + opacity: 0.5; +} + +/*** Alt-Keys Popup extension ***/ +/* clickable overlay on top of keyboard to hide the popup */ +.ui-keyboard-overlay { + position: absolute; + top: 0; + left: 0; + bottom: 0; + right: 0; + background: rgba(0, 0, 0, 0.5); +} +/* the actual popup styling, class names from the css.container option are also + added */ +.ui-keyboard-popup { + display: inline-block; + /* default buttons are 2em wide + .1em margin on either side (set in + .ui-keyboard-button definition); so use multiples of 2.2em for a max-width + if you don't want any extra white space on the sides, e.g. + 5 buttons * 2.2em = 11em, + 6 buttons * 2.2em = 13.2em, etc + */ + max-width: 22em; /* 10 buttons */ +} + +/*** Extender keyboard extension ***/ +div.ui-keyboard-extender { + margin-left: 5px; +} +button.ui-keyboard-extender span { + width: .9em; + height: .9em; + display: inline-block; + margin-bottom: 3px; + background-repeat: no-repeat; + background-position: center center; + background-size: contain; + /* light theme extender icon - fill: #111 */ + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgc3R5bGU9ImZpbGw6IzExMSI+PGc+PHBhdGggc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzExMSIgZD0iTSAwLjUsNC41IDE1LjUsNC41IDE1LjUsMTUuNSAwLjUsMTUuNSBaIj48L3BhdGg+PHJlY3Qgd2lkdGg9IjIiIGhlaWdodD0iMiIgeD0iMiIgeT0iNiI+PC9yZWN0PjxyZWN0IHdpZHRoPSIyIiBoZWlnaHQ9IjIiIHg9IjUiIHk9IjYiPjwvcmVjdD48cmVjdCB3aWR0aD0iMiIgaGVpZ2h0PSIyIiB4PSI4IiB5PSI2Ij48L3JlY3Q+PHBhdGggZD0ibSAxMSw2IDMsMCAwLDUgLTIsMCAwLC0zIC0xLDAgeiI+PC9wYXRoPjxyZWN0IHdpZHRoPSIyIiBoZWlnaHQ9IjIiIHg9IjEyIiB5PSIxMiI+PC9yZWN0PjxyZWN0IHdpZHRoPSI2IiBoZWlnaHQ9IjIiIHg9IjUiIHk9IjEyIj48L3JlY3Q+PHJlY3Qgd2lkdGg9IjIiIGhlaWdodD0iMiIgeD0iOSIgeT0iOSI+PC9yZWN0PjxyZWN0IHdpZHRoPSIyIiBoZWlnaHQ9IjIiIHg9IjYiIHk9IjkiPjwvcmVjdD48cmVjdCB3aWR0aD0iMiIgaGVpZ2h0PSIyIiB4PSIyIiB5PSIxMiI+PC9yZWN0PjxyZWN0IHdpZHRoPSIzIiBoZWlnaHQ9IjIiIHg9IjIiIHk9IjkiPjwvcmVjdD48L2c+PC9zdmc+); +} +.ui-keyboard-dark-theme button.ui-keyboard-extender span { + /* dark theme extender icon - fill: #eee */ + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgc3R5bGU9ImZpbGw6I2VlZSI+PGc+PHBhdGggc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6I2VlZSIgZD0iTSAwLjUsNC41IDE1LjUsNC41IDE1LjUsMTUuNSAwLjUsMTUuNSBaIj48L3BhdGg+PHJlY3Qgd2lkdGg9IjIiIGhlaWdodD0iMiIgeD0iMiIgeT0iNiI+PC9yZWN0PjxyZWN0IHdpZHRoPSIyIiBoZWlnaHQ9IjIiIHg9IjUiIHk9IjYiPjwvcmVjdD48cmVjdCB3aWR0aD0iMiIgaGVpZ2h0PSIyIiB4PSI4IiB5PSI2Ij48L3JlY3Q+PHBhdGggZD0ibSAxMSw2IDMsMCAwLDUgLTIsMCAwLC0zIC0xLDAgeiI+PC9wYXRoPjxyZWN0IHdpZHRoPSIyIiBoZWlnaHQ9IjIiIHg9IjEyIiB5PSIxMiI+PC9yZWN0PjxyZWN0IHdpZHRoPSI2IiBoZWlnaHQ9IjIiIHg9IjUiIHk9IjEyIj48L3JlY3Q+PHJlY3Qgd2lkdGg9IjIiIGhlaWdodD0iMiIgeD0iOSIgeT0iOSI+PC9yZWN0PjxyZWN0IHdpZHRoPSIyIiBoZWlnaHQ9IjIiIHg9IjYiIHk9IjkiPjwvcmVjdD48cmVjdCB3aWR0aD0iMiIgaGVpZ2h0PSIyIiB4PSIyIiB5PSIxMiI+PC9yZWN0PjxyZWN0IHdpZHRoPSIzIiBoZWlnaHQ9IjIiIHg9IjIiIHk9IjkiPjwvcmVjdD48L2c+PC9zdmc+); +} + +/* Media Queries (optimized for jQuery UI themes; + may be slightly off in jQuery Mobile themes) */ +/* 240 x 320 (small phone) */ +@media all and (max-width: 319px) { + .ui-keyboard div { + font-size: 9px; + } + .ui-keyboard .ui-keyboard-input { + font-size: 12px; + } + /* I don't own an iPhone so I have no idea how small this really is... is it + even clickable with your finger? */ + .ui-body .ui-btn { + margin: 0; + font-size: 9px; + } + .ui-body .ui-keyboard-button { + width: 1.8em; + height: 2.5em; + } + .ui-body .ui-keyboard-widekey { + width: 4em; + } + .ui-body .ui-keyboard-space { + width: 8em; + } + .ui-body .ui-btn-inner { + height: 2.5em; + padding: 0.3em 0; + } +} + +/* 320 x 480 (iPhone) */ +@media all and (min-width: 320px) and (max-width: 479px) { + .ui-keyboard div { + font-size: 9px; + } + .ui-keyboard .ui-keyboard-input { + font-size: 14px; + } + /* I don't own an iPhone so I have no idea how small this really is... is it + even clickable with your finger? */ + .ui-body .ui-btn { + margin: 0; + font-size: 11px; + } + .ui-body .ui-keyboard-button { + width: 1.8em; + height: 3em; + } + .ui-body .ui-keyboard-widekey { + width: 4.5em; + } + .ui-body .ui-keyboard-space { + width: 10em; + } + .ui-body .ui-btn-inner { + height: 3em; + padding: 0.7em 0; + } +} + +/* 480 x 640 (small tablet) */ +@media all and (min-width: 480px) and (max-width: 767px) { + .ui-keyboard div { + font-size: 13px; + } + .ui-keyboard .ui-keyboard-input { + font-size: 14px; + } + .ui-body .ui-btn { + margin: 0; + font-size: 10px; + } + .ui-body .ui-keyboard-button { + height: 2.5em; + } + .ui-body .ui-btn-inner { + height: 2.5em; + padding: 0.5em 0; + } +} diff --git a/src/css/walletkeyboard.css b/src/css/walletkeyboard.css new file mode 100644 index 0000000..d15afb2 --- /dev/null +++ b/src/css/walletkeyboard.css @@ -0,0 +1,6 @@ +.ui-keyboard-has-focus { + background: #eeeeee 50% bottom repeat-x; + border-style: solid; + border-width: 1px; + border-color: #cccccc; +} diff --git a/src/js/deps.js b/src/js/deps.js index cf57039..26b423d 100644 --- a/src/js/deps.js +++ b/src/js/deps.js @@ -1,5 +1,120 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.warpwallet = f()}})(function(){var define,module,exports;return (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 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} + +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],2:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * @@ -12,59 +127,57 @@ 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 // not used by this implementation -var rootParent = {} +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} function typedArraySupport () { + // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) - arr.foo = function () { return 42 } - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 } catch (e) { return false } } -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf } /** @@ -76,197 +189,220 @@ function kMaxLength () { * * The `Uint8Array` prototype remains unmodified. */ -function Buffer (arg) { - if (!(this instanceof Buffer)) { - // Avoid going through an ArgumentsAdaptorTrampoline in the common case. - if (arguments.length > 1) return new Buffer(arg, arguments[1]) - return new Buffer(arg) + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(arg) } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation - if (!Buffer.TYPED_ARRAY_SUPPORT) { - this.length = 0 - this.parent = undefined +function from (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') } - // Common case. - if (typeof arg === 'number') { - return fromNumber(this, arg) + if (value instanceof ArrayBuffer) { + return fromArrayBuffer(value, encodingOrOffset, length) } - // Slightly less common case. - if (typeof arg === 'string') { - return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) } - // Unusual. - return fromObject(this, arg) + return fromObject(value) } -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } } -function 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 - } +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) } - return that + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) } -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' - - // Assumption: byteLength() return value is always < kMaxLength. - var length = byteLength(string, encoding) | 0 - that = allocate(that, length) - - that.write(string, encoding) - return that +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) } -function fromObject (that, object) { - if (Buffer.isBuffer(object)) return fromBuffer(that, object) +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} - if (isArray(object)) return fromArray(that, object) +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} - if (object == null) { - throw new TypeError('must start with number, buffer, array or string') +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' } - if (typeof ArrayBuffer !== 'undefined') { - if (object.buffer instanceof ArrayBuffer) { - return fromTypedArray(that, object) - } - if (object instanceof ArrayBuffer) { - return fromArrayBuffer(that, object) - } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') } - if (object.length) return fromArrayLike(that, object) + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) - return fromJsonObject(that, object) -} + var actual = buf.write(string, encoding) -function fromBuffer (that, buffer) { - var length = checked(buffer.length) | 0 - that = allocate(that, length) - buffer.copy(that, 0, 0, length) - return that + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf } -function fromArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 + buf[i] = array[i] & 255 } - return that + return buf } -// Duplicate of fromArray() to keep fromArray() monomorphic. -function fromTypedArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - // Truncating the elements is probably not what people expect from typed - // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior - // of the old Buffer constructor. - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') } - return that -} -function fromArrayBuffer (that, array) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(array) - that.__proto__ = Buffer.prototype + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) } else { - // Fallback: Return an object instance of the Buffer class - that = fromTypedArray(that, new Uint8Array(array)) + buf = new Uint8Array(array, byteOffset, length) } - 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 + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf } -// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. -// Returns a zero-length buffer for inputs that don't conform to the spec. -function fromJsonObject (that, object) { - var array - var length = 0 +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) - if (object.type === 'Buffer' && isArray(object.data)) { - array = object.data - length = checked(array.length) | 0 - } - that = allocate(that, length) + if (buf.length === 0) { + return buf + } - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 + obj.copy(buf, 0, 0, len) + return buf } - return that -} -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array -} else { - // pre-set for values that may exist in the future - Buffer.prototype.length = undefined - Buffer.prototype.parent = undefined -} + if (obj) { + if (isArrayBufferView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } -function allocate (that, length) { - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that.length = length + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } } - var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 - if (fromPool) that.parent = rootParent - - return that + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { - // Note: cannot use `length < kMaxLength` here because that fails when + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { + if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') + 'size: 0x' + K_MAX_LENGTH.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 +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) + return b != null && b._isBuffer === true } Buffer.compare = function compare (a, b) { @@ -279,17 +415,12 @@ Buffer.compare = function compare (a, b) { 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] + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } } if (x < y) return -1 @@ -303,9 +434,9 @@ Buffer.isEncoding = function isEncoding (encoding) { case 'utf8': case 'utf-8': case 'ascii': + case 'latin1': case 'binary': case 'base64': - case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': @@ -317,32 +448,45 @@ Buffer.isEncoding = function isEncoding (encoding) { } Buffer.concat = function concat (list, length) { - if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } if (list.length === 0) { - return new Buffer(0) + return Buffer.alloc(0) } var i if (length === undefined) { length = 0 - for (i = 0; i < list.length; i++) { + for (i = 0; i < list.length; ++i) { length += list[i].length } } - var buf = new Buffer(length) + var buffer = Buffer.allocUnsafe(length) var pos = 0 - for (i = 0; i < list.length; i++) { - var item = list[i] - item.copy(buf, pos) - pos += item.length + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length } - return buf + return buffer } function byteLength (string, encoding) { - if (typeof string !== 'string') string = '' + string + if (Buffer.isBuffer(string)) { + return string.length + } + if (isArrayBufferView(string) || string instanceof ArrayBuffer) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } var len = string.length if (len === 0) return 0 @@ -352,13 +496,12 @@ function byteLength (string, encoding) { for (;;) { switch (encoding) { case 'ascii': + case 'latin1': case 'binary': - // Deprecated - case 'raw': - case 'raws': return len case 'utf8': case 'utf-8': + case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': @@ -381,13 +524,39 @@ Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false - start = start | 0 - end = end === undefined || end === Infinity ? this.length : end | 0 + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } if (!encoding) encoding = 'utf8' - if (start < 0) start = 0 - if (end > this.length) end = this.length - if (end <= start) return '' while (true) { switch (encoding) { @@ -401,8 +570,9 @@ function slowToString (encoding, start, end) { case 'ascii': return asciiSlice(this, start, end) + case 'latin1': case 'binary': - return binarySlice(this, start, end) + return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) @@ -421,12 +591,59 @@ function slowToString (encoding, start, end) { } } -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + Buffer.prototype.toString = function toString () { - var length = this.length | 0 + var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) @@ -448,51 +665,196 @@ Buffer.prototype.inspect = function inspect () { return '' } -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.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } -Buffer.prototype.indexOf = function indexOf (val, byteOffset) { - if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff - else if (byteOffset < -0x80000000) byteOffset = -0x80000000 - byteOffset >>= 0 + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + // Normalize val if (typeof val === 'string') { - if (val.length === 0) return -1 // special case: looking for empty string always fails - return String.prototype.indexOf.call(this, val, byteOffset) + val = Buffer.from(val, encoding) } + + // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { - return arrayIndexOf(this, val, byteOffset) + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } - if (typeof val === 'number') { - if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { - return Uint8Array.prototype.indexOf.call(this, val, byteOffset) + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) } - return arrayIndexOf(this, [ val ], byteOffset) } - function arrayIndexOf (arr, val, byteOffset) { + var i + if (dir) { var foundIndex = -1 - for (var i = 0; byteOffset + i < arr.length; i++) { - if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { + if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } - return -1 + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } } - throw new TypeError('val must be string, number or Buffer') + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { @@ -509,14 +871,14 @@ function hexWrite (buf, string, offset, length) { // must be an even number of digits var strLen = string.length - if (strLen % 2 !== 0) throw new Error('Invalid hex string') + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } - for (var i = 0; i < length; i++) { + 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') + if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i @@ -530,7 +892,7 @@ function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } -function binaryWrite (buf, string, offset, length) { +function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } @@ -555,27 +917,25 @@ Buffer.prototype.write = function write (string, offset, length, encoding) { offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { - offset = offset | 0 + offset = offset >>> 0 if (isFinite(length)) { - length = length | 0 + length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } - // legacy write(string, encoding, offset, length) - remove in v0.13 } else { - var swap = encoding - encoding = offset - offset = length | 0 - length = swap + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('attempt to write outside buffer bounds') + throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' @@ -593,8 +953,9 @@ Buffer.prototype.write = function write (string, offset, length, encoding) { case 'ascii': return asciiWrite(this, string, offset, length) + case 'latin1': case 'binary': - return binaryWrite(this, string, offset, length) + return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write @@ -729,17 +1090,17 @@ function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) - for (var i = start; i < end; i++) { + for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } -function binarySlice (buf, start, end) { +function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) - for (var i = start; i < end; i++) { + for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret @@ -752,7 +1113,7 @@ function hexSlice (buf, start, end) { if (!end || end < 0 || end > len) end = len var out = '' - for (var i = start; i < end; i++) { + for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out @@ -762,7 +1123,7 @@ 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) + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } @@ -788,20 +1149,9 @@ Buffer.prototype.slice = function slice (start, end) { 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 - + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype return newBuf } @@ -814,8 +1164,8 @@ function checkOffset (offset, ext, length) { } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] @@ -829,8 +1179,8 @@ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } @@ -845,21 +1195,25 @@ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | @@ -869,6 +1223,7 @@ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + @@ -878,8 +1233,8 @@ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] @@ -896,8 +1251,8 @@ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 + offset = offset >>> 0 + byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength @@ -914,24 +1269,28 @@ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | @@ -941,6 +1300,7 @@ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | @@ -950,36 +1310,43 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.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') + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = 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) + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } var mul = 1 var i = 0 @@ -993,9 +1360,12 @@ Buffer.prototype.writeUIntLE = function writeUIntLE (value, 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) + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } var i = byteLength - 1 var mul = 1 @@ -1009,98 +1379,69 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) return offset + 2 } -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) + 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 + var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -1109,18 +1450,21 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) + 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 + var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -1129,9 +1473,8 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 @@ -1139,67 +1482,53 @@ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value - offset = offset | 0 + offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + 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 & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) 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') + 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) { + value = +value + offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } @@ -1216,6 +1545,8 @@ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } @@ -1261,12 +1592,12 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (this === target && start < targetStart && targetStart < end) { // descending copy from end - for (i = len - 1; i >= 0; i--) { + for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000) { // ascending copy from start - for (i = 0; i < len; i++) { + for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { @@ -1280,31 +1611,63 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { return len } -// fill(value, start=0, end=buffer.length) -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') - - // Fill 0 bytes; we're done - if (end === start) return - if (this.length === 0) return +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - if (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') + if (!val) val = 0 var i - if (typeof value === 'number') { - for (i = start; i < end; i++) { - this[i] = value + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val } } else { - var bytes = utf8ToBytes(value.toString()) + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) var len = bytes.length - for (i = start; i < end; i++) { - this[i] = bytes[i % len] + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] } } @@ -1314,11 +1677,11 @@ Buffer.prototype.fill = function fill (value, start, end) { // HELPER FUNCTIONS // ================ -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') + str = str.trim().replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not @@ -1328,11 +1691,6 @@ function base64clean (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) @@ -1345,7 +1703,7 @@ function utf8ToBytes (string, units) { var leadSurrogate = null var bytes = [] - for (var i = 0; i < length; i++) { + for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component @@ -1420,7 +1778,7 @@ function utf8ToBytes (string, units) { function asciiToBytes (str) { var byteArray = [] - for (var i = 0; i < str.length; i++) { + for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } @@ -1430,7 +1788,7 @@ function asciiToBytes (str) { function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] - for (var i = 0; i < str.length; i++) { + for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) @@ -1448,1327 +1806,409 @@ function base64ToBytes (str) { } function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; i++) { + 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":2,"ieee754":3,"isarray":4}],2:[function(require,module,exports){ -;(function (exports) { - 'use strict' +// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` +function isArrayBufferView (obj) { + return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) +} + +function numberIsNaN (obj) { + return obj !== obj // eslint-disable-line no-self-compare +} - var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +},{"base64-js":1,"ieee754":9}],3:[function(require,module,exports){ +// Generated by IcedCoffeeScript 1.7.1-g +(function() { + exports.transform = function(x, options) { + return x.icedTransform(options); + }; - var Arr = (typeof Uint8Array !== 'undefined') - ? Uint8Array - : Array + exports.runtime = require('iced-runtime'); - var PLUS = '+'.charCodeAt(0) - var SLASH = '/'.charCodeAt(0) - var NUMBER = '0'.charCodeAt(0) - var LOWER = 'a'.charCodeAt(0) - var UPPER = 'A'.charCodeAt(0) - var PLUS_URL_SAFE = '-'.charCodeAt(0) - var SLASH_URL_SAFE = '_'.charCodeAt(0) +}).call(this); - function decode (elt) { - var code = elt.charCodeAt(0) - if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+' - if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/' - if (code < NUMBER) return -1 // no match - if (code < NUMBER + 10) return code - NUMBER + 26 + 26 - if (code < UPPER + 26) return code - UPPER - if (code < LOWER + 26) return code - LOWER + 26 - } +},{"iced-runtime":7}],4:[function(require,module,exports){ +// Generated by IcedCoffeeScript 108.0.11 +(function() { + var BaseError, Canceler, EscErr, EscOk, c_to_camel, ipush, make_error_klass, make_errors, make_esc, to_lower, util, + __slice = [].slice; - function b64ToByteArray (b64) { - var i, j, l, tmp, placeHolders, arr + util = require('util'); - if (b64.length % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') + exports.BaseError = BaseError = function(msg, constructor) { + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, this.constructor); } + return this.message = msg || 'Error'; + }; + + util.inherits(BaseError, Error); - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - var len = b64.length - placeHolders = b64.charAt(len - 2) === '=' ? 2 : b64.charAt(len - 1) === '=' ? 1 : 0 + BaseError.prototype.name = "BaseError"; - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(b64.length * 3 / 4 - placeHolders) + to_lower = function(s) { + return s[0].toUpperCase() + s.slice(1).toLowerCase(); + }; - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length + c_to_camel = function(s) { + var p; + return ((function() { + var _i, _len, _ref, _results; + _ref = s.split(/_/); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + p = _ref[_i]; + _results.push(to_lower(p)); + } + return _results; + })()).join(''); + }; - var L = 0 + make_error_klass = function(k, code, default_msg) { + var ctor; + ctor = function(msg) { + BaseError.call(this, msg || default_msg, this.constructor); + this.istack = []; + this.code = code; + return this; + }; + util.inherits(ctor, BaseError); + ctor.prototype.name = k; + ctor.prototype.inspect = function() { + return "[" + k + ": " + this.message + " (code " + this.code + ")]"; + }; + return ctor; + }; - function push (v) { - arr[L++] = v + exports.make_errors = make_errors = function(d) { + var enam, errno, k, msg, out, val; + out = { + msg: {}, + name: {}, + code: {} + }; + d.OK = "Success"; + errno = 100; + for (k in d) { + msg = d[k]; + if (k !== "OK") { + enam = (c_to_camel(k)) + "Error"; + val = errno++; + out[enam] = make_error_klass(enam, val, msg); + } else { + val = 0; + } + out[k] = val; + out.msg[k] = out.msg[val] = msg; + out.name[k] = out.name[val] = k; + out.code[k] = val; } + return out; + }; - 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 & 0xFF0000) >> 16) - push((tmp & 0xFF00) >> 8) - push(tmp & 0xFF) + ipush = function(e, msg) { + if (msg != null) { + if (e.istack == null) { + e.istack = []; + } + return e.istack.push(msg); } + }; + + exports.make_esc = make_esc = function(gcb, where) { + return function(lcb) { + return function() { + var args, err; + err = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + if (err == null) { + return lcb.apply(null, args); + } else if (!gcb.__esc) { + gcb.__esc = true; + ipush(err, where); + return gcb(err); + } + }; + }; + }; - if (placeHolders === 2) { - tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) - push(tmp & 0xFF) - } 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) & 0xFF) - push(tmp & 0xFF) + exports.EscOk = EscOk = (function() { + function EscOk(gcb, where) { + this.gcb = gcb; + this.where = where; } - return arr - } + EscOk.prototype.bailout = function() { + var t; + if (this.gcb) { + t = this.gcb; + this.gcb = null; + return t(false); + } + }; - function uint8ToBase64 (uint8) { - var i - var extraBytes = uint8.length % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var temp, length + EscOk.prototype.check_ok = function(cb) { + return (function(_this) { + return function() { + var args, ok; + ok = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + if (!ok) { + return _this.bailout(); + } else { + return cb.apply(null, args); + } + }; + })(this); + }; - function encode (num) { - return lookup.charAt(num) - } + EscOk.prototype.check_err = function(cb) { + return (function(_this) { + return function() { + var args, err; + err = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + if (err != null) { + ipush(err, _this.where); + return _this.bailout(); + } else { + return cb.apply(null, args); + } + }; + })(this); + }; - function tripletToBase64 (num) { - return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) - } + EscOk.prototype.check_non_null = function(cb) { + return (function(_this) { + return function() { + var args; + args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; + if (args[0] == null) { + return _this.bailout(); + } else { + return cb.apply(null, args); + } + }; + })(this); + }; - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output += tripletToBase64(temp) - } + return EscOk; - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1] - output += encode(temp >> 2) - output += encode((temp << 4) & 0x3F) - output += '==' - break - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) - output += encode(temp >> 10) - output += encode((temp >> 4) & 0x3F) - output += encode((temp << 2) & 0x3F) - output += '=' - break - default: - break - } + })(); - return output - } + exports.EscErr = EscErr = (function() { + function EscErr(gcb, where) { + this.gcb = gcb; + this.where = where; + } - exports.toByteArray = b64ToByteArray - exports.fromByteArray = uint8ToBase64 -}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + EscErr.prototype.finish = function(err) { + var t; + if (this.gcb) { + t = this.gcb; + this.gcb = null; + return t(err); + } + }; -},{}],3:[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] + EscErr.prototype.check_ok = function(cb, eclass, emsg) { + if (eclass == null) { + eclass = Error; + } + if (emsg == null) { + emsg = null; + } + return function() { + var args, err, ok; + ok = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + if (!ok) { + err = new eclass(emsg); + ipush(err, this.where); + return this.finish(err); + } else { + return cb.apply(null, args); + } + }; + }; - i += d + EscErr.prototype.check_err = function(cb) { + return function() { + var args, err; + err = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + if (err != null) { + ipush(err, this.where); + return this.finish(err); + } else { + return cb.apply(null, args); + } + }; + }; - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + return EscErr; - 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.Canceler = Canceler = (function() { + function Canceler(klass) { + this.klass = klass != null ? klass : Error; + this._canceled = false; + } -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 + Canceler.prototype.is_canceled = function() { + return this._canceled; + }; - value = Math.abs(value) + Canceler.prototype.is_ok = function() { + return !this._canceled; + }; - 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 - } + Canceler.prototype.cancel = function() { + return this._canceled = true; + }; - 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 - } - } + Canceler.prototype.err = function() { + if (this._canceled) { + return new this.klass("Aborted"); + } else { + return null; + } + }; - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + return Canceler; - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + })(); - buffer[offset + i - d] |= s * 128 -} + exports.chain = function(cb, f) { + return function() { + var args; + args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; + return f(function() { + return cb.apply(null, args); + }); + }; + }; -},{}],4:[function(require,module,exports){ -var toString = {}.toString; + exports.chain_err = function(cb, f) { + return function() { + var args0; + args0 = 1 <= arguments.length ? __slice.call(arguments, 0) : []; + return f(function() { + var args1; + args1 = 1 <= arguments.length ? __slice.call(arguments, 0) : []; + return cb.apply(null, ((args1[0] != null) && !(args0[0] != null) ? args1 : args0)); + }); + }; + }; -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; +}).call(this); -},{}],5:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); + + +},{"util":39}],5:[function(require,module,exports){ +// Generated by IcedCoffeeScript 108.0.8 +(function() { + module.exports = { + k: "__iced_k", + k_noop: "__iced_k_noop", + param: "__iced_p_", + ns: "iced", + runtime: "runtime", + Deferrals: "Deferrals", + deferrals: "__iced_deferrals", + fulfill: "_fulfill", + b_while: "_break", + t_while: "_while", + c_while: "_continue", + n_while: "_next", + n_arg: "__iced_next_arg", + defer_method: "defer", + slot: "__slot", + assign_fn: "assign_fn", + autocb: "autocb", + retslot: "ret", + trace: "__iced_trace", + passed_deferral: "__iced_passed_deferral", + findDeferral: "findDeferral", + lineno: "lineno", + parent: "parent", + filename: "filename", + funcname: "funcname", + catchExceptions: 'catchExceptions', + runtime_modes: ["node", "inline", "window", "none", "browserify", "interp"], + trampoline: "trampoline", + context: "context", + defer_arg: "__iced_defer_" }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} + +}).call(this); },{}],6:[function(require,module,exports){ -// shim for using process in browser +// Generated by IcedCoffeeScript 108.0.8 +(function() { + var C, Pipeliner, iced, __iced_k, __iced_k_noop, _iand, _ior, _timeout, + __slice = [].slice; -var process = module.exports = {}; -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; + __iced_k = __iced_k_noop = function() {}; -function cleanUpNextTick() { - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} + C = require('./const'); -function drainQueue() { - if (draining) { - return; - } - var timeout = setTimeout(cleanUpNextTick); - draining = true; + exports.iced = iced = require('./runtime'); - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } + _timeout = function(cb, t, res, tmp) { + var arr, rv, which, ___iced_passed_deferral, __iced_deferrals, __iced_k; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + rv = new iced.Rendezvous; + tmp[0] = rv.id(true).defer({ + assign_fn: (function(_this) { + return function() { + return function() { + return arr = __slice.call(arguments, 0); + }; + }; + })(this)(), + lineno: 20, + context: __iced_deferrals + }); + setTimeout(rv.id(false).defer({ + lineno: 21, + context: __iced_deferrals + }), t); + (function(_this) { + return (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "/Users/max/src/iced/iced-runtime/src/library.iced" + }); + rv.wait(__iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return which = arguments[0]; + }; + })(), + lineno: 22 + })); + __iced_deferrals._fulfill(); + }); + })(this)((function(_this) { + return function() { + if (res) { + res[0] = which; } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - clearTimeout(timeout); -} + return cb.apply(null, arr); + }; + })(this)); + }; -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); - } -}; - -// v8 likes predictible objects -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 = ''; // empty string to avoid regexp issues -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; }; - -},{}],7:[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'; -} -},{}],8:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var 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; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - 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]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var 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]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -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' || // ES6 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']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":7,"_process":6,"inherits":5}],9:[function(require,module,exports){ -// Generated by IcedCoffeeScript 1.7.1-g -(function() { - exports.transform = function(x, options) { - return x.icedTransform(options); - }; - - exports.runtime = require('iced-runtime'); - -}).call(this); - -},{"iced-runtime":13}],10:[function(require,module,exports){ -// Generated by IcedCoffeeScript 1.7.1-c -(function() { - var BaseError, Canceler, EscErr, EscOk, c_to_camel, ipush, make_error_klass, make_errors, make_esc, to_lower, util, - __slice = [].slice; - - util = require('util'); - - exports.BaseError = BaseError = function(msg, constructor) { - Error.captureStackTrace(this, this.constructor); - return this.message = msg || 'Error'; - }; - - util.inherits(BaseError, Error); - - BaseError.prototype.name = "BaseError"; - - to_lower = function(s) { - return s[0].toUpperCase() + s.slice(1).toLowerCase(); - }; - - c_to_camel = function(s) { - var p; - return ((function() { - var _i, _len, _ref, _results; - _ref = s.split(/_/); - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - p = _ref[_i]; - _results.push(to_lower(p)); - } - return _results; - })()).join(''); - }; - - make_error_klass = function(k, code, default_msg) { - var ctor; - ctor = function(msg) { - BaseError.call(this, msg || default_msg, this.constructor); - this.istack = []; - this.code = code; - return this; - }; - util.inherits(ctor, BaseError); - ctor.prototype.name = k; - ctor.prototype.inspect = function() { - return "[" + k + ": " + this.message + " (code " + this.code + ")]"; - }; - return ctor; - }; - - exports.make_errors = make_errors = function(d) { - var enam, errno, k, msg, out, val; - out = { - msg: {}, - name: {}, - code: {} - }; - d.OK = "Success"; - errno = 100; - for (k in d) { - msg = d[k]; - if (k !== "OK") { - enam = (c_to_camel(k)) + "Error"; - val = errno++; - out[enam] = make_error_klass(enam, val, msg); - } else { - val = 0; - } - out[k] = val; - out.msg[k] = out.msg[val] = msg; - out.name[k] = out.name[val] = k; - out.code[k] = val; - } - return out; - }; - - ipush = function(e, msg) { - if (msg != null) { - if (e.istack == null) { - e.istack = []; - } - return e.istack.push(msg); - } - }; - - exports.make_esc = make_esc = function(gcb, where) { - return function(lcb) { - return function() { - var args, err; - err = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; - if (err == null) { - return lcb.apply(null, args); - } else if (!gcb.__esc) { - gcb.__esc = true; - ipush(err, where); - return gcb(err); - } - }; - }; - }; - - exports.EscOk = EscOk = (function() { - function EscOk(gcb, where) { - this.gcb = gcb; - this.where = where; - } - - EscOk.prototype.bailout = function() { - var t; - if (this.gcb) { - t = this.gcb; - this.gcb = null; - return t(false); - } - }; - - EscOk.prototype.check_ok = function(cb) { - return (function(_this) { - return function() { - var args, ok; - ok = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; - if (!ok) { - return _this.bailout(); - } else { - return cb.apply(null, args); - } - }; - })(this); - }; - - EscOk.prototype.check_err = function(cb) { - return (function(_this) { - return function() { - var args, err; - err = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; - if (err != null) { - ipush(err, _this.where); - return _this.bailout(); - } else { - return cb.apply(null, args); - } - }; - })(this); - }; - - EscOk.prototype.check_non_null = function(cb) { - return (function(_this) { - return function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - if (args[0] == null) { - return _this.bailout(); - } else { - return cb.apply(null, args); - } - }; - })(this); - }; - - return EscOk; - - })(); - - exports.EscErr = EscErr = (function() { - function EscErr(gcb, where) { - this.gcb = gcb; - this.where = where; - } - - EscErr.prototype.finish = function(err) { - var t; - if (this.gcb) { - t = this.gcb; - this.gcb = null; - return t(err); - } - }; - - EscErr.prototype.check_ok = function(cb, eclass, emsg) { - if (eclass == null) { - eclass = Error; - } - if (emsg == null) { - emsg = null; - } - return function() { - var args, err, ok; - ok = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; - if (!ok) { - err = new eclass(emsg); - ipush(err, this.where); - return this.finish(err); - } else { - return cb.apply(null, args); - } - }; - }; - - EscErr.prototype.check_err = function(cb) { - return function() { - var args, err; - err = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; - if (err != null) { - ipush(err, this.where); - return this.finish(err); - } else { - return cb.apply(null, args); - } - }; - }; - - return EscErr; - - })(); - - exports.Canceler = Canceler = (function() { - function Canceler(klass) { - this.klass = klass != null ? klass : Error; - this._canceled = false; - } - - Canceler.prototype.is_canceled = function() { - return this._canceled; - }; - - Canceler.prototype.is_ok = function() { - return !this._canceled; - }; - - Canceler.prototype.cancel = function() { - return this._canceled = true; - }; - - Canceler.prototype.err = function() { - if (this._canceled) { - return new this.klass("Aborted"); - } else { - return null; - } - }; - - return Canceler; - - })(); - - exports.chain = function(cb, f) { - return function() { - var args; - args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return f(function() { - return cb.apply(null, args); - }); - }; - }; - - exports.chain_err = function(cb, f) { - return function() { - var args0; - args0 = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return f(function() { - var args1; - args1 = 1 <= arguments.length ? __slice.call(arguments, 0) : []; - return cb.apply(null, ((args1[0] != null) && !(args0[0] != null) ? args1 : args0)); - }); - }; - }; - -}).call(this); - - - -},{"util":8}],11:[function(require,module,exports){ -// Generated by IcedCoffeeScript 108.0.8 -(function() { - module.exports = { - k: "__iced_k", - k_noop: "__iced_k_noop", - param: "__iced_p_", - ns: "iced", - runtime: "runtime", - Deferrals: "Deferrals", - deferrals: "__iced_deferrals", - fulfill: "_fulfill", - b_while: "_break", - t_while: "_while", - c_while: "_continue", - n_while: "_next", - n_arg: "__iced_next_arg", - defer_method: "defer", - slot: "__slot", - assign_fn: "assign_fn", - autocb: "autocb", - retslot: "ret", - trace: "__iced_trace", - passed_deferral: "__iced_passed_deferral", - findDeferral: "findDeferral", - lineno: "lineno", - parent: "parent", - filename: "filename", - funcname: "funcname", - catchExceptions: 'catchExceptions', - runtime_modes: ["node", "inline", "window", "none", "browserify", "interp"], - trampoline: "trampoline", - context: "context", - defer_arg: "__iced_defer_" - }; - -}).call(this); - -},{}],12:[function(require,module,exports){ -// Generated by IcedCoffeeScript 108.0.8 -(function() { - var C, Pipeliner, iced, __iced_k, __iced_k_noop, _iand, _ior, _timeout, - __slice = [].slice; - - __iced_k = __iced_k_noop = function() {}; - - C = require('./const'); - - exports.iced = iced = require('./runtime'); - - _timeout = function(cb, t, res, tmp) { - var arr, rv, which, ___iced_passed_deferral, __iced_deferrals, __iced_k; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - rv = new iced.Rendezvous; - tmp[0] = rv.id(true).defer({ - assign_fn: (function(_this) { - return function() { - return function() { - return arr = __slice.call(arguments, 0); - }; - }; - })(this)(), - lineno: 20, - context: __iced_deferrals - }); - setTimeout(rv.id(false).defer({ - lineno: 21, - context: __iced_deferrals - }), t); - (function(_this) { - return (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "/Users/max/src/iced/iced-runtime/src/library.iced" - }); - rv.wait(__iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return which = arguments[0]; - }; - })(), - lineno: 22 - })); - __iced_deferrals._fulfill(); - }); - })(this)((function(_this) { - return function() { - if (res) { - res[0] = which; - } - return cb.apply(null, arr); - }; - })(this)); - }; - - exports.timeout = function(cb, t, res) { - var tmp; - tmp = []; - _timeout(cb, t, res, tmp); - return tmp[0]; - }; + exports.timeout = function(cb, t, res) { + var tmp; + tmp = []; + _timeout(cb, t, res, tmp); + return tmp[0]; + }; _iand = function(cb, res, tmp) { var ok, ___iced_passed_deferral, __iced_deferrals, __iced_k; @@ -2999,7 +2439,7 @@ function hasOwnProperty(obj, prop) { }).call(this); -},{"./const":11,"./runtime":14}],13:[function(require,module,exports){ +},{"./const":5,"./runtime":8}],7:[function(require,module,exports){ // Generated by IcedCoffeeScript 108.0.8 (function() { var k, mod, mods, v, _i, _len; @@ -3018,7 +2458,7 @@ function hasOwnProperty(obj, prop) { }).call(this); -},{"./const":11,"./library":12,"./runtime":14}],14:[function(require,module,exports){ +},{"./const":5,"./library":6,"./runtime":8}],8:[function(require,module,exports){ (function (process){ // Generated by IcedCoffeeScript 108.0.8 (function() { @@ -3218,33 +2658,119 @@ function hasOwnProperty(obj, prop) { ret.push(line); tr = tr != null ? (_ref = tr[C.parent]) != null ? _ref[C.trace] : void 0 : void 0; } - return ret; - }; - - exports.exceptionHandler = exceptionHandler = function(err, logger) { - var stack; - if (!logger) { - logger = console.error; + return ret; + }; + + exports.exceptionHandler = exceptionHandler = function(err, logger) { + var stack; + if (!logger) { + logger = console.error; + } + logger(err.stack); + stack = stackWalk(); + if (stack.length) { + logger("Iced 'stack' trace (w/ real line numbers):"); + return logger(stack.join("\n")); + } + }; + + exports.catchExceptions = function(logger) { + return typeof process !== "undefined" && process !== null ? process.on('uncaughtException', function(err) { + exceptionHandler(err, logger); + return process.exit(1); + }) : void 0; + }; + +}).call(this); + +}).call(this,require('_process')) +},{"./const":5,"_process":14}],9:[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) } - logger(err.stack); - stack = stackWalk(); - if (stack.length) { - logger("Iced 'stack' trace (w/ real line numbers):"); - return logger(stack.join("\n")); + if (value * c >= 2) { + e++ + c /= 2 } - }; - exports.catchExceptions = function(logger) { - return typeof process !== "undefined" && process !== null ? process.on('uncaughtException', function(err) { - exceptionHandler(err, logger); - return process.exit(1); - }) : void 0; - }; + 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 + } + } -}).call(this); + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} -}).call(this,require('_process')) -},{"./const":11,"_process":6}],15:[function(require,module,exports){ + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],10:[function(require,module,exports){ var lib = require('./lib/lib.js'); @@ -3264,7 +2790,7 @@ exports.generate = function(buffer) { return ret; }; -},{"./lib/lib.js":16}],16:[function(require,module,exports){ +},{"./lib/lib.js":11}],11:[function(require,module,exports){ var Crypto = exports.Crypto = {}; var Bitcoin = exports.Bitcoin = {}; @@ -5495,685 +5021,1096 @@ var BigInteger = exports.BigInteger; return lhs.equals(rhs); }; - ec.PointFp.prototype.toString = function () { - return '(' + this.getX().toBigInteger().toString() + ',' + this.getY().toBigInteger().toString() + ')'; + ec.PointFp.prototype.toString = function () { + return '(' + this.getX().toBigInteger().toString() + ',' + this.getY().toBigInteger().toString() + ')'; + }; + + /** + * Validate an elliptic curve point. + * + * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive + */ + ec.PointFp.prototype.validate = function () { + var n = this.curve.getQ(); + + // Check Q != O + if (this.isInfinity()) { + throw new Error("Point is at infinity."); + } + + // Check coordinate bounds + var x = this.getX().toBigInteger(); + var y = this.getY().toBigInteger(); + if (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(n.subtract(BigInteger.ONE)) > 0) { + throw new Error('x coordinate out of bounds'); + } + if (y.compareTo(BigInteger.ONE) < 0 || y.compareTo(n.subtract(BigInteger.ONE)) > 0) { + throw new Error('y coordinate out of bounds'); + } + + // Check y^2 = x^3 + ax + b (mod n) + if (!this.isOnCurve()) { + throw new Error("Point is not on the curve."); + } + + // Check nQ = 0 (Q is a scalar multiple of G) + if (this.multiply(n).isInfinity()) { + // TODO: This check doesn't work - fix. + throw new Error("Point is not a scalar multiple of G."); + } + + return true; + }; + + + + + // ---------------- + // ECCurveFp constructor + ec.CurveFp = function (q, a, b) { + this.q = q; + this.a = this.fromBigInteger(a); + this.b = this.fromBigInteger(b); + this.infinity = new ec.PointFp(this, null, null); + } + + ec.CurveFp.prototype.getQ = function () { + return this.q; + }; + + ec.CurveFp.prototype.getA = function () { + return this.a; + }; + + ec.CurveFp.prototype.getB = function () { + return this.b; + }; + + ec.CurveFp.prototype.equals = function (other) { + if (other == this) return true; + return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); + }; + + ec.CurveFp.prototype.getInfinity = function () { + return this.infinity; + }; + + ec.CurveFp.prototype.fromBigInteger = function (x) { + return new ec.FieldElementFp(this.q, x); + }; + + // for now, work with hex strings because they're easier in JS + // compressed support added by bitaddress.org + ec.CurveFp.prototype.decodePointHex = function (s) { + var firstByte = parseInt(s.substr(0, 2), 16); + switch (firstByte) { // first byte + case 0: + return this.infinity; + case 2: // compressed + case 3: // compressed + var yTilde = firstByte & 1; + var xHex = s.substr(2, s.length - 2); + var X1 = new BigInteger(xHex, 16); + return this.decompressPoint(yTilde, X1); + case 4: // uncompressed + case 6: // hybrid + case 7: // hybrid + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len + 2, len); + + return new ec.PointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); + + default: // unsupported + return null; + } + }; + + /* + * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) + * Ported to JavaScript by bitaddress.org + * + * Number yTilde + * BigInteger X1 + */ + ec.CurveFp.prototype.decompressPoint = function (yTilde, X1) { + var x = this.fromBigInteger(X1); + var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); + var beta = alpha.sqrt(); + // if we can't find a sqrt we haven't got a point on the curve - run! + if (beta == null) throw new Error("Invalid point compression"); + var betaValue = beta.toBigInteger(); + var bit0 = betaValue.testBit(0) ? 1 : 0; + if (bit0 != yTilde) { + // Use the other root + beta = this.fromBigInteger(this.getQ().subtract(betaValue)); + } + return new ec.PointFp(this, x, beta, null, true); + }; + + + ec.fromHex = function (s) { return new BigInteger(s, 16); }; + + ec.integerToBytes = function (i, len) { + var bytes = i.toByteArrayUnsigned(); + if (len < bytes.length) { + bytes = bytes.slice(bytes.length - len); + } else while (len > bytes.length) { + bytes.unshift(0); + } + return bytes; + }; + + + // Named EC curves + // ---------------- + // X9ECParameters constructor + ec.X9Parameters = function (curve, g, n, h) { + this.curve = curve; + this.g = g; + this.n = n; + this.h = h; + } + ec.X9Parameters.prototype.getCurve = function () { return this.curve; }; + ec.X9Parameters.prototype.getG = function () { return this.g; }; + ec.X9Parameters.prototype.getN = function () { return this.n; }; + ec.X9Parameters.prototype.getH = function () { return this.h; }; + + // secp256k1 is the Curve used by Bitcoin + ec.secNamedCurves = { + // used by Bitcoin + "secp256k1": function () { + // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 + var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); + var a = BigInteger.ZERO; + var b = ec.fromHex("7"); + var n = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); + var h = BigInteger.ONE; + var curve = new ec.CurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"); + return new ec.X9Parameters(curve, G, n, h); + } + }; + + // secp256k1 called by Bitcoin's ECKEY + ec.getSECCurveByName = function (name) { + if (ec.secNamedCurves[name] == undefined) return null; + return ec.secNamedCurves[name](); + } +})(exports); + +var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js +// See here for license information: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE +(function (Bitcoin) { + Bitcoin.Address = function (bytes) { + if ("string" == typeof bytes) { + bytes = Bitcoin.Address.decodeString(bytes); + } + this.hash = bytes; + this.version = Bitcoin.Address.networkVersion; + }; + + Bitcoin.Address.networkVersion = 0x00; // mainnet + + /** + * Serialize this object as a standard Bitcoin address. + * + * Returns the address as a base58-encoded string in the standardized format. + */ + Bitcoin.Address.prototype.toString = function () { + // Get a copy of the hash + var hash = this.hash.slice(0); + + // Version + hash.unshift(this.version); + var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); + var bytes = hash.concat(checksum.slice(0, 4)); + return Bitcoin.Base58.encode(bytes); + }; + + Bitcoin.Address.prototype.getHashBase64 = function () { + return Crypto.util.bytesToBase64(this.hash); }; /** - * Validate an elliptic curve point. - * - * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive + * Parse a Bitcoin address contained in a string. */ - ec.PointFp.prototype.validate = function () { - var n = this.curve.getQ(); - - // Check Q != O - if (this.isInfinity()) { - throw new Error("Point is at infinity."); - } + Bitcoin.Address.decodeString = function (string) { + var bytes = Bitcoin.Base58.decode(string); + var hash = bytes.slice(0, 21); + var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); - // Check coordinate bounds - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - if (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('x coordinate out of bounds'); - } - if (y.compareTo(BigInteger.ONE) < 0 || y.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('y coordinate out of bounds'); + if (checksum[0] != bytes[21] || + checksum[1] != bytes[22] || + checksum[2] != bytes[23] || + checksum[3] != bytes[24]) { + throw "Checksum validation failed!"; } - // Check y^2 = x^3 + ax + b (mod n) - if (!this.isOnCurve()) { - throw new Error("Point is not on the curve."); - } + var version = hash.shift(); - // Check nQ = 0 (Q is a scalar multiple of G) - if (this.multiply(n).isInfinity()) { - // TODO: This check doesn't work - fix. - throw new Error("Point is not a scalar multiple of G."); + if (version != 0) { + throw "Version " + version + " not supported!"; } - return true; + return hash; }; +})(Bitcoin); +//https://raw.github.com/bitcoinjs/bitcoinjs-lib/c952aaeb3ee472e3776655b8ea07299ebed702c7/src/base58.js +// See here for license information: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE +(function (Bitcoin) { + Bitcoin.Base58 = { + alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", + validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/, + base: BigInteger.valueOf(58), + /** + * Convert a byte array to a base58-encoded string. + * + * Written by Mike Hearn for BitcoinJ. + * Copyright (c) 2011 Google Inc. + * + * Ported to JavaScript by Stefan Thomas. + */ + encode: function (input) { + var bi = BigInteger.fromByteArrayUnsigned(input); + var chars = []; + while (bi.compareTo(B58.base) >= 0) { + var mod = bi.mod(B58.base); + chars.unshift(B58.alphabet[mod.intValue()]); + bi = bi.subtract(mod).divide(B58.base); + } + chars.unshift(B58.alphabet[bi.intValue()]); + // Convert leading zeros too. + for (var i = 0; i < input.length; i++) { + if (input[i] == 0x00) { + chars.unshift(B58.alphabet[0]); + } else break; + } - // ---------------- - // ECCurveFp constructor - ec.CurveFp = function (q, a, b) { - this.q = q; - this.a = this.fromBigInteger(a); - this.b = this.fromBigInteger(b); - this.infinity = new ec.PointFp(this, null, null); - } + return chars.join(''); + }, - ec.CurveFp.prototype.getQ = function () { - return this.q; - }; + /** + * Convert a base58-encoded string to a byte array. + * + * Written by Mike Hearn for BitcoinJ. + * Copyright (c) 2011 Google Inc. + * + * Ported to JavaScript by Stefan Thomas. + */ + decode: function (input) { + var bi = BigInteger.valueOf(0); + var leadingZerosNum = 0; + for (var i = input.length - 1; i >= 0; i--) { + var alphaIndex = B58.alphabet.indexOf(input[i]); + if (alphaIndex < 0) { + throw "Invalid character"; + } + bi = bi.add(BigInteger.valueOf(alphaIndex) + .multiply(B58.base.pow(input.length - 1 - i))); - ec.CurveFp.prototype.getA = function () { - return this.a; - }; + // This counts leading zero bytes + if (input[i] == "1") leadingZerosNum++; + else leadingZerosNum = 0; + } + var bytes = bi.toByteArrayUnsigned(); - ec.CurveFp.prototype.getB = function () { - return this.b; - }; + // Add leading zeros + while (leadingZerosNum-- > 0) bytes.unshift(0); - ec.CurveFp.prototype.equals = function (other) { - if (other == this) return true; - return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); + return bytes; + } }; - ec.CurveFp.prototype.getInfinity = function () { - return this.infinity; - }; + var B58 = Bitcoin.Base58; +})(Bitcoin); +//https://raw.github.com/pointbiz/bitcoinjs-lib/9b2f94a028a7bc9bed94e0722563e9ff1d8e8db8/src/eckey.js +// See here for license information: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE +(function (Bitcoin) { + Bitcoin.ECKey = (function () { + var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - ec.CurveFp.prototype.fromBigInteger = function (x) { - return new ec.FieldElementFp(this.q, x); - }; + var ECKey = function (input) { + if (input instanceof BigInteger) { + // Input is a private key value + this.priv = input; + } else if (Bitcoin.Util.isArray(input)) { + // Prepend zero byte to prevent interpretation as negative integer + this.priv = BigInteger.fromByteArrayUnsigned(input); + } else if ("string" == typeof input) { + var bytes = null; + if (ECKey.isWalletImportFormat(input)) { + bytes = ECKey.decodeWalletImportFormat(input); + } else if (ECKey.isCompressedWalletImportFormat(input)) { + bytes = ECKey.decodeCompressedWalletImportFormat(input); + this.compressed = true; + } else if (ECKey.isMiniFormat(input)) { + bytes = Crypto.SHA256(input, { asBytes: true }); + } else if (ECKey.isHexFormat(input)) { + bytes = Crypto.util.hexToBytes(input); + } else if (ECKey.isBase64Format(input)) { + bytes = Crypto.util.base64ToBytes(input); + } + + if (ECKey.isBase6Format(input)) { + this.priv = new BigInteger(input, 6); + } else if (bytes == null || bytes.length != 32) { + this.priv = null; + } else { + // Prepend zero byte to prevent interpretation as negative integer + this.priv = BigInteger.fromByteArrayUnsigned(bytes); + } + } else { + throw new Error("no plausible constructor behavior"); + } - // for now, work with hex strings because they're easier in JS - // compressed support added by bitaddress.org - ec.CurveFp.prototype.decodePointHex = function (s) { - var firstByte = parseInt(s.substr(0, 2), 16); - switch (firstByte) { // first byte - case 0: - return this.infinity; - case 2: // compressed - case 3: // compressed - var yTilde = firstByte & 1; - var xHex = s.substr(2, s.length - 2); - var X1 = new BigInteger(xHex, 16); - return this.decompressPoint(yTilde, X1); - case 4: // uncompressed - case 6: // hybrid - case 7: // hybrid - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len + 2, len); + this.compressed = (this.compressed == undefined) ? !!ECKey.compressByDefault : this.compressed; + }; - return new ec.PointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); + ECKey.privateKeyPrefix = 0x80; // mainnet 0x80 testnet 0xEF - default: // unsupported - return null; - } - }; + /** + * Whether public keys should be returned compressed by default. + */ + ECKey.compressByDefault = false; - /* - * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) - * Ported to JavaScript by bitaddress.org - * - * Number yTilde - * BigInteger X1 - */ - ec.CurveFp.prototype.decompressPoint = function (yTilde, X1) { - var x = this.fromBigInteger(X1); - var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); - var beta = alpha.sqrt(); - // if we can't find a sqrt we haven't got a point on the curve - run! - if (beta == null) throw new Error("Invalid point compression"); - var betaValue = beta.toBigInteger(); - var bit0 = betaValue.testBit(0) ? 1 : 0; - if (bit0 != yTilde) { - // Use the other root - beta = this.fromBigInteger(this.getQ().subtract(betaValue)); - } - return new ec.PointFp(this, x, beta, null, true); - }; + /** + * Set whether the public key should be returned compressed or not. + */ + ECKey.prototype.setCompressed = function (v) { + this.compressed = !!v; + if (this.pubPoint) this.pubPoint.compressed = this.compressed; + return this; + }; + + /* + * Return public key as a byte array in DER encoding + */ + ECKey.prototype.getPub = function () { + if (this.compressed) { + if (this.pubComp) return this.pubComp; + return this.pubComp = this.getPubPoint().getEncoded(1); + } else { + if (this.pubUncomp) return this.pubUncomp; + return this.pubUncomp = this.getPubPoint().getEncoded(0); + } + }; + + /** + * Return public point as ECPoint object. + */ + ECKey.prototype.getPubPoint = function () { + if (!this.pubPoint) { + this.pubPoint = ecparams.getG().multiply(this.priv); + this.pubPoint.compressed = this.compressed; + } + return this.pubPoint; + }; + ECKey.prototype.getPubKeyHex = function () { + if (this.compressed) { + if (this.pubKeyHexComp) return this.pubKeyHexComp; + return this.pubKeyHexComp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); + } else { + if (this.pubKeyHexUncomp) return this.pubKeyHexUncomp; + return this.pubKeyHexUncomp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); + } + }; - ec.fromHex = function (s) { return new BigInteger(s, 16); }; + /** + * Get the pubKeyHash for this key. + * + * This is calculated as RIPE160(SHA256([encoded pubkey])) and returned as + * a byte array. + */ + ECKey.prototype.getPubKeyHash = function () { + if (this.compressed) { + if (this.pubKeyHashComp) return this.pubKeyHashComp; + return this.pubKeyHashComp = Bitcoin.Util.sha256ripe160(this.getPub()); + } else { + if (this.pubKeyHashUncomp) return this.pubKeyHashUncomp; + return this.pubKeyHashUncomp = Bitcoin.Util.sha256ripe160(this.getPub()); + } + }; - ec.integerToBytes = function (i, len) { - var bytes = i.toByteArrayUnsigned(); - if (len < bytes.length) { - bytes = bytes.slice(bytes.length - len); - } else while (len > bytes.length) { - bytes.unshift(0); - } - return bytes; - }; + ECKey.prototype.getBitcoinAddress = function () { + var hash = this.getPubKeyHash(); + var addr = new Bitcoin.Address(hash); + return addr.toString(); + }; + /* + * Takes a public point as a hex string or byte array + */ + ECKey.prototype.setPub = function (pub) { + // byte array + if (Bitcoin.Util.isArray(pub)) { + pub = Crypto.util.bytesToHex(pub).toString().toUpperCase(); + } + var ecPoint = ecparams.getCurve().decodePointHex(pub); + this.setCompressed(ecPoint.compressed); + this.pubPoint = ecPoint; + return this; + }; - // Named EC curves - // ---------------- - // X9ECParameters constructor - ec.X9Parameters = function (curve, g, n, h) { - this.curve = curve; - this.g = g; - this.n = n; - this.h = h; - } - ec.X9Parameters.prototype.getCurve = function () { return this.curve; }; - ec.X9Parameters.prototype.getG = function () { return this.g; }; - ec.X9Parameters.prototype.getN = function () { return this.n; }; - ec.X9Parameters.prototype.getH = function () { return this.h; }; + // Sipa Private Key Wallet Import Format + ECKey.prototype.getBitcoinWalletImportFormat = function () { + var bytes = this.getBitcoinPrivateKeyByteArray(); + bytes.unshift(ECKey.privateKeyPrefix); // prepend 0x80 byte + if (this.compressed) bytes.push(0x01); // append 0x01 byte for compressed format + var checksum = Crypto.SHA256(Crypto.SHA256(bytes, { asBytes: true }), { asBytes: true }); + bytes = bytes.concat(checksum.slice(0, 4)); + var privWif = Bitcoin.Base58.encode(bytes); + return privWif; + }; - // secp256k1 is the Curve used by Bitcoin - ec.secNamedCurves = { - // used by Bitcoin - "secp256k1": function () { - // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 - var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); - var a = BigInteger.ZERO; - var b = ec.fromHex("7"); - var n = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); - var h = BigInteger.ONE; - var curve = new ec.CurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" - + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"); - return new ec.X9Parameters(curve, G, n, h); - } - }; + // Private Key Hex Format + ECKey.prototype.getBitcoinHexFormat = function () { + return Crypto.util.bytesToHex(this.getBitcoinPrivateKeyByteArray()).toString().toUpperCase(); + }; - // secp256k1 called by Bitcoin's ECKEY - ec.getSECCurveByName = function (name) { - if (ec.secNamedCurves[name] == undefined) return null; - return ec.secNamedCurves[name](); - } -})(exports); + // Private Key Base64 Format + ECKey.prototype.getBitcoinBase64Format = function () { + return Crypto.util.bytesToBase64(this.getBitcoinPrivateKeyByteArray()); + }; -var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js -// See here for license information: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE -(function (Bitcoin) { - Bitcoin.Address = function (bytes) { - if ("string" == typeof bytes) { - bytes = Bitcoin.Address.decodeString(bytes); - } - this.hash = bytes; - this.version = Bitcoin.Address.networkVersion; - }; + ECKey.prototype.getBitcoinPrivateKeyByteArray = function () { + // Get a copy of private key as a byte array + var bytes = this.priv.toByteArrayUnsigned(); + // zero pad if private key is less than 32 bytes + while (bytes.length < 32) bytes.unshift(0x00); + return bytes; + }; - Bitcoin.Address.networkVersion = 0x00; // mainnet + ECKey.prototype.toString = function (format) { + format = format || ""; + if (format.toString().toLowerCase() == "base64" || format.toString().toLowerCase() == "b64") { + return this.getBitcoinBase64Format(); + } + // Wallet Import Format + else if (format.toString().toLowerCase() == "wif") { + return this.getBitcoinWalletImportFormat(); + } + else { + return this.getBitcoinHexFormat(); + } + }; - /** - * Serialize this object as a standard Bitcoin address. - * - * Returns the address as a base58-encoded string in the standardized format. - */ - Bitcoin.Address.prototype.toString = function () { - // Get a copy of the hash - var hash = this.hash.slice(0); + /** + * Parse a wallet import format private key contained in a string. + */ + ECKey.decodeWalletImportFormat = function (privStr) { + var bytes = Bitcoin.Base58.decode(privStr); + var hash = bytes.slice(0, 33); + var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); + if (checksum[0] != bytes[33] || + checksum[1] != bytes[34] || + checksum[2] != bytes[35] || + checksum[3] != bytes[36]) { + throw "Checksum validation failed!"; + } + var version = hash.shift(); + if (version != ECKey.privateKeyPrefix) { + throw "Version " + version + " not supported!"; + } + return hash; + }; - // Version - hash.unshift(this.version); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); - var bytes = hash.concat(checksum.slice(0, 4)); - return Bitcoin.Base58.encode(bytes); - }; + /** + * Parse a compressed wallet import format private key contained in a string. + */ + ECKey.decodeCompressedWalletImportFormat = function (privStr) { + var bytes = Bitcoin.Base58.decode(privStr); + var hash = bytes.slice(0, 34); + var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); + if (checksum[0] != bytes[34] || + checksum[1] != bytes[35] || + checksum[2] != bytes[36] || + checksum[3] != bytes[37]) { + throw "Checksum validation failed!"; + } + var version = hash.shift(); + if (version != ECKey.privateKeyPrefix) { + throw "Version " + version + " not supported!"; + } + hash.pop(); + return hash; + }; - Bitcoin.Address.prototype.getHashBase64 = function () { - return Crypto.util.bytesToBase64(this.hash); - }; + // 64 characters [0-9A-F] + ECKey.isHexFormat = function (key) { + key = key.toString(); + return /^[A-Fa-f0-9]{64}$/.test(key); + }; - /** - * Parse a Bitcoin address contained in a string. - */ - Bitcoin.Address.decodeString = function (string) { - var bytes = Bitcoin.Base58.decode(string); - var hash = bytes.slice(0, 21); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); + // 51 characters base58, always starts with a '5' + ECKey.isWalletImportFormat = function (key) { + key = key.toString(); + return (ECKey.privateKeyPrefix == 0x80) ? + (/^5[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)) : + (/^9[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)); + }; - if (checksum[0] != bytes[21] || - checksum[1] != bytes[22] || - checksum[2] != bytes[23] || - checksum[3] != bytes[24]) { - throw "Checksum validation failed!"; - } + // 52 characters base58 + ECKey.isCompressedWalletImportFormat = function (key) { + key = key.toString(); + return (ECKey.privateKeyPrefix == 0x80) ? + (/^[LK][123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)) : + (/^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)); + }; - var version = hash.shift(); + // 44 characters + ECKey.isBase64Format = function (key) { + key = key.toString(); + return (/^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789=+\/]{44}$/.test(key)); + }; - if (version != 0) { - throw "Version " + version + " not supported!"; - } + // 99 characters, 1=1, if using dice convert 6 to 0 + ECKey.isBase6Format = function (key) { + key = key.toString(); + return (/^[012345]{99}$/.test(key)); + }; - return hash; - }; -})(Bitcoin); -//https://raw.github.com/bitcoinjs/bitcoinjs-lib/c952aaeb3ee472e3776655b8ea07299ebed702c7/src/base58.js + // 22, 26 or 30 characters, always starts with an 'S' + ECKey.isMiniFormat = function (key) { + key = key.toString(); + var validChars22 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21}$/.test(key); + var validChars26 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{25}$/.test(key); + var validChars30 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{29}$/.test(key); + var testBytes = Crypto.SHA256(key + "?", { asBytes: true }); + + return ((testBytes[0] === 0x00 || testBytes[0] === 0x01) && (validChars22 || validChars26 || validChars30)); + }; + + return ECKey; + })(); +})(Bitcoin);//https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/util.js // See here for license information: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE +// Bitcoin utility functions (function (Bitcoin) { - Bitcoin.Base58 = { - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", - validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/, - base: BigInteger.valueOf(58), - + Bitcoin.Util = { /** - * Convert a byte array to a base58-encoded string. + * Cross-browser compatibility version of Array.isArray. + */ + isArray: Array.isArray || function (o) { + return Object.prototype.toString.call(o) === '[object Array]'; + }, + /** + * Create an array of a certain length filled with a specific value. + */ + makeFilledArray: function (len, val) { + var array = []; + var i = 0; + while (i < len) { + array[i++] = val; + } + return array; + }, + /** + * Turn an integer into a "var_int". * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. + * "var_int" is a variable length integer used by Bitcoin's binary format. * - * Ported to JavaScript by Stefan Thomas. + * Returns a byte array. */ - encode: function (input) { - var bi = BigInteger.fromByteArrayUnsigned(input); - var chars = []; - - while (bi.compareTo(B58.base) >= 0) { - var mod = bi.mod(B58.base); - chars.unshift(B58.alphabet[mod.intValue()]); - bi = bi.subtract(mod).divide(B58.base); - } - chars.unshift(B58.alphabet[bi.intValue()]); - - // Convert leading zeros too. - for (var i = 0; i < input.length; i++) { - if (input[i] == 0x00) { - chars.unshift(B58.alphabet[0]); - } else break; + numToVarInt: function (i) { + if (i < 0xfd) { + // unsigned char + return [i]; + } else if (i <= 1 << 16) { + // unsigned short (LE) + return [0xfd, i >>> 8, i & 255]; + } else if (i <= 1 << 32) { + // unsigned int (LE) + return [0xfe].concat(Crypto.util.wordsToBytes([i])); + } else { + // unsigned long long (LE) + return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i])); } - - return chars.join(''); }, + /** + * Parse a Bitcoin value byte array, returning a BigInteger. + */ + valueToBigInt: function (valueBuffer) { + if (valueBuffer instanceof BigInteger) return valueBuffer; + // Prepend zero byte to prevent interpretation as negative integer + return BigInteger.fromByteArrayUnsigned(valueBuffer); + }, /** - * Convert a base58-encoded string to a byte array. + * Format a Bitcoin value as a string. * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. + * Takes a BigInteger or byte-array and returns that amount of Bitcoins in a + * nice standard formatting. * - * Ported to JavaScript by Stefan Thomas. + * Examples: + * 12.3555 + * 0.1234 + * 900.99998888 + * 34.00 */ - decode: function (input) { - var bi = BigInteger.valueOf(0); - var leadingZerosNum = 0; - for (var i = input.length - 1; i >= 0; i--) { - var alphaIndex = B58.alphabet.indexOf(input[i]); - if (alphaIndex < 0) { - throw "Invalid character"; - } - bi = bi.add(BigInteger.valueOf(alphaIndex) - .multiply(B58.base.pow(input.length - 1 - i))); - - // This counts leading zero bytes - if (input[i] == "1") leadingZerosNum++; - else leadingZerosNum = 0; - } - var bytes = bi.toByteArrayUnsigned(); - - // Add leading zeros - while (leadingZerosNum-- > 0) bytes.unshift(0); - - return bytes; + formatValue: function (valueBuffer) { + var value = this.valueToBigInt(valueBuffer).toString(); + var integerPart = value.length > 8 ? value.substr(0, value.length - 8) : '0'; + var decimalPart = value.length > 8 ? value.substr(value.length - 8) : value; + while (decimalPart.length < 8) decimalPart = "0" + decimalPart; + decimalPart = decimalPart.replace(/0*$/, ''); + while (decimalPart.length < 2) decimalPart += "0"; + return integerPart + "." + decimalPart; + }, + /** + * Parse a floating point string as a Bitcoin value. + * + * Keep in mind that parsing user input is messy. You should always display + * the parsed value back to the user to make sure we understood his input + * correctly. + */ + parseValue: function (valueString) { + // TODO: Detect other number formats (e.g. comma as decimal separator) + var valueComp = valueString.split('.'); + var integralPart = valueComp[0]; + var fractionalPart = valueComp[1] || "0"; + while (fractionalPart.length < 8) fractionalPart += "0"; + fractionalPart = fractionalPart.replace(/^0+/g, ''); + var value = BigInteger.valueOf(parseInt(integralPart)); + value = value.multiply(BigInteger.valueOf(100000000)); + value = value.add(BigInteger.valueOf(parseInt(fractionalPart))); + return value; + }, + /** + * Calculate RIPEMD160(SHA256(data)). + * + * Takes an arbitrary byte array as inputs and returns the hash as a byte + * array. + */ + sha256ripe160: function (data) { + return Crypto.RIPEMD160(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); + }, + // double sha256 + dsha256: function (data) { + return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); } }; - - var B58 = Bitcoin.Base58; })(Bitcoin); -//https://raw.github.com/pointbiz/bitcoinjs-lib/9b2f94a028a7bc9bed94e0722563e9ff1d8e8db8/src/eckey.js -// See here for license information: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE -(function (Bitcoin) { - Bitcoin.ECKey = (function () { - var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); +},{}],12:[function(require,module,exports){ +// Generated by IcedCoffeeScript 1.7.1-f +(function() { + var Generator, iced, __iced_k, __iced_k_noop; - var ECKey = function (input) { - if (input instanceof BigInteger) { - // Input is a private key value - this.priv = input; - } else if (Bitcoin.Util.isArray(input)) { - // Prepend zero byte to prevent interpretation as negative integer - this.priv = BigInteger.fromByteArrayUnsigned(input); - } else if ("string" == typeof input) { - var bytes = null; - if (ECKey.isWalletImportFormat(input)) { - bytes = ECKey.decodeWalletImportFormat(input); - } else if (ECKey.isCompressedWalletImportFormat(input)) { - bytes = ECKey.decodeCompressedWalletImportFormat(input); - this.compressed = true; - } else if (ECKey.isMiniFormat(input)) { - bytes = Crypto.SHA256(input, { asBytes: true }); - } else if (ECKey.isHexFormat(input)) { - bytes = Crypto.util.hexToBytes(input); - } else if (ECKey.isBase64Format(input)) { - bytes = Crypto.util.base64ToBytes(input); - } - - if (ECKey.isBase6Format(input)) { - this.priv = new BigInteger(input, 6); - } else if (bytes == null || bytes.length != 32) { - this.priv = null; - } else { - // Prepend zero byte to prevent interpretation as negative integer - this.priv = BigInteger.fromByteArrayUnsigned(bytes); - } - } else { - throw new Error("no plausible constructor behavior"); - } + iced = require('iced-runtime'); + __iced_k = __iced_k_noop = function() {}; + + Generator = Generator = (function() { + function Generator(opts) { + opts = opts || {}; + this.lazy_loop_delay = opts.lazy_loop_delay || 30; + this.loop_delay = opts.loop_delay || 5; + this.work_min = opts.work_min || 1; + this.auto_stop_bits = opts.auto_stop_bits || 4096; + this.max_bits_per_delta = opts.max_bits_per_delta || 4; + this.auto_stop = opts.auto_stop ? opts.auto_stop : true; + this.entropies = []; + this.running = true; + this.is_generating = false; + this.timer_race_loop(); + } + + Generator.prototype.generate = function(bits_wanted, cb) { + var e, harvested_bits, res, ___iced_passed_deferral, __iced_deferrals, __iced_k; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + this.is_generating = true; + if (!this.running) { + this.resume(); + } + harvested_bits = 0; + res = []; + (function(_this) { + return (function(__iced_k) { + var _results, _while; + _results = []; + _while = function(__iced_k) { + var _break, _continue, _next; + _break = function() { + return __iced_k(_results); + }; + _continue = function() { + return iced.trampoline(function() { + return _while(__iced_k); + }); + }; + _next = function(__iced_next_arg) { + _results.push(__iced_next_arg); + return _continue(); + }; + if (!(harvested_bits < bits_wanted)) { + return _break(); + } else { + (function(__iced_k) { + if (_this.entropies.length) { + e = _this.entropies.splice(0, 1)[0]; + harvested_bits += e[1]; + return __iced_k(res.push(e[0])); + } else { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "/Users/chris/git/more-entropy/src/generator.iced", + funcname: "Generator.generate" + }); + _this.delay(__iced_deferrals.defer({ + lineno: 28 + })); + __iced_deferrals._fulfill(); + })(__iced_k); + } + })(_next); + } + }; + _while(__iced_k); + }); + })(this)((function(_this) { + return function() { + if (_this.auto_stop) { + _this.stop(); + } + _this.is_generating = false; + return cb(res); + }; + })(this)); + }; - this.compressed = (this.compressed == undefined) ? !!ECKey.compressByDefault : this.compressed; - }; + Generator.prototype.stop = function() { + return this.running = false; + }; - ECKey.privateKeyPrefix = 0x80; // mainnet 0x80 testnet 0xEF + Generator.prototype.resume = function() { + this.running = true; + return this.timer_race_loop(); + }; - /** - * Whether public keys should be returned compressed by default. - */ - ECKey.compressByDefault = false; + Generator.prototype.reset = function() { + this.entropies = []; + return this.total_bits = 0; + }; - /** - * Set whether the public key should be returned compressed or not. - */ - ECKey.prototype.setCompressed = function (v) { - this.compressed = !!v; - if (this.pubPoint) this.pubPoint.compressed = this.compressed; - return this; - }; + Generator.prototype.count_unused_bits = function() { + var bits, e, _i, _len, _ref; + bits = 0; + _ref = this.entropies; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + e = _ref[_i]; + bits += e[1]; + } + return bits; + }; - /* - * Return public key as a byte array in DER encoding - */ - ECKey.prototype.getPub = function () { - if (this.compressed) { - if (this.pubComp) return this.pubComp; - return this.pubComp = this.getPubPoint().getEncoded(1); - } else { - if (this.pubUncomp) return this.pubUncomp; - return this.pubUncomp = this.getPubPoint().getEncoded(0); - } - }; + Generator.prototype.delay = function(cb) { + var delay, ___iced_passed_deferral, __iced_deferrals, __iced_k; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + delay = this.is_generating ? this.loop_delay : this.lazy_loop_delay; + (function(_this) { + return (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "/Users/chris/git/more-entropy/src/generator.iced", + funcname: "Generator.delay" + }); + setTimeout(__iced_deferrals.defer({ + lineno: 50 + }), delay); + __iced_deferrals._fulfill(); + }); + })(this)((function(_this) { + return function() { + return cb(); + }; + })(this)); + }; - /** - * Return public point as ECPoint object. - */ - ECKey.prototype.getPubPoint = function () { - if (!this.pubPoint) { - this.pubPoint = ecparams.getG().multiply(this.priv); - this.pubPoint.compressed = this.compressed; - } - return this.pubPoint; - }; + Generator.prototype.timer_race_loop = function() { + var ___iced_passed_deferral, __iced_k, _results, _while; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + this._last_count = null; + _results = []; + _while = (function(_this) { + var count, delta, entropy, v, __iced_deferrals; + return function(__iced_k) { + var _break, _continue, _next; + _break = function() { + return __iced_k(_results); + }; + _continue = function() { + return iced.trampoline(function() { + return _while(__iced_k); + }); + }; + _next = function(__iced_next_arg) { + _results.push(__iced_next_arg); + return _continue(); + }; + if (!_this.running) { + return _break(); + } else { + if (_this.count_unused_bits() < _this.auto_stop_bits) { + count = _this.millisecond_count(); + if ((_this._last_count != null) && (delta = count - _this._last_count)) { + entropy = Math.floor(_this.log_2(Math.abs(delta))); + entropy = Math.min(_this.max_bits_per_delta, entropy); + v = [delta, entropy]; + _this.entropies.push(v); + } + _this._last_count = count; + } + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "/Users/chris/git/more-entropy/src/generator.iced", + funcname: "Generator.timer_race_loop" + }); + _this.delay(__iced_deferrals.defer({ + lineno: 64 + })); + __iced_deferrals._fulfill(); + })(_next); + } + }; + })(this); + _while(__iced_k); + }; - ECKey.prototype.getPubKeyHex = function () { - if (this.compressed) { - if (this.pubKeyHexComp) return this.pubKeyHexComp; - return this.pubKeyHexComp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); - } else { - if (this.pubKeyHexUncomp) return this.pubKeyHexUncomp; - return this.pubKeyHexUncomp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); - } - }; + Generator.prototype.log_2 = function(x) { + return Math.log(x) / Math.LN2; + }; - /** - * Get the pubKeyHash for this key. - * - * This is calculated as RIPE160(SHA256([encoded pubkey])) and returned as - * a byte array. - */ - ECKey.prototype.getPubKeyHash = function () { - if (this.compressed) { - if (this.pubKeyHashComp) return this.pubKeyHashComp; - return this.pubKeyHashComp = Bitcoin.Util.sha256ripe160(this.getPub()); - } else { - if (this.pubKeyHashUncomp) return this.pubKeyHashUncomp; - return this.pubKeyHashUncomp = Bitcoin.Util.sha256ripe160(this.getPub()); - } - }; + Generator.prototype.millisecond_count = function() { + var d, i, x; + d = Date.now(); + i = x = 0; + while (Date.now() < d + this.work_min + 1) { + i++; + x = Math.sin(Math.sqrt(Math.log(i + x))); + } + return i; + }; - ECKey.prototype.getBitcoinAddress = function () { - var hash = this.getPubKeyHash(); - var addr = new Bitcoin.Address(hash); - return addr.toString(); - }; + return Generator; - /* - * Takes a public point as a hex string or byte array - */ - ECKey.prototype.setPub = function (pub) { - // byte array - if (Bitcoin.Util.isArray(pub)) { - pub = Crypto.util.bytesToHex(pub).toString().toUpperCase(); - } - var ecPoint = ecparams.getCurve().decodePointHex(pub); - this.setCompressed(ecPoint.compressed); - this.pubPoint = ecPoint; - return this; - }; + })(); - // Sipa Private Key Wallet Import Format - ECKey.prototype.getBitcoinWalletImportFormat = function () { - var bytes = this.getBitcoinPrivateKeyByteArray(); - bytes.unshift(ECKey.privateKeyPrefix); // prepend 0x80 byte - if (this.compressed) bytes.push(0x01); // append 0x01 byte for compressed format - var checksum = Crypto.SHA256(Crypto.SHA256(bytes, { asBytes: true }), { asBytes: true }); - bytes = bytes.concat(checksum.slice(0, 4)); - var privWif = Bitcoin.Base58.encode(bytes); - return privWif; - }; + if (typeof window !== "undefined" && window !== null) { + window.Generator = Generator; + } - // Private Key Hex Format - ECKey.prototype.getBitcoinHexFormat = function () { - return Crypto.util.bytesToHex(this.getBitcoinPrivateKeyByteArray()).toString().toUpperCase(); - }; + if (typeof exports !== "undefined" && exports !== null) { + exports.Generator = Generator; + } - // Private Key Base64 Format - ECKey.prototype.getBitcoinBase64Format = function () { - return Crypto.util.bytesToBase64(this.getBitcoinPrivateKeyByteArray()); - }; +}).call(this); - ECKey.prototype.getBitcoinPrivateKeyByteArray = function () { - // Get a copy of private key as a byte array - var bytes = this.priv.toByteArrayUnsigned(); - // zero pad if private key is less than 32 bytes - while (bytes.length < 32) bytes.unshift(0x00); - return bytes; - }; +},{"iced-runtime":7}],13:[function(require,module,exports){ +// Generated by IcedCoffeeScript 1.7.1-c +(function() { + exports.Generator = require('../lib/generator').Generator; - ECKey.prototype.toString = function (format) { - format = format || ""; - if (format.toString().toLowerCase() == "base64" || format.toString().toLowerCase() == "b64") { - return this.getBitcoinBase64Format(); - } - // Wallet Import Format - else if (format.toString().toLowerCase() == "wif") { - return this.getBitcoinWalletImportFormat(); - } - else { - return this.getBitcoinHexFormat(); - } - }; +}).call(this); - /** - * Parse a wallet import format private key contained in a string. - */ - ECKey.decodeWalletImportFormat = function (privStr) { - var bytes = Bitcoin.Base58.decode(privStr); - var hash = bytes.slice(0, 33); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); - if (checksum[0] != bytes[33] || - checksum[1] != bytes[34] || - checksum[2] != bytes[35] || - checksum[3] != bytes[36]) { - throw "Checksum validation failed!"; - } - var version = hash.shift(); - if (version != ECKey.privateKeyPrefix) { - throw "Version " + version + " not supported!"; - } - return hash; - }; +},{"../lib/generator":12}],14:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; - /** - * Parse a compressed wallet import format private key contained in a string. - */ - ECKey.decodeCompressedWalletImportFormat = function (privStr) { - var bytes = Bitcoin.Base58.decode(privStr); - var hash = bytes.slice(0, 34); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); - if (checksum[0] != bytes[34] || - checksum[1] != bytes[35] || - checksum[2] != bytes[36] || - checksum[3] != bytes[37]) { - throw "Checksum validation failed!"; - } - var version = hash.shift(); - if (version != ECKey.privateKeyPrefix) { - throw "Version " + version + " not supported!"; - } - hash.pop(); - return hash; - }; +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. - // 64 characters [0-9A-F] - ECKey.isHexFormat = function (key) { - key = key.toString(); - return /^[A-Fa-f0-9]{64}$/.test(key); - }; +var cachedSetTimeout; +var cachedClearTimeout; - // 51 characters base58, always starts with a '5' - ECKey.isWalletImportFormat = function (key) { - key = key.toString(); - return (ECKey.privateKeyPrefix == 0x80) ? - (/^5[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)) : - (/^9[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)); - }; +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } - // 52 characters base58 - ECKey.isCompressedWalletImportFormat = function (key) { - key = key.toString(); - return (ECKey.privateKeyPrefix == 0x80) ? - (/^[LK][123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)) : - (/^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)); - }; - // 44 characters - ECKey.isBase64Format = function (key) { - key = key.toString(); - return (/^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789=+\/]{44}$/.test(key)); - }; +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } - // 99 characters, 1=1, if using dice convert 6 to 0 - ECKey.isBase6Format = function (key) { - key = key.toString(); - return (/^[012345]{99}$/.test(key)); - }; - // 22, 26 or 30 characters, always starts with an 'S' - ECKey.isMiniFormat = function (key) { - key = key.toString(); - var validChars22 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21}$/.test(key); - var validChars26 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{25}$/.test(key); - var validChars30 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{29}$/.test(key); - var testBytes = Crypto.SHA256(key + "?", { asBytes: true }); - return ((testBytes[0] === 0x00 || testBytes[0] === 0x01) && (validChars22 || validChars26 || validChars30)); - }; +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; - return ECKey; - })(); -})(Bitcoin);//https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/util.js -// See here for license information: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE -// Bitcoin utility functions -(function (Bitcoin) { - Bitcoin.Util = { - /** - * Cross-browser compatibility version of Array.isArray. - */ - isArray: Array.isArray || function (o) { - return Object.prototype.toString.call(o) === '[object Array]'; - }, - /** - * Create an array of a certain length filled with a specific value. - */ - makeFilledArray: function (len, val) { - var array = []; - var i = 0; - while (i < len) { - array[i++] = val; - } - return array; - }, - /** - * Turn an integer into a "var_int". - * - * "var_int" is a variable length integer used by Bitcoin's binary format. - * - * Returns a byte array. - */ - numToVarInt: function (i) { - if (i < 0xfd) { - // unsigned char - return [i]; - } else if (i <= 1 << 16) { - // unsigned short (LE) - return [0xfd, i >>> 8, i & 255]; - } else if (i <= 1 << 32) { - // unsigned int (LE) - return [0xfe].concat(Crypto.util.wordsToBytes([i])); - } else { - // unsigned long long (LE) - return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i])); - } - }, - /** - * Parse a Bitcoin value byte array, returning a BigInteger. - */ - valueToBigInt: function (valueBuffer) { - if (valueBuffer instanceof BigInteger) return valueBuffer; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} - // Prepend zero byte to prevent interpretation as negative integer - return BigInteger.fromByteArrayUnsigned(valueBuffer); - }, - /** - * Format a Bitcoin value as a string. - * - * Takes a BigInteger or byte-array and returns that amount of Bitcoins in a - * nice standard formatting. - * - * Examples: - * 12.3555 - * 0.1234 - * 900.99998888 - * 34.00 - */ - formatValue: function (valueBuffer) { - var value = this.valueToBigInt(valueBuffer).toString(); - var integerPart = value.length > 8 ? value.substr(0, value.length - 8) : '0'; - var decimalPart = value.length > 8 ? value.substr(value.length - 8) : value; - while (decimalPart.length < 8) decimalPart = "0" + decimalPart; - decimalPart = decimalPart.replace(/0*$/, ''); - while (decimalPart.length < 2) decimalPart += "0"; - return integerPart + "." + decimalPart; - }, - /** - * Parse a floating point string as a Bitcoin value. - * - * Keep in mind that parsing user input is messy. You should always display - * the parsed value back to the user to make sure we understood his input - * correctly. - */ - parseValue: function (valueString) { - // TODO: Detect other number formats (e.g. comma as decimal separator) - var valueComp = valueString.split('.'); - var integralPart = valueComp[0]; - var fractionalPart = valueComp[1] || "0"; - while (fractionalPart.length < 8) fractionalPart += "0"; - fractionalPart = fractionalPart.replace(/^0+/g, ''); - var value = BigInteger.valueOf(parseInt(integralPart)); - value = value.multiply(BigInteger.valueOf(100000000)); - value = value.add(BigInteger.valueOf(parseInt(fractionalPart))); - return value; - }, - /** - * Calculate RIPEMD160(SHA256(data)). - * - * Takes an arbitrary byte array as inputs and returns the hash as a byte - * array. - */ - sha256ripe160: function (data) { - return Crypto.RIPEMD160(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); - }, - // double sha256 - dsha256: function (data) { - return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); - } - }; -})(Bitcoin); -},{}],17:[function(require,module,exports){ +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +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) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +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.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +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; }; + +},{}],15:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { var AES, BlockCipher, G, Global, scrub_vec, @@ -6358,7 +6295,7 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit }).call(this); -},{"./algbase":18,"./util":37}],18:[function(require,module,exports){ +},{"./algbase":16,"./util":35}],16:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { var BlockCipher, BufferedBlockAlgorithm, Hasher, StreamCipher, WordArray, util, @@ -6543,7 +6480,7 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit }).call(this); -},{"./util":37,"./wordarray":38}],19:[function(require,module,exports){ +},{"./util":35,"./wordarray":36}],17:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { var CombineBase, Concat, HMAC, SHA3, SHA512, WordArray, XOR, bulk_sign, _ref, @@ -6757,7 +6694,7 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit }).call(this); -},{"./hmac":24,"./sha3":34,"./sha512":35,"./wordarray":38}],20:[function(require,module,exports){ +},{"./hmac":22,"./sha3":32,"./sha512":33,"./wordarray":36}],18:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { var Cipher, Counter, StreamCipher, WordArray, bulk_encrypt, encrypt, iced, __iced_k, __iced_k_noop, @@ -6916,7 +6853,7 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit }).call(this); -},{"./algbase":18,"./wordarray":38,"iced-coffee-script/lib/coffee-script/iced":9}],21:[function(require,module,exports){ +},{"./algbase":16,"./wordarray":36,"iced-coffee-script/lib/coffee-script/iced":3}],19:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { var AES, Base, Concat, Decryptor, SHA512, Salsa20, TwoFish, V, WordArray, ctr, decrypt, iced, make_esc, salsa20, __iced_k, __iced_k_noop, _ref, @@ -7225,730 +7162,1394 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit }); }); }); - }); + }); + }); + }); + }); + }; + + return Decryptor; + + })(Base); + + decrypt = function(_arg, cb) { + var data, dec, err, key, progress_hook, pt, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + key = _arg.key, data = _arg.data, progress_hook = _arg.progress_hook; + dec = new Decryptor({ + key: key + }); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/dec.iced", + funcname: "decrypt" + }); + dec.run({ + data: data, + progress_hook: progress_hook + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + err = arguments[0]; + return pt = arguments[1]; + }; + })(), + lineno: 168 + })); + __iced_deferrals._fulfill(); + })(function() { + dec.scrub(); + return cb(err, pt); + }); + }; + + exports.Decryptor = Decryptor; + + exports.decrypt = decrypt; + +}).call(this); + +},{"./aes":15,"./combine":17,"./ctr":18,"./enc":21,"./salsa20":27,"./sha512":33,"./twofish":34,"./wordarray":36,"iced-coffee-script/lib/coffee-script/iced":3,"iced-error":4}],20:[function(require,module,exports){ +(function (Buffer){ +// Generated by IcedCoffeeScript 1.6.3-g +(function() { + var ADRBG, DRBG, Lock, WordArray, XOR, hmac, iced, sha3, sha512, __iced_k, __iced_k_noop; + + iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; + __iced_k = __iced_k_noop = function() {}; + + hmac = require('./hmac'); + + XOR = require('./combine').XOR; + + sha512 = require('./sha512'); + + sha3 = require('./sha3'); + + WordArray = require('./wordarray').WordArray; + + Lock = require('./lock').Lock; + + DRBG = (function() { + function DRBG(entropy, personalization_string, hmac_func) { + this.hmac = hmac_func || hmac.sign; + this.security_strength = 256; + entropy = this.check_entropy(entropy); + personalization_string || (personalization_string = new WordArray([])); + this._instantiate(entropy, personalization_string); + } + + DRBG.prototype.check_entropy = function(entropy, reseed) { + if (reseed == null) { + reseed = false; + } + if ((entropy.sigBytes * 8 * 2) < ((reseed ? 2 : 3) * this.security_strength)) { + throw new Error("entropy must be at least " + (1.5 * this.security_strength) + " bits."); + } + return entropy; + }; + + DRBG.prototype._hmac = function(key, input) { + return this.hmac({ + key: key, + input: input + }); + }; + + DRBG.prototype._update = function(provided_data) { + var V, V_in; + V = new WordArray([0], 1); + if (provided_data != null) { + V = V.concat(provided_data); + } + V_in = this.V.clone().concat(V); + this.K = this._hmac(this.K, V_in); + V_in.scrub(); + V.scrub(); + this.V = this._hmac(this.K, this.V); + if (provided_data != null) { + V_in = this.V.clone().concat(new WordArray([1 << 24], 1)).concat(provided_data); + this.K = this._hmac(this.K, V_in); + V_in.scrub(); + this.V = this._hmac(this.K, this.V); + } + return provided_data != null ? provided_data.scrub() : void 0; + }; + + DRBG.prototype._instantiate = function(entropy, personalization_string) { + var i, n, seed_material; + seed_material = entropy.concat(personalization_string); + n = 64; + this.K = WordArray.from_buffer(new Buffer((function() { + var _i, _results; + _results = []; + for (i = _i = 0; 0 <= n ? _i < n : _i > n; i = 0 <= n ? ++_i : --_i) { + _results.push(0); + } + return _results; + })())); + this.V = WordArray.from_buffer(new Buffer((function() { + var _i, _results; + _results = []; + for (i = _i = 0; 0 <= n ? _i < n : _i > n; i = 0 <= n ? ++_i : --_i) { + _results.push(1); + } + return _results; + })())); + this._update(seed_material); + entropy.scrub(); + return this.reseed_counter = 1; + }; + + DRBG.prototype.reseed = function(entropy) { + this._update(this.check_entropy(entropy, true)); + return this.reseed_counter = 1; + }; + + DRBG.prototype.generate = function(num_bytes) { + var i, tmp, _ref; + if ((num_bytes * 8) > 7500) { + throw new Error("generate cannot generate > 7500 bits in 1 call."); + } + if (this.reseed_counter >= 10000) { + throw new Error("Need a reseed!"); + } + tmp = []; + i = 0; + while ((tmp.length === 0) || (tmp.length * tmp[0].length * 4) < num_bytes) { + this.V = this._hmac(this.K, this.V); + tmp.push(this.V.words); + } + this._update(); + this.reseed_counter += 1; + return (new WordArray((_ref = []).concat.apply(_ref, tmp))).truncate(num_bytes); + }; + + return DRBG; + + })(); + + ADRBG = (function() { + function ADRBG(gen_seed, hmac) { + this.gen_seed = gen_seed; + this.hmac = hmac; + this.drbg = null; + this.lock = new Lock(); + } + + ADRBG.prototype.generate = function(n, cb) { + var ret, seed, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/drbg.iced", + funcname: "ADRBG.generate" + }); + _this.lock.acquire(__iced_deferrals.defer({ + lineno: 148 + })); + __iced_deferrals._fulfill(); + })(function() { + (function(__iced_k) { + if (_this.drbg == null) { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/drbg.iced", + funcname: "ADRBG.generate" + }); + _this.gen_seed(256, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return seed = arguments[0]; + }; + })(), + lineno: 150 + })); + __iced_deferrals._fulfill(); + })(function() { + return __iced_k(_this.drbg = new DRBG(seed, null, _this.hmac)); + }); + } else { + return __iced_k(); + } + })(function() { + (function(__iced_k) { + if (_this.drbg.reseed_counter > 100) { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/drbg.iced", + funcname: "ADRBG.generate" + }); + _this.gen_seed(256, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return seed = arguments[0]; + }; + })(), + lineno: 153 + })); + __iced_deferrals._fulfill(); + })(function() { + return __iced_k(_this.drbg.reseed(seed)); + }); + } else { + return __iced_k(); + } + })(function() { + ret = _this.drbg.generate(n); + _this.lock.release(); + return cb(ret); }); }); }); }; - return Decryptor; - - })(Base); + return ADRBG; - decrypt = function(_arg, cb) { - var data, dec, err, key, progress_hook, pt, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, data = _arg.data, progress_hook = _arg.progress_hook; - dec = new Decryptor({ - key: key - }); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/dec.iced", - funcname: "decrypt" - }); - dec.run({ - data: data, - progress_hook: progress_hook - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - err = arguments[0]; - return pt = arguments[1]; - }; - })(), - lineno: 168 - })); - __iced_deferrals._fulfill(); - })(function() { - dec.scrub(); - return cb(err, pt); - }); - }; + })(); - exports.Decryptor = Decryptor; + exports.DRBG = DRBG; - exports.decrypt = decrypt; + exports.ADRBG = ADRBG; }).call(this); -},{"./aes":17,"./combine":19,"./ctr":20,"./enc":23,"./salsa20":29,"./sha512":35,"./twofish":36,"./wordarray":38,"iced-coffee-script/lib/coffee-script/iced":9,"iced-error":10}],22:[function(require,module,exports){ -(function (Buffer){ +}).call(this,require("buffer").Buffer) +},{"./combine":17,"./hmac":22,"./lock":23,"./sha3":32,"./sha512":33,"./wordarray":36,"buffer":2,"iced-coffee-script/lib/coffee-script/iced":3}],21:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var ADRBG, DRBG, Lock, WordArray, XOR, hmac, iced, sha3, sha512, __iced_k, __iced_k_noop; + var AES, Base, Concat, Encryptor, HMAC_SHA256, PBKDF2, SHA512, Scrypt, TwoFish, V, WordArray, XOR, ctr, encrypt, iced, make_esc, prng, salsa20, util, __iced_k, __iced_k_noop, _ref, + __hasProp = {}.hasOwnProperty, + __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; __iced_k = __iced_k_noop = function() {}; - hmac = require('./hmac'); + WordArray = require('./wordarray').WordArray; - XOR = require('./combine').XOR; + salsa20 = require('./salsa20'); - sha512 = require('./sha512'); + AES = require('./aes').AES; - sha3 = require('./sha3'); + TwoFish = require('./twofish').TwoFish; - WordArray = require('./wordarray').WordArray; + ctr = require('./ctr'); - Lock = require('./lock').Lock; + _ref = require('./combine'), XOR = _ref.XOR, Concat = _ref.Concat; - DRBG = (function() { - function DRBG(entropy, personalization_string, hmac_func) { - this.hmac = hmac_func || hmac.sign; - this.security_strength = 256; - entropy = this.check_entropy(entropy); - personalization_string || (personalization_string = new WordArray([])); - this._instantiate(entropy, personalization_string); + SHA512 = require('./sha512').SHA512; + + PBKDF2 = require('./pbkdf2').PBKDF2; + + Scrypt = require('./scrypt').Scrypt; + + util = require('./util'); + + prng = require('./prng'); + + make_esc = require('iced-error').make_esc; + + HMAC_SHA256 = require('./hmac').HMAC_SHA256; + + V = { + "1": { + header: [0x1c94d7de, 1], + salt_size: 8, + xsalsa20_rev: true, + kdf: { + klass: PBKDF2, + opts: { + c: 1024, + klass: XOR + } + }, + hmac_key_size: 768 / 8 + }, + "2": { + header: [0x1c94d7de, 2], + salt_size: 16, + xsalsa20_rev: true, + kdf: { + klass: Scrypt, + opts: { + c: 64, + klass: XOR, + N: 12, + r: 8, + p: 1 + } + }, + hmac_key_size: 768 / 8 + }, + "3": { + header: [0x1c94d7de, 3], + salt_size: 16, + xsalsa20_rev: false, + kdf: { + klass: Scrypt, + opts: { + c: 1, + klass: HMAC_SHA256, + N: 16, + r: 8, + p: 1 + } + }, + hmac_key_size: 768 / 8 + } + }; + + Base = (function() { + function Base(_arg) { + var key, version; + key = _arg.key, version = _arg.version; + this.version = V[version != null ? version : 1]; + if (this.version == null) { + throw new Error("unknown version: " + version); + } + this.set_key(key); + this.derived_keys = {}; } - DRBG.prototype.check_entropy = function(entropy, reseed) { - if (reseed == null) { - reseed = false; + Base.prototype.kdf = function(_arg, cb) { + var args, dkLen, end, extra_keymaterial, i, k, key, keys, len, lens, order, progress_hook, raw, salt, salt_hex, v, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + salt = _arg.salt, extra_keymaterial = _arg.extra_keymaterial, progress_hook = _arg.progress_hook; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.kdf" + }); + _this._check_scrubbed(_this.key, "in KDF", cb, __iced_deferrals.defer({ + lineno: 90 + })); + __iced_deferrals._fulfill(); + })(function() { + salt_hex = salt.to_hex(); + key = _this.key.clone(); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.kdf" + }); + _this._check_scrubbed(key, "KDF", cb, __iced_deferrals.defer({ + lineno: 98 + })); + __iced_deferrals._fulfill(); + })(function() { + (function(__iced_k) { + if ((keys = _this.derived_keys[salt_hex]) == null) { + _this._kdf = new _this.version.kdf.klass(_this.version.kdf.opts); + lens = { + hmac: _this.version.hmac_key_size, + aes: AES.keySize, + twofish: TwoFish.keySize, + salsa20: salsa20.Salsa20.keySize + }; + order = ['hmac', 'aes', 'twofish', 'salsa20']; + dkLen = extra_keymaterial || 0; + for (k in lens) { + v = lens[k]; + dkLen += v; + } + args = { + dkLen: dkLen, + key: key, + progress_hook: progress_hook, + salt: salt + }; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.kdf" + }); + _this._kdf.run(args, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return raw = arguments[0]; + }; + })(), + lineno: 117 + })); + __iced_deferrals._fulfill(); + })(function() { + var _i, _len; + keys = {}; + i = 0; + for (_i = 0, _len = order.length; _i < _len; _i++) { + k = order[_i]; + v = lens[k]; + len = v / 4; + end = i + len; + keys[k] = new WordArray(raw.words.slice(i, end)); + i = end; + } + keys.extra = (new WordArray(raw.words.slice(end))).to_buffer(); + return __iced_k(_this.derived_keys[salt_hex] = keys); + }); + } else { + return __iced_k(); + } + })(function() { + return cb(null, keys); + }); + }); + }); + }; + + Base.prototype.set_key = function(key) { + var wakey; + if (key != null) { + wakey = WordArray.from_buffer(key); + if (!this.key || !this.key.equal(wakey)) { + this.scrub(); + return this.key = wakey; + } + } else { + return this.scrub(); } - if ((entropy.sigBytes * 8 * 2) < ((reseed ? 2 : 3) * this.security_strength)) { - throw new Error("entropy must be at least " + (1.5 * this.security_strength) + " bits."); + }; + + Base.prototype._check_scrubbed = function(key, where, ecb, okcb) { + if ((key != null) && !key.is_scrubbed()) { + return okcb(); + } else { + return ecb(new Error("" + where + ": Failed due to scrubbed key!"), null); } - return entropy; }; - DRBG.prototype._hmac = function(key, input) { - return this.hmac({ - key: key, - input: input + Base.prototype.sign = function(_arg, cb) { + var input, key, out, progress_hook, salt, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + input = _arg.input, key = _arg.key, salt = _arg.salt, progress_hook = _arg.progress_hook; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.sign" + }); + _this._check_scrubbed(key, "HMAC", cb, __iced_deferrals.defer({ + lineno: 175 + })); + __iced_deferrals._fulfill(); + })(function() { + input = (new WordArray(_this.version.header)).concat(salt).concat(input); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.sign" + }); + Concat.bulk_sign({ + key: key, + input: input, + progress_hook: progress_hook + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return out = arguments[0]; + }; + })(), + lineno: 177 + })); + __iced_deferrals._fulfill(); + })(function() { + input.scrub(); + return cb(null, out); + }); }); }; - DRBG.prototype._update = function(provided_data) { - var V, V_in; - V = new WordArray([0], 1); - if (provided_data != null) { - V = V.concat(provided_data); - } - V_in = this.V.clone().concat(V); - this.K = this._hmac(this.K, V_in); - V_in.scrub(); - V.scrub(); - this.V = this._hmac(this.K, this.V); - if (provided_data != null) { - V_in = this.V.clone().concat(new WordArray([1 << 24], 1)).concat(provided_data); - this.K = this._hmac(this.K, V_in); - V_in.scrub(); - this.V = this._hmac(this.K, this.V); - } - return provided_data != null ? provided_data.scrub() : void 0; + Base.prototype.run_salsa20 = function(_arg, cb) { + var args, ct, input, iv, key, output_iv, progress_hook, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + input = _arg.input, key = _arg.key, iv = _arg.iv, output_iv = _arg.output_iv, progress_hook = _arg.progress_hook; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.run_salsa20" + }); + _this._check_scrubbed(key, "Salsa20", cb, __iced_deferrals.defer({ + lineno: 193 + })); + __iced_deferrals._fulfill(); + })(function() { + args = { + input: input, + progress_hook: progress_hook, + key: key, + iv: iv + }; + if (_this.version.xsalsa20_rev) { + args.key = key.clone().endian_reverse(); + args.iv = iv.clone().endian_reverse(); + } + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.run_salsa20" + }); + salsa20.bulk_encrypt(args, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return ct = arguments[0]; + }; + })(), + lineno: 205 + })); + __iced_deferrals._fulfill(); + })(function() { + if (output_iv) { + ct = iv.clone().concat(ct); + } + if (_this.version.xsalsa20_rev) { + args.key.scrub(); + args.iv.scrub(); + } + return cb(null, ct); + }); + }); }; - DRBG.prototype._instantiate = function(entropy, personalization_string) { - var i, n, seed_material; - seed_material = entropy.concat(personalization_string); - n = 64; - this.K = WordArray.from_buffer(new Buffer((function() { - var _i, _results; - _results = []; - for (i = _i = 0; 0 <= n ? _i < n : _i > n; i = 0 <= n ? ++_i : --_i) { - _results.push(0); - } - return _results; - })())); - this.V = WordArray.from_buffer(new Buffer((function() { - var _i, _results; - _results = []; - for (i = _i = 0; 0 <= n ? _i < n : _i > n; i = 0 <= n ? ++_i : --_i) { - _results.push(1); - } - return _results; - })())); - this._update(seed_material); - entropy.scrub(); - return this.reseed_counter = 1; + Base.prototype.run_twofish = function(_arg, cb) { + var block_cipher, ct, input, iv, key, progress_hook, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + input = _arg.input, key = _arg.key, iv = _arg.iv, progress_hook = _arg.progress_hook; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.run_twofish" + }); + _this._check_scrubbed(key, "TwoFish", cb, __iced_deferrals.defer({ + lineno: 228 + })); + __iced_deferrals._fulfill(); + })(function() { + block_cipher = new TwoFish(key); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.run_twofish" + }); + ctr.bulk_encrypt({ + block_cipher: block_cipher, + iv: iv, + input: input, + progress_hook: progress_hook, + what: "twofish" + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return ct = arguments[0]; + }; + })(), + lineno: 230 + })); + __iced_deferrals._fulfill(); + })(function() { + block_cipher.scrub(); + return cb(null, iv.clone().concat(ct)); + }); + }); }; - DRBG.prototype.reseed = function(entropy) { - this._update(this.check_entropy(entropy, true)); - return this.reseed_counter = 1; + Base.prototype.run_aes = function(_arg, cb) { + var block_cipher, ct, input, iv, key, progress_hook, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + input = _arg.input, key = _arg.key, iv = _arg.iv, progress_hook = _arg.progress_hook; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.run_aes" + }); + _this._check_scrubbed(key, "AES", cb, __iced_deferrals.defer({ + lineno: 245 + })); + __iced_deferrals._fulfill(); + })(function() { + block_cipher = new AES(key); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Base.run_aes" + }); + ctr.bulk_encrypt({ + block_cipher: block_cipher, + iv: iv, + input: input, + progress_hook: progress_hook, + what: "aes" + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return ct = arguments[0]; + }; + })(), + lineno: 247 + })); + __iced_deferrals._fulfill(); + })(function() { + block_cipher.scrub(); + return cb(null, iv.clone().concat(ct)); + }); + }); }; - DRBG.prototype.generate = function(num_bytes) { - var i, tmp, _ref; - if ((num_bytes * 8) > 7500) { - throw new Error("generate cannot generate > 7500 bits in 1 call."); + Base.prototype.scrub = function() { + var key, key_ring, salt, _i, _len, _ref1; + if (this.key != null) { + this.key.scrub(); } - if (this.reseed_counter >= 10000) { - throw new Error("Need a reseed!"); + if (this.derived_keys != null) { + _ref1 = this.derived_keys; + for (salt in _ref1) { + key_ring = _ref1[salt]; + for (_i = 0, _len = key_ring.length; _i < _len; _i++) { + key = key_ring[_i]; + key.scrub(); + } + } } - tmp = []; - i = 0; - while ((tmp.length === 0) || (tmp.length * tmp[0].length * 4) < num_bytes) { - this.V = this._hmac(this.K, this.V); - tmp.push(this.V.words); + this.derived_keys = {}; + if (this.salt != null) { + this.salt.scrub(); } - this._update(); - this.reseed_counter += 1; - return (new WordArray((_ref = []).concat.apply(_ref, tmp))).truncate(num_bytes); + this.salt = null; + return this.key = null; }; - return DRBG; + return Base; })(); - ADRBG = (function() { - function ADRBG(gen_seed, hmac) { - this.gen_seed = gen_seed; - this.hmac = hmac; - this.drbg = null; - this.lock = new Lock(); + Encryptor = (function(_super) { + __extends(Encryptor, _super); + + function Encryptor(_arg) { + var key, rng, version; + key = _arg.key, rng = _arg.rng, version = _arg.version; + Encryptor.__super__.constructor.call(this, { + key: key, + version: version + }); + this.rng = rng || prng.generate; } - ADRBG.prototype.generate = function(n, cb) { - var ret, seed, ___iced_passed_deferral, __iced_deferrals, __iced_k, + Encryptor.prototype.pick_random_ivs = function(_arg, cb) { + var iv_lens, ivs, k, progress_hook, v, ___iced_passed_deferral, __iced_deferrals, __iced_k, _this = this; __iced_k = __iced_k_noop; ___iced_passed_deferral = iced.findDeferral(arguments); + progress_hook = _arg.progress_hook; + iv_lens = { + aes: AES.ivSize, + twofish: TwoFish.ivSize, + salsa20: salsa20.Salsa20.ivSize + }; + ivs = {}; (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/drbg.iced", - funcname: "ADRBG.generate" + var _i, _k, _keys, _ref1, _results, _while; + _ref1 = iv_lens; + _keys = (function() { + var _results1; + _results1 = []; + for (_k in _ref1) { + _results1.push(_k); + } + return _results1; + })(); + _i = 0; + _results = []; + _while = function(__iced_k) { + var _break, _continue, _next; + _break = function() { + return __iced_k(_results); + }; + _continue = function() { + return iced.trampoline(function() { + ++_i; + return _while(__iced_k); + }); + }; + _next = function(__iced_next_arg) { + _results.push(__iced_next_arg); + return _continue(); + }; + if (!(_i < _keys.length)) { + return _break(); + } else { + k = _keys[_i]; + v = _ref1[k]; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Encryptor.pick_random_ivs" + }); + _this.rng(v, __iced_deferrals.defer({ + assign_fn: (function(__slot_1, __slot_2) { + return function() { + return __slot_1[__slot_2] = arguments[0]; + }; + })(ivs, k), + lineno: 349 + })); + __iced_deferrals._fulfill(); + })(_next); + } + }; + _while(__iced_k); + })(function() { + return cb(ivs); + }); + }; + + Encryptor.prototype.resalt = function(_arg, cb) { + var err, extra_keymaterial, progress_hook, salt, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + salt = _arg.salt, extra_keymaterial = _arg.extra_keymaterial, progress_hook = _arg.progress_hook; + err = null; + (function(__iced_k) { + if (salt == null) { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Encryptor.resalt" + }); + _this.rng(_this.version.salt_size, __iced_deferrals.defer({ + assign_fn: (function(__slot_1) { + return function() { + return __slot_1.salt = arguments[0]; + }; + })(_this), + lineno: 365 + })); + __iced_deferrals._fulfill(); + })(__iced_k); + } else { + return __iced_k(salt.length !== _this.version.salt_size ? err = new Error("Need a salt of exactly " + _this.version.salt_size + " bytes (got " + salt.length + ")") : _this.salt = WordArray.alloc(salt)); + } + })(function() { + (function(__iced_k) { + if (err == null) { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Encryptor.resalt" + }); + _this.kdf({ + extra_keymaterial: extra_keymaterial, + progress_hook: progress_hook, + salt: _this.salt + }, __iced_deferrals.defer({ + assign_fn: (function(__slot_1) { + return function() { + err = arguments[0]; + return __slot_1.keys = arguments[1]; + }; + })(_this), + lineno: 371 + })); + __iced_deferrals._fulfill(); + })(__iced_k); + } else { + return __iced_k(); + } + })(function() { + return cb(err, _this.keys); }); - _this.lock.acquire(__iced_deferrals.defer({ - lineno: 148 - })); - __iced_deferrals._fulfill(); + }); + }; + + Encryptor.prototype.run = function(_arg, cb) { + var ct1, ct2, ct3, data, esc, extra_keymaterial, ivs, progress_hook, pt, ret, salt, sig, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + data = _arg.data, salt = _arg.salt, extra_keymaterial = _arg.extra_keymaterial, progress_hook = _arg.progress_hook; + esc = make_esc(cb, "Encryptor::run"); + (function(__iced_k) { + if ((salt != null) || (_this.salt == null)) { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Encryptor.run" + }); + _this.resalt({ + salt: salt, + extra_keymaterial: extra_keymaterial, + progress_hook: progress_hook + }, esc(__iced_deferrals.defer({ + lineno: 402 + }))); + __iced_deferrals._fulfill(); + })(__iced_k); + } else { + return __iced_k(); + } })(function() { (function(__iced_k) { - if (_this.drbg == null) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Encryptor.run" + }); + _this.pick_random_ivs({ + progress_hook: progress_hook + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return ivs = arguments[0]; + }; + })(), + lineno: 403 + })); + __iced_deferrals._fulfill(); + })(function() { + pt = WordArray.from_buffer(data); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Encryptor.run" + }); + _this.run_salsa20({ + input: pt, + key: _this.keys.salsa20, + progress_hook: progress_hook, + iv: ivs.salsa20, + output_iv: true + }, esc(__iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return ct1 = arguments[0]; + }; + })(), + lineno: 405 + }))); + __iced_deferrals._fulfill(); + })(function() { (function(__iced_k) { __iced_deferrals = new iced.Deferrals(__iced_k, { parent: ___iced_passed_deferral, - filename: "src/drbg.iced", - funcname: "ADRBG.generate" + filename: "src/enc.iced", + funcname: "Encryptor.run" }); - _this.gen_seed(256, __iced_deferrals.defer({ + _this.run_twofish({ + input: ct1, + key: _this.keys.twofish, + progress_hook: progress_hook, + iv: ivs.twofish + }, esc(__iced_deferrals.defer({ assign_fn: (function() { return function() { - return seed = arguments[0]; + return ct2 = arguments[0]; }; })(), - lineno: 150 - })); + lineno: 406 + }))); __iced_deferrals._fulfill(); })(function() { - return __iced_k(_this.drbg = new DRBG(seed, null, _this.hmac)); - }); - } else { - return __iced_k(); - } - })(function() { - (function(__iced_k) { - if (_this.drbg.reseed_counter > 100) { (function(__iced_k) { __iced_deferrals = new iced.Deferrals(__iced_k, { parent: ___iced_passed_deferral, - filename: "src/drbg.iced", - funcname: "ADRBG.generate" + filename: "src/enc.iced", + funcname: "Encryptor.run" }); - _this.gen_seed(256, __iced_deferrals.defer({ + _this.run_aes({ + input: ct2, + key: _this.keys.aes, + progress_hook: progress_hook, + iv: ivs.aes + }, esc(__iced_deferrals.defer({ assign_fn: (function() { return function() { - return seed = arguments[0]; + return ct3 = arguments[0]; }; })(), - lineno: 153 - })); + lineno: 407 + }))); __iced_deferrals._fulfill(); })(function() { - return __iced_k(_this.drbg.reseed(seed)); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "Encryptor.run" + }); + _this.sign({ + input: ct3, + key: _this.keys.hmac, + progress_hook: progress_hook, + salt: _this.salt + }, esc(__iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return sig = arguments[0]; + }; + })(), + lineno: 408 + }))); + __iced_deferrals._fulfill(); + })(function() { + ret = (new WordArray(_this.version.header)).concat(_this.salt).concat(sig).concat(ct3).to_buffer(); + util.scrub_buffer(data); + return cb(null, ret); + }); }); - } else { - return __iced_k(); - } - })(function() { - ret = _this.drbg.generate(n); - _this.lock.release(); - return cb(ret); + }); }); }); }); }; - return ADRBG; + return Encryptor; - })(); + })(Base); - exports.DRBG = DRBG; + encrypt = function(_arg, cb) { + var data, enc, err, key, progress_hook, ret, rng, version, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + key = _arg.key, data = _arg.data, rng = _arg.rng, progress_hook = _arg.progress_hook, version = _arg.version; + enc = new Encryptor({ + key: key, + rng: rng, + version: version + }); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/enc.iced", + funcname: "encrypt" + }); + enc.run({ + data: data, + progress_hook: progress_hook + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + err = arguments[0]; + return ret = arguments[1]; + }; + })(), + lineno: 436 + })); + __iced_deferrals._fulfill(); + })(function() { + enc.scrub(); + return cb(err, ret); + }); + }; - exports.ADRBG = ADRBG; + exports.V = V; + + exports.encrypt = encrypt; + + exports.Base = Base; + + exports.Encryptor = Encryptor; }).call(this); -}).call(this,require("buffer").Buffer) -},{"./combine":19,"./hmac":24,"./lock":25,"./sha3":34,"./sha512":35,"./wordarray":38,"buffer":1,"iced-coffee-script/lib/coffee-script/iced":9}],23:[function(require,module,exports){ +},{"./aes":15,"./combine":17,"./ctr":18,"./hmac":22,"./pbkdf2":25,"./prng":26,"./salsa20":27,"./scrypt":28,"./sha512":33,"./twofish":34,"./util":35,"./wordarray":36,"iced-coffee-script/lib/coffee-script/iced":3,"iced-error":4}],22:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var AES, Base, Concat, Encryptor, HMAC_SHA256, PBKDF2, SHA512, Scrypt, TwoFish, V, WordArray, XOR, ctr, encrypt, iced, make_esc, prng, salsa20, util, __iced_k, __iced_k_noop, _ref, + var HMAC, HMAC_SHA256, SHA256, SHA512, bulk_sign, iced, sign, util, __iced_k, __iced_k_noop, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; __iced_k = __iced_k_noop = function() {}; - WordArray = require('./wordarray').WordArray; + SHA512 = require('./sha512').SHA512; - salsa20 = require('./salsa20'); + SHA256 = require('./sha256').SHA256; - AES = require('./aes').AES; + util = require('./util'); - TwoFish = require('./twofish').TwoFish; + HMAC = (function() { + HMAC.outputSize = 512 / 8; - ctr = require('./ctr'); + HMAC.prototype.outputSize = HMAC.outputSize; + + function HMAC(key, klass) { + var i, _i, _ref; + if (klass == null) { + klass = SHA512; + } + this.key = key.clone(); + this.hasher = new klass(); + this.hasherBlockSize = this.hasher.blockSize; + this.hasherBlockSizeBytes = this.hasherBlockSize * 4; + if (this.key.sigBytes > this.hasherBlockSizeBytes) { + this.key = this.hasher.finalize(this.key); + } + this.key.clamp(); + this._oKey = this.key.clone(); + this._iKey = this.key.clone(); + for (i = _i = 0, _ref = this.hasherBlockSize; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + this._oKey.words[i] ^= 0x5c5c5c5c; + this._iKey.words[i] ^= 0x36363636; + } + this._oKey.sigBytes = this._iKey.sigBytes = this.hasherBlockSizeBytes; + this.reset(); + } + + HMAC.prototype.get_output_size = function() { + return this.hasher.output_size; + }; + + HMAC.prototype.reset = function() { + return this.hasher.reset().update(this._iKey); + }; + + HMAC.prototype.update = function(wa) { + this.hasher.update(wa); + return this; + }; + + HMAC.prototype.finalize = function(wa) { + var innerHash, innerHash2, out; + innerHash = this.hasher.finalize(wa); + this.hasher.reset(); + innerHash2 = this._oKey.clone().concat(innerHash); + out = this.hasher.finalize(innerHash2); + innerHash.scrub(); + innerHash2.scrub(); + return out; + }; + + HMAC.prototype.scrub = function() { + this.key.scrub(); + this._iKey.scrub(); + return this._oKey.scrub(); + }; + + return HMAC; + + })(); + + sign = function(_arg) { + var eng, hash_class, input, key, out; + key = _arg.key, input = _arg.input, hash_class = _arg.hash_class; + eng = new HMAC(key, hash_class); + out = eng.finalize(input.clamp()); + eng.scrub(); + return out; + }; + + bulk_sign = function(_arg, cb) { + var eng, input, key, klass, progress_hook, res, slice_args, what, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + key = _arg.key, input = _arg.input, progress_hook = _arg.progress_hook, klass = _arg.klass, what = _arg.what; + klass || (klass = HMAC); + what || (what = "hmac_sha512"); + eng = new klass(key); + input.clamp(); + slice_args = { + update: function(lo, hi) { + return eng.update(input.slice(lo, hi)); + }, + finalize: function() { + return eng.finalize(); + }, + default_n: eng.hasherBlockSize * 1000 + }; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/hmac.iced", + funcname: "bulk_sign" + }); + util.bulk(input.sigBytes, slice_args, { + what: what, + progress_hook: progress_hook, + cb: __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return res = arguments[0]; + }; + })(), + lineno: 137 + }) + }); + __iced_deferrals._fulfill(); + })(function() { + eng.scrub(); + return cb(res); + }); + }; + + exports.HMAC_SHA256 = HMAC_SHA256 = (function(_super) { + __extends(HMAC_SHA256, _super); + + function HMAC_SHA256(key) { + HMAC_SHA256.__super__.constructor.call(this, key, SHA256); + } - _ref = require('./combine'), XOR = _ref.XOR, Concat = _ref.Concat; + return HMAC_SHA256; - SHA512 = require('./sha512').SHA512; + })(HMAC); - PBKDF2 = require('./pbkdf2').PBKDF2; + exports.HMAC = HMAC; - Scrypt = require('./scrypt').Scrypt; + exports.sign = sign; - util = require('./util'); + exports.bulk_sign = bulk_sign; - prng = require('./prng'); +}).call(this); - make_esc = require('iced-error').make_esc; +},{"./sha256":31,"./sha512":33,"./util":35,"iced-coffee-script/lib/coffee-script/iced":3}],23:[function(require,module,exports){ +// Generated by IcedCoffeeScript 1.6.3-g +(function() { + var Lock, NamedLock, Table, iced, __iced_k, __iced_k_noop, + __hasProp = {}.hasOwnProperty, + __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - HMAC_SHA256 = require('./hmac').HMAC_SHA256; + iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; + __iced_k = __iced_k_noop = function() {}; - V = { - "1": { - header: [0x1c94d7de, 1], - salt_size: 8, - xsalsa20_rev: true, - kdf: { - klass: PBKDF2, - opts: { - c: 1024, - klass: XOR - } - }, - hmac_key_size: 768 / 8 - }, - "2": { - header: [0x1c94d7de, 2], - salt_size: 16, - xsalsa20_rev: true, - kdf: { - klass: Scrypt, - opts: { - c: 64, - klass: XOR, - N: 12, - r: 8, - p: 1 - } - }, - hmac_key_size: 768 / 8 - }, - "3": { - header: [0x1c94d7de, 3], - salt_size: 16, - xsalsa20_rev: false, - kdf: { - klass: Scrypt, - opts: { - c: 1, - klass: HMAC_SHA256, - N: 16, - r: 8, - p: 1 - } - }, - hmac_key_size: 768 / 8 + Lock = (function() { + function Lock() { + this._open = true; + this._waiters = []; } - }; - Base = (function() { - function Base(_arg) { - var key, version; - key = _arg.key, version = _arg.version; - this.version = V[version != null ? version : 1]; - if (this.version == null) { - throw new Error("unknown version: " + version); + Lock.prototype.acquire = function(cb) { + if (this._open) { + this._open = false; + return cb(); + } else { + return this._waiters.push(cb); } - this.set_key(key); - this.derived_keys = {}; - } - - Base.prototype.kdf = function(_arg, cb) { - var args, dkLen, end, extra_keymaterial, i, k, key, keys, len, lens, order, progress_hook, raw, salt, salt_hex, v, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - salt = _arg.salt, extra_keymaterial = _arg.extra_keymaterial, progress_hook = _arg.progress_hook; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.kdf" - }); - _this._check_scrubbed(_this.key, "in KDF", cb, __iced_deferrals.defer({ - lineno: 90 - })); - __iced_deferrals._fulfill(); - })(function() { - salt_hex = salt.to_hex(); - key = _this.key.clone(); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.kdf" - }); - _this._check_scrubbed(key, "KDF", cb, __iced_deferrals.defer({ - lineno: 98 - })); - __iced_deferrals._fulfill(); - })(function() { - (function(__iced_k) { - if ((keys = _this.derived_keys[salt_hex]) == null) { - _this._kdf = new _this.version.kdf.klass(_this.version.kdf.opts); - lens = { - hmac: _this.version.hmac_key_size, - aes: AES.keySize, - twofish: TwoFish.keySize, - salsa20: salsa20.Salsa20.keySize - }; - order = ['hmac', 'aes', 'twofish', 'salsa20']; - dkLen = extra_keymaterial || 0; - for (k in lens) { - v = lens[k]; - dkLen += v; - } - args = { - dkLen: dkLen, - key: key, - progress_hook: progress_hook, - salt: salt - }; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.kdf" - }); - _this._kdf.run(args, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return raw = arguments[0]; - }; - })(), - lineno: 117 - })); - __iced_deferrals._fulfill(); - })(function() { - var _i, _len; - keys = {}; - i = 0; - for (_i = 0, _len = order.length; _i < _len; _i++) { - k = order[_i]; - v = lens[k]; - len = v / 4; - end = i + len; - keys[k] = new WordArray(raw.words.slice(i, end)); - i = end; - } - keys.extra = (new WordArray(raw.words.slice(end))).to_buffer(); - return __iced_k(_this.derived_keys[salt_hex] = keys); - }); - } else { - return __iced_k(); - } - })(function() { - return cb(null, keys); - }); - }); - }); }; - Base.prototype.set_key = function(key) { - var wakey; - if (key != null) { - wakey = WordArray.from_buffer(key); - if (!this.key || !this.key.equal(wakey)) { - this.scrub(); - return this.key = wakey; - } + Lock.prototype.release = function() { + var w; + if (this._waiters.length) { + w = this._waiters.shift(); + return w(); } else { - return this.scrub(); + return this._open = true; } }; - Base.prototype._check_scrubbed = function(key, where, ecb, okcb) { - if ((key != null) && !key.is_scrubbed()) { - return okcb(); - } else { - return ecb(new Error("" + where + ": Failed due to scrubbed key!"), null); - } + Lock.prototype.open = function() { + return this._open; }; - Base.prototype.sign = function(_arg, cb) { - var input, key, out, progress_hook, salt, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - input = _arg.input, key = _arg.key, salt = _arg.salt, progress_hook = _arg.progress_hook; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.sign" - }); - _this._check_scrubbed(key, "HMAC", cb, __iced_deferrals.defer({ - lineno: 175 - })); - __iced_deferrals._fulfill(); - })(function() { - input = (new WordArray(_this.version.header)).concat(salt).concat(input); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.sign" - }); - Concat.bulk_sign({ - key: key, - input: input, - progress_hook: progress_hook - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return out = arguments[0]; - }; - })(), - lineno: 177 - })); - __iced_deferrals._fulfill(); - })(function() { - input.scrub(); - return cb(null, out); - }); - }); + return Lock; + + })(); + + NamedLock = (function(_super) { + __extends(NamedLock, _super); + + function NamedLock(tab, name) { + this.tab = tab; + this.name = name; + NamedLock.__super__.constructor.call(this); + this.refs = 0; + } + + NamedLock.prototype.incref = function() { + return ++this.refs; }; - Base.prototype.run_salsa20 = function(_arg, cb) { - var args, ct, input, iv, key, output_iv, progress_hook, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - input = _arg.input, key = _arg.key, iv = _arg.iv, output_iv = _arg.output_iv, progress_hook = _arg.progress_hook; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.run_salsa20" - }); - _this._check_scrubbed(key, "Salsa20", cb, __iced_deferrals.defer({ - lineno: 193 - })); - __iced_deferrals._fulfill(); - })(function() { - args = { - input: input, - progress_hook: progress_hook, - key: key, - iv: iv - }; - if (_this.version.xsalsa20_rev) { - args.key = key.clone().endian_reverse(); - args.iv = iv.clone().endian_reverse(); - } - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.run_salsa20" - }); - salsa20.bulk_encrypt(args, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return ct = arguments[0]; - }; - })(), - lineno: 205 - })); - __iced_deferrals._fulfill(); - })(function() { - if (output_iv) { - ct = iv.clone().concat(ct); - } - if (_this.version.xsalsa20_rev) { - args.key.scrub(); - args.iv.scrub(); - } - return cb(null, ct); - }); - }); + NamedLock.prototype.decref = function() { + return --this.refs; }; - Base.prototype.run_twofish = function(_arg, cb) { - var block_cipher, ct, input, iv, key, progress_hook, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - input = _arg.input, key = _arg.key, iv = _arg.iv, progress_hook = _arg.progress_hook; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.run_twofish" - }); - _this._check_scrubbed(key, "TwoFish", cb, __iced_deferrals.defer({ - lineno: 228 - })); - __iced_deferrals._fulfill(); - })(function() { - block_cipher = new TwoFish(key); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.run_twofish" - }); - ctr.bulk_encrypt({ - block_cipher: block_cipher, - iv: iv, - input: input, - progress_hook: progress_hook, - what: "twofish" - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return ct = arguments[0]; - }; - })(), - lineno: 230 - })); - __iced_deferrals._fulfill(); - })(function() { - block_cipher.scrub(); - return cb(null, iv.clone().concat(ct)); - }); - }); + NamedLock.prototype.release = function() { + NamedLock.__super__.release.call(this); + if (this.decref() === 0) { + return delete this.tab[this.name]; + } }; - Base.prototype.run_aes = function(_arg, cb) { - var block_cipher, ct, input, iv, key, progress_hook, ___iced_passed_deferral, __iced_deferrals, __iced_k, + return NamedLock; + + })(Lock); + + Table = (function() { + function Table() { + this.locks = {}; + } + + Table.prototype.create = function(name) { + var l; + l = new NamedLock(this, name); + return this.locks[name] = l; + }; + + Table.prototype.acquire = function(name, cb, wait) { + var l, was_open, ___iced_passed_deferral, __iced_deferrals, __iced_k, _this = this; __iced_k = __iced_k_noop; ___iced_passed_deferral = iced.findDeferral(arguments); - input = _arg.input, key = _arg.key, iv = _arg.iv, progress_hook = _arg.progress_hook; + l = this.locks[name] || this.create(name); + was_open = l._open; + l.incref(); (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.run_aes" - }); - _this._check_scrubbed(key, "AES", cb, __iced_deferrals.defer({ - lineno: 245 - })); - __iced_deferrals._fulfill(); + if (wait || l._open) { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/lock.iced", + funcname: "Table.acquire" + }); + l.acquire(__iced_deferrals.defer({ + lineno: 68 + })); + __iced_deferrals._fulfill(); + })(__iced_k); + } else { + return __iced_k(l = null); + } })(function() { - block_cipher = new AES(key); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Base.run_aes" - }); - ctr.bulk_encrypt({ - block_cipher: block_cipher, - iv: iv, - input: input, - progress_hook: progress_hook, - what: "aes" - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return ct = arguments[0]; - }; - })(), - lineno: 247 - })); - __iced_deferrals._fulfill(); - })(function() { - block_cipher.scrub(); - return cb(null, iv.clone().concat(ct)); - }); + return cb(l, was_open); }); }; - Base.prototype.scrub = function() { - var key, key_ring, salt, _i, _len, _ref1; - if (this.key != null) { - this.key.scrub(); - } - if (this.derived_keys != null) { - _ref1 = this.derived_keys; - for (salt in _ref1) { - key_ring = _ref1[salt]; - for (_i = 0, _len = key_ring.length; _i < _len; _i++) { - key = key_ring[_i]; - key.scrub(); - } - } - } - this.derived_keys = {}; - if (this.salt != null) { - this.salt.scrub(); - } - this.salt = null; - return this.key = null; + Table.prototype.lookup = function(name) { + return this.locks[name]; }; - return Base; + return Table; + + })(); + + exports.Lock = Lock; + + exports.Table = Table; + +}).call(this); + +},{"iced-coffee-script/lib/coffee-script/iced":3}],24:[function(require,module,exports){ +(function (Buffer){ +// Generated by IcedCoffeeScript 1.6.3-g +(function() { + var k, v, _ref, _ref1; + + + + _ref = require('./enc'); + for (k in _ref) { + v = _ref[k]; + exports[k] = v; + } + + _ref1 = require('./dec'); + for (k in _ref1) { + v = _ref1[k]; + exports[k] = v; + } + + exports.prng = require('./prng'); + + exports.Buffer = Buffer; + + exports.WordArray = require('./wordarray').WordArray; + + exports.util = require('./util'); + + exports.ciphers = { + AES: require('./aes').AES, + TwoFish: require('./twofish').TwoFish + }; + + exports.hash = { + SHA1: require('./sha1').SHA1, + SHA224: require('./sha224').SHA224, + SHA256: require('./sha256').SHA256, + SHA512: require('./sha512').SHA512, + SHA3: require('./sha3').SHA3 + }; + + exports.scrypt = require('./scrypt').scrypt; + + exports.pbkdf2 = require('./pbkdf2').pbkdf2; - })(); + exports.HMAC_SHA256 = require('./hmac').HMAC_SHA256; - Encryptor = (function(_super) { - __extends(Encryptor, _super); +}).call(this); - function Encryptor(_arg) { - var key, rng, version; - key = _arg.key, rng = _arg.rng, version = _arg.version; - Encryptor.__super__.constructor.call(this, { - key: key, - version: version - }); - this.rng = rng || prng.generate; +}).call(this,require("buffer").Buffer) +},{"./aes":15,"./dec":19,"./enc":21,"./hmac":22,"./pbkdf2":25,"./prng":26,"./scrypt":28,"./sha1":29,"./sha224":30,"./sha256":31,"./sha3":32,"./sha512":33,"./twofish":34,"./util":35,"./wordarray":36,"buffer":2}],25:[function(require,module,exports){ +// Generated by IcedCoffeeScript 1.6.3-g +(function() { + var HMAC, PBKDF2, WordArray, iced, pbkdf2, util, __iced_k, __iced_k_noop; + + iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; + __iced_k = __iced_k_noop = function() {}; + + HMAC = require('./hmac').HMAC; + + WordArray = require('./wordarray').WordArray; + + util = require('./util'); + + PBKDF2 = (function() { + function PBKDF2(_arg) { + this.klass = _arg.klass, this.c = _arg.c; + this.c || (this.c = 1024); + this.klass || (this.klass = HMAC); } - Encryptor.prototype.pick_random_ivs = function(_arg, cb) { - var iv_lens, ivs, k, progress_hook, v, ___iced_passed_deferral, __iced_deferrals, __iced_k, + PBKDF2.prototype._PRF = function(input) { + this.prf.reset(); + return this.prf.finalize(input); + }; + + PBKDF2.prototype._gen_T_i = function(_arg, cb) { + var U, i, progress_hook, ret, salt, seed, stop, ___iced_passed_deferral, __iced_deferrals, __iced_k, _this = this; __iced_k = __iced_k_noop; ___iced_passed_deferral = iced.findDeferral(arguments); - progress_hook = _arg.progress_hook; - iv_lens = { - aes: AES.ivSize, - twofish: TwoFish.ivSize, - salsa20: salsa20.Salsa20.ivSize - }; - ivs = {}; + salt = _arg.salt, i = _arg.i, progress_hook = _arg.progress_hook; + progress_hook(0); + seed = salt.clone().concat(new WordArray([i])); + U = this._PRF(seed); + ret = U.clone(); + i = 1; (function(__iced_k) { - var _i, _k, _keys, _ref1, _results, _while; - _ref1 = iv_lens; - _keys = (function() { - var _results1; - _results1 = []; - for (_k in _ref1) { - _results1.push(_k); - } - return _results1; - })(); - _i = 0; + var _results, _while; _results = []; _while = function(__iced_k) { var _break, _continue, _next; @@ -7957,7 +8558,6 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit }; _continue = function() { return iced.trampoline(function() { - ++_i; return _while(__iced_k); }); }; @@ -7965,725 +8565,861 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit _results.push(__iced_next_arg); return _continue(); }; - if (!(_i < _keys.length)) { + if (!(i < _this.c)) { return _break(); } else { - k = _keys[_i]; - v = _ref1[k]; + stop = Math.min(_this.c, i + 128); + while (i < stop) { + U = _this._PRF(U); + ret.xor(U, {}); + i++; + } + progress_hook(i); (function(__iced_k) { __iced_deferrals = new iced.Deferrals(__iced_k, { parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.pick_random_ivs" + filename: "src/pbkdf2.iced", + funcname: "PBKDF2._gen_T_i" }); - _this.rng(v, __iced_deferrals.defer({ - assign_fn: (function(__slot_1, __slot_2) { - return function() { - return __slot_1[__slot_2] = arguments[0]; - }; - })(ivs, k), - lineno: 349 + util.default_delay(0, 0, __iced_deferrals.defer({ + lineno: 57 })); __iced_deferrals._fulfill(); - })(_next); + })(function() { + return _next(null); + }); } }; _while(__iced_k); })(function() { - return cb(ivs); - }); - }; - - Encryptor.prototype.resalt = function(_arg, cb) { - var err, extra_keymaterial, progress_hook, salt, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - salt = _arg.salt, extra_keymaterial = _arg.extra_keymaterial, progress_hook = _arg.progress_hook; - err = null; - (function(__iced_k) { - if (salt == null) { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.resalt" - }); - _this.rng(_this.version.salt_size, __iced_deferrals.defer({ - assign_fn: (function(__slot_1) { - return function() { - return __slot_1.salt = arguments[0]; - }; - })(_this), - lineno: 365 - })); - __iced_deferrals._fulfill(); - })(__iced_k); - } else { - return __iced_k(salt.length !== _this.version.salt_size ? err = new Error("Need a salt of exactly " + _this.version.salt_size + " bytes (got " + salt.length + ")") : _this.salt = WordArray.alloc(salt)); - } - })(function() { - (function(__iced_k) { - if (err == null) { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.resalt" - }); - _this.kdf({ - extra_keymaterial: extra_keymaterial, - progress_hook: progress_hook, - salt: _this.salt - }, __iced_deferrals.defer({ - assign_fn: (function(__slot_1) { - return function() { - err = arguments[0]; - return __slot_1.keys = arguments[1]; - }; - })(_this), - lineno: 371 - })); - __iced_deferrals._fulfill(); - })(__iced_k); - } else { - return __iced_k(); - } - })(function() { - return cb(err, _this.keys); - }); + progress_hook(i); + return cb(ret); }); }; - Encryptor.prototype.run = function(_arg, cb) { - var ct1, ct2, ct3, data, esc, extra_keymaterial, ivs, progress_hook, pt, ret, salt, sig, ___iced_passed_deferral, __iced_deferrals, __iced_k, + PBKDF2.prototype.run = function(_arg, cb) { + var bs, dkLen, flat, i, key, n, ph, progress_hook, salt, tmp, tph, words, ___iced_passed_deferral, __iced_deferrals, __iced_k, _this = this; __iced_k = __iced_k_noop; ___iced_passed_deferral = iced.findDeferral(arguments); - data = _arg.data, salt = _arg.salt, extra_keymaterial = _arg.extra_keymaterial, progress_hook = _arg.progress_hook; - esc = make_esc(cb, "Encryptor::run"); + key = _arg.key, salt = _arg.salt, dkLen = _arg.dkLen, progress_hook = _arg.progress_hook; + this.prf = new this.klass(key); + bs = this.prf.get_output_size(); + n = Math.ceil(dkLen / bs); + words = []; + tph = null; + ph = function(block) { + return function(iter) { + return typeof progress_hook === "function" ? progress_hook({ + what: "pbkdf2", + total: n * _this.c, + i: block * _this.c + iter + }) : void 0; + }; + }; + ph(0)(0); (function(__iced_k) { - if ((salt != null) || (_this.salt == null)) { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.run" - }); - _this.resalt({ - salt: salt, - extra_keymaterial: extra_keymaterial, - progress_hook: progress_hook - }, esc(__iced_deferrals.defer({ - lineno: 402 - }))); - __iced_deferrals._fulfill(); - })(__iced_k); - } else { - return __iced_k(); - } - })(function() { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.run" - }); - _this.pick_random_ivs({ - progress_hook: progress_hook - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return ivs = arguments[0]; - }; - })(), - lineno: 403 - })); - __iced_deferrals._fulfill(); - })(function() { - pt = WordArray.from_buffer(data); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.run" + var _i, _results, _while; + i = 1; + _results = []; + _while = function(__iced_k) { + var _break, _continue, _next; + _break = function() { + return __iced_k(_results); + }; + _continue = function() { + return iced.trampoline(function() { + ++i; + return _while(__iced_k); }); - _this.run_salsa20({ - input: pt, - key: _this.keys.salsa20, - progress_hook: progress_hook, - iv: ivs.salsa20, - output_iv: true - }, esc(__iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return ct1 = arguments[0]; - }; - })(), - lineno: 405 - }))); - __iced_deferrals._fulfill(); - })(function() { + }; + _next = function(__iced_next_arg) { + _results.push(__iced_next_arg); + return _continue(); + }; + if (!(i <= n)) { + return _break(); + } else { + (function(__iced_k) { __iced_deferrals = new iced.Deferrals(__iced_k, { parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.run" + filename: "src/pbkdf2.iced", + funcname: "PBKDF2.run" }); - _this.run_twofish({ - input: ct1, - key: _this.keys.twofish, - progress_hook: progress_hook, - iv: ivs.twofish - }, esc(__iced_deferrals.defer({ + _this._gen_T_i({ + salt: salt, + i: i, + progress_hook: ph(i - 1) + }, __iced_deferrals.defer({ assign_fn: (function() { return function() { - return ct2 = arguments[0]; + return tmp = arguments[0]; }; })(), - lineno: 406 - }))); + lineno: 80 + })); __iced_deferrals._fulfill(); })(function() { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.run" - }); - _this.run_aes({ - input: ct2, - key: _this.keys.aes, - progress_hook: progress_hook, - iv: ivs.aes - }, esc(__iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return ct3 = arguments[0]; - }; - })(), - lineno: 407 - }))); - __iced_deferrals._fulfill(); - })(function() { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "Encryptor.run" - }); - _this.sign({ - input: ct3, - key: _this.keys.hmac, - progress_hook: progress_hook, - salt: _this.salt - }, esc(__iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return sig = arguments[0]; - }; - })(), - lineno: 408 - }))); - __iced_deferrals._fulfill(); - })(function() { - ret = (new WordArray(_this.version.header)).concat(_this.salt).concat(sig).concat(ct3).to_buffer(); - util.scrub_buffer(data); - return cb(null, ret); - }); - }); + return _next(words.push(tmp.words)); }); - }); - }); + } + }; + _while(__iced_k); + })(function() { + var _ref; + ph(n)(0); + flat = (_ref = []).concat.apply(_ref, words); + key.scrub(); + _this.prf.scrub(); + _this.prf = null; + return cb(new WordArray(flat, dkLen)); }); }; - return Encryptor; + return PBKDF2; - })(Base); + })(); - encrypt = function(_arg, cb) { - var data, enc, err, key, progress_hook, ret, rng, version, ___iced_passed_deferral, __iced_deferrals, __iced_k, + pbkdf2 = function(_arg, cb) { + var c, dkLen, eng, key, klass, out, progress_hook, salt, ___iced_passed_deferral, __iced_deferrals, __iced_k, _this = this; __iced_k = __iced_k_noop; ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, data = _arg.data, rng = _arg.rng, progress_hook = _arg.progress_hook, version = _arg.version; - enc = new Encryptor({ - key: key, - rng: rng, - version: version + key = _arg.key, salt = _arg.salt, klass = _arg.klass, c = _arg.c, dkLen = _arg.dkLen, progress_hook = _arg.progress_hook; + eng = new PBKDF2({ + klass: klass, + c: c }); (function(__iced_k) { __iced_deferrals = new iced.Deferrals(__iced_k, { parent: ___iced_passed_deferral, - filename: "src/enc.iced", - funcname: "encrypt" + filename: "src/pbkdf2.iced", + funcname: "pbkdf2" }); - enc.run({ - data: data, + eng.run({ + key: key, + salt: salt, + dkLen: dkLen, progress_hook: progress_hook }, __iced_deferrals.defer({ assign_fn: (function() { return function() { - err = arguments[0]; - return ret = arguments[1]; + return out = arguments[0]; }; })(), - lineno: 436 + lineno: 106 })); __iced_deferrals._fulfill(); })(function() { - enc.scrub(); - return cb(err, ret); + return cb(out); }); }; - exports.V = V; - - exports.encrypt = encrypt; - - exports.Base = Base; + exports.pbkdf2 = pbkdf2; - exports.Encryptor = Encryptor; + exports.PBKDF2 = PBKDF2; }).call(this); -},{"./aes":17,"./combine":19,"./ctr":20,"./hmac":24,"./pbkdf2":27,"./prng":28,"./salsa20":29,"./scrypt":30,"./sha512":35,"./twofish":36,"./util":37,"./wordarray":38,"iced-coffee-script/lib/coffee-script/iced":9,"iced-error":10}],24:[function(require,module,exports){ +},{"./hmac":22,"./util":35,"./wordarray":36,"iced-coffee-script/lib/coffee-script/iced":3}],26:[function(require,module,exports){ +(function (Buffer){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var HMAC, HMAC_SHA256, SHA256, SHA512, bulk_sign, iced, sign, util, __iced_k, __iced_k_noop, - __hasProp = {}.hasOwnProperty, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; + var ADRBG, PRNG, WordArray, XOR, browser_rng, e, generate, iced, more_entropy, native_rng, rng, util, __iced_k, __iced_k_noop, _native_rng, _prng, _ref; iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; __iced_k = __iced_k_noop = function() {}; - SHA512 = require('./sha512').SHA512; + more_entropy = require('more-entropy'); - SHA256 = require('./sha256').SHA256; + ADRBG = require('./drbg').ADRBG; - util = require('./util'); + WordArray = require('./wordarray').WordArray; - HMAC = (function() { - HMAC.outputSize = 512 / 8; + XOR = require('./combine').XOR; - HMAC.prototype.outputSize = HMAC.outputSize; + util = require('./util'); - function HMAC(key, klass) { - var i, _i, _ref; - if (klass == null) { - klass = SHA512; - } - this.key = key.clone(); - this.hasher = new klass(); - this.hasherBlockSize = this.hasher.blockSize; - this.hasherBlockSizeBytes = this.hasherBlockSize * 4; - if (this.key.sigBytes > this.hasherBlockSizeBytes) { - this.key = this.hasher.finalize(this.key); - } - this.key.clamp(); - this._oKey = this.key.clone(); - this._iKey = this.key.clone(); - for (i = _i = 0, _ref = this.hasherBlockSize; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { - this._oKey.words[i] ^= 0x5c5c5c5c; - this._iKey.words[i] ^= 0x36363636; + browser_rng = function(n) { + var v; + v = new Uint8Array(n); + window.crypto.getRandomValues(v); + return new Buffer(v); + }; + + if ((typeof window !== "undefined" && window !== null ? (_ref = window.crypto) != null ? _ref.getRandomValues : void 0 : void 0) != null) { + _native_rng = browser_rng; + } else { + try { + rng = require('cry' + 'pto').rng; + if (rng != null) { + _native_rng = rng; } - this._oKey.sigBytes = this._iKey.sigBytes = this.hasherBlockSizeBytes; - this.reset(); + } catch (_error) { + e = _error; } + } - HMAC.prototype.get_output_size = function() { - return this.hasher.output_size; - }; - - HMAC.prototype.reset = function() { - return this.hasher.reset().update(this._iKey); - }; - - HMAC.prototype.update = function(wa) { - this.hasher.update(wa); - return this; - }; - - HMAC.prototype.finalize = function(wa) { - var innerHash, innerHash2, out; - innerHash = this.hasher.finalize(wa); - this.hasher.reset(); - innerHash2 = this._oKey.clone().concat(innerHash); - out = this.hasher.finalize(innerHash2); - innerHash.scrub(); - innerHash2.scrub(); - return out; - }; - - HMAC.prototype.scrub = function() { - this.key.scrub(); - this._iKey.scrub(); - return this._oKey.scrub(); - }; - - return HMAC; - - })(); - - sign = function(_arg) { - var eng, hash_class, input, key, out; - key = _arg.key, input = _arg.input, hash_class = _arg.hash_class; - eng = new HMAC(key, hash_class); - out = eng.finalize(input.clamp()); - eng.scrub(); - return out; + native_rng = function(x) { + if (_native_rng == null) { + throw new Error('No rng found; tried requiring "crypto" and window.crypto'); + } + return _native_rng(x); }; - bulk_sign = function(_arg, cb) { - var eng, input, key, klass, progress_hook, res, slice_args, what, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, input = _arg.input, progress_hook = _arg.progress_hook, klass = _arg.klass, what = _arg.what; - klass || (klass = HMAC); - what || (what = "hmac_sha512"); - eng = new klass(key); - input.clamp(); - slice_args = { - update: function(lo, hi) { - return eng.update(input.slice(lo, hi)); - }, - finalize: function() { - return eng.finalize(); - }, - default_n: eng.hasherBlockSize * 1000 + PRNG = (function() { + function PRNG() { + var _this = this; + this.meg = new more_entropy.Generator(); + this.adrbg = new ADRBG((function(n, cb) { + return _this.gen_seed(n, cb); + }), XOR.sign); + } + + PRNG.prototype.now_to_buffer = function() { + var buf, d, ms, s; + d = Date.now(); + ms = d % 1000; + s = Math.floor(d / 1000); + buf = new Buffer(8); + buf.writeUInt32BE(s, 0); + buf.writeUInt32BE(ms, 4); + return buf; }; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/hmac.iced", - funcname: "bulk_sign" - }); - util.bulk(input.sigBytes, slice_args, { - what: what, - progress_hook: progress_hook, - cb: __iced_deferrals.defer({ + + PRNG.prototype.gen_seed = function(nbits, cb) { + var b, bufs, cat, nbytes, wa, words, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + nbytes = nbits / 8; + bufs = []; + bufs.push(this.now_to_buffer()); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/prng.iced", + funcname: "PRNG.gen_seed" + }); + _this.meg.generate(nbits, __iced_deferrals.defer({ assign_fn: (function() { return function() { - return res = arguments[0]; + return words = arguments[0]; }; })(), - lineno: 137 - }) + lineno: 76 + })); + __iced_deferrals._fulfill(); + })(function() { + var _i, _len; + bufs.push(_this.now_to_buffer()); + bufs.push(new Buffer(words)); + bufs.push(native_rng(nbytes)); + bufs.push(_this.now_to_buffer()); + cat = Buffer.concat(bufs); + wa = WordArray.from_buffer(cat); + util.scrub_buffer(cat); + for (_i = 0, _len = bufs.length; _i < _len; _i++) { + b = bufs[_i]; + util.scrub_buffer(b); + } + return cb(wa); }); - __iced_deferrals._fulfill(); - })(function() { - eng.scrub(); - return cb(res); - }); - }; + }; - exports.HMAC_SHA256 = HMAC_SHA256 = (function(_super) { - __extends(HMAC_SHA256, _super); + PRNG.prototype.generate = function(n, cb) { + return this.adrbg.generate(n, cb); + }; - function HMAC_SHA256(key) { - HMAC_SHA256.__super__.constructor.call(this, key, SHA256); - } + return PRNG; - return HMAC_SHA256; + })(); - })(HMAC); + _prng = null; - exports.HMAC = HMAC; + generate = function(n, cb) { + if (_prng == null) { + _prng = new PRNG(); + } + return _prng.generate(n, cb); + }; - exports.sign = sign; + exports.PRNG = PRNG; - exports.bulk_sign = bulk_sign; + exports.generate = generate; + + exports.native_rng = native_rng; }).call(this); -},{"./sha256":33,"./sha512":35,"./util":37,"iced-coffee-script/lib/coffee-script/iced":9}],25:[function(require,module,exports){ +}).call(this,require("buffer").Buffer) +},{"./combine":17,"./drbg":20,"./util":35,"./wordarray":36,"buffer":2,"iced-coffee-script/lib/coffee-script/iced":3,"more-entropy":13}],27:[function(require,module,exports){ +(function (Buffer){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var Lock, NamedLock, Table, iced, __iced_k, __iced_k_noop, + var Cipher, Counter, Salsa20, Salsa20Core, Salsa20InnerCore, Salsa20WordStream, StreamCipher, WordArray, asum, bulk_encrypt, encrypt, endian_reverse, fixup_uint32, iced, util, __iced_k, __iced_k_noop, _ref, _ref1, _ref2, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; __iced_k = __iced_k_noop = function() {}; - Lock = (function() { - function Lock() { - this._open = true; - this._waiters = []; + _ref = require('./wordarray'), endian_reverse = _ref.endian_reverse, WordArray = _ref.WordArray; + + Counter = require('./ctr').Counter; + + fixup_uint32 = require('./util').fixup_uint32; + + StreamCipher = require('./algbase').StreamCipher; + + util = require('./util'); + + asum = function(out, v) { + var e, i, _i, _len; + for (i = _i = 0, _len = v.length; _i < _len; i = ++_i) { + e = v[i]; + out[i] += e; + } + return false; + }; + + Salsa20InnerCore = (function() { + function Salsa20InnerCore(rounds) { + this.rounds = rounds; + } + + Salsa20InnerCore.prototype._core = function(v) { + "use asm"; + var i, u, x0, x1, x10, x11, x12, x13, x14, x15, x2, x3, x4, x5, x6, x7, x8, x9, _i, _ref1; + x0 = v[0], x1 = v[1], x2 = v[2], x3 = v[3], x4 = v[4], x5 = v[5], x6 = v[6], x7 = v[7], x8 = v[8], x9 = v[9], x10 = v[10], x11 = v[11], x12 = v[12], x13 = v[13], x14 = v[14], x15 = v[15]; + for (i = _i = 0, _ref1 = this.rounds; _i < _ref1; i = _i += 2) { + u = (x0 + x12) | 0; + x4 ^= (u << 7) | (u >>> 25); + u = (x4 + x0) | 0; + x8 ^= (u << 9) | (u >>> 23); + u = (x8 + x4) | 0; + x12 ^= (u << 13) | (u >>> 19); + u = (x12 + x8) | 0; + x0 ^= (u << 18) | (u >>> 14); + u = (x5 + x1) | 0; + x9 ^= (u << 7) | (u >>> 25); + u = (x9 + x5) | 0; + x13 ^= (u << 9) | (u >>> 23); + u = (x13 + x9) | 0; + x1 ^= (u << 13) | (u >>> 19); + u = (x1 + x13) | 0; + x5 ^= (u << 18) | (u >>> 14); + u = (x10 + x6) | 0; + x14 ^= (u << 7) | (u >>> 25); + u = (x14 + x10) | 0; + x2 ^= (u << 9) | (u >>> 23); + u = (x2 + x14) | 0; + x6 ^= (u << 13) | (u >>> 19); + u = (x6 + x2) | 0; + x10 ^= (u << 18) | (u >>> 14); + u = (x15 + x11) | 0; + x3 ^= (u << 7) | (u >>> 25); + u = (x3 + x15) | 0; + x7 ^= (u << 9) | (u >>> 23); + u = (x7 + x3) | 0; + x11 ^= (u << 13) | (u >>> 19); + u = (x11 + x7) | 0; + x15 ^= (u << 18) | (u >>> 14); + u = (x0 + x3) | 0; + x1 ^= (u << 7) | (u >>> 25); + u = (x1 + x0) | 0; + x2 ^= (u << 9) | (u >>> 23); + u = (x2 + x1) | 0; + x3 ^= (u << 13) | (u >>> 19); + u = (x3 + x2) | 0; + x0 ^= (u << 18) | (u >>> 14); + u = (x5 + x4) | 0; + x6 ^= (u << 7) | (u >>> 25); + u = (x6 + x5) | 0; + x7 ^= (u << 9) | (u >>> 23); + u = (x7 + x6) | 0; + x4 ^= (u << 13) | (u >>> 19); + u = (x4 + x7) | 0; + x5 ^= (u << 18) | (u >>> 14); + u = (x10 + x9) | 0; + x11 ^= (u << 7) | (u >>> 25); + u = (x11 + x10) | 0; + x8 ^= (u << 9) | (u >>> 23); + u = (x8 + x11) | 0; + x9 ^= (u << 13) | (u >>> 19); + u = (x9 + x8) | 0; + x10 ^= (u << 18) | (u >>> 14); + u = (x15 + x14) | 0; + x12 ^= (u << 7) | (u >>> 25); + u = (x12 + x15) | 0; + x13 ^= (u << 9) | (u >>> 23); + u = (x13 + x12) | 0; + x14 ^= (u << 13) | (u >>> 19); + u = (x14 + x13) | 0; + x15 ^= (u << 18) | (u >>> 14); + } + return [x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15]; + }; + + return Salsa20InnerCore; + + })(); + + Salsa20Core = (function(_super) { + __extends(Salsa20Core, _super); + + Salsa20Core.prototype.sigma = WordArray.from_buffer_le(new Buffer("expand 32-byte k")); + + Salsa20Core.prototype.tau = WordArray.from_buffer_le(new Buffer("expand 16-byte k")); + + Salsa20Core.blockSize = 64; + + Salsa20Core.prototype.blockSize = Salsa20Core.blockSize; + + Salsa20Core.keySize = 32; + + Salsa20Core.prototype.keySize = Salsa20Core.keySize; + + Salsa20Core.ivSize = 192 / 8; + + Salsa20Core.prototype.ivSize = Salsa20Core.ivSize; + + function Salsa20Core(key, nonce) { + var _ref1; + Salsa20Core.__super__.constructor.call(this, 20); + this.key = key.clone().endian_reverse(); + this.nonce = nonce.clone().endian_reverse(); + if (!(((this.key.sigBytes === 16) && (this.nonce.sigBytes === 8)) || ((this.key.sigBytes === 32) && ((_ref1 = this.nonce.sigBytes) === 8 || _ref1 === 24)))) { + throw new Error("Bad key/nonce lengths"); + } + if (this.nonce.sigBytes === 24) { + this.xsalsa_setup(); + } + this.input = this.key_iv_setup(this.nonce, this.key); + this._reset(); } - Lock.prototype.acquire = function(cb) { - if (this._open) { - this._open = false; - return cb(); - } else { - return this._waiters.push(cb); + Salsa20Core.prototype.scrub = function() { + this.key.scrub(); + this.nonce.scrub(); + return util.scrub_vec(this.input); + }; + + Salsa20Core.prototype.xsalsa_setup = function() { + var n0, n1; + n0 = new WordArray(this.nonce.words.slice(0, 4)); + this.nonce = n1 = new WordArray(this.nonce.words.slice(4)); + return this.key = this.hsalsa20(n0, this.key); + }; + + Salsa20Core.prototype.hsalsa20 = function(nonce, key) { + var i, indexes, input, v; + input = this.key_iv_setup(nonce, key); + input[8] = nonce.words[2]; + input[9] = nonce.words[3]; + v = this._core(input); + indexes = [0, 5, 10, 15, 6, 7, 8, 9]; + v = (function() { + var _i, _len, _results; + _results = []; + for (_i = 0, _len = indexes.length; _i < _len; _i++) { + i = indexes[_i]; + _results.push(fixup_uint32(v[i])); + } + return _results; + })(); + util.scrub_vec(input); + return new WordArray(v); + }; + + Salsa20Core.prototype.key_iv_setup = function(nonce, key) { + var A, C, i, out, _i, _j, _k, _ref1; + out = []; + for (i = _i = 0; _i < 4; i = ++_i) { + out[i + 1] = key.words[i]; + } + _ref1 = key.sigBytes === 32 ? [this.sigma, key.words.slice(4)] : [this.tau, key.words], C = _ref1[0], A = _ref1[1]; + for (i = _j = 0; _j < 4; i = ++_j) { + out[i + 11] = A[i]; + } + for (i = _k = 0; _k < 4; i = ++_k) { + out[i * 5] = C.words[i]; } + out[6] = nonce.words[0]; + out[7] = nonce.words[1]; + return out; }; - Lock.prototype.release = function() { - var w; - if (this._waiters.length) { - w = this._waiters.shift(); - return w(); - } else { - return this._open = true; - } + Salsa20Core.prototype.counter_setup = function() { + this.input[8] = this.counter.get().words[0]; + return this.input[9] = this.counter.get().words[1]; }; - Lock.prototype.open = function() { - return this._open; + Salsa20Core.prototype._reset = function() { + return this.counter = new Counter({ + len: 2 + }); }; - return Lock; + Salsa20Core.prototype._generateBlock = function() { + var v; + this.counter_setup(); + v = this._core(this.input); + asum(v, this.input); + this.counter.inc_le(); + return v; + }; - })(); + return Salsa20Core; - NamedLock = (function(_super) { - __extends(NamedLock, _super); + })(Salsa20InnerCore); - function NamedLock(tab, name) { - this.tab = tab; - this.name = name; - NamedLock.__super__.constructor.call(this); - this.refs = 0; - } + exports.Salsa20WordStream = Salsa20WordStream = (function(_super) { + __extends(Salsa20WordStream, _super); - NamedLock.prototype.incref = function() { - return ++this.refs; - }; + function Salsa20WordStream() { + _ref1 = Salsa20WordStream.__super__.constructor.apply(this, arguments); + return _ref1; + } - NamedLock.prototype.decref = function() { - return --this.refs; + Salsa20WordStream.prototype._reset = function() { + return Salsa20WordStream.__super__._reset.call(this); }; - NamedLock.prototype.release = function() { - NamedLock.__super__.release.call(this); - if (this.decref() === 0) { - return delete this.tab[this.name]; + Salsa20WordStream.prototype.getWordArray = function(nbytes) { + var blocks, i, nblocks, w, words, _i, _len, _ref2; + if ((nbytes == null) || nbytes === this.blockSize) { + words = this._generateBlock(); + } else { + nblocks = Math.ceil(nbytes / this.blockSize); + blocks = (function() { + var _i, _results; + _results = []; + for (i = _i = 0; 0 <= nblocks ? _i < nblocks : _i > nblocks; i = 0 <= nblocks ? ++_i : --_i) { + _results.push(this._generateBlock()); + } + return _results; + }).call(this); + words = (_ref2 = []).concat.apply(_ref2, blocks); + } + for (i = _i = 0, _len = words.length; _i < _len; i = ++_i) { + w = words[i]; + words[i] = endian_reverse(w); } + return new WordArray(words, nbytes); }; - return NamedLock; + return Salsa20WordStream; - })(Lock); + })(Salsa20Core); - Table = (function() { - function Table() { - this.locks = {}; + exports.Salsa20 = Salsa20 = (function(_super) { + __extends(Salsa20, _super); + + function Salsa20() { + _ref2 = Salsa20.__super__.constructor.apply(this, arguments); + return _ref2; } - Table.prototype.create = function(name) { - var l; - l = new NamedLock(this, name); - return this.locks[name] = l; + Salsa20.prototype._reset = function() { + Salsa20.__super__._reset.call(this); + return this._i = this.blockSize; }; - Table.prototype.acquire = function(name, cb, wait) { - var l, was_open, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - l = this.locks[name] || this.create(name); - was_open = l._open; - l.incref(); - (function(__iced_k) { - if (wait || l._open) { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/lock.iced", - funcname: "Table.acquire" - }); - l.acquire(__iced_deferrals.defer({ - lineno: 68 - })); - __iced_deferrals._fulfill(); - })(__iced_k); - } else { - return __iced_k(l = null); + Salsa20.prototype.getBytes = function(needed) { + var bsz, n, v; + if (needed == null) { + needed = this.blockSize; + } + v = []; + bsz = this.blockSize; + if ((this._i === bsz) && (needed === bsz)) { + return this._generateBlockBuffer(); + } else { + while (needed > 0) { + if (this._i === bsz) { + this._generateBlockBuffer(); + this._i = 0; + } + n = Math.min(needed, bsz - this._i); + v.push((n === bsz ? this._buf : this._buf.slice(this._i, this._i + n))); + this._i += n; + needed -= n; } - })(function() { - return cb(l, was_open); - }); + return Buffer.concat(v); + } }; - Table.prototype.lookup = function(name) { - return this.locks[name]; + Salsa20.prototype._generateBlockBuffer = function() { + var e, i, v, _i, _len; + this._buf = new Buffer(this.blockSize); + v = this._generateBlock(); + for (i = _i = 0, _len = v.length; _i < _len; i = ++_i) { + e = v[i]; + this._buf.writeUInt32LE(fixup_uint32(e), i * 4); + } + return this._buf; }; - return Table; - - })(); - - exports.Lock = Lock; - - exports.Table = Table; - -}).call(this); - -},{"iced-coffee-script/lib/coffee-script/iced":9}],26:[function(require,module,exports){ -(function (Buffer){ -// Generated by IcedCoffeeScript 1.6.3-g -(function() { - var k, v, _ref, _ref1; - + return Salsa20; + })(Salsa20Core); - _ref = require('./enc'); - for (k in _ref) { - v = _ref[k]; - exports[k] = v; - } + exports.Cipher = Cipher = (function(_super) { + __extends(Cipher, _super); - _ref1 = require('./dec'); - for (k in _ref1) { - v = _ref1[k]; - exports[k] = v; - } + function Cipher(_arg) { + var iv, key; + key = _arg.key, iv = _arg.iv; + Cipher.__super__.constructor.call(this); + this.salsa = new Salsa20WordStream(key, iv); + this.bsiw = this.salsa.blockSize / 4; + } - exports.prng = require('./prng'); + Cipher.prototype.scrub = function() { + return this.salsa.scrub(); + }; - exports.Buffer = Buffer; + Cipher.prototype.get_pad = function() { + var pad; + pad = this.salsa.getWordArray(); + return pad; + }; - exports.WordArray = require('./wordarray').WordArray; + return Cipher; - exports.util = require('./util'); + })(StreamCipher); - exports.ciphers = { - AES: require('./aes').AES, - TwoFish: require('./twofish').TwoFish + exports.encrypt = encrypt = function(_arg) { + var cipher, input, iv, key, ret; + key = _arg.key, iv = _arg.iv, input = _arg.input; + cipher = new Cipher({ + key: key, + iv: iv + }); + ret = cipher.encrypt(input); + cipher.scrub(); + return ret; }; - exports.hash = { - SHA1: require('./sha1').SHA1, - SHA224: require('./sha224').SHA224, - SHA256: require('./sha256').SHA256, - SHA512: require('./sha512').SHA512, - SHA3: require('./sha3').SHA3 + exports.bulk_encrypt = bulk_encrypt = function(_arg, cb) { + var cipher, input, iv, key, progress_hook, ret, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + key = _arg.key, iv = _arg.iv, input = _arg.input, progress_hook = _arg.progress_hook; + cipher = new Cipher({ + key: key, + iv: iv + }); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/salsa20.iced", + funcname: "bulk_encrypt" + }); + cipher.bulk_encrypt({ + input: input, + progress_hook: progress_hook, + what: "salsa20" + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return ret = arguments[0]; + }; + })(), + lineno: 257 + })); + __iced_deferrals._fulfill(); + })(function() { + cipher.scrub(); + return cb(ret); + }); }; - exports.scrypt = require('./scrypt').scrypt; + exports.Salsa20InnerCore = Salsa20InnerCore; - exports.pbkdf2 = require('./pbkdf2').pbkdf2; + exports.endian_reverse = endian_reverse; - exports.HMAC_SHA256 = require('./hmac').HMAC_SHA256; + exports.asum = asum; }).call(this); }).call(this,require("buffer").Buffer) -},{"./aes":17,"./dec":21,"./enc":23,"./hmac":24,"./pbkdf2":27,"./prng":28,"./scrypt":30,"./sha1":31,"./sha224":32,"./sha256":33,"./sha3":34,"./sha512":35,"./twofish":36,"./util":37,"./wordarray":38,"buffer":1}],27:[function(require,module,exports){ +},{"./algbase":16,"./ctr":18,"./util":35,"./wordarray":36,"buffer":2,"iced-coffee-script/lib/coffee-script/iced":3}],28:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var HMAC, PBKDF2, WordArray, iced, pbkdf2, util, __iced_k, __iced_k_noop; + var HMAC_SHA256, Salsa20InnerCore, Scrypt, WordArray, blkcpy, blkxor, default_delay, endian_reverse, fixup_uint32, iced, pbkdf2, scrub_vec, scrypt, ui8a_to_buffer, v_endian_reverse, __iced_k, __iced_k_noop, _ref, _ref1, _ref2; iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; __iced_k = __iced_k_noop = function() {}; - HMAC = require('./hmac').HMAC; + HMAC_SHA256 = require('./hmac').HMAC_SHA256; - WordArray = require('./wordarray').WordArray; + pbkdf2 = require('./pbkdf2').pbkdf2; - util = require('./util'); + _ref = require('./salsa20'), endian_reverse = _ref.endian_reverse, Salsa20InnerCore = _ref.Salsa20InnerCore; - PBKDF2 = (function() { - function PBKDF2(_arg) { - this.klass = _arg.klass, this.c = _arg.c; - this.c || (this.c = 1024); - this.klass || (this.klass = HMAC); + _ref1 = require('./wordarray'), ui8a_to_buffer = _ref1.ui8a_to_buffer, WordArray = _ref1.WordArray; + + _ref2 = require('./util'), fixup_uint32 = _ref2.fixup_uint32, default_delay = _ref2.default_delay, scrub_vec = _ref2.scrub_vec; + + blkcpy = function(D, S, d_offset, s_offset, len) { + "use asm"; + var end, i, j; + j = (d_offset << 4) | 0; + i = (s_offset << 4) | 0; + end = (i + (len << 4)) | 0; + while (i < end) { + D[j] = S[i]; + D[j + 1] = S[i + 1]; + D[j + 2] = S[i + 2]; + D[j + 3] = S[i + 3]; + D[j + 4] = S[i + 4]; + D[j + 5] = S[i + 5]; + D[j + 6] = S[i + 6]; + D[j + 7] = S[i + 7]; + D[j + 8] = S[i + 8]; + D[j + 9] = S[i + 9]; + D[j + 10] = S[i + 10]; + D[j + 11] = S[i + 11]; + D[j + 12] = S[i + 12]; + D[j + 13] = S[i + 13]; + D[j + 14] = S[i + 14]; + D[j + 15] = S[i + 15]; + i += 16; + j += 16; } + return true; + }; - PBKDF2.prototype._PRF = function(input) { - this.prf.reset(); - return this.prf.finalize(input); + blkxor = function(D, S, s_offset, len) { + "use asm"; + var i, j; + len = (len << 4) | 0; + i = 0; + j = (s_offset << 4) | 0; + while (i < len) { + D[i] ^= S[j]; + D[i + 1] ^= S[j + 1]; + D[i + 2] ^= S[j + 2]; + D[i + 3] ^= S[j + 3]; + D[i + 4] ^= S[j + 4]; + D[i + 5] ^= S[j + 5]; + D[i + 6] ^= S[j + 6]; + D[i + 7] ^= S[j + 7]; + D[i + 8] ^= S[j + 8]; + D[i + 9] ^= S[j + 9]; + D[i + 10] ^= S[j + 10]; + D[i + 11] ^= S[j + 11]; + D[i + 12] ^= S[j + 12]; + D[i + 13] ^= S[j + 13]; + D[i + 14] ^= S[j + 14]; + D[i + 15] ^= S[j + 15]; + i += 16; + j += 16; + } + return true; + }; + + v_endian_reverse = function(v) { + var e, i, _i, _len; + for (i = _i = 0, _len = v.length; _i < _len; i = ++_i) { + e = v[i]; + v[i] = endian_reverse(e); + } + return true; + }; + + Scrypt = (function() { + function Scrypt(_arg) { + var N, c, c0, c1; + N = _arg.N, this.r = _arg.r, this.p = _arg.p, c = _arg.c, c0 = _arg.c0, c1 = _arg.c1, this.klass = _arg.klass; + this.N || (this.N = 1 << (N || 10)); + this.r || (this.r = 16); + this.p || (this.p = 2); + this.c0 = c0 || c || 1; + this.c1 = c1 || c || 1; + this.klass || (this.klass = HMAC_SHA256); + this.X16_tmp = new Int32Array(0x10); + this.s20ic = new Salsa20InnerCore(8); + } + + Scrypt.prototype.salsa20_8 = function(B) { + var X, i, x, _i, _len; + X = this.s20ic._core(B); + for (i = _i = 0, _len = X.length; _i < _len; i = ++_i) { + x = X[i]; + B[i] += x; + } + return true; }; - PBKDF2.prototype._gen_T_i = function(_arg, cb) { - var U, i, progress_hook, ret, salt, seed, stop, ___iced_passed_deferral, __iced_deferrals, __iced_k, + Scrypt.prototype.pbkdf2 = function(_arg, cb) { + var c, dkLen, key, progress_hook, salt, wa, ___iced_passed_deferral, __iced_deferrals, __iced_k, _this = this; __iced_k = __iced_k_noop; ___iced_passed_deferral = iced.findDeferral(arguments); - salt = _arg.salt, i = _arg.i, progress_hook = _arg.progress_hook; - progress_hook(0); - seed = salt.clone().concat(new WordArray([i])); - U = this._PRF(seed); - ret = U.clone(); - i = 1; + key = _arg.key, salt = _arg.salt, dkLen = _arg.dkLen, progress_hook = _arg.progress_hook, c = _arg.c; (function(__iced_k) { - var _results, _while; - _results = []; - _while = function(__iced_k) { - var _break, _continue, _next; - _break = function() { - return __iced_k(_results); - }; - _continue = function() { - return iced.trampoline(function() { - return _while(__iced_k); - }); - }; - _next = function(__iced_next_arg) { - _results.push(__iced_next_arg); - return _continue(); - }; - if (!(i < _this.c)) { - return _break(); - } else { - stop = Math.min(_this.c, i + 128); - while (i < stop) { - U = _this._PRF(U); - ret.xor(U, {}); - i++; - } - progress_hook(i); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/pbkdf2.iced", - funcname: "PBKDF2._gen_T_i" - }); - util.default_delay(0, 0, __iced_deferrals.defer({ - lineno: 57 - })); - __iced_deferrals._fulfill(); - })(function() { - return _next(null); - }); - } - }; - _while(__iced_k); + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/scrypt.iced", + funcname: "Scrypt.pbkdf2" + }); + pbkdf2({ + key: key, + salt: salt, + c: c, + dkLen: dkLen, + klass: _this.klass, + progress_hook: progress_hook + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return wa = arguments[0]; + }; + })(), + lineno: 103 + })); + __iced_deferrals._fulfill(); })(function() { - progress_hook(i); - return cb(ret); + return cb(wa); }); }; - PBKDF2.prototype.run = function(_arg, cb) { - var bs, dkLen, flat, i, key, n, ph, progress_hook, salt, tmp, tph, words, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, salt = _arg.salt, dkLen = _arg.dkLen, progress_hook = _arg.progress_hook; - this.prf = new this.klass(key); - bs = this.prf.get_output_size(); - n = Math.ceil(dkLen / bs); - words = []; - tph = null; - ph = function(block) { - return function(iter) { - return typeof progress_hook === "function" ? progress_hook({ - what: "pbkdf2", - total: n * _this.c, - i: block * _this.c + iter - }) : void 0; - }; - }; - ph(0)(0); + Scrypt.prototype.blockmix_salsa8 = function(B, Y) { + var X, i, _i, _j, _k, _ref3, _ref4, _ref5; + X = this.X16_tmp; + blkcpy(X, B, 0, 2 * this.r - 1, 1); + for (i = _i = 0, _ref3 = 2 * this.r; 0 <= _ref3 ? _i < _ref3 : _i > _ref3; i = 0 <= _ref3 ? ++_i : --_i) { + blkxor(X, B, i, 1); + this.salsa20_8(X); + blkcpy(Y, X, i, 0, 1); + } + for (i = _j = 0, _ref4 = this.r; 0 <= _ref4 ? _j < _ref4 : _j > _ref4; i = 0 <= _ref4 ? ++_j : --_j) { + blkcpy(B, Y, i, i * 2, 1); + } + for (i = _k = 0, _ref5 = this.r; 0 <= _ref5 ? _k < _ref5 : _k > _ref5; i = 0 <= _ref5 ? ++_k : --_k) { + blkcpy(B, Y, i + this.r, i * 2 + 1, 1); + } + return true; + }; + + Scrypt.prototype.smix = function(_arg, cb) { + var B, V, X, XY, Y, i, j, lim, progress_hook, stop, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + B = _arg.B, V = _arg.V, XY = _arg.XY, progress_hook = _arg.progress_hook; + X = XY; + lim = 2 * this.r; + Y = XY.subarray(0x10 * lim); + blkcpy(X, B, 0, 0, lim); + i = 0; (function(__iced_k) { - var _i, _results, _while; - i = 1; + var _results, _while; _results = []; _while = function(__iced_k) { var _break, _continue, _next; @@ -8692,7 +9428,6 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit }; _continue = function() { return iced.trampoline(function() { - ++i; return _while(__iced_k); }); }; @@ -8700,2953 +9435,2552 @@ var EllipticCurve = exports.EllipticCurve;//https://raw.github.com/bitcoinjs/bit _results.push(__iced_next_arg); return _continue(); }; - if (!(i <= n)) { + if (!(i < _this.N)) { return _break(); } else { - + stop = Math.min(_this.N, i + 2048); + while (i < stop) { + blkcpy(V, X, lim * i, 0, lim); + _this.blockmix_salsa8(X, Y); + i++; + } + if (typeof progress_hook === "function") { + progress_hook(i); + } (function(__iced_k) { __iced_deferrals = new iced.Deferrals(__iced_k, { parent: ___iced_passed_deferral, - filename: "src/pbkdf2.iced", - funcname: "PBKDF2.run" + filename: "src/scrypt.iced", + funcname: "Scrypt.smix" }); - _this._gen_T_i({ - salt: salt, - i: i, - progress_hook: ph(i - 1) - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return tmp = arguments[0]; - }; - })(), - lineno: 80 + default_delay(0, 0, __iced_deferrals.defer({ + lineno: 156 })); __iced_deferrals._fulfill(); - })(function() { - return _next(words.push(tmp.words)); - }); + })(_next); } }; _while(__iced_k); })(function() { - var _ref; - ph(n)(0); - flat = (_ref = []).concat.apply(_ref, words); - key.scrub(); - _this.prf.scrub(); - _this.prf = null; - return cb(new WordArray(flat, dkLen)); + i = 0; + (function(__iced_k) { + var _results, _while; + _results = []; + _while = function(__iced_k) { + var _break, _continue, _next; + _break = function() { + return __iced_k(_results); + }; + _continue = function() { + return iced.trampoline(function() { + return _while(__iced_k); + }); + }; + _next = function(__iced_next_arg) { + _results.push(__iced_next_arg); + return _continue(); + }; + if (!(i < _this.N)) { + return _break(); + } else { + stop = Math.min(_this.N, i + 256); + while (i < stop) { + j = fixup_uint32(X[0x10 * (lim - 1)]) & (_this.N - 1); + blkxor(X, V, j * lim, lim); + _this.blockmix_salsa8(X, Y); + i++; + } + if (typeof progress_hook === "function") { + progress_hook(i + _this.N); + } + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/scrypt.iced", + funcname: "Scrypt.smix" + }); + default_delay(0, 0, __iced_deferrals.defer({ + lineno: 173 + })); + __iced_deferrals._fulfill(); + })(_next); + } + }; + _while(__iced_k); + })(function() { + blkcpy(B, X, 0, 0, lim); + return cb(); + }); }); }; - return PBKDF2; + Scrypt.prototype.run = function(_arg, cb) { + var B, MAX, V, XY, dkLen, err, j, key, lph, out, progress_hook, ret, salt, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + key = _arg.key, salt = _arg.salt, dkLen = _arg.dkLen, progress_hook = _arg.progress_hook; + MAX = 0xffffffff; + err = ret = null; + err = dkLen > MAX ? err = new Error("asked for too much data") : this.r * this.p >= (1 << 30) ? new Error("r & p are too big") : (this.r > MAX / 128 / this.p) || (this.r > MAX / 256) || (this.N > MAX / 128 / this.r) ? new Error("N is too big") : null; + XY = new Int32Array(64 * this.r); + V = new Int32Array(32 * this.r * this.N); + lph = function(o) { + o.what += " (pass 1)"; + return typeof progress_hook === "function" ? progress_hook(o) : void 0; + }; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/scrypt.iced", + funcname: "Scrypt.run" + }); + _this.pbkdf2({ + key: key.clone(), + salt: salt, + dkLen: 128 * _this.r * _this.p, + c: _this.c0, + progress_hook: lph + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return B = arguments[0]; + }; + })(), + lineno: 204 + })); + __iced_deferrals._fulfill(); + })(function() { + B = new Int32Array(B.words); + v_endian_reverse(B); + lph = function(j) { + return function(i) { + return typeof progress_hook === "function" ? progress_hook({ + i: i + j * _this.N * 2, + what: "scrypt", + total: _this.p * _this.N * 2 + }) : void 0; + }; + }; + (function(__iced_k) { + var _i, _results, _while; + j = 0; + _results = []; + _while = function(__iced_k) { + var _break, _continue, _next; + _break = function() { + return __iced_k(_results); + }; + _continue = function() { + return iced.trampoline(function() { + ++j; + return _while(__iced_k); + }); + }; + _next = function(__iced_next_arg) { + _results.push(__iced_next_arg); + return _continue(); + }; + if (!(j < _this.p)) { + return _break(); + } else { + + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/scrypt.iced", + funcname: "Scrypt.run" + }); + _this.smix({ + B: B.subarray(32 * _this.r * j), + V: V, + XY: XY, + progress_hook: lph(j) + }, __iced_deferrals.defer({ + lineno: 211 + })); + __iced_deferrals._fulfill(); + })(_next); + } + }; + _while(__iced_k); + })(function() { + v_endian_reverse(B); + lph = function(o) { + o.what += " (pass 2)"; + return typeof progress_hook === "function" ? progress_hook(o) : void 0; + }; + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/scrypt.iced", + funcname: "Scrypt.run" + }); + _this.pbkdf2({ + key: key, + salt: WordArray.from_i32a(B), + dkLen: dkLen, + c: _this.c1, + progress_hook: lph + }, __iced_deferrals.defer({ + assign_fn: (function() { + return function() { + return out = arguments[0]; + }; + })(), + lineno: 219 + })); + __iced_deferrals._fulfill(); + })(function() { + scrub_vec(XY); + scrub_vec(V); + scrub_vec(B); + key.scrub(); + return cb(out); + }); + }); + }); + }; + + return Scrypt; })(); - pbkdf2 = function(_arg, cb) { - var c, dkLen, eng, key, klass, out, progress_hook, salt, ___iced_passed_deferral, __iced_deferrals, __iced_k, + scrypt = function(_arg, cb) { + var N, c, c0, c1, dkLen, eng, key, klass, p, progress_hook, r, salt, wa, ___iced_passed_deferral, __iced_deferrals, __iced_k, _this = this; __iced_k = __iced_k_noop; ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, salt = _arg.salt, klass = _arg.klass, c = _arg.c, dkLen = _arg.dkLen, progress_hook = _arg.progress_hook; - eng = new PBKDF2({ - klass: klass, - c: c + key = _arg.key, salt = _arg.salt, r = _arg.r, N = _arg.N, p = _arg.p, c0 = _arg.c0, c1 = _arg.c1, c = _arg.c, klass = _arg.klass, progress_hook = _arg.progress_hook, dkLen = _arg.dkLen; + eng = new Scrypt({ + r: r, + N: N, + p: p, + c: c, + c0: c0, + c1: c1, + klass: klass }); (function(__iced_k) { __iced_deferrals = new iced.Deferrals(__iced_k, { parent: ___iced_passed_deferral, - filename: "src/pbkdf2.iced", - funcname: "pbkdf2" + filename: "src/scrypt.iced", + funcname: "scrypt" }); eng.run({ key: key, salt: salt, - dkLen: dkLen, - progress_hook: progress_hook + progress_hook: progress_hook, + dkLen: dkLen }, __iced_deferrals.defer({ assign_fn: (function() { return function() { - return out = arguments[0]; + return wa = arguments[0]; }; })(), - lineno: 106 + lineno: 249 })); __iced_deferrals._fulfill(); })(function() { - return cb(out); + return cb(wa); }); }; - exports.pbkdf2 = pbkdf2; - - exports.PBKDF2 = PBKDF2; - -}).call(this); - -},{"./hmac":24,"./util":37,"./wordarray":38,"iced-coffee-script/lib/coffee-script/iced":9}],28:[function(require,module,exports){ -(function (Buffer){ -// Generated by IcedCoffeeScript 1.6.3-g -(function() { - var ADRBG, PRNG, WordArray, XOR, browser_rng, e, generate, iced, more_entropy, native_rng, rng, util, __iced_k, __iced_k_noop, _native_rng, _prng, _ref; - - iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; - __iced_k = __iced_k_noop = function() {}; - - more_entropy = require('more-entropy'); - - ADRBG = require('./drbg').ADRBG; - - WordArray = require('./wordarray').WordArray; - - XOR = require('./combine').XOR; - - util = require('./util'); - - browser_rng = function(n) { - var v; - v = new Uint8Array(n); - window.crypto.getRandomValues(v); - return new Buffer(v); - }; - - if ((typeof window !== "undefined" && window !== null ? (_ref = window.crypto) != null ? _ref.getRandomValues : void 0 : void 0) != null) { - _native_rng = browser_rng; - } else { - try { - rng = require('cry' + 'pto').rng; - if (rng != null) { - _native_rng = rng; - } - } catch (_error) { - e = _error; - } - } - - native_rng = function(x) { - if (_native_rng == null) { - throw new Error('No rng found; tried requiring "crypto" and window.crypto'); - } - return _native_rng(x); - }; - - PRNG = (function() { - function PRNG() { - var _this = this; - this.meg = new more_entropy.Generator(); - this.adrbg = new ADRBG((function(n, cb) { - return _this.gen_seed(n, cb); - }), XOR.sign); - } - - PRNG.prototype.now_to_buffer = function() { - var buf, d, ms, s; - d = Date.now(); - ms = d % 1000; - s = Math.floor(d / 1000); - buf = new Buffer(8); - buf.writeUInt32BE(s, 0); - buf.writeUInt32BE(ms, 4); - return buf; - }; - - PRNG.prototype.gen_seed = function(nbits, cb) { - var b, bufs, cat, nbytes, wa, words, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - nbytes = nbits / 8; - bufs = []; - bufs.push(this.now_to_buffer()); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/prng.iced", - funcname: "PRNG.gen_seed" - }); - _this.meg.generate(nbits, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return words = arguments[0]; - }; - })(), - lineno: 76 - })); - __iced_deferrals._fulfill(); - })(function() { - var _i, _len; - bufs.push(_this.now_to_buffer()); - bufs.push(new Buffer(words)); - bufs.push(native_rng(nbytes)); - bufs.push(_this.now_to_buffer()); - cat = Buffer.concat(bufs); - wa = WordArray.from_buffer(cat); - util.scrub_buffer(cat); - for (_i = 0, _len = bufs.length; _i < _len; _i++) { - b = bufs[_i]; - util.scrub_buffer(b); - } - return cb(wa); - }); - }; - - PRNG.prototype.generate = function(n, cb) { - return this.adrbg.generate(n, cb); - }; - - return PRNG; - - })(); - - _prng = null; - - generate = function(n, cb) { - if (_prng == null) { - _prng = new PRNG(); - } - return _prng.generate(n, cb); - }; - - exports.PRNG = PRNG; - - exports.generate = generate; - - exports.native_rng = native_rng; - -}).call(this); - -}).call(this,require("buffer").Buffer) -},{"./combine":19,"./drbg":22,"./util":37,"./wordarray":38,"buffer":1,"iced-coffee-script/lib/coffee-script/iced":9,"more-entropy":40}],29:[function(require,module,exports){ -(function (Buffer){ -// Generated by IcedCoffeeScript 1.6.3-g -(function() { - var Cipher, Counter, Salsa20, Salsa20Core, Salsa20InnerCore, Salsa20WordStream, StreamCipher, WordArray, asum, bulk_encrypt, encrypt, endian_reverse, fixup_uint32, iced, util, __iced_k, __iced_k_noop, _ref, _ref1, _ref2, - __hasProp = {}.hasOwnProperty, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - - iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; - __iced_k = __iced_k_noop = function() {}; - - _ref = require('./wordarray'), endian_reverse = _ref.endian_reverse, WordArray = _ref.WordArray; - - Counter = require('./ctr').Counter; - - fixup_uint32 = require('./util').fixup_uint32; - - StreamCipher = require('./algbase').StreamCipher; - - util = require('./util'); - - asum = function(out, v) { - var e, i, _i, _len; - for (i = _i = 0, _len = v.length; _i < _len; i = ++_i) { - e = v[i]; - out[i] += e; - } - return false; - }; - - Salsa20InnerCore = (function() { - function Salsa20InnerCore(rounds) { - this.rounds = rounds; - } - - Salsa20InnerCore.prototype._core = function(v) { - "use asm"; - var i, u, x0, x1, x10, x11, x12, x13, x14, x15, x2, x3, x4, x5, x6, x7, x8, x9, _i, _ref1; - x0 = v[0], x1 = v[1], x2 = v[2], x3 = v[3], x4 = v[4], x5 = v[5], x6 = v[6], x7 = v[7], x8 = v[8], x9 = v[9], x10 = v[10], x11 = v[11], x12 = v[12], x13 = v[13], x14 = v[14], x15 = v[15]; - for (i = _i = 0, _ref1 = this.rounds; _i < _ref1; i = _i += 2) { - u = (x0 + x12) | 0; - x4 ^= (u << 7) | (u >>> 25); - u = (x4 + x0) | 0; - x8 ^= (u << 9) | (u >>> 23); - u = (x8 + x4) | 0; - x12 ^= (u << 13) | (u >>> 19); - u = (x12 + x8) | 0; - x0 ^= (u << 18) | (u >>> 14); - u = (x5 + x1) | 0; - x9 ^= (u << 7) | (u >>> 25); - u = (x9 + x5) | 0; - x13 ^= (u << 9) | (u >>> 23); - u = (x13 + x9) | 0; - x1 ^= (u << 13) | (u >>> 19); - u = (x1 + x13) | 0; - x5 ^= (u << 18) | (u >>> 14); - u = (x10 + x6) | 0; - x14 ^= (u << 7) | (u >>> 25); - u = (x14 + x10) | 0; - x2 ^= (u << 9) | (u >>> 23); - u = (x2 + x14) | 0; - x6 ^= (u << 13) | (u >>> 19); - u = (x6 + x2) | 0; - x10 ^= (u << 18) | (u >>> 14); - u = (x15 + x11) | 0; - x3 ^= (u << 7) | (u >>> 25); - u = (x3 + x15) | 0; - x7 ^= (u << 9) | (u >>> 23); - u = (x7 + x3) | 0; - x11 ^= (u << 13) | (u >>> 19); - u = (x11 + x7) | 0; - x15 ^= (u << 18) | (u >>> 14); - u = (x0 + x3) | 0; - x1 ^= (u << 7) | (u >>> 25); - u = (x1 + x0) | 0; - x2 ^= (u << 9) | (u >>> 23); - u = (x2 + x1) | 0; - x3 ^= (u << 13) | (u >>> 19); - u = (x3 + x2) | 0; - x0 ^= (u << 18) | (u >>> 14); - u = (x5 + x4) | 0; - x6 ^= (u << 7) | (u >>> 25); - u = (x6 + x5) | 0; - x7 ^= (u << 9) | (u >>> 23); - u = (x7 + x6) | 0; - x4 ^= (u << 13) | (u >>> 19); - u = (x4 + x7) | 0; - x5 ^= (u << 18) | (u >>> 14); - u = (x10 + x9) | 0; - x11 ^= (u << 7) | (u >>> 25); - u = (x11 + x10) | 0; - x8 ^= (u << 9) | (u >>> 23); - u = (x8 + x11) | 0; - x9 ^= (u << 13) | (u >>> 19); - u = (x9 + x8) | 0; - x10 ^= (u << 18) | (u >>> 14); - u = (x15 + x14) | 0; - x12 ^= (u << 7) | (u >>> 25); - u = (x12 + x15) | 0; - x13 ^= (u << 9) | (u >>> 23); - u = (x13 + x12) | 0; - x14 ^= (u << 13) | (u >>> 19); - u = (x14 + x13) | 0; - x15 ^= (u << 18) | (u >>> 14); - } - return [x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15]; - }; - - return Salsa20InnerCore; + exports.Scrypt = Scrypt; - })(); + exports.scrypt = scrypt; - Salsa20Core = (function(_super) { - __extends(Salsa20Core, _super); + exports.v_endian_reverse = v_endian_reverse; - Salsa20Core.prototype.sigma = WordArray.from_buffer_le(new Buffer("expand 32-byte k")); +}).call(this); - Salsa20Core.prototype.tau = WordArray.from_buffer_le(new Buffer("expand 16-byte k")); +},{"./hmac":22,"./pbkdf2":25,"./salsa20":27,"./util":35,"./wordarray":36,"iced-coffee-script/lib/coffee-script/iced":3}],29:[function(require,module,exports){ +// Generated by IcedCoffeeScript 1.6.3-g +(function() { + var Hasher, SHA1, W, WordArray, transform, _ref, + __hasProp = {}.hasOwnProperty, + __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - Salsa20Core.blockSize = 64; - Salsa20Core.prototype.blockSize = Salsa20Core.blockSize; - Salsa20Core.keySize = 32; + WordArray = require('./wordarray').WordArray; - Salsa20Core.prototype.keySize = Salsa20Core.keySize; + Hasher = require('./algbase').Hasher; - Salsa20Core.ivSize = 192 / 8; + W = []; - Salsa20Core.prototype.ivSize = Salsa20Core.ivSize; + SHA1 = (function(_super) { + __extends(SHA1, _super); - function Salsa20Core(key, nonce) { - var _ref1; - Salsa20Core.__super__.constructor.call(this, 20); - this.key = key.clone().endian_reverse(); - this.nonce = nonce.clone().endian_reverse(); - if (!(((this.key.sigBytes === 16) && (this.nonce.sigBytes === 8)) || ((this.key.sigBytes === 32) && ((_ref1 = this.nonce.sigBytes) === 8 || _ref1 === 24)))) { - throw new Error("Bad key/nonce lengths"); - } - if (this.nonce.sigBytes === 24) { - this.xsalsa_setup(); - } - this.input = this.key_iv_setup(this.nonce, this.key); - this._reset(); + function SHA1() { + _ref = SHA1.__super__.constructor.apply(this, arguments); + return _ref; } - Salsa20Core.prototype.scrub = function() { - this.key.scrub(); - this.nonce.scrub(); - return util.scrub_vec(this.input); - }; + SHA1.blockSize = 512 / 32; - Salsa20Core.prototype.xsalsa_setup = function() { - var n0, n1; - n0 = new WordArray(this.nonce.words.slice(0, 4)); - this.nonce = n1 = new WordArray(this.nonce.words.slice(4)); - return this.key = this.hsalsa20(n0, this.key); - }; + SHA1.prototype.blockSize = SHA1.blockSize; - Salsa20Core.prototype.hsalsa20 = function(nonce, key) { - var i, indexes, input, v; - input = this.key_iv_setup(nonce, key); - input[8] = nonce.words[2]; - input[9] = nonce.words[3]; - v = this._core(input); - indexes = [0, 5, 10, 15, 6, 7, 8, 9]; - v = (function() { - var _i, _len, _results; - _results = []; - for (_i = 0, _len = indexes.length; _i < _len; _i++) { - i = indexes[_i]; - _results.push(fixup_uint32(v[i])); - } - return _results; - })(); - util.scrub_vec(input); - return new WordArray(v); - }; + SHA1.output_size = 20; - Salsa20Core.prototype.key_iv_setup = function(nonce, key) { - var A, C, i, out, _i, _j, _k, _ref1; - out = []; - for (i = _i = 0; _i < 4; i = ++_i) { - out[i + 1] = key.words[i]; - } - _ref1 = key.sigBytes === 32 ? [this.sigma, key.words.slice(4)] : [this.tau, key.words], C = _ref1[0], A = _ref1[1]; - for (i = _j = 0; _j < 4; i = ++_j) { - out[i + 11] = A[i]; - } - for (i = _k = 0; _k < 4; i = ++_k) { - out[i * 5] = C.words[i]; - } - out[6] = nonce.words[0]; - out[7] = nonce.words[1]; - return out; - }; + SHA1.prototype.output_size = SHA1.output_size; - Salsa20Core.prototype.counter_setup = function() { - this.input[8] = this.counter.get().words[0]; - return this.input[9] = this.counter.get().words[1]; + SHA1.prototype._doReset = function() { + return this._hash = new WordArray([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); }; - Salsa20Core.prototype._reset = function() { - return this.counter = new Counter({ - len: 2 - }); + SHA1.prototype._doProcessBlock = function(M, offset) { + var H, a, b, c, d, e, i, n, t, _i; + H = this._hash.words; + a = H[0]; + b = H[1]; + c = H[2]; + d = H[3]; + e = H[4]; + for (i = _i = 0; _i < 80; i = ++_i) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + W[i] = (n << 1) | (n >>> 31); + } + t = ((a << 5) | (a >>> 27)) + e + W[i]; + if (i < 20) { + t += ((b & c) | (~b & d)) + 0x5a827999; + } else if (i < 40) { + t += (b ^ c ^ d) + 0x6ed9eba1; + } else if (i < 60) { + t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; + } else { + t += (b ^ c ^ d) - 0x359d3e2a; + } + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + return H[4] = (H[4] + e) | 0; }; - Salsa20Core.prototype._generateBlock = function() { - var v; - this.counter_setup(); - v = this._core(this.input); - asum(v, this.input); - this.counter.inc_le(); - return v; + SHA1.prototype._doFinalize = function() { + var data, dataWords, nBitsLeft, nBitsTotal; + data = this._data; + dataWords = data.words; + nBitsTotal = this._nDataBytes * 8; + nBitsLeft = data.sigBytes * 8; + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + this._process(); + return this._hash; }; - return Salsa20Core; - - })(Salsa20InnerCore); - - exports.Salsa20WordStream = Salsa20WordStream = (function(_super) { - __extends(Salsa20WordStream, _super); - - function Salsa20WordStream() { - _ref1 = Salsa20WordStream.__super__.constructor.apply(this, arguments); - return _ref1; - } - - Salsa20WordStream.prototype._reset = function() { - return Salsa20WordStream.__super__._reset.call(this); + SHA1.prototype.copy_to = function(obj) { + SHA1.__super__.copy_to.call(this, obj); + return obj._hash = this._hash.clone(); }; - Salsa20WordStream.prototype.getWordArray = function(nbytes) { - var blocks, i, nblocks, w, words, _i, _len, _ref2; - if ((nbytes == null) || nbytes === this.blockSize) { - words = this._generateBlock(); - } else { - nblocks = Math.ceil(nbytes / this.blockSize); - blocks = (function() { - var _i, _results; - _results = []; - for (i = _i = 0; 0 <= nblocks ? _i < nblocks : _i > nblocks; i = 0 <= nblocks ? ++_i : --_i) { - _results.push(this._generateBlock()); - } - return _results; - }).call(this); - words = (_ref2 = []).concat.apply(_ref2, blocks); - } - for (i = _i = 0, _len = words.length; _i < _len; i = ++_i) { - w = words[i]; - words[i] = endian_reverse(w); - } - return new WordArray(words, nbytes); + SHA1.prototype.clone = function() { + var out; + out = new SHA1(); + this.copy_to(out); + return out; }; - return Salsa20WordStream; - - })(Salsa20Core); + return SHA1; - exports.Salsa20 = Salsa20 = (function(_super) { - __extends(Salsa20, _super); + })(Hasher); - function Salsa20() { - _ref2 = Salsa20.__super__.constructor.apply(this, arguments); - return _ref2; - } + transform = transform = function(x) { + var out; + out = (new SHA1).finalize(x); + x.scrub(); + return out; + }; - Salsa20.prototype._reset = function() { - Salsa20.__super__._reset.call(this); - return this._i = this.blockSize; - }; + exports.SHA1 = SHA1; - Salsa20.prototype.getBytes = function(needed) { - var bsz, n, v; - if (needed == null) { - needed = this.blockSize; - } - v = []; - bsz = this.blockSize; - if ((this._i === bsz) && (needed === bsz)) { - return this._generateBlockBuffer(); - } else { - while (needed > 0) { - if (this._i === bsz) { - this._generateBlockBuffer(); - this._i = 0; - } - n = Math.min(needed, bsz - this._i); - v.push((n === bsz ? this._buf : this._buf.slice(this._i, this._i + n))); - this._i += n; - needed -= n; - } - return Buffer.concat(v); - } - }; + exports.transform = transform; - Salsa20.prototype._generateBlockBuffer = function() { - var e, i, v, _i, _len; - this._buf = new Buffer(this.blockSize); - v = this._generateBlock(); - for (i = _i = 0, _len = v.length; _i < _len; i = ++_i) { - e = v[i]; - this._buf.writeUInt32LE(fixup_uint32(e), i * 4); - } - return this._buf; - }; +}).call(this); - return Salsa20; +},{"./algbase":16,"./wordarray":36}],30:[function(require,module,exports){ +// Generated by IcedCoffeeScript 1.6.3-g +(function() { + var SHA224, SHA256, WordArray, transform, _ref, + __hasProp = {}.hasOwnProperty, + __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - })(Salsa20Core); - exports.Cipher = Cipher = (function(_super) { - __extends(Cipher, _super); - function Cipher(_arg) { - var iv, key; - key = _arg.key, iv = _arg.iv; - Cipher.__super__.constructor.call(this); - this.salsa = new Salsa20WordStream(key, iv); - this.bsiw = this.salsa.blockSize / 4; + WordArray = require('./wordarray').WordArray; + + SHA256 = require('./sha256').SHA256; + + SHA224 = (function(_super) { + __extends(SHA224, _super); + + function SHA224() { + _ref = SHA224.__super__.constructor.apply(this, arguments); + return _ref; } - Cipher.prototype.scrub = function() { - return this.salsa.scrub(); + SHA224.prototype._doReset = function() { + return this._hash = new WordArray([0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]); }; - Cipher.prototype.get_pad = function() { - var pad; - pad = this.salsa.getWordArray(); - return pad; + SHA224.prototype._doFinalize = function() { + var hash; + hash = SHA224.__super__._doFinalize.call(this); + hash.sigBytes -= 4; + return hash; }; - return Cipher; + SHA224.prototype.clone = function() { + var out; + out = new SHA224(); + this.copy_to(out); + return out; + }; - })(StreamCipher); + return SHA224; - exports.encrypt = encrypt = function(_arg) { - var cipher, input, iv, key, ret; - key = _arg.key, iv = _arg.iv, input = _arg.input; - cipher = new Cipher({ - key: key, - iv: iv - }); - ret = cipher.encrypt(input); - cipher.scrub(); - return ret; - }; + })(SHA256); - exports.bulk_encrypt = bulk_encrypt = function(_arg, cb) { - var cipher, input, iv, key, progress_hook, ret, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, iv = _arg.iv, input = _arg.input, progress_hook = _arg.progress_hook; - cipher = new Cipher({ - key: key, - iv: iv - }); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/salsa20.iced", - funcname: "bulk_encrypt" - }); - cipher.bulk_encrypt({ - input: input, - progress_hook: progress_hook, - what: "salsa20" - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return ret = arguments[0]; - }; - })(), - lineno: 257 - })); - __iced_deferrals._fulfill(); - })(function() { - cipher.scrub(); - return cb(ret); - }); + transform = function(x) { + var out; + out = (new SHA224).finalize(x); + x.scrub(); + return out; }; - exports.Salsa20InnerCore = Salsa20InnerCore; - - exports.endian_reverse = endian_reverse; + exports.SHA224 = SHA224; - exports.asum = asum; + exports.transform = transform; }).call(this); -}).call(this,require("buffer").Buffer) -},{"./algbase":18,"./ctr":20,"./util":37,"./wordarray":38,"buffer":1,"iced-coffee-script/lib/coffee-script/iced":9}],30:[function(require,module,exports){ +},{"./sha256":31,"./wordarray":36}],31:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var HMAC_SHA256, Salsa20InnerCore, Scrypt, WordArray, blkcpy, blkxor, default_delay, endian_reverse, fixup_uint32, iced, pbkdf2, scrub_vec, scrypt, ui8a_to_buffer, v_endian_reverse, __iced_k, __iced_k_noop, _ref, _ref1, _ref2; - - iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; - __iced_k = __iced_k_noop = function() {}; - - HMAC_SHA256 = require('./hmac').HMAC_SHA256; - - pbkdf2 = require('./pbkdf2').pbkdf2; - - _ref = require('./salsa20'), endian_reverse = _ref.endian_reverse, Salsa20InnerCore = _ref.Salsa20InnerCore; - - _ref1 = require('./wordarray'), ui8a_to_buffer = _ref1.ui8a_to_buffer, WordArray = _ref1.WordArray; + var Global, Hasher, SHA256, WordArray, glbl, transform, _ref, + __hasProp = {}.hasOwnProperty, + __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - _ref2 = require('./util'), fixup_uint32 = _ref2.fixup_uint32, default_delay = _ref2.default_delay, scrub_vec = _ref2.scrub_vec; - blkcpy = function(D, S, d_offset, s_offset, len) { - "use asm"; - var end, i, j; - j = (d_offset << 4) | 0; - i = (s_offset << 4) | 0; - end = (i + (len << 4)) | 0; - while (i < end) { - D[j] = S[i]; - D[j + 1] = S[i + 1]; - D[j + 2] = S[i + 2]; - D[j + 3] = S[i + 3]; - D[j + 4] = S[i + 4]; - D[j + 5] = S[i + 5]; - D[j + 6] = S[i + 6]; - D[j + 7] = S[i + 7]; - D[j + 8] = S[i + 8]; - D[j + 9] = S[i + 9]; - D[j + 10] = S[i + 10]; - D[j + 11] = S[i + 11]; - D[j + 12] = S[i + 12]; - D[j + 13] = S[i + 13]; - D[j + 14] = S[i + 14]; - D[j + 15] = S[i + 15]; - i += 16; - j += 16; - } - return true; - }; - blkxor = function(D, S, s_offset, len) { - "use asm"; - var i, j; - len = (len << 4) | 0; - i = 0; - j = (s_offset << 4) | 0; - while (i < len) { - D[i] ^= S[j]; - D[i + 1] ^= S[j + 1]; - D[i + 2] ^= S[j + 2]; - D[i + 3] ^= S[j + 3]; - D[i + 4] ^= S[j + 4]; - D[i + 5] ^= S[j + 5]; - D[i + 6] ^= S[j + 6]; - D[i + 7] ^= S[j + 7]; - D[i + 8] ^= S[j + 8]; - D[i + 9] ^= S[j + 9]; - D[i + 10] ^= S[j + 10]; - D[i + 11] ^= S[j + 11]; - D[i + 12] ^= S[j + 12]; - D[i + 13] ^= S[j + 13]; - D[i + 14] ^= S[j + 14]; - D[i + 15] ^= S[j + 15]; - i += 16; - j += 16; - } - return true; - }; + WordArray = require('./wordarray').WordArray; - v_endian_reverse = function(v) { - var e, i, _i, _len; - for (i = _i = 0, _len = v.length; _i < _len; i = ++_i) { - e = v[i]; - v[i] = endian_reverse(e); - } - return true; - }; + Hasher = require('./algbase').Hasher; - Scrypt = (function() { - function Scrypt(_arg) { - var N, c, c0, c1; - N = _arg.N, this.r = _arg.r, this.p = _arg.p, c = _arg.c, c0 = _arg.c0, c1 = _arg.c1, this.klass = _arg.klass; - this.N || (this.N = 1 << (N || 10)); - this.r || (this.r = 16); - this.p || (this.p = 2); - this.c0 = c0 || c || 1; - this.c1 = c1 || c || 1; - this.klass || (this.klass = HMAC_SHA256); - this.X16_tmp = new Int32Array(0x10); - this.s20ic = new Salsa20InnerCore(8); + Global = (function() { + function Global() { + this.H = []; + this.K = []; + this.W = []; + this.init(); } - Scrypt.prototype.salsa20_8 = function(B) { - var X, i, x, _i, _len; - X = this.s20ic._core(B); - for (i = _i = 0, _len = X.length; _i < _len; i = ++_i) { - x = X[i]; - B[i] += x; - } - return true; - }; - - Scrypt.prototype.pbkdf2 = function(_arg, cb) { - var c, dkLen, key, progress_hook, salt, wa, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, salt = _arg.salt, dkLen = _arg.dkLen, progress_hook = _arg.progress_hook, c = _arg.c; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/scrypt.iced", - funcname: "Scrypt.pbkdf2" - }); - pbkdf2({ - key: key, - salt: salt, - c: c, - dkLen: dkLen, - klass: _this.klass, - progress_hook: progress_hook - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return wa = arguments[0]; - }; - })(), - lineno: 103 - })); - __iced_deferrals._fulfill(); - })(function() { - return cb(wa); - }); - }; - - Scrypt.prototype.blockmix_salsa8 = function(B, Y) { - var X, i, _i, _j, _k, _ref3, _ref4, _ref5; - X = this.X16_tmp; - blkcpy(X, B, 0, 2 * this.r - 1, 1); - for (i = _i = 0, _ref3 = 2 * this.r; 0 <= _ref3 ? _i < _ref3 : _i > _ref3; i = 0 <= _ref3 ? ++_i : --_i) { - blkxor(X, B, i, 1); - this.salsa20_8(X); - blkcpy(Y, X, i, 0, 1); + Global.prototype.isPrime = function(n) { + var f, sqn, _i; + if (n === 2 || n === 3 || n === 5 || n === 7) { + return true; } - for (i = _j = 0, _ref4 = this.r; 0 <= _ref4 ? _j < _ref4 : _j > _ref4; i = 0 <= _ref4 ? ++_j : --_j) { - blkcpy(B, Y, i, i * 2, 1); + if (n === 1 || n === 4 || n === 6 || n === 8 || n === 9) { + return false; } - for (i = _k = 0, _ref5 = this.r; 0 <= _ref5 ? _k < _ref5 : _k > _ref5; i = 0 <= _ref5 ? ++_k : --_k) { - blkcpy(B, Y, i + this.r, i * 2 + 1, 1); + sqn = Math.ceil(Math.sqrt(n)); + for (f = _i = 2; 2 <= sqn ? _i <= sqn : _i >= sqn; f = 2 <= sqn ? ++_i : --_i) { + if ((n % f) === 0) { + return false; + } } return true; }; - Scrypt.prototype.smix = function(_arg, cb) { - var B, V, X, XY, Y, i, j, lim, progress_hook, stop, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - B = _arg.B, V = _arg.V, XY = _arg.XY, progress_hook = _arg.progress_hook; - X = XY; - lim = 2 * this.r; - Y = XY.subarray(0x10 * lim); - blkcpy(X, B, 0, 0, lim); - i = 0; - (function(__iced_k) { - var _results, _while; - _results = []; - _while = function(__iced_k) { - var _break, _continue, _next; - _break = function() { - return __iced_k(_results); - }; - _continue = function() { - return iced.trampoline(function() { - return _while(__iced_k); - }); - }; - _next = function(__iced_next_arg) { - _results.push(__iced_next_arg); - return _continue(); - }; - if (!(i < _this.N)) { - return _break(); - } else { - stop = Math.min(_this.N, i + 2048); - while (i < stop) { - blkcpy(V, X, lim * i, 0, lim); - _this.blockmix_salsa8(X, Y); - i++; - } - if (typeof progress_hook === "function") { - progress_hook(i); - } - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/scrypt.iced", - funcname: "Scrypt.smix" - }); - default_delay(0, 0, __iced_deferrals.defer({ - lineno: 156 - })); - __iced_deferrals._fulfill(); - })(_next); - } - }; - _while(__iced_k); - })(function() { - i = 0; - (function(__iced_k) { - var _results, _while; - _results = []; - _while = function(__iced_k) { - var _break, _continue, _next; - _break = function() { - return __iced_k(_results); - }; - _continue = function() { - return iced.trampoline(function() { - return _while(__iced_k); - }); - }; - _next = function(__iced_next_arg) { - _results.push(__iced_next_arg); - return _continue(); - }; - if (!(i < _this.N)) { - return _break(); - } else { - stop = Math.min(_this.N, i + 256); - while (i < stop) { - j = fixup_uint32(X[0x10 * (lim - 1)]) & (_this.N - 1); - blkxor(X, V, j * lim, lim); - _this.blockmix_salsa8(X, Y); - i++; - } - if (typeof progress_hook === "function") { - progress_hook(i + _this.N); - } - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/scrypt.iced", - funcname: "Scrypt.smix" - }); - default_delay(0, 0, __iced_deferrals.defer({ - lineno: 173 - })); - __iced_deferrals._fulfill(); - })(_next); - } - }; - _while(__iced_k); - })(function() { - blkcpy(B, X, 0, 0, lim); - return cb(); - }); - }); + Global.prototype.getFractionalBits = function(n) { + return ((n - (n | 0)) * 0x100000000) | 0; }; - Scrypt.prototype.run = function(_arg, cb) { - var B, MAX, V, XY, dkLen, err, j, key, lph, out, progress_hook, ret, salt, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, salt = _arg.salt, dkLen = _arg.dkLen, progress_hook = _arg.progress_hook; - MAX = 0xffffffff; - err = ret = null; - err = dkLen > MAX ? err = new Error("asked for too much data") : this.r * this.p >= (1 << 30) ? new Error("r & p are too big") : (this.r > MAX / 128 / this.p) || (this.r > MAX / 256) || (this.N > MAX / 128 / this.r) ? new Error("N is too big") : null; - XY = new Int32Array(64 * this.r); - V = new Int32Array(32 * this.r * this.N); - lph = function(o) { - o.what += " (pass 1)"; - return typeof progress_hook === "function" ? progress_hook(o) : void 0; - }; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/scrypt.iced", - funcname: "Scrypt.run" - }); - _this.pbkdf2({ - key: key.clone(), - salt: salt, - dkLen: 128 * _this.r * _this.p, - c: _this.c0, - progress_hook: lph - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return B = arguments[0]; - }; - })(), - lineno: 204 - })); - __iced_deferrals._fulfill(); - })(function() { - B = new Int32Array(B.words); - v_endian_reverse(B); - lph = function(j) { - return function(i) { - return typeof progress_hook === "function" ? progress_hook({ - i: i + j * _this.N * 2, - what: "scrypt", - total: _this.p * _this.N * 2 - }) : void 0; - }; - }; - (function(__iced_k) { - var _i, _results, _while; - j = 0; - _results = []; - _while = function(__iced_k) { - var _break, _continue, _next; - _break = function() { - return __iced_k(_results); - }; - _continue = function() { - return iced.trampoline(function() { - ++j; - return _while(__iced_k); - }); - }; - _next = function(__iced_next_arg) { - _results.push(__iced_next_arg); - return _continue(); - }; - if (!(j < _this.p)) { - return _break(); - } else { - - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/scrypt.iced", - funcname: "Scrypt.run" - }); - _this.smix({ - B: B.subarray(32 * _this.r * j), - V: V, - XY: XY, - progress_hook: lph(j) - }, __iced_deferrals.defer({ - lineno: 211 - })); - __iced_deferrals._fulfill(); - })(_next); - } - }; - _while(__iced_k); - })(function() { - v_endian_reverse(B); - lph = function(o) { - o.what += " (pass 2)"; - return typeof progress_hook === "function" ? progress_hook(o) : void 0; - }; - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/scrypt.iced", - funcname: "Scrypt.run" - }); - _this.pbkdf2({ - key: key, - salt: WordArray.from_i32a(B), - dkLen: dkLen, - c: _this.c1, - progress_hook: lph - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return out = arguments[0]; - }; - })(), - lineno: 219 - })); - __iced_deferrals._fulfill(); - })(function() { - scrub_vec(XY); - scrub_vec(V); - scrub_vec(B); - key.scrub(); - return cb(out); - }); - }); - }); + Global.prototype.init = function() { + var n, nPrime, _results; + n = 2; + nPrime = 0; + _results = []; + while (nPrime < 64) { + if (this.isPrime(n)) { + if (nPrime < 8) { + this.H[nPrime] = this.getFractionalBits(Math.pow(n, 1 / 2)); + } + this.K[nPrime] = this.getFractionalBits(Math.pow(n, 1 / 3)); + nPrime++; + } + _results.push(n++); + } + return _results; }; - return Scrypt; + return Global; })(); - scrypt = function(_arg, cb) { - var N, c, c0, c1, dkLen, eng, key, klass, p, progress_hook, r, salt, wa, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - key = _arg.key, salt = _arg.salt, r = _arg.r, N = _arg.N, p = _arg.p, c0 = _arg.c0, c1 = _arg.c1, c = _arg.c, klass = _arg.klass, progress_hook = _arg.progress_hook, dkLen = _arg.dkLen; - eng = new Scrypt({ - r: r, - N: N, - p: p, - c: c, - c0: c0, - c1: c1, - klass: klass - }); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/scrypt.iced", - funcname: "scrypt" - }); - eng.run({ - key: key, - salt: salt, - progress_hook: progress_hook, - dkLen: dkLen - }, __iced_deferrals.defer({ - assign_fn: (function() { - return function() { - return wa = arguments[0]; - }; - })(), - lineno: 249 - })); - __iced_deferrals._fulfill(); - })(function() { - return cb(wa); - }); - }; + glbl = new Global(); - exports.Scrypt = Scrypt; + SHA256 = (function(_super) { + __extends(SHA256, _super); - exports.scrypt = scrypt; + function SHA256() { + _ref = SHA256.__super__.constructor.apply(this, arguments); + return _ref; + } - exports.v_endian_reverse = v_endian_reverse; + SHA256.blockSize = 512 / 32; + + SHA256.prototype.blockSize = SHA256.blockSize; + + SHA256.output_size = 256 / 8; + + SHA256.prototype.output_size = SHA256.output_size; + + SHA256.prototype._doReset = function() { + return this._hash = new WordArray(glbl.H.slice(0)); + }; + + SHA256.prototype.get_output_size = function() { + return this.output_size; + }; + + SHA256.prototype._doProcessBlock = function(M, offset) { + var H, K, W, a, b, c, ch, d, e, f, g, gamma0, gamma0x, gamma1, gamma1x, h, i, maj, sigma0, sigma1, t1, t2, _i; + H = this._hash.words; + W = glbl.W; + K = glbl.K; + a = H[0]; + b = H[1]; + c = H[2]; + d = H[3]; + e = H[4]; + f = H[5]; + g = H[6]; + h = H[7]; + for (i = _i = 0; _i < 64; i = ++_i) { + if (i < 16) { + W[i] = M[offset + i] | 0; + } else { + gamma0x = W[i - 15]; + gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); + gamma1x = W[i - 2]; + gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); + W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; + } + ch = (e & f) ^ (~e & g); + maj = (a & b) ^ (a & c) ^ (b & c); + sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); + sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); + t1 = h + sigma1 + ch + K[i] + W[i]; + t2 = sigma0 + maj; + h = g; + g = f; + f = e; + e = (d + t1) | 0; + d = c; + c = b; + b = a; + a = (t1 + t2) | 0; + } + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + H[4] = (H[4] + e) | 0; + H[5] = (H[5] + f) | 0; + H[6] = (H[6] + g) | 0; + return H[7] = (H[7] + h) | 0; + }; + + SHA256.prototype._doFinalize = function() { + var data, dataWords, nBitsLeft, nBitsTotal; + data = this._data; + dataWords = data.words; + nBitsTotal = this._nDataBytes * 8; + nBitsLeft = data.sigBytes * 8; + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + data.sigBytes = dataWords.length * 4; + this._process(); + return this._hash; + }; + + SHA256.prototype.scrub = function() { + return this._hash.scrub(); + }; + + SHA256.prototype.copy_to = function(obj) { + SHA256.__super__.copy_to.call(this, obj); + return obj._hash = this._hash.clone(); + }; + + SHA256.prototype.clone = function() { + var out; + out = new SHA256(); + this.copy_to(out); + return out; + }; + + return SHA256; + + })(Hasher); + + transform = function(x) { + var out; + out = (new SHA256).finalize(x); + x.scrub(); + return out; + }; + + exports.SHA256 = SHA256; + + exports.transform = transform; }).call(this); -},{"./hmac":24,"./pbkdf2":27,"./salsa20":29,"./util":37,"./wordarray":38,"iced-coffee-script/lib/coffee-script/iced":9}],31:[function(require,module,exports){ +},{"./algbase":16,"./wordarray":36}],32:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var Hasher, SHA1, W, WordArray, transform, _ref, + var Global, Hasher, SHA3, WordArray, X64Word, X64WordArray, glbl, _ref, _ref1, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - WordArray = require('./wordarray').WordArray; + _ref = require('./wordarray'), WordArray = _ref.WordArray, X64Word = _ref.X64Word, X64WordArray = _ref.X64WordArray; Hasher = require('./algbase').Hasher; - W = []; + Global = (function() { + function Global() { + this.RHO_OFFSETS = []; + this.PI_INDEXES = []; + this.ROUND_CONSTANTS = []; + this.T = []; + this.compute_rho_offsets(); + this.compute_pi_indexes(); + this.compute_round_constants(); + this.make_reusables(); + } + + Global.prototype.compute_rho_offsets = function() { + var newX, newY, t, x, y, _i, _results; + x = 1; + y = 0; + _results = []; + for (t = _i = 0; _i < 24; t = ++_i) { + this.RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; + newX = y % 5; + newY = (2 * x + 3 * y) % 5; + x = newX; + _results.push(y = newY); + } + return _results; + }; + + Global.prototype.compute_pi_indexes = function() { + var x, y, _i, _results; + _results = []; + for (x = _i = 0; _i < 5; x = ++_i) { + _results.push((function() { + var _j, _results1; + _results1 = []; + for (y = _j = 0; _j < 5; y = ++_j) { + _results1.push(this.PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5); + } + return _results1; + }).call(this)); + } + return _results; + }; + + Global.prototype.compute_round_constants = function() { + var LFSR, bitPosition, i, j, roundConstantLsw, roundConstantMsw, _i, _j, _results; + LFSR = 0x01; + _results = []; + for (i = _i = 0; _i < 24; i = ++_i) { + roundConstantMsw = 0; + roundConstantLsw = 0; + for (j = _j = 0; _j < 7; j = ++_j) { + if (LFSR & 0x01) { + bitPosition = (1 << j) - 1; + if (bitPosition < 32) { + roundConstantLsw ^= 1 << bitPosition; + } else { + roundConstantMsw ^= 1 << (bitPosition - 32); + } + } + if (LFSR & 0x80) { + LFSR = (LFSR << 1) ^ 0x71; + } else { + LFSR <<= 1; + } + } + _results.push(this.ROUND_CONSTANTS[i] = new X64Word(roundConstantMsw, roundConstantLsw)); + } + return _results; + }; + + Global.prototype.make_reusables = function() { + var i; + return this.T = (function() { + var _i, _results; + _results = []; + for (i = _i = 0; _i < 25; i = ++_i) { + _results.push(new X64Word(0, 0)); + } + return _results; + })(); + }; + + return Global; + + })(); + + glbl = new Global(); - SHA1 = (function(_super) { - __extends(SHA1, _super); + exports.SHA3 = SHA3 = (function(_super) { + __extends(SHA3, _super); - function SHA1() { - _ref = SHA1.__super__.constructor.apply(this, arguments); - return _ref; + function SHA3() { + _ref1 = SHA3.__super__.constructor.apply(this, arguments); + return _ref1; } - SHA1.blockSize = 512 / 32; + SHA3.outputLength = 512; - SHA1.prototype.blockSize = SHA1.blockSize; + SHA3.prototype.outputLength = SHA3.outputLength; - SHA1.output_size = 20; + SHA3.blockSize = (1600 - 2 * SHA3.outputLength) / 32; - SHA1.prototype.output_size = SHA1.output_size; + SHA3.prototype.blockSize = SHA3.blockSize; - SHA1.prototype._doReset = function() { - return this._hash = new WordArray([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); + SHA3.output_size = SHA3.outputLength / 8; + + SHA3.prototype.output_size = SHA3.output_size; + + SHA3.prototype._doReset = function() { + var i; + return this._state = (function() { + var _i, _results; + _results = []; + for (i = _i = 0; _i < 25; i = ++_i) { + _results.push(new X64Word(0, 0)); + } + return _results; + })(); }; - SHA1.prototype._doProcessBlock = function(M, offset) { - var H, a, b, c, d, e, i, n, t, _i; - H = this._hash.words; - a = H[0]; - b = H[1]; - c = H[2]; - d = H[3]; - e = H[4]; - for (i = _i = 0; _i < 80; i = ++_i) { - if (i < 16) { - W[i] = M[offset + i] | 0; - } else { - n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - W[i] = (n << 1) | (n >>> 31); + SHA3.prototype._doProcessBlock = function(M, offset) { + var G, M2i, M2i1, T0, TLane, TPiLane, Tx, Tx1, Tx1Lane, Tx1Lsw, Tx1Msw, Tx2Lane, Tx4, i, lane, laneIndex, laneLsw, laneMsw, nBlockSizeLanes, rhoOffset, round, roundConstant, state, state0, tLsw, tMsw, x, y, _i, _j, _k, _l, _m, _n, _o, _p, _q, _results; + G = glbl; + state = this._state; + nBlockSizeLanes = this.blockSize / 2; + for (i = _i = 0; 0 <= nBlockSizeLanes ? _i < nBlockSizeLanes : _i > nBlockSizeLanes; i = 0 <= nBlockSizeLanes ? ++_i : --_i) { + M2i = M[offset + 2 * i]; + M2i1 = M[offset + 2 * i + 1]; + M2i = (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00); + M2i1 = (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00); + lane = state[i]; + lane.high ^= M2i1; + lane.low ^= M2i; + } + _results = []; + for (round = _j = 0; _j < 24; round = ++_j) { + for (x = _k = 0; _k < 5; x = ++_k) { + tMsw = tLsw = 0; + for (y = _l = 0; _l < 5; y = ++_l) { + lane = state[x + 5 * y]; + tMsw ^= lane.high; + tLsw ^= lane.low; + } + Tx = G.T[x]; + Tx.high = tMsw; + Tx.low = tLsw; } - t = ((a << 5) | (a >>> 27)) + e + W[i]; - if (i < 20) { - t += ((b & c) | (~b & d)) + 0x5a827999; - } else if (i < 40) { - t += (b ^ c ^ d) + 0x6ed9eba1; - } else if (i < 60) { - t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; - } else { - t += (b ^ c ^ d) - 0x359d3e2a; + for (x = _m = 0; _m < 5; x = ++_m) { + Tx4 = G.T[(x + 4) % 5]; + Tx1 = G.T[(x + 1) % 5]; + Tx1Msw = Tx1.high; + Tx1Lsw = Tx1.low; + tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); + tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); + for (y = _n = 0; _n < 5; y = ++_n) { + lane = state[x + 5 * y]; + lane.high ^= tMsw; + lane.low ^= tLsw; + } } - e = d; - d = c; - c = (b << 30) | (b >>> 2); - b = a; - a = t; + for (laneIndex = _o = 1; _o < 25; laneIndex = ++_o) { + lane = state[laneIndex]; + laneMsw = lane.high; + laneLsw = lane.low; + rhoOffset = G.RHO_OFFSETS[laneIndex]; + if (rhoOffset < 32) { + tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); + tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); + } else { + tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); + tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); + } + TPiLane = G.T[G.PI_INDEXES[laneIndex]]; + TPiLane.high = tMsw; + TPiLane.low = tLsw; + } + T0 = G.T[0]; + state0 = state[0]; + T0.high = state0.high; + T0.low = state0.low; + for (x = _p = 0; _p < 5; x = ++_p) { + for (y = _q = 0; _q < 5; y = ++_q) { + laneIndex = x + 5 * y; + lane = state[laneIndex]; + TLane = G.T[laneIndex]; + Tx1Lane = G.T[((x + 1) % 5) + 5 * y]; + Tx2Lane = G.T[((x + 2) % 5) + 5 * y]; + lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); + lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); + } + } + lane = state[0]; + roundConstant = G.ROUND_CONSTANTS[round]; + lane.high ^= roundConstant.high; + _results.push(lane.low ^= roundConstant.low); } - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - return H[4] = (H[4] + e) | 0; + return _results; }; - SHA1.prototype._doFinalize = function() { - var data, dataWords, nBitsLeft, nBitsTotal; + SHA3.prototype._doFinalize = function() { + var blockSizeBits, data, dataWords, hashWords, i, lane, laneLsw, laneMsw, nBitsLeft, nBitsTotal, outputLengthBytes, outputLengthLanes, state, _i; data = this._data; dataWords = data.words; nBitsTotal = this._nDataBytes * 8; nBitsLeft = data.sigBytes * 8; - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; + blockSizeBits = this.blockSize * 32; + dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); + dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; this._process(); - return this._hash; - }; - - SHA1.prototype.copy_to = function(obj) { - SHA1.__super__.copy_to.call(this, obj); - return obj._hash = this._hash.clone(); - }; - - SHA1.prototype.clone = function() { - var out; - out = new SHA1(); - this.copy_to(out); - return out; + state = this._state; + outputLengthBytes = this.outputLength / 8; + outputLengthLanes = outputLengthBytes / 8; + hashWords = []; + for (i = _i = 0; 0 <= outputLengthLanes ? _i < outputLengthLanes : _i > outputLengthLanes; i = 0 <= outputLengthLanes ? ++_i : --_i) { + lane = state[i]; + laneMsw = lane.high; + laneLsw = lane.low; + laneMsw = (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00); + laneLsw = (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00); + hashWords.push(laneLsw); + hashWords.push(laneMsw); + } + return new WordArray(hashWords, outputLengthBytes); }; - return SHA1; - - })(Hasher); - - transform = transform = function(x) { - var out; - out = (new SHA1).finalize(x); - x.scrub(); - return out; - }; - - exports.SHA1 = SHA1; - - exports.transform = transform; - -}).call(this); - -},{"./algbase":18,"./wordarray":38}],32:[function(require,module,exports){ -// Generated by IcedCoffeeScript 1.6.3-g -(function() { - var SHA224, SHA256, WordArray, transform, _ref, - __hasProp = {}.hasOwnProperty, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - - - - WordArray = require('./wordarray').WordArray; - - SHA256 = require('./sha256').SHA256; - - SHA224 = (function(_super) { - __extends(SHA224, _super); - - function SHA224() { - _ref = SHA224.__super__.constructor.apply(this, arguments); - return _ref; - } - - SHA224.prototype._doReset = function() { - return this._hash = new WordArray([0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]); + SHA3.prototype.copy_to = function(obj) { + var s; + SHA3.__super__.copy_to.call(this, obj); + return obj._state = (function() { + var _i, _len, _ref2, _results; + _ref2 = this._state; + _results = []; + for (_i = 0, _len = _ref2.length; _i < _len; _i++) { + s = _ref2[_i]; + _results.push(s.clone()); + } + return _results; + }).call(this); }; - SHA224.prototype._doFinalize = function() { - var hash; - hash = SHA224.__super__._doFinalize.call(this); - hash.sigBytes -= 4; - return hash; - }; + SHA3.prototype.scrub = function() {}; - SHA224.prototype.clone = function() { + SHA3.prototype.clone = function() { var out; - out = new SHA224(); + out = new SHA3(); this.copy_to(out); return out; }; - return SHA224; + return SHA3; - })(SHA256); + })(Hasher); - transform = function(x) { + exports.transform = function(x) { var out; - out = (new SHA224).finalize(x); + out = (new SHA3).finalize(x); x.scrub(); return out; }; - exports.SHA224 = SHA224; - - exports.transform = transform; - }).call(this); -},{"./sha256":33,"./wordarray":38}],33:[function(require,module,exports){ +},{"./algbase":16,"./wordarray":36}],33:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var Global, Hasher, SHA256, WordArray, glbl, transform, _ref, + var Global, Hasher, SHA512, X64Word, X64WordArray, glbl, _ref, _ref1, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - WordArray = require('./wordarray').WordArray; + _ref = require('./wordarray'), X64Word = _ref.X64Word, X64WordArray = _ref.X64WordArray; Hasher = require('./algbase').Hasher; Global = (function() { - function Global() { - this.H = []; - this.K = []; - this.W = []; - this.init(); - } - - Global.prototype.isPrime = function(n) { - var f, sqn, _i; - if (n === 2 || n === 3 || n === 5 || n === 7) { - return true; - } - if (n === 1 || n === 4 || n === 6 || n === 8 || n === 9) { - return false; - } - sqn = Math.ceil(Math.sqrt(n)); - for (f = _i = 2; 2 <= sqn ? _i <= sqn : _i >= sqn; f = 2 <= sqn ? ++_i : --_i) { - if ((n % f) === 0) { - return false; - } - } - return true; - }; - - Global.prototype.getFractionalBits = function(n) { - return ((n - (n | 0)) * 0x100000000) | 0; - }; - - Global.prototype.init = function() { - var n, nPrime, _results; - n = 2; - nPrime = 0; + Global.prototype.convert = function(raw) { + var i, _i, _ref1, _results; _results = []; - while (nPrime < 64) { - if (this.isPrime(n)) { - if (nPrime < 8) { - this.H[nPrime] = this.getFractionalBits(Math.pow(n, 1 / 2)); - } - this.K[nPrime] = this.getFractionalBits(Math.pow(n, 1 / 3)); - nPrime++; - } - _results.push(n++); + for (i = _i = 0, _ref1 = raw.length; _i < _ref1; i = _i += 2) { + _results.push(new X64Word(raw[i], raw[i + 1])); } return _results; }; + function Global() { + var i; + this.K = this.convert([0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817]); + this.I = new X64WordArray(this.convert([0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179])); + this.W = (function() { + var _i, _results; + _results = []; + for (i = _i = 0; _i < 80; i = ++_i) { + _results.push(new X64Word(0, 0)); + } + return _results; + })(); + } + return Global; })(); glbl = new Global(); - SHA256 = (function(_super) { - __extends(SHA256, _super); + exports.SHA512 = SHA512 = (function(_super) { + __extends(SHA512, _super); - function SHA256() { - _ref = SHA256.__super__.constructor.apply(this, arguments); - return _ref; + function SHA512() { + _ref1 = SHA512.__super__.constructor.apply(this, arguments); + return _ref1; } - SHA256.blockSize = 512 / 32; - - SHA256.prototype.blockSize = SHA256.blockSize; + SHA512.blockSize = 1024 / 32; - SHA256.output_size = 256 / 8; + SHA512.prototype.blockSize = SHA512.blockSize; - SHA256.prototype.output_size = SHA256.output_size; + SHA512.output_size = 512 / 8; - SHA256.prototype._doReset = function() { - return this._hash = new WordArray(glbl.H.slice(0)); - }; + SHA512.prototype.output_size = SHA512.output_size; - SHA256.prototype.get_output_size = function() { - return this.output_size; + SHA512.prototype._doReset = function() { + return this._hash = glbl.I.clone(); }; - SHA256.prototype._doProcessBlock = function(M, offset) { - var H, K, W, a, b, c, ch, d, e, f, g, gamma0, gamma0x, gamma1, gamma1x, h, i, maj, sigma0, sigma1, t1, t2, _i; + SHA512.prototype._doProcessBlock = function(M, offset) { + var H, H0, H0h, H0l, H1, H1h, H1l, H2, H2h, H2l, H3, H3h, H3l, H4, H4h, H4l, H5, H5h, H5l, H6, H6h, H6l, H7, H7h, H7l, Ki, Kih, Kil, W, Wi, Wi16, Wi16h, Wi16l, Wi7, Wi7h, Wi7l, Wih, Wil, ah, al, bh, bl, ch, chh, chl, cl, dh, dl, eh, el, fh, fl, gamma0h, gamma0l, gamma0x, gamma0xh, gamma0xl, gamma1h, gamma1l, gamma1x, gamma1xh, gamma1xl, gh, gl, hh, hl, i, majh, majl, sigma0h, sigma0l, sigma1h, sigma1l, t1h, t1l, t2h, t2l, _i; H = this._hash.words; W = glbl.W; - K = glbl.K; - a = H[0]; - b = H[1]; - c = H[2]; - d = H[3]; - e = H[4]; - f = H[5]; - g = H[6]; - h = H[7]; - for (i = _i = 0; _i < 64; i = ++_i) { + H0 = H[0]; + H1 = H[1]; + H2 = H[2]; + H3 = H[3]; + H4 = H[4]; + H5 = H[5]; + H6 = H[6]; + H7 = H[7]; + H0h = H0.high; + H0l = H0.low; + H1h = H1.high; + H1l = H1.low; + H2h = H2.high; + H2l = H2.low; + H3h = H3.high; + H3l = H3.low; + H4h = H4.high; + H4l = H4.low; + H5h = H5.high; + H5l = H5.low; + H6h = H6.high; + H6l = H6.low; + H7h = H7.high; + H7l = H7.low; + ah = H0h; + al = H0l; + bh = H1h; + bl = H1l; + ch = H2h; + cl = H2l; + dh = H3h; + dl = H3l; + eh = H4h; + el = H4l; + fh = H5h; + fl = H5l; + gh = H6h; + gl = H6l; + hh = H7h; + hl = H7l; + for (i = _i = 0; _i < 80; i = ++_i) { + Wi = W[i]; if (i < 16) { - W[i] = M[offset + i] | 0; + Wih = Wi.high = M[offset + i * 2] | 0; + Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { gamma0x = W[i - 15]; - gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); + gamma0xh = gamma0x.high; + gamma0xl = gamma0x.low; + gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); + gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); gamma1x = W[i - 2]; - gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); - W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; + gamma1xh = gamma1x.high; + gamma1xl = gamma1x.low; + gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); + gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); + Wi7 = W[i - 7]; + Wi7h = Wi7.high; + Wi7l = Wi7.low; + Wi16 = W[i - 16]; + Wi16h = Wi16.high; + Wi16l = Wi16.low; + Wil = gamma0l + Wi7l; + Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); + Wil = Wil + gamma1l; + Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); + Wil = Wil + Wi16l; + Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); + Wi.high = Wih; + Wi.low = Wil; } - ch = (e & f) ^ (~e & g); - maj = (a & b) ^ (a & c) ^ (b & c); - sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); - sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); - t1 = h + sigma1 + ch + K[i] + W[i]; - t2 = sigma0 + maj; - h = g; - g = f; - f = e; - e = (d + t1) | 0; - d = c; - c = b; - b = a; - a = (t1 + t2) | 0; + chh = (eh & fh) ^ (~eh & gh); + chl = (el & fl) ^ (~el & gl); + majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); + majl = (al & bl) ^ (al & cl) ^ (bl & cl); + sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); + sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); + sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); + sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); + Ki = glbl.K[i]; + Kih = Ki.high; + Kil = Ki.low; + t1l = hl + sigma1l; + t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); + t1l = t1l + chl; + t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); + t1l = t1l + Kil; + t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); + t1l = t1l + Wil; + t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); + t2l = sigma0l + majl; + t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - H[4] = (H[4] + e) | 0; - H[5] = (H[5] + f) | 0; - H[6] = (H[6] + g) | 0; - return H[7] = (H[7] + h) | 0; + H0l = H0.low = H0l + al; + H0.high = H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0); + H1l = H1.low = H1l + bl; + H1.high = H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0); + H2l = H2.low = H2l + cl; + H2.high = H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0); + H3l = H3.low = H3l + dl; + H3.high = H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0); + H4l = H4.low = H4l + el; + H4.high = H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0); + H5l = H5.low = H5l + fl; + H5.high = H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0); + H6l = H6.low = H6l + gl; + H6.high = H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0); + H7l = H7.low = H7l + hl; + return H7.high = H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0); }; - SHA256.prototype._doFinalize = function() { - var data, dataWords, nBitsLeft, nBitsTotal; - data = this._data; - dataWords = data.words; + SHA512.prototype._doFinalize = function() { + var dataWords, nBitsLeft, nBitsTotal; + dataWords = this._data.words; nBitsTotal = this._nDataBytes * 8; - nBitsLeft = data.sigBytes * 8; + nBitsLeft = this._data.sigBytes * 8; dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; - data.sigBytes = dataWords.length * 4; + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); + dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; + this._data.sigBytes = dataWords.length * 4; this._process(); - return this._hash; - }; - - SHA256.prototype.scrub = function() { - return this._hash.scrub(); + return this._hash.toX32(); }; - SHA256.prototype.copy_to = function(obj) { - SHA256.__super__.copy_to.call(this, obj); + SHA512.prototype.copy_to = function(obj) { + SHA512.__super__.copy_to.call(this, obj); return obj._hash = this._hash.clone(); }; - SHA256.prototype.clone = function() { + SHA512.prototype.clone = function() { var out; - out = new SHA256(); + out = new SHA512(); this.copy_to(out); return out; }; - return SHA256; + return SHA512; })(Hasher); - transform = function(x) { + exports.transform = function(x) { var out; - out = (new SHA256).finalize(x); + out = (new SHA512).finalize(x); x.scrub(); return out; }; - exports.SHA256 = SHA256; - - exports.transform = transform; - }).call(this); -},{"./algbase":18,"./wordarray":38}],34:[function(require,module,exports){ +},{"./algbase":16,"./wordarray":36}],34:[function(require,module,exports){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var Global, Hasher, SHA3, WordArray, X64Word, X64WordArray, glbl, _ref, _ref1, + var BlockCipher, G, Global, TwoFish, scrub_vec, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - _ref = require('./wordarray'), WordArray = _ref.WordArray, X64Word = _ref.X64Word, X64WordArray = _ref.X64WordArray; + BlockCipher = require('./algbase').BlockCipher; - Hasher = require('./algbase').Hasher; + scrub_vec = require('./util').scrub_vec; Global = (function() { function Global() { - this.RHO_OFFSETS = []; - this.PI_INDEXES = []; - this.ROUND_CONSTANTS = []; - this.T = []; - this.compute_rho_offsets(); - this.compute_pi_indexes(); - this.compute_round_constants(); - this.make_reusables(); + this.P = [[0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76, 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38, 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C, 0x43, 0x75, 0x37, 0x26, 0xFA, 0x13, 0x94, 0x48, 0xF2, 0xD0, 0x8B, 0x30, 0x84, 0x54, 0xDF, 0x23, 0x19, 0x5B, 0x3D, 0x59, 0xF3, 0xAE, 0xA2, 0x82, 0x63, 0x01, 0x83, 0x2E, 0xD9, 0x51, 0x9B, 0x7C, 0xA6, 0xEB, 0xA5, 0xBE, 0x16, 0x0C, 0xE3, 0x61, 0xC0, 0x8C, 0x3A, 0xF5, 0x73, 0x2C, 0x25, 0x0B, 0xBB, 0x4E, 0x89, 0x6B, 0x53, 0x6A, 0xB4, 0xF1, 0xE1, 0xE6, 0xBD, 0x45, 0xE2, 0xF4, 0xB6, 0x66, 0xCC, 0x95, 0x03, 0x56, 0xD4, 0x1C, 0x1E, 0xD7, 0xFB, 0xC3, 0x8E, 0xB5, 0xE9, 0xCF, 0xBF, 0xBA, 0xEA, 0x77, 0x39, 0xAF, 0x33, 0xC9, 0x62, 0x71, 0x81, 0x79, 0x09, 0xAD, 0x24, 0xCD, 0xF9, 0xD8, 0xE5, 0xC5, 0xB9, 0x4D, 0x44, 0x08, 0x86, 0xE7, 0xA1, 0x1D, 0xAA, 0xED, 0x06, 0x70, 0xB2, 0xD2, 0x41, 0x7B, 0xA0, 0x11, 0x31, 0xC2, 0x27, 0x90, 0x20, 0xF6, 0x60, 0xFF, 0x96, 0x5C, 0xB1, 0xAB, 0x9E, 0x9C, 0x52, 0x1B, 0x5F, 0x93, 0x0A, 0xEF, 0x91, 0x85, 0x49, 0xEE, 0x2D, 0x4F, 0x8F, 0x3B, 0x47, 0x87, 0x6D, 0x46, 0xD6, 0x3E, 0x69, 0x64, 0x2A, 0xCE, 0xCB, 0x2F, 0xFC, 0x97, 0x05, 0x7A, 0xAC, 0x7F, 0xD5, 0x1A, 0x4B, 0x0E, 0xA7, 0x5A, 0x28, 0x14, 0x3F, 0x29, 0x88, 0x3C, 0x4C, 0x02, 0xB8, 0xDA, 0xB0, 0x17, 0x55, 0x1F, 0x8A, 0x7D, 0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72, 0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34, 0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8, 0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xFE, 0x32, 0xA4, 0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00, 0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0], [0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8, 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B, 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1, 0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F, 0x5E, 0xBA, 0xAE, 0x5B, 0x8A, 0x00, 0xBC, 0x9D, 0x6D, 0xC1, 0xB1, 0x0E, 0x80, 0x5D, 0xD2, 0xD5, 0xA0, 0x84, 0x07, 0x14, 0xB5, 0x90, 0x2C, 0xA3, 0xB2, 0x73, 0x4C, 0x54, 0x92, 0x74, 0x36, 0x51, 0x38, 0xB0, 0xBD, 0x5A, 0xFC, 0x60, 0x62, 0x96, 0x6C, 0x42, 0xF7, 0x10, 0x7C, 0x28, 0x27, 0x8C, 0x13, 0x95, 0x9C, 0xC7, 0x24, 0x46, 0x3B, 0x70, 0xCA, 0xE3, 0x85, 0xCB, 0x11, 0xD0, 0x93, 0xB8, 0xA6, 0x83, 0x20, 0xFF, 0x9F, 0x77, 0xC3, 0xCC, 0x03, 0x6F, 0x08, 0xBF, 0x40, 0xE7, 0x2B, 0xE2, 0x79, 0x0C, 0xAA, 0x82, 0x41, 0x3A, 0xEA, 0xB9, 0xE4, 0x9A, 0xA4, 0x97, 0x7E, 0xDA, 0x7A, 0x17, 0x66, 0x94, 0xA1, 0x1D, 0x3D, 0xF0, 0xDE, 0xB3, 0x0B, 0x72, 0xA7, 0x1C, 0xEF, 0xD1, 0x53, 0x3E, 0x8F, 0x33, 0x26, 0x5F, 0xEC, 0x76, 0x2A, 0x49, 0x81, 0x88, 0xEE, 0x21, 0xC4, 0x1A, 0xEB, 0xD9, 0xC5, 0x39, 0x99, 0xCD, 0xAD, 0x31, 0x8B, 0x01, 0x18, 0x23, 0xDD, 0x1F, 0x4E, 0x2D, 0xF9, 0x48, 0x4F, 0xF2, 0x65, 0x8E, 0x78, 0x5C, 0x58, 0x19, 0x8D, 0xE5, 0x98, 0x57, 0x67, 0x7F, 0x05, 0x64, 0xAF, 0x63, 0xB6, 0xFE, 0xF5, 0xB7, 0x3C, 0xA5, 0xCE, 0xE9, 0x68, 0x44, 0xE0, 0x4D, 0x43, 0x69, 0x29, 0x2E, 0xAC, 0x15, 0x59, 0xA8, 0x0A, 0x9E, 0x6E, 0x47, 0xDF, 0x34, 0x35, 0x6A, 0xCF, 0xDC, 0x22, 0xC9, 0xC0, 0x9B, 0x89, 0xD4, 0xED, 0xAB, 0x12, 0xA2, 0x0D, 0x52, 0xBB, 0x02, 0x2F, 0xA9, 0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2, 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91]]; + this.P_00 = 1; + this.P_01 = 0; + this.P_02 = 0; + this.P_03 = 1; + this.P_04 = 1; + this.P_10 = 0; + this.P_11 = 0; + this.P_12 = 1; + this.P_13 = 1; + this.P_14 = 0; + this.P_20 = 1; + this.P_21 = 1; + this.P_22 = 0; + this.P_23 = 0; + this.P_24 = 0; + this.P_30 = 0; + this.P_31 = 1; + this.P_32 = 1; + this.P_33 = 0; + this.P_34 = 1; + this.GF256_FDBK = 0x169; + this.GF256_FDBK_2 = this.GF256_FDBK / 2; + this.GF256_FDBK_4 = this.GF256_FDBK / 4; + this.RS_GF_FDBK = 0x14D; + this.SK_STEP = 0x02020202; + this.SK_BUMP = 0x01010101; + this.SK_ROTL = 9; } - Global.prototype.compute_rho_offsets = function() { - var newX, newY, t, x, y, _i, _results; - x = 1; - y = 0; - _results = []; - for (t = _i = 0; _i < 24; t = ++_i) { - this.RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; - newX = y % 5; - newY = (2 * x + 3 * y) % 5; - x = newX; - _results.push(y = newY); - } - return _results; - }; - - Global.prototype.compute_pi_indexes = function() { - var x, y, _i, _results; - _results = []; - for (x = _i = 0; _i < 5; x = ++_i) { - _results.push((function() { - var _j, _results1; - _results1 = []; - for (y = _j = 0; _j < 5; y = ++_j) { - _results1.push(this.PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5); - } - return _results1; - }).call(this)); - } - return _results; - }; - - Global.prototype.compute_round_constants = function() { - var LFSR, bitPosition, i, j, roundConstantLsw, roundConstantMsw, _i, _j, _results; - LFSR = 0x01; - _results = []; - for (i = _i = 0; _i < 24; i = ++_i) { - roundConstantMsw = 0; - roundConstantLsw = 0; - for (j = _j = 0; _j < 7; j = ++_j) { - if (LFSR & 0x01) { - bitPosition = (1 << j) - 1; - if (bitPosition < 32) { - roundConstantLsw ^= 1 << bitPosition; - } else { - roundConstantMsw ^= 1 << (bitPosition - 32); - } - } - if (LFSR & 0x80) { - LFSR = (LFSR << 1) ^ 0x71; - } else { - LFSR <<= 1; - } - } - _results.push(this.ROUND_CONSTANTS[i] = new X64Word(roundConstantMsw, roundConstantLsw)); - } - return _results; - }; - - Global.prototype.make_reusables = function() { - var i; - return this.T = (function() { - var _i, _results; - _results = []; - for (i = _i = 0; _i < 25; i = ++_i) { - _results.push(new X64Word(0, 0)); - } - return _results; - })(); - }; - return Global; })(); - glbl = new Global(); - - exports.SHA3 = SHA3 = (function(_super) { - __extends(SHA3, _super); - - function SHA3() { - _ref1 = SHA3.__super__.constructor.apply(this, arguments); - return _ref1; - } + G = new Global(); - SHA3.outputLength = 512; + exports.TwoFish = TwoFish = (function(_super) { + __extends(TwoFish, _super); - SHA3.prototype.outputLength = SHA3.outputLength; + TwoFish.blockSize = 4 * 4; - SHA3.blockSize = (1600 - 2 * SHA3.outputLength) / 32; + TwoFish.prototype.blockSize = TwoFish.blockSize; - SHA3.prototype.blockSize = SHA3.blockSize; + TwoFish.keySize = 256 / 8; - SHA3.output_size = SHA3.outputLength / 8; + TwoFish.prototype.keySize = TwoFish.keySize; - SHA3.prototype.output_size = SHA3.output_size; + TwoFish.ivSize = TwoFish.blockSize; - SHA3.prototype._doReset = function() { - var i; - return this._state = (function() { - var _i, _results; - _results = []; - for (i = _i = 0; _i < 25; i = ++_i) { - _results.push(new X64Word(0, 0)); - } - return _results; - })(); - }; + TwoFish.prototype.ivSize = TwoFish.ivSize; - SHA3.prototype._doProcessBlock = function(M, offset) { - var G, M2i, M2i1, T0, TLane, TPiLane, Tx, Tx1, Tx1Lane, Tx1Lsw, Tx1Msw, Tx2Lane, Tx4, i, lane, laneIndex, laneLsw, laneMsw, nBlockSizeLanes, rhoOffset, round, roundConstant, state, state0, tLsw, tMsw, x, y, _i, _j, _k, _l, _m, _n, _o, _p, _q, _results; - G = glbl; - state = this._state; - nBlockSizeLanes = this.blockSize / 2; - for (i = _i = 0; 0 <= nBlockSizeLanes ? _i < nBlockSizeLanes : _i > nBlockSizeLanes; i = 0 <= nBlockSizeLanes ? ++_i : --_i) { - M2i = M[offset + 2 * i]; - M2i1 = M[offset + 2 * i + 1]; - M2i = (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00); - M2i1 = (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00); - lane = state[i]; - lane.high ^= M2i1; - lane.low ^= M2i; - } - _results = []; - for (round = _j = 0; _j < 24; round = ++_j) { - for (x = _k = 0; _k < 5; x = ++_k) { - tMsw = tLsw = 0; - for (y = _l = 0; _l < 5; y = ++_l) { - lane = state[x + 5 * y]; - tMsw ^= lane.high; - tLsw ^= lane.low; - } - Tx = G.T[x]; - Tx.high = tMsw; - Tx.low = tLsw; - } - for (x = _m = 0; _m < 5; x = ++_m) { - Tx4 = G.T[(x + 4) % 5]; - Tx1 = G.T[(x + 1) % 5]; - Tx1Msw = Tx1.high; - Tx1Lsw = Tx1.low; - tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); - tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); - for (y = _n = 0; _n < 5; y = ++_n) { - lane = state[x + 5 * y]; - lane.high ^= tMsw; - lane.low ^= tLsw; - } - } - for (laneIndex = _o = 1; _o < 25; laneIndex = ++_o) { - lane = state[laneIndex]; - laneMsw = lane.high; - laneLsw = lane.low; - rhoOffset = G.RHO_OFFSETS[laneIndex]; - if (rhoOffset < 32) { - tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); - tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); - } else { - tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); - tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); - } - TPiLane = G.T[G.PI_INDEXES[laneIndex]]; - TPiLane.high = tMsw; - TPiLane.low = tLsw; - } - T0 = G.T[0]; - state0 = state[0]; - T0.high = state0.high; - T0.low = state0.low; - for (x = _p = 0; _p < 5; x = ++_p) { - for (y = _q = 0; _q < 5; y = ++_q) { - laneIndex = x + 5 * y; - lane = state[laneIndex]; - TLane = G.T[laneIndex]; - Tx1Lane = G.T[((x + 1) % 5) + 5 * y]; - Tx2Lane = G.T[((x + 2) % 5) + 5 * y]; - lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); - lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); - } - } - lane = state[0]; - roundConstant = G.ROUND_CONSTANTS[round]; - lane.high ^= roundConstant.high; - _results.push(lane.low ^= roundConstant.low); - } - return _results; + function TwoFish(key) { + this._key = key.clone(); + this.gMDS0 = []; + this.gMDS1 = []; + this.gMDS2 = []; + this.gMDS3 = []; + this.gSubKeys = []; + this.gSBox = []; + this.k64Cnt = 0; + this._doReset(); + } + + TwoFish.prototype.getByte = function(x, n) { + return (x >>> (n * 8)) & 0xFF; }; - SHA3.prototype._doFinalize = function() { - var blockSizeBits, data, dataWords, hashWords, i, lane, laneLsw, laneMsw, nBitsLeft, nBitsTotal, outputLengthBytes, outputLengthLanes, state, _i; - data = this._data; - dataWords = data.words; - nBitsTotal = this._nDataBytes * 8; - nBitsLeft = data.sigBytes * 8; - blockSizeBits = this.blockSize * 32; - dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); - dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; - data.sigBytes = dataWords.length * 4; - this._process(); - state = this._state; - outputLengthBytes = this.outputLength / 8; - outputLengthLanes = outputLengthBytes / 8; - hashWords = []; - for (i = _i = 0; 0 <= outputLengthLanes ? _i < outputLengthLanes : _i > outputLengthLanes; i = 0 <= outputLengthLanes ? ++_i : --_i) { - lane = state[i]; - laneMsw = lane.high; - laneLsw = lane.low; - laneMsw = (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00); - laneLsw = (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00); - hashWords.push(laneLsw); - hashWords.push(laneMsw); - } - return new WordArray(hashWords, outputLengthBytes); + TwoFish.prototype.switchEndianness = function(word) { + return ((word & 0xff) << 24) | (((word >> 8) & 0xff) << 16) | (((word >> 16) & 0xff) << 8) | ((word >> 24) & 0xff); }; - SHA3.prototype.copy_to = function(obj) { - var s; - SHA3.__super__.copy_to.call(this, obj); - return obj._state = (function() { - var _i, _len, _ref2, _results; - _ref2 = this._state; - _results = []; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - s = _ref2[_i]; - _results.push(s.clone()); - } - return _results; - }).call(this); + TwoFish.prototype.LFSR1 = function(x) { + return (x >> 1) ^ ((x & 0x01) !== 0 ? G.GF256_FDBK_2 : 0); }; - SHA3.prototype.scrub = function() {}; + TwoFish.prototype.LFSR2 = function(x) { + return (x >> 2) ^ ((x & 0x02) !== 0 ? G.GF256_FDBK_2 : 0) ^ ((x & 0x01) !== 0 ? G.GF256_FDBK_4 : 0); + }; - SHA3.prototype.clone = function() { - var out; - out = new SHA3(); - this.copy_to(out); - return out; + TwoFish.prototype.Mx_X = function(x) { + return x ^ this.LFSR2(x); }; - return SHA3; + TwoFish.prototype.Mx_Y = function(x) { + return x ^ this.LFSR1(x) ^ this.LFSR2(x); + }; - })(Hasher); + TwoFish.prototype.RS_rem = function(x) { + var b, g2, g3; + b = (x >>> 24) & 0xff; + g2 = ((b << 1) ^ ((b & 0x80) !== 0 ? G.RS_GF_FDBK : 0)) & 0xff; + g3 = ((b >>> 1) ^ ((b & 0x01) !== 0 ? G.RS_GF_FDBK >>> 1 : 0)) ^ g2; + return (x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b; + }; - exports.transform = function(x) { - var out; - out = (new SHA3).finalize(x); - x.scrub(); - return out; - }; + TwoFish.prototype.RS_MDS_Encode = function(k0, k1) { + var i, r, _i, _j; + r = k1; + for (i = _i = 0; _i < 4; i = ++_i) { + r = this.RS_rem(r); + } + r ^= k0; + for (i = _j = 0; _j < 4; i = ++_j) { + r = this.RS_rem(r); + } + return r; + }; -}).call(this); + TwoFish.prototype.F32 = function(x, k32) { + var b0, b1, b2, b3, k0, k1, k2, k3, m, res; + b0 = this.getByte(x, 0); + b1 = this.getByte(x, 1); + b2 = this.getByte(x, 2); + b3 = this.getByte(x, 3); + k0 = k32[0]; + k1 = k32[1]; + k2 = k32[2]; + k3 = k32[3]; + m = this.k64Cnt & 3; + res = m === 1 ? this.gMDS0[(G.P[G.P_01][b0] & 0xff) ^ this.getByte(k0, 0)] ^ this.gMDS1[(G.P[G.P_11][b1] & 0xff) ^ this.getByte(k0, 1)] ^ this.gMDS2[(G.P[G.P_21][b2] & 0xff) ^ this.getByte(k0, 2)] ^ this.gMDS3[(G.P[G.P_31][b3] & 0xff) ^ this.getByte(k0, 3)] : (m === 0 ? (b0 = (G.P[G.P_04][b0] & 0xff) ^ this.getByte(k3, 0), b1 = (G.P[G.P_14][b1] & 0xff) ^ this.getByte(k3, 1), b2 = (G.P[G.P_24][b2] & 0xff) ^ this.getByte(k3, 2), b3 = (G.P[G.P_34][b3] & 0xff) ^ this.getByte(k3, 3)) : void 0, m === 0 || m === 3 ? (b0 = (G.P[G.P_03][b0] & 0xff) ^ this.getByte(k2, 0), b1 = (G.P[G.P_13][b1] & 0xff) ^ this.getByte(k2, 1), b2 = (G.P[G.P_23][b2] & 0xff) ^ this.getByte(k2, 2), b3 = (G.P[G.P_33][b3] & 0xff) ^ this.getByte(k2, 3)) : void 0, this.gMDS0[(G.P[G.P_01][(G.P[G.P_02][b0] & 0xff) ^ this.getByte(k1, 0)] & 0xff) ^ this.getByte(k0, 0)] ^ this.gMDS1[(G.P[G.P_11][(G.P[G.P_12][b1] & 0xff) ^ this.getByte(k1, 1)] & 0xff) ^ this.getByte(k0, 1)] ^ this.gMDS2[(G.P[G.P_21][(G.P[G.P_22][b2] & 0xff) ^ this.getByte(k1, 2)] & 0xff) ^ this.getByte(k0, 2)] ^ this.gMDS3[(G.P[G.P_31][(G.P[G.P_32][b3] & 0xff) ^ this.getByte(k1, 3)] & 0xff) ^ this.getByte(k0, 3)]); + return res; + }; -},{"./algbase":18,"./wordarray":38}],35:[function(require,module,exports){ -// Generated by IcedCoffeeScript 1.6.3-g -(function() { - var Global, Hasher, SHA512, X64Word, X64WordArray, glbl, _ref, _ref1, - __hasProp = {}.hasOwnProperty, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; + TwoFish.prototype.Fe32_0 = function(x) { + return this.gSBox[0x000 + 2 * (x & 0xff)] ^ this.gSBox[0x001 + 2 * ((x >>> 8) & 0xff)] ^ this.gSBox[0x200 + 2 * ((x >>> 16) & 0xff)] ^ this.gSBox[0x201 + 2 * ((x >>> 24) & 0xff)]; + }; + TwoFish.prototype.Fe32_3 = function(x) { + return this.gSBox[0x000 + 2 * ((x >>> 24) & 0xff)] ^ this.gSBox[0x001 + 2 * (x & 0xff)] ^ this.gSBox[0x200 + 2 * ((x >>> 8) & 0xff)] ^ this.gSBox[0x201 + 2 * ((x >>> 16) & 0xff)]; + }; + TwoFish.prototype._doReset = function() { + var A, B, b0, b1, b2, b3, i, j, k0, k1, k2, k3, k32e, k32o, m, m1, mX, mY, p, q, sBoxKeys, _i, _j, _k, _l, _ref, _ref1, _results; + k32e = []; + k32o = []; + sBoxKeys = []; + m1 = []; + mX = []; + mY = []; + this.k64Cnt = this._key.words.length / 2; + if (this.k64Cnt < 1) { + throw "Key size less than 64 bits"; + } + if (this.k64Cnt > 4) { + throw "Key size larger than 256 bits"; + } + for (i = _i = 0; _i < 256; i = ++_i) { + j = G.P[0][i] & 0xff; + m1[0] = j; + mX[0] = this.Mx_X(j) & 0xff; + mY[0] = this.Mx_Y(j) & 0xff; + j = G.P[1][i] & 0xff; + m1[1] = j; + mX[1] = this.Mx_X(j) & 0xff; + mY[1] = this.Mx_Y(j) & 0xff; + this.gMDS0[i] = m1[G.P_00] | mX[G.P_00] << 8 | mY[G.P_00] << 16 | mY[G.P_00] << 24; + this.gMDS1[i] = mY[G.P_10] | mY[G.P_10] << 8 | mX[G.P_10] << 16 | m1[G.P_10] << 24; + this.gMDS2[i] = mX[G.P_20] | mY[G.P_20] << 8 | m1[G.P_20] << 16 | mY[G.P_20] << 24; + this.gMDS3[i] = mX[G.P_30] | m1[G.P_30] << 8 | mY[G.P_30] << 16 | mX[G.P_30] << 24; + } + for (i = _j = 0, _ref = this.k64Cnt; 0 <= _ref ? _j < _ref : _j > _ref; i = 0 <= _ref ? ++_j : --_j) { + p = i * 2; + k32e[i] = this.switchEndianness(this._key.words[p]); + k32o[i] = this.switchEndianness(this._key.words[p + 1]); + sBoxKeys[this.k64Cnt - 1 - i] = this.RS_MDS_Encode(k32e[i], k32o[i]); + } + for (i = _k = 0, _ref1 = 40 / 2; 0 <= _ref1 ? _k < _ref1 : _k > _ref1; i = 0 <= _ref1 ? ++_k : --_k) { + q = i * G.SK_STEP; + A = this.F32(q, k32e); + B = this.F32(q + G.SK_BUMP, k32o); + B = B << 8 | B >>> 24; + A += B; + this.gSubKeys[i * 2] = A; + A += B; + this.gSubKeys[i * 2 + 1] = A << G.SK_ROTL | A >>> (32 - G.SK_ROTL); + } + k0 = sBoxKeys[0]; + k1 = sBoxKeys[1]; + k2 = sBoxKeys[2]; + k3 = sBoxKeys[3]; + this.gSBox = []; + _results = []; + for (i = _l = 0; _l < 256; i = ++_l) { + b0 = b1 = b2 = b3 = i; + m = this.k64Cnt & 3; + if (m === 1) { + this.gSBox[i * 2] = this.gMDS0[(G.P[G.P_01][b0] & 0xff) ^ this.getByte(k0, 0)]; + this.gSBox[i * 2 + 1] = this.gMDS1[(G.P[G.P_11][b1] & 0xff) ^ this.getByte(k0, 1)]; + this.gSBox[i * 2 + 0x200] = this.gMDS2[(G.P[G.P_21][b2] & 0xff) ^ this.getByte(k0, 2)]; + _results.push(this.gSBox[i * 2 + 0x201] = this.gMDS3[(G.P[G.P_31][b3] & 0xff) ^ this.getByte(k0, 3)]); + } else { + if (m === 0) { + b0 = (G.P[G.P_04][b0] & 0xff) ^ this.getByte(k3, 0); + b1 = (G.P[G.P_14][b1] & 0xff) ^ this.getByte(k3, 1); + b2 = (G.P[G.P_24][b2] & 0xff) ^ this.getByte(k3, 2); + b3 = (G.P[G.P_34][b3] & 0xff) ^ this.getByte(k3, 3); + } + if (m === 0 || m === 3) { + b0 = (G.P[G.P_03][b0] & 0xff) ^ this.getByte(k2, 0); + b1 = (G.P[G.P_13][b1] & 0xff) ^ this.getByte(k2, 1); + b2 = (G.P[G.P_23][b2] & 0xff) ^ this.getByte(k2, 2); + b3 = (G.P[G.P_33][b3] & 0xff) ^ this.getByte(k2, 3); + } + this.gSBox[i * 2] = this.gMDS0[(G.P[G.P_01][(G.P[G.P_02][b0] & 0xff) ^ this.getByte(k1, 0)] & 0xff) ^ this.getByte(k0, 0)]; + this.gSBox[i * 2 + 1] = this.gMDS1[(G.P[G.P_11][(G.P[G.P_12][b1] & 0xff) ^ this.getByte(k1, 1)] & 0xff) ^ this.getByte(k0, 1)]; + this.gSBox[i * 2 + 0x200] = this.gMDS2[(G.P[G.P_21][(G.P[G.P_22][b2] & 0xff) ^ this.getByte(k1, 2)] & 0xff) ^ this.getByte(k0, 2)]; + _results.push(this.gSBox[i * 2 + 0x201] = this.gMDS3[(G.P[G.P_31][(G.P[G.P_32][b3] & 0xff) ^ this.getByte(k1, 3)] & 0xff) ^ this.getByte(k0, 3)]); + } + } + return _results; + }; - _ref = require('./wordarray'), X64Word = _ref.X64Word, X64WordArray = _ref.X64WordArray; + TwoFish.prototype.scrub = function() { + scrub_vec(this.gSubKeys); + scrub_vec(this.gSBox); + return this._key.scrub(); + }; - Hasher = require('./algbase').Hasher; + TwoFish.prototype.decryptBlock = function(M, offset) { + var k, r, t0, t1, x0, x1, x2, x3, _i; + if (offset == null) { + offset = 0; + } + x2 = this.switchEndianness(M[offset]) ^ this.gSubKeys[4]; + x3 = this.switchEndianness(M[offset + 1]) ^ this.gSubKeys[5]; + x0 = this.switchEndianness(M[offset + 2]) ^ this.gSubKeys[6]; + x1 = this.switchEndianness(M[offset + 3]) ^ this.gSubKeys[7]; + k = 8 + 2 * 16 - 1; + for (r = _i = 0; _i < 16; r = _i += 2) { + t0 = this.Fe32_0(x2); + t1 = this.Fe32_3(x3); + x1 ^= t0 + 2 * t1 + this.gSubKeys[k--]; + x0 = (x0 << 1 | x0 >>> 31) ^ (t0 + t1 + this.gSubKeys[k--]); + x1 = x1 >>> 1 | x1 << 31; + t0 = this.Fe32_0(x0); + t1 = this.Fe32_3(x1); + x3 ^= t0 + 2 * t1 + this.gSubKeys[k--]; + x2 = (x2 << 1 | x2 >>> 31) ^ (t0 + t1 + this.gSubKeys[k--]); + x3 = x3 >>> 1 | x3 << 31; + } + M[offset] = this.switchEndianness(x0 ^ this.gSubKeys[0]); + M[offset + 1] = this.switchEndianness(x1 ^ this.gSubKeys[1]); + M[offset + 2] = this.switchEndianness(x2 ^ this.gSubKeys[2]); + return M[offset + 3] = this.switchEndianness(x3 ^ this.gSubKeys[3]); + }; - Global = (function() { - Global.prototype.convert = function(raw) { - var i, _i, _ref1, _results; - _results = []; - for (i = _i = 0, _ref1 = raw.length; _i < _ref1; i = _i += 2) { - _results.push(new X64Word(raw[i], raw[i + 1])); + TwoFish.prototype.encryptBlock = function(M, offset) { + var k, r, t0, t1, x0, x1, x2, x3, _i; + if (offset == null) { + offset = 0; + } + x0 = this.switchEndianness(M[offset]) ^ this.gSubKeys[0]; + x1 = this.switchEndianness(M[offset + 1]) ^ this.gSubKeys[1]; + x2 = this.switchEndianness(M[offset + 2]) ^ this.gSubKeys[2]; + x3 = this.switchEndianness(M[offset + 3]) ^ this.gSubKeys[3]; + k = 8; + for (r = _i = 0; _i < 16; r = _i += 2) { + t0 = this.Fe32_0(x0); + t1 = this.Fe32_3(x1); + x2 ^= t0 + t1 + this.gSubKeys[k++]; + x2 = x2 >>> 1 | x2 << 31; + x3 = (x3 << 1 | x3 >>> 31) ^ (t0 + 2 * t1 + this.gSubKeys[k++]); + t0 = this.Fe32_0(x2); + t1 = this.Fe32_3(x3); + x0 ^= t0 + t1 + this.gSubKeys[k++]; + x0 = x0 >>> 1 | x0 << 31; + x1 = (x1 << 1 | x1 >>> 31) ^ (t0 + 2 * t1 + this.gSubKeys[k++]); } - return _results; + M[offset] = this.switchEndianness(x2 ^ this.gSubKeys[4]); + M[offset + 1] = this.switchEndianness(x3 ^ this.gSubKeys[5]); + M[offset + 2] = this.switchEndianness(x0 ^ this.gSubKeys[6]); + return M[offset + 3] = this.switchEndianness(x1 ^ this.gSubKeys[7]); }; - function Global() { - var i; - this.K = this.convert([0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817]); - this.I = new X64WordArray(this.convert([0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179])); - this.W = (function() { - var _i, _results; - _results = []; - for (i = _i = 0; _i < 80; i = ++_i) { - _results.push(new X64Word(0, 0)); - } - return _results; - })(); - } - - return Global; - - })(); + return TwoFish; - glbl = new Global(); + })(BlockCipher); - exports.SHA512 = SHA512 = (function(_super) { - __extends(SHA512, _super); +}).call(this); - function SHA512() { - _ref1 = SHA512.__super__.constructor.apply(this, arguments); - return _ref1; - } +},{"./algbase":16,"./util":35}],35:[function(require,module,exports){ +// Generated by IcedCoffeeScript 1.6.3-g +(function() { + var default_delay, iced, uint_max, __iced_k, __iced_k_noop; - SHA512.blockSize = 1024 / 32; + iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; + __iced_k = __iced_k_noop = function() {}; - SHA512.prototype.blockSize = SHA512.blockSize; + uint_max = Math.pow(2, 32); - SHA512.output_size = 512 / 8; + exports.fixup_uint32 = function(x) { + var ret, x_pos; + ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x; + return ret; + }; - SHA512.prototype.output_size = SHA512.output_size; + exports.scrub_buffer = function(b) { + var i, n_full_words; + n_full_words = b.length >> 2; + i = 0; + while (i < n_full_words) { + b.writeUInt32LE(0, i); + i += 4; + } + while (i < b.length) { + b.writeUInt8(0, i); + i++; + } + return false; + }; - SHA512.prototype._doReset = function() { - return this._hash = glbl.I.clone(); - }; + exports.scrub_vec = function(v) { + var i, _i, _ref; + for (i = _i = 0, _ref = v.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + v[i] = 0; + } + return false; + }; - SHA512.prototype._doProcessBlock = function(M, offset) { - var H, H0, H0h, H0l, H1, H1h, H1l, H2, H2h, H2l, H3, H3h, H3l, H4, H4h, H4l, H5, H5h, H5l, H6, H6h, H6l, H7, H7h, H7l, Ki, Kih, Kil, W, Wi, Wi16, Wi16h, Wi16l, Wi7, Wi7h, Wi7l, Wih, Wil, ah, al, bh, bl, ch, chh, chl, cl, dh, dl, eh, el, fh, fl, gamma0h, gamma0l, gamma0x, gamma0xh, gamma0xl, gamma1h, gamma1l, gamma1x, gamma1xh, gamma1xl, gh, gl, hh, hl, i, majh, majl, sigma0h, sigma0l, sigma1h, sigma1l, t1h, t1l, t2h, t2l, _i; - H = this._hash.words; - W = glbl.W; - H0 = H[0]; - H1 = H[1]; - H2 = H[2]; - H3 = H[3]; - H4 = H[4]; - H5 = H[5]; - H6 = H[6]; - H7 = H[7]; - H0h = H0.high; - H0l = H0.low; - H1h = H1.high; - H1l = H1.low; - H2h = H2.high; - H2l = H2.low; - H3h = H3.high; - H3l = H3.low; - H4h = H4.high; - H4l = H4.low; - H5h = H5.high; - H5l = H5.low; - H6h = H6.high; - H6l = H6.low; - H7h = H7.high; - H7l = H7.low; - ah = H0h; - al = H0l; - bh = H1h; - bl = H1l; - ch = H2h; - cl = H2l; - dh = H3h; - dl = H3l; - eh = H4h; - el = H4l; - fh = H5h; - fl = H5l; - gh = H6h; - gl = H6l; - hh = H7h; - hl = H7l; - for (i = _i = 0; _i < 80; i = ++_i) { - Wi = W[i]; - if (i < 16) { - Wih = Wi.high = M[offset + i * 2] | 0; - Wil = Wi.low = M[offset + i * 2 + 1] | 0; - } else { - gamma0x = W[i - 15]; - gamma0xh = gamma0x.high; - gamma0xl = gamma0x.low; - gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); - gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); - gamma1x = W[i - 2]; - gamma1xh = gamma1x.high; - gamma1xl = gamma1x.low; - gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); - gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); - Wi7 = W[i - 7]; - Wi7h = Wi7.high; - Wi7l = Wi7.low; - Wi16 = W[i - 16]; - Wi16h = Wi16.high; - Wi16l = Wi16.low; - Wil = gamma0l + Wi7l; - Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); - Wil = Wil + gamma1l; - Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); - Wil = Wil + Wi16l; - Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); - Wi.high = Wih; - Wi.low = Wil; - } - chh = (eh & fh) ^ (~eh & gh); - chl = (el & fl) ^ (~el & gl); - majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); - majl = (al & bl) ^ (al & cl) ^ (bl & cl); - sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); - sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); - sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); - sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); - Ki = glbl.K[i]; - Kih = Ki.high; - Kil = Ki.low; - t1l = hl + sigma1l; - t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); - t1l = t1l + chl; - t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); - t1l = t1l + Kil; - t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); - t1l = t1l + Wil; - t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); - t2l = sigma0l + majl; - t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; + exports.default_delay = default_delay = function(i, n, cb) { + var ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + (function(__iced_k) { + if (typeof setImmediate !== "undefined" && setImmediate !== null) { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/util.iced", + funcname: "default_delay" + }); + setImmediate(__iced_deferrals.defer({ + lineno: 37 + })); + __iced_deferrals._fulfill(); + })(__iced_k); + } else { + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/util.iced", + funcname: "default_delay" + }); + setTimeout(__iced_deferrals.defer({ + lineno: 39 + }), 1); + __iced_deferrals._fulfill(); + })(__iced_k); } - H0l = H0.low = H0l + al; - H0.high = H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0); - H1l = H1.low = H1l + bl; - H1.high = H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0); - H2l = H2.low = H2l + cl; - H2.high = H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0); - H3l = H3.low = H3l + dl; - H3.high = H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0); - H4l = H4.low = H4l + el; - H4.high = H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0); - H5l = H5.low = H5l + fl; - H5.high = H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0); - H6l = H6.low = H6l + gl; - H6.high = H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0); - H7l = H7.low = H7l + hl; - return H7.high = H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0); - }; - - SHA512.prototype._doFinalize = function() { - var dataWords, nBitsLeft, nBitsTotal; - dataWords = this._data.words; - nBitsTotal = this._nDataBytes * 8; - nBitsLeft = this._data.sigBytes * 8; - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; - this._data.sigBytes = dataWords.length * 4; - this._process(); - return this._hash.toX32(); - }; - - SHA512.prototype.copy_to = function(obj) { - SHA512.__super__.copy_to.call(this, obj); - return obj._hash = this._hash.clone(); - }; + })(function() { + return cb(); + }); + }; - SHA512.prototype.clone = function() { - var out; - out = new SHA512(); - this.copy_to(out); - return out; + exports.bulk = function(n_input_bytes, _arg, _arg1) { + var call_ph, cb, default_n, delay, finalize, i, left, n, n_words, progress_hook, ret, total_words, update, what, ___iced_passed_deferral, __iced_deferrals, __iced_k, + _this = this; + __iced_k = __iced_k_noop; + ___iced_passed_deferral = iced.findDeferral(arguments); + update = _arg.update, finalize = _arg.finalize, default_n = _arg.default_n; + delay = _arg1.delay, n = _arg1.n, cb = _arg1.cb, what = _arg1.what, progress_hook = _arg1.progress_hook; + i = 0; + left = 0; + total_words = Math.ceil(n_input_bytes / 4); + delay || (delay = default_delay); + n || (n = default_n); + call_ph = function(i) { + return typeof progress_hook === "function" ? progress_hook({ + what: what, + i: i, + total: total_words + }) : void 0; }; - - return SHA512; - - })(Hasher); - - exports.transform = function(x) { - var out; - out = (new SHA512).finalize(x); - x.scrub(); - return out; + call_ph(0); + (function(__iced_k) { + var _results, _while; + _results = []; + _while = function(__iced_k) { + var _break, _continue, _next; + _break = function() { + return __iced_k(_results); + }; + _continue = function() { + return iced.trampoline(function() { + return _while(__iced_k); + }); + }; + _next = function(__iced_next_arg) { + _results.push(__iced_next_arg); + return _continue(); + }; + if (!((left = total_words - i) > 0)) { + return _break(); + } else { + n_words = Math.min(n, left); + update(i, i + n_words); + call_ph(i); + (function(__iced_k) { + __iced_deferrals = new iced.Deferrals(__iced_k, { + parent: ___iced_passed_deferral, + filename: "src/util.iced", + funcname: "bulk" + }); + delay(i, total_words, __iced_deferrals.defer({ + lineno: 73 + })); + __iced_deferrals._fulfill(); + })(function() { + return _next(i += n_words); + }); + } + }; + _while(__iced_k); + })(function() { + call_ph(total_words); + ret = finalize(); + return cb(ret); + }); }; }).call(this); -},{"./algbase":18,"./wordarray":38}],36:[function(require,module,exports){ +},{"iced-coffee-script/lib/coffee-script/iced":3}],36:[function(require,module,exports){ +(function (Buffer){ // Generated by IcedCoffeeScript 1.6.3-g (function() { - var BlockCipher, G, Global, TwoFish, scrub_vec, - __hasProp = {}.hasOwnProperty, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; + var WordArray, X64Word, X64WordArray, buffer_to_ui8a, endian_reverse, ui8a_to_buffer, util; - BlockCipher = require('./algbase').BlockCipher; + util = require('./util'); - scrub_vec = require('./util').scrub_vec; + buffer_to_ui8a = function(b) { + var i, ret, _i, _ref; + ret = new Uint8Array(b.length); + for (i = _i = 0, _ref = b.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + ret[i] = b.readUInt8(i); + } + return ret; + }; - Global = (function() { - function Global() { - this.P = [[0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76, 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38, 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C, 0x43, 0x75, 0x37, 0x26, 0xFA, 0x13, 0x94, 0x48, 0xF2, 0xD0, 0x8B, 0x30, 0x84, 0x54, 0xDF, 0x23, 0x19, 0x5B, 0x3D, 0x59, 0xF3, 0xAE, 0xA2, 0x82, 0x63, 0x01, 0x83, 0x2E, 0xD9, 0x51, 0x9B, 0x7C, 0xA6, 0xEB, 0xA5, 0xBE, 0x16, 0x0C, 0xE3, 0x61, 0xC0, 0x8C, 0x3A, 0xF5, 0x73, 0x2C, 0x25, 0x0B, 0xBB, 0x4E, 0x89, 0x6B, 0x53, 0x6A, 0xB4, 0xF1, 0xE1, 0xE6, 0xBD, 0x45, 0xE2, 0xF4, 0xB6, 0x66, 0xCC, 0x95, 0x03, 0x56, 0xD4, 0x1C, 0x1E, 0xD7, 0xFB, 0xC3, 0x8E, 0xB5, 0xE9, 0xCF, 0xBF, 0xBA, 0xEA, 0x77, 0x39, 0xAF, 0x33, 0xC9, 0x62, 0x71, 0x81, 0x79, 0x09, 0xAD, 0x24, 0xCD, 0xF9, 0xD8, 0xE5, 0xC5, 0xB9, 0x4D, 0x44, 0x08, 0x86, 0xE7, 0xA1, 0x1D, 0xAA, 0xED, 0x06, 0x70, 0xB2, 0xD2, 0x41, 0x7B, 0xA0, 0x11, 0x31, 0xC2, 0x27, 0x90, 0x20, 0xF6, 0x60, 0xFF, 0x96, 0x5C, 0xB1, 0xAB, 0x9E, 0x9C, 0x52, 0x1B, 0x5F, 0x93, 0x0A, 0xEF, 0x91, 0x85, 0x49, 0xEE, 0x2D, 0x4F, 0x8F, 0x3B, 0x47, 0x87, 0x6D, 0x46, 0xD6, 0x3E, 0x69, 0x64, 0x2A, 0xCE, 0xCB, 0x2F, 0xFC, 0x97, 0x05, 0x7A, 0xAC, 0x7F, 0xD5, 0x1A, 0x4B, 0x0E, 0xA7, 0x5A, 0x28, 0x14, 0x3F, 0x29, 0x88, 0x3C, 0x4C, 0x02, 0xB8, 0xDA, 0xB0, 0x17, 0x55, 0x1F, 0x8A, 0x7D, 0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72, 0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34, 0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8, 0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xFE, 0x32, 0xA4, 0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00, 0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0], [0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8, 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B, 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1, 0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F, 0x5E, 0xBA, 0xAE, 0x5B, 0x8A, 0x00, 0xBC, 0x9D, 0x6D, 0xC1, 0xB1, 0x0E, 0x80, 0x5D, 0xD2, 0xD5, 0xA0, 0x84, 0x07, 0x14, 0xB5, 0x90, 0x2C, 0xA3, 0xB2, 0x73, 0x4C, 0x54, 0x92, 0x74, 0x36, 0x51, 0x38, 0xB0, 0xBD, 0x5A, 0xFC, 0x60, 0x62, 0x96, 0x6C, 0x42, 0xF7, 0x10, 0x7C, 0x28, 0x27, 0x8C, 0x13, 0x95, 0x9C, 0xC7, 0x24, 0x46, 0x3B, 0x70, 0xCA, 0xE3, 0x85, 0xCB, 0x11, 0xD0, 0x93, 0xB8, 0xA6, 0x83, 0x20, 0xFF, 0x9F, 0x77, 0xC3, 0xCC, 0x03, 0x6F, 0x08, 0xBF, 0x40, 0xE7, 0x2B, 0xE2, 0x79, 0x0C, 0xAA, 0x82, 0x41, 0x3A, 0xEA, 0xB9, 0xE4, 0x9A, 0xA4, 0x97, 0x7E, 0xDA, 0x7A, 0x17, 0x66, 0x94, 0xA1, 0x1D, 0x3D, 0xF0, 0xDE, 0xB3, 0x0B, 0x72, 0xA7, 0x1C, 0xEF, 0xD1, 0x53, 0x3E, 0x8F, 0x33, 0x26, 0x5F, 0xEC, 0x76, 0x2A, 0x49, 0x81, 0x88, 0xEE, 0x21, 0xC4, 0x1A, 0xEB, 0xD9, 0xC5, 0x39, 0x99, 0xCD, 0xAD, 0x31, 0x8B, 0x01, 0x18, 0x23, 0xDD, 0x1F, 0x4E, 0x2D, 0xF9, 0x48, 0x4F, 0xF2, 0x65, 0x8E, 0x78, 0x5C, 0x58, 0x19, 0x8D, 0xE5, 0x98, 0x57, 0x67, 0x7F, 0x05, 0x64, 0xAF, 0x63, 0xB6, 0xFE, 0xF5, 0xB7, 0x3C, 0xA5, 0xCE, 0xE9, 0x68, 0x44, 0xE0, 0x4D, 0x43, 0x69, 0x29, 0x2E, 0xAC, 0x15, 0x59, 0xA8, 0x0A, 0x9E, 0x6E, 0x47, 0xDF, 0x34, 0x35, 0x6A, 0xCF, 0xDC, 0x22, 0xC9, 0xC0, 0x9B, 0x89, 0xD4, 0xED, 0xAB, 0x12, 0xA2, 0x0D, 0x52, 0xBB, 0x02, 0x2F, 0xA9, 0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2, 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91]]; - this.P_00 = 1; - this.P_01 = 0; - this.P_02 = 0; - this.P_03 = 1; - this.P_04 = 1; - this.P_10 = 0; - this.P_11 = 0; - this.P_12 = 1; - this.P_13 = 1; - this.P_14 = 0; - this.P_20 = 1; - this.P_21 = 1; - this.P_22 = 0; - this.P_23 = 0; - this.P_24 = 0; - this.P_30 = 0; - this.P_31 = 1; - this.P_32 = 1; - this.P_33 = 0; - this.P_34 = 1; - this.GF256_FDBK = 0x169; - this.GF256_FDBK_2 = this.GF256_FDBK / 2; - this.GF256_FDBK_4 = this.GF256_FDBK / 4; - this.RS_GF_FDBK = 0x14D; - this.SK_STEP = 0x02020202; - this.SK_BUMP = 0x01010101; - this.SK_ROTL = 9; + ui8a_to_buffer = function(v) { + var i, ret, _i, _ref; + ret = new Buffer(v.length); + for (i = _i = 0, _ref = v.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + ret.writeUInt8(v[i], i); } + return ret; + }; - return Global; + endian_reverse = function(x) { + return ((x >>> 24) & 0xff) | (((x >>> 16) & 0xff) << 8) | (((x >>> 8) & 0xff) << 16) | ((x & 0xff) << 24); + }; - })(); + exports.WordArray = WordArray = (function() { + function WordArray(words, sigBytes) { + this.words = words || []; + this.sigBytes = sigBytes != null ? sigBytes : this.words.length * 4; + } - G = new Global(); + WordArray.prototype.concat = function(wordArray) { + var i, thatByte, thatSigBytes, thatWords, _i; + thatWords = wordArray.words; + thatSigBytes = wordArray.sigBytes; + this.clamp(); + if (this.sigBytes % 4) { + for (i = _i = 0; 0 <= thatSigBytes ? _i < thatSigBytes : _i > thatSigBytes; i = 0 <= thatSigBytes ? ++_i : --_i) { + thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + this.words[(this.sigBytes + i) >>> 2] |= thatByte << (24 - ((this.sigBytes + i) % 4) * 8); + } + } else { + this.words = this.words.concat(thatWords); + } + this.sigBytes += thatSigBytes; + return this; + }; - exports.TwoFish = TwoFish = (function(_super) { - __extends(TwoFish, _super); + WordArray.prototype.clamp = function() { + this.words[this.sigBytes >>> 2] &= 0xffffffff << (32 - (this.sigBytes % 4) * 8); + this.words.length = Math.ceil(this.sigBytes / 4); + return this; + }; - TwoFish.blockSize = 4 * 4; + WordArray.prototype.clone = function() { + return new WordArray(this.words.slice(0), this.sigBytes); + }; - TwoFish.prototype.blockSize = TwoFish.blockSize; + WordArray.prototype.to_buffer = function() { + var ch, out, p, w, _i, _len, _ref; + out = new Buffer(this.sigBytes); + p = 0; + _ref = this.words; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + w = _ref[_i]; + if (!((this.sigBytes - p) >= 4)) { + continue; + } + w = util.fixup_uint32(w); + out.writeUInt32BE(w, p); + p += 4; + } + while (p < this.sigBytes) { + ch = (this.words[p >>> 2] >>> (24 - (p % 4) * 8)) & 0xff; + out.writeUInt8(ch, p); + p++; + } + return out; + }; - TwoFish.keySize = 256 / 8; + WordArray.prototype.endian_reverse = function() { + var i, w, _i, _len, _ref; + _ref = this.words; + for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { + w = _ref[i]; + this.words[i] = endian_reverse(w); + } + return this; + }; - TwoFish.prototype.keySize = TwoFish.keySize; + WordArray.prototype.split = function(n) { + var i, out, sz; + if (!(((this.sigBytes % 4) === 0) && ((this.words.length % n) === 0))) { + throw new Error("bad key alignment"); + } + sz = this.words.length / n; + out = (function() { + var _i, _ref, _results; + _results = []; + for (i = _i = 0, _ref = this.words.length; sz > 0 ? _i < _ref : _i > _ref; i = _i += sz) { + _results.push(new WordArray(this.words.slice(i, i + sz))); + } + return _results; + }).call(this); + return out; + }; - TwoFish.ivSize = TwoFish.blockSize; + WordArray.prototype.to_utf8 = function() { + return this.to_buffer().toString('utf8'); + }; - TwoFish.prototype.ivSize = TwoFish.ivSize; + WordArray.prototype.to_hex = function() { + return this.to_buffer().toString('hex'); + }; + + WordArray.prototype.to_ui8a = function() { + return buffer_to_ui8a(this.to_buffer()); + }; + + WordArray.alloc = function(b) { + if (Buffer.isBuffer(b)) { + return WordArray.from_buffer(b); + } else if ((typeof b === 'object') && (b instanceof WordArray)) { + return b; + } else if (typeof b === 'string') { + return WordArray.from_hex(b); + } else { + return null; + } + }; + + WordArray.from_buffer = function(b) { + var ch, last, p, words; + words = []; + p = 0; + while ((b.length - p) >= 4) { + words.push(b.readUInt32BE(p)); + p += 4; + } + if (p < b.length) { + last = 0; + while (p < b.length) { + ch = b.readUInt8(p); + last |= ch << (24 - (p % 4) * 8); + p++; + } + last = util.fixup_uint32(last); + words.push(last); + } + return new WordArray(words, b.length); + }; - function TwoFish(key) { - this._key = key.clone(); - this.gMDS0 = []; - this.gMDS1 = []; - this.gMDS2 = []; - this.gMDS3 = []; - this.gSubKeys = []; - this.gSBox = []; - this.k64Cnt = 0; - this._doReset(); - } + WordArray.from_buffer_le = function(b) { + var ch, last, p, words; + words = []; + p = 0; + while ((b.length - p) >= 4) { + words.push(b.readUInt32LE(p)); + p += 4; + } + if (p < b.length) { + last = 0; + while (p < b.length) { + ch = b.readUInt8(p); + last |= ch << ((p % 4) * 8); + p++; + } + last = util.fixup_uint32(last); + words.push(last); + } + return new WordArray(words, b.length); + }; - TwoFish.prototype.getByte = function(x, n) { - return (x >>> (n * 8)) & 0xFF; + WordArray.from_utf8 = function(s) { + return WordArray.from_buffer(new Buffer(s, 'utf8')); }; - TwoFish.prototype.switchEndianness = function(word) { - return ((word & 0xff) << 24) | (((word >> 8) & 0xff) << 16) | (((word >> 16) & 0xff) << 8) | ((word >> 24) & 0xff); + WordArray.from_utf8_le = function(s) { + return WordArray.from_buffer_le(new Buffer(s, 'utf8')); }; - TwoFish.prototype.LFSR1 = function(x) { - return (x >> 1) ^ ((x & 0x01) !== 0 ? G.GF256_FDBK_2 : 0); + WordArray.from_hex = function(s) { + return WordArray.from_buffer(new Buffer(s, 'hex')); }; - TwoFish.prototype.LFSR2 = function(x) { - return (x >> 2) ^ ((x & 0x02) !== 0 ? G.GF256_FDBK_2 : 0) ^ ((x & 0x01) !== 0 ? G.GF256_FDBK_4 : 0); + WordArray.from_hex_le = function(s) { + return WordArray.from_buffer_le(new Buffer(s, 'hex')); }; - TwoFish.prototype.Mx_X = function(x) { - return x ^ this.LFSR2(x); + WordArray.from_ui8a = function(v) { + return WordArray.from_buffer(ui8a_to_buffer(v)); }; - TwoFish.prototype.Mx_Y = function(x) { - return x ^ this.LFSR1(x) ^ this.LFSR2(x); + WordArray.from_i32a = function(v) { + return new WordArray(Array.apply([], v)); }; - TwoFish.prototype.RS_rem = function(x) { - var b, g2, g3; - b = (x >>> 24) & 0xff; - g2 = ((b << 1) ^ ((b & 0x80) !== 0 ? G.RS_GF_FDBK : 0)) & 0xff; - g3 = ((b >>> 1) ^ ((b & 0x01) !== 0 ? G.RS_GF_FDBK >>> 1 : 0)) ^ g2; - return (x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b; + WordArray.prototype.equal = function(wa) { + var i, ret, w, _i, _len, _ref; + ret = true; + if (wa.sigBytes !== this.sigBytes) { + ret = false; + } else { + _ref = this.words; + for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { + w = _ref[i]; + if (util.fixup_uint32(w) !== util.fixup_uint32(wa.words[i])) { + ret = false; + } + } + } + return ret; }; - TwoFish.prototype.RS_MDS_Encode = function(k0, k1) { - var i, r, _i, _j; - r = k1; - for (i = _i = 0; _i < 4; i = ++_i) { - r = this.RS_rem(r); + WordArray.prototype.xor = function(wa2, _arg) { + var dst_offset, i, n_words, src_offset, tmp, _i; + dst_offset = _arg.dst_offset, src_offset = _arg.src_offset, n_words = _arg.n_words; + if (!dst_offset) { + dst_offset = 0; } - r ^= k0; - for (i = _j = 0; _j < 4; i = ++_j) { - r = this.RS_rem(r); + if (!src_offset) { + src_offset = 0; } - return r; + if (n_words == null) { + n_words = wa2.words.length - src_offset; + } + if (this.words.length < dst_offset + n_words) { + throw new Error("dest range exceeded (" + this.words.length + " < " + (dst_offset + n_words) + ")"); + } + if (wa2.words.length < src_offset + n_words) { + throw new Error("source range exceeded"); + } + for (i = _i = 0; 0 <= n_words ? _i < n_words : _i > n_words; i = 0 <= n_words ? ++_i : --_i) { + tmp = this.words[dst_offset + i] ^ wa2.words[src_offset + i]; + this.words[dst_offset + i] = util.fixup_uint32(tmp); + } + return this; }; - TwoFish.prototype.F32 = function(x, k32) { - var b0, b1, b2, b3, k0, k1, k2, k3, m, res; - b0 = this.getByte(x, 0); - b1 = this.getByte(x, 1); - b2 = this.getByte(x, 2); - b3 = this.getByte(x, 3); - k0 = k32[0]; - k1 = k32[1]; - k2 = k32[2]; - k3 = k32[3]; - m = this.k64Cnt & 3; - res = m === 1 ? this.gMDS0[(G.P[G.P_01][b0] & 0xff) ^ this.getByte(k0, 0)] ^ this.gMDS1[(G.P[G.P_11][b1] & 0xff) ^ this.getByte(k0, 1)] ^ this.gMDS2[(G.P[G.P_21][b2] & 0xff) ^ this.getByte(k0, 2)] ^ this.gMDS3[(G.P[G.P_31][b3] & 0xff) ^ this.getByte(k0, 3)] : (m === 0 ? (b0 = (G.P[G.P_04][b0] & 0xff) ^ this.getByte(k3, 0), b1 = (G.P[G.P_14][b1] & 0xff) ^ this.getByte(k3, 1), b2 = (G.P[G.P_24][b2] & 0xff) ^ this.getByte(k3, 2), b3 = (G.P[G.P_34][b3] & 0xff) ^ this.getByte(k3, 3)) : void 0, m === 0 || m === 3 ? (b0 = (G.P[G.P_03][b0] & 0xff) ^ this.getByte(k2, 0), b1 = (G.P[G.P_13][b1] & 0xff) ^ this.getByte(k2, 1), b2 = (G.P[G.P_23][b2] & 0xff) ^ this.getByte(k2, 2), b3 = (G.P[G.P_33][b3] & 0xff) ^ this.getByte(k2, 3)) : void 0, this.gMDS0[(G.P[G.P_01][(G.P[G.P_02][b0] & 0xff) ^ this.getByte(k1, 0)] & 0xff) ^ this.getByte(k0, 0)] ^ this.gMDS1[(G.P[G.P_11][(G.P[G.P_12][b1] & 0xff) ^ this.getByte(k1, 1)] & 0xff) ^ this.getByte(k0, 1)] ^ this.gMDS2[(G.P[G.P_21][(G.P[G.P_22][b2] & 0xff) ^ this.getByte(k1, 2)] & 0xff) ^ this.getByte(k0, 2)] ^ this.gMDS3[(G.P[G.P_31][(G.P[G.P_32][b3] & 0xff) ^ this.getByte(k1, 3)] & 0xff) ^ this.getByte(k0, 3)]); - return res; + WordArray.prototype.truncate = function(n_bytes) { + var n_words; + if (!(n_bytes <= this.sigBytes)) { + throw new Error("Cannot truncate: " + n_bytes + " > " + this.sigBytes); + } + n_words = Math.ceil(n_bytes / 4); + return new WordArray(this.words.slice(0, n_words), n_bytes); }; - TwoFish.prototype.Fe32_0 = function(x) { - return this.gSBox[0x000 + 2 * (x & 0xff)] ^ this.gSBox[0x001 + 2 * ((x >>> 8) & 0xff)] ^ this.gSBox[0x200 + 2 * ((x >>> 16) & 0xff)] ^ this.gSBox[0x201 + 2 * ((x >>> 24) & 0xff)]; + WordArray.prototype.unshift = function(n_words) { + var ret; + if (this.words.length >= n_words) { + ret = this.words.splice(0, n_words); + this.sigBytes -= n_words * 4; + return new WordArray(ret); + } else { + return null; + } }; - TwoFish.prototype.Fe32_3 = function(x) { - return this.gSBox[0x000 + 2 * ((x >>> 24) & 0xff)] ^ this.gSBox[0x001 + 2 * (x & 0xff)] ^ this.gSBox[0x200 + 2 * ((x >>> 8) & 0xff)] ^ this.gSBox[0x201 + 2 * ((x >>> 16) & 0xff)]; + WordArray.prototype.is_scrubbed = function() { + var w, _i, _len, _ref; + _ref = this.words; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + w = _ref[_i]; + if (w !== 0) { + return false; + } + } + return true; }; - TwoFish.prototype._doReset = function() { - var A, B, b0, b1, b2, b3, i, j, k0, k1, k2, k3, k32e, k32o, m, m1, mX, mY, p, q, sBoxKeys, _i, _j, _k, _l, _ref, _ref1, _results; - k32e = []; - k32o = []; - sBoxKeys = []; - m1 = []; - mX = []; - mY = []; - this.k64Cnt = this._key.words.length / 2; - if (this.k64Cnt < 1) { - throw "Key size less than 64 bits"; - } - if (this.k64Cnt > 4) { - throw "Key size larger than 256 bits"; - } - for (i = _i = 0; _i < 256; i = ++_i) { - j = G.P[0][i] & 0xff; - m1[0] = j; - mX[0] = this.Mx_X(j) & 0xff; - mY[0] = this.Mx_Y(j) & 0xff; - j = G.P[1][i] & 0xff; - m1[1] = j; - mX[1] = this.Mx_X(j) & 0xff; - mY[1] = this.Mx_Y(j) & 0xff; - this.gMDS0[i] = m1[G.P_00] | mX[G.P_00] << 8 | mY[G.P_00] << 16 | mY[G.P_00] << 24; - this.gMDS1[i] = mY[G.P_10] | mY[G.P_10] << 8 | mX[G.P_10] << 16 | m1[G.P_10] << 24; - this.gMDS2[i] = mX[G.P_20] | mY[G.P_20] << 8 | m1[G.P_20] << 16 | mY[G.P_20] << 24; - this.gMDS3[i] = mX[G.P_30] | m1[G.P_30] << 8 | mY[G.P_30] << 16 | mX[G.P_30] << 24; - } - for (i = _j = 0, _ref = this.k64Cnt; 0 <= _ref ? _j < _ref : _j > _ref; i = 0 <= _ref ? ++_j : --_j) { - p = i * 2; - k32e[i] = this.switchEndianness(this._key.words[p]); - k32o[i] = this.switchEndianness(this._key.words[p + 1]); - sBoxKeys[this.k64Cnt - 1 - i] = this.RS_MDS_Encode(k32e[i], k32o[i]); - } - for (i = _k = 0, _ref1 = 40 / 2; 0 <= _ref1 ? _k < _ref1 : _k > _ref1; i = 0 <= _ref1 ? ++_k : --_k) { - q = i * G.SK_STEP; - A = this.F32(q, k32e); - B = this.F32(q + G.SK_BUMP, k32o); - B = B << 8 | B >>> 24; - A += B; - this.gSubKeys[i * 2] = A; - A += B; - this.gSubKeys[i * 2 + 1] = A << G.SK_ROTL | A >>> (32 - G.SK_ROTL); + WordArray.prototype.scrub = function() { + return util.scrub_vec(this.words); + }; + + WordArray.prototype.slice = function(low, hi) { + var n, sb; + n = this.words.length; + if (!((low < hi) && (hi <= n))) { + throw new Error("Bad WordArray slice [" + low + "," + hi + ")] when only " + n + " avail"); } - k0 = sBoxKeys[0]; - k1 = sBoxKeys[1]; - k2 = sBoxKeys[2]; - k3 = sBoxKeys[3]; - this.gSBox = []; - _results = []; - for (i = _l = 0; _l < 256; i = ++_l) { - b0 = b1 = b2 = b3 = i; - m = this.k64Cnt & 3; - if (m === 1) { - this.gSBox[i * 2] = this.gMDS0[(G.P[G.P_01][b0] & 0xff) ^ this.getByte(k0, 0)]; - this.gSBox[i * 2 + 1] = this.gMDS1[(G.P[G.P_11][b1] & 0xff) ^ this.getByte(k0, 1)]; - this.gSBox[i * 2 + 0x200] = this.gMDS2[(G.P[G.P_21][b2] & 0xff) ^ this.getByte(k0, 2)]; - _results.push(this.gSBox[i * 2 + 0x201] = this.gMDS3[(G.P[G.P_31][b3] & 0xff) ^ this.getByte(k0, 3)]); - } else { - if (m === 0) { - b0 = (G.P[G.P_04][b0] & 0xff) ^ this.getByte(k3, 0); - b1 = (G.P[G.P_14][b1] & 0xff) ^ this.getByte(k3, 1); - b2 = (G.P[G.P_24][b2] & 0xff) ^ this.getByte(k3, 2); - b3 = (G.P[G.P_34][b3] & 0xff) ^ this.getByte(k3, 3); - } - if (m === 0 || m === 3) { - b0 = (G.P[G.P_03][b0] & 0xff) ^ this.getByte(k2, 0); - b1 = (G.P[G.P_13][b1] & 0xff) ^ this.getByte(k2, 1); - b2 = (G.P[G.P_23][b2] & 0xff) ^ this.getByte(k2, 2); - b3 = (G.P[G.P_33][b3] & 0xff) ^ this.getByte(k2, 3); - } - this.gSBox[i * 2] = this.gMDS0[(G.P[G.P_01][(G.P[G.P_02][b0] & 0xff) ^ this.getByte(k1, 0)] & 0xff) ^ this.getByte(k0, 0)]; - this.gSBox[i * 2 + 1] = this.gMDS1[(G.P[G.P_11][(G.P[G.P_12][b1] & 0xff) ^ this.getByte(k1, 1)] & 0xff) ^ this.getByte(k0, 1)]; - this.gSBox[i * 2 + 0x200] = this.gMDS2[(G.P[G.P_21][(G.P[G.P_22][b2] & 0xff) ^ this.getByte(k1, 2)] & 0xff) ^ this.getByte(k0, 2)]; - _results.push(this.gSBox[i * 2 + 0x201] = this.gMDS3[(G.P[G.P_31][(G.P[G.P_32][b3] & 0xff) ^ this.getByte(k1, 3)] & 0xff) ^ this.getByte(k0, 3)]); - } + sb = (hi - low) * 4; + if (hi === n) { + sb -= n * 4 - this.sigBytes; } - return _results; + return new WordArray(this.words.slice(low, hi), sb); }; - TwoFish.prototype.scrub = function() { - scrub_vec(this.gSubKeys); - scrub_vec(this.gSBox); - return this._key.scrub(); + return WordArray; + + })(); + + exports.X64Word = X64Word = (function() { + function X64Word(high, low) { + this.high = high; + this.low = low; + } + + X64Word.prototype.clone = function() { + return new X64Word(this.high, this.low); }; - TwoFish.prototype.decryptBlock = function(M, offset) { - var k, r, t0, t1, x0, x1, x2, x3, _i; - if (offset == null) { - offset = 0; + return X64Word; + + })(); + + exports.X64WordArray = X64WordArray = (function() { + function X64WordArray(words, sigBytes) { + this.sigBytes = sigBytes; + this.words = words || []; + if (!this.sigBytes) { + this.sigBytes = this.words.length * 8; } - x2 = this.switchEndianness(M[offset]) ^ this.gSubKeys[4]; - x3 = this.switchEndianness(M[offset + 1]) ^ this.gSubKeys[5]; - x0 = this.switchEndianness(M[offset + 2]) ^ this.gSubKeys[6]; - x1 = this.switchEndianness(M[offset + 3]) ^ this.gSubKeys[7]; - k = 8 + 2 * 16 - 1; - for (r = _i = 0; _i < 16; r = _i += 2) { - t0 = this.Fe32_0(x2); - t1 = this.Fe32_3(x3); - x1 ^= t0 + 2 * t1 + this.gSubKeys[k--]; - x0 = (x0 << 1 | x0 >>> 31) ^ (t0 + t1 + this.gSubKeys[k--]); - x1 = x1 >>> 1 | x1 << 31; - t0 = this.Fe32_0(x0); - t1 = this.Fe32_3(x1); - x3 ^= t0 + 2 * t1 + this.gSubKeys[k--]; - x2 = (x2 << 1 | x2 >>> 31) ^ (t0 + t1 + this.gSubKeys[k--]); - x3 = x3 >>> 1 | x3 << 31; + } + + X64WordArray.prototype.toX32 = function() { + var v, w, _i, _len, _ref; + v = []; + _ref = this.words; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + w = _ref[_i]; + v.push(w.high); + v.push(w.low); } - M[offset] = this.switchEndianness(x0 ^ this.gSubKeys[0]); - M[offset + 1] = this.switchEndianness(x1 ^ this.gSubKeys[1]); - M[offset + 2] = this.switchEndianness(x2 ^ this.gSubKeys[2]); - return M[offset + 3] = this.switchEndianness(x3 ^ this.gSubKeys[3]); + return new WordArray(v, this.sigBytes); }; - TwoFish.prototype.encryptBlock = function(M, offset) { - var k, r, t0, t1, x0, x1, x2, x3, _i; - if (offset == null) { - offset = 0; - } - x0 = this.switchEndianness(M[offset]) ^ this.gSubKeys[0]; - x1 = this.switchEndianness(M[offset + 1]) ^ this.gSubKeys[1]; - x2 = this.switchEndianness(M[offset + 2]) ^ this.gSubKeys[2]; - x3 = this.switchEndianness(M[offset + 3]) ^ this.gSubKeys[3]; - k = 8; - for (r = _i = 0; _i < 16; r = _i += 2) { - t0 = this.Fe32_0(x0); - t1 = this.Fe32_3(x1); - x2 ^= t0 + t1 + this.gSubKeys[k++]; - x2 = x2 >>> 1 | x2 << 31; - x3 = (x3 << 1 | x3 >>> 31) ^ (t0 + 2 * t1 + this.gSubKeys[k++]); - t0 = this.Fe32_0(x2); - t1 = this.Fe32_3(x3); - x0 ^= t0 + t1 + this.gSubKeys[k++]; - x0 = x0 >>> 1 | x0 << 31; - x1 = (x1 << 1 | x1 >>> 31) ^ (t0 + 2 * t1 + this.gSubKeys[k++]); - } - M[offset] = this.switchEndianness(x2 ^ this.gSubKeys[4]); - M[offset + 1] = this.switchEndianness(x3 ^ this.gSubKeys[5]); - M[offset + 2] = this.switchEndianness(x0 ^ this.gSubKeys[6]); - return M[offset + 3] = this.switchEndianness(x1 ^ this.gSubKeys[7]); + X64WordArray.prototype.clone = function() { + var w; + return new X64WordArray((function() { + var _i, _len, _ref, _results; + _ref = this.words; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + w = _ref[_i]; + _results.push(w.clone()); + } + return _results; + }).call(this), this.sigBytes); }; - return TwoFish; + return X64WordArray; - })(BlockCipher); + })(); -}).call(this); + exports.buffer_to_ui8a = buffer_to_ui8a; -},{"./algbase":18,"./util":37}],37:[function(require,module,exports){ -// Generated by IcedCoffeeScript 1.6.3-g -(function() { - var default_delay, iced, uint_max, __iced_k, __iced_k_noop; + exports.ui8a_to_buffer = ui8a_to_buffer; - iced = require('iced-coffee-script/lib/coffee-script/iced').runtime; - __iced_k = __iced_k_noop = function() {}; + exports.endian_reverse = endian_reverse; - uint_max = Math.pow(2, 32); +}).call(this); - exports.fixup_uint32 = function(x) { - var ret, x_pos; - ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x; - return ret; +}).call(this,require("buffer").Buffer) +},{"./util":35,"buffer":2}],37:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} - exports.scrub_buffer = function(b) { - var i, n_full_words; - n_full_words = b.length >> 2; - i = 0; - while (i < n_full_words) { - b.writeUInt32LE(0, i); - i += 4; - } - while (i < b.length) { - b.writeUInt8(0, i); - i++; +},{}],38:[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'; +} +},{}],39:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var 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 false; - }; + return objects.join(' '); + } - exports.scrub_vec = function(v) { - var i, _i, _ref; - for (i = _i = 0, _ref = v.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { - v[i] = 0; + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; } - return false; - }; + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; - exports.default_delay = default_delay = function(i, n, cb) { - var ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - (function(__iced_k) { - if (typeof setImmediate !== "undefined" && setImmediate !== null) { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/util.iced", - funcname: "default_delay" - }); - setImmediate(__iced_deferrals.defer({ - lineno: 37 - })); - __iced_deferrals._fulfill(); - })(__iced_k); + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + 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 { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/util.iced", - funcname: "default_delay" - }); - setTimeout(__iced_deferrals.defer({ - lineno: 39 - }), 1); - __iced_deferrals._fulfill(); - })(__iced_k); + console.error(msg); } - })(function() { - return cb(); - }); - }; + warned = true; + } + return fn.apply(this, arguments); + } - exports.bulk = function(n_input_bytes, _arg, _arg1) { - var call_ph, cb, default_n, delay, finalize, i, left, n, n_words, progress_hook, ret, total_words, update, what, ___iced_passed_deferral, __iced_deferrals, __iced_k, - _this = this; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - update = _arg.update, finalize = _arg.finalize, default_n = _arg.default_n; - delay = _arg1.delay, n = _arg1.n, cb = _arg1.cb, what = _arg1.what, progress_hook = _arg1.progress_hook; - i = 0; - left = 0; - total_words = Math.ceil(n_input_bytes / 4); - delay || (delay = default_delay); - n || (n = default_n); - call_ph = function(i) { - return typeof progress_hook === "function" ? progress_hook({ - what: what, - i: i, - total: total_words - }) : void 0; - }; - call_ph(0); - (function(__iced_k) { - var _results, _while; - _results = []; - _while = function(__iced_k) { - var _break, _continue, _next; - _break = function() { - return __iced_k(_results); - }; - _continue = function() { - return iced.trampoline(function() { - return _while(__iced_k); - }); - }; - _next = function(__iced_next_arg) { - _results.push(__iced_next_arg); - return _continue(); - }; - if (!((left = total_words - i) > 0)) { - return _break(); - } else { - n_words = Math.min(n, left); - update(i, i + n_words); - call_ph(i); - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "src/util.iced", - funcname: "bulk" - }); - delay(i, total_words, __iced_deferrals.defer({ - lineno: 73 - })); - __iced_deferrals._fulfill(); - })(function() { - return _next(i += n_words); - }); - } + 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); }; - _while(__iced_k); - })(function() { - call_ph(total_words); - ret = finalize(); - return cb(ret); - }); + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; -}).call(this); -},{"iced-coffee-script/lib/coffee-script/iced":9}],38:[function(require,module,exports){ -(function (Buffer){ -// Generated by IcedCoffeeScript 1.6.3-g -(function() { - var WordArray, X64Word, X64WordArray, buffer_to_ui8a, endian_reverse, ui8a_to_buffer, util; +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; - util = require('./util'); +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; - buffer_to_ui8a = function(b) { - var i, ret, _i, _ref; - ret = new Uint8Array(b.length); - for (i = _i = 0, _ref = b.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { - ret[i] = b.readUInt8(i); - } - return ret; - }; + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} - ui8a_to_buffer = function(v) { - var i, ret, _i, _ref; - ret = new Buffer(v.length); - for (i = _i = 0, _ref = v.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { - ret.writeUInt8(v[i], i); - } - return ret; - }; - endian_reverse = function(x) { - return ((x >>> 24) & 0xff) | (((x >>> 16) & 0xff) << 8) | (((x >>> 8) & 0xff) << 16) | ((x & 0xff) << 24); - }; +function stylizeNoColor(str, styleType) { + return str; +} - exports.WordArray = WordArray = (function() { - function WordArray(words, sigBytes) { - this.words = words || []; - this.sigBytes = sigBytes != null ? sigBytes : this.words.length * 4; - } - WordArray.prototype.concat = function(wordArray) { - var i, thatByte, thatSigBytes, thatWords, _i; - thatWords = wordArray.words; - thatSigBytes = wordArray.sigBytes; - this.clamp(); - if (this.sigBytes % 4) { - for (i = _i = 0; 0 <= thatSigBytes ? _i < thatSigBytes : _i > thatSigBytes; i = 0 <= thatSigBytes ? ++_i : --_i) { - thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - this.words[(this.sigBytes + i) >>> 2] |= thatByte << (24 - ((this.sigBytes + i) % 4) * 8); - } - } else { - this.words = this.words.concat(thatWords); - } - this.sigBytes += thatSigBytes; - return this; - }; +function arrayToHash(array) { + var hash = {}; - WordArray.prototype.clamp = function() { - this.words[this.sigBytes >>> 2] &= 0xffffffff << (32 - (this.sigBytes % 4) * 8); - this.words.length = Math.ceil(this.sigBytes / 4); - return this; - }; + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } - WordArray.prototype.clone = function() { - return new WordArray(this.words.slice(0), this.sigBytes); - }; + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - WordArray.prototype.to_buffer = function() { - var ch, out, p, w, _i, _len, _ref; - out = new Buffer(this.sigBytes); - p = 0; - _ref = this.words; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - w = _ref[_i]; - if (!((this.sigBytes - p) >= 4)) { - continue; - } - w = util.fixup_uint32(w); - out.writeUInt32BE(w, p); - p += 4; - } - while (p < this.sigBytes) { - ch = (this.words[p >>> 2] >>> (24 - (p % 4) * 8)) & 0xff; - out.writeUInt8(ch, p); - p++; - } - return out; - }; + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - WordArray.prototype.endian_reverse = function() { - var i, w, _i, _len, _ref; - _ref = this.words; - for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { - w = _ref[i]; - this.words[i] = endian_reverse(w); - } - return this; - }; + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - WordArray.prototype.split = function(n) { - var i, out, sz; - if (!(((this.sigBytes % 4) === 0) && ((this.words.length % n) === 0))) { - throw new Error("bad key alignment"); - } - sz = this.words.length / n; - out = (function() { - var _i, _ref, _results; - _results = []; - for (i = _i = 0, _ref = this.words.length; sz > 0 ? _i < _ref : _i > _ref; i = _i += sz) { - _results.push(new WordArray(this.words.slice(i, i + sz))); - } - return _results; - }).call(this); - return out; - }; + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } - WordArray.prototype.to_utf8 = function() { - return this.to_buffer().toString('utf8'); - }; + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } - WordArray.prototype.to_hex = function() { - return this.to_buffer().toString('hex'); - }; + var base = '', array = false, braces = ['{', '}']; - WordArray.prototype.to_ui8a = function() { - return buffer_to_ui8a(this.to_buffer()); - }; + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } - WordArray.alloc = function(b) { - if (Buffer.isBuffer(b)) { - return WordArray.from_buffer(b); - } else if ((typeof b === 'object') && (b instanceof WordArray)) { - return b; - } else if (typeof b === 'string') { - return WordArray.from_hex(b); - } else { - return null; - } - }; + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } - WordArray.from_buffer = function(b) { - var ch, last, p, words; - words = []; - p = 0; - while ((b.length - p) >= 4) { - words.push(b.readUInt32BE(p)); - p += 4; - } - if (p < b.length) { - last = 0; - while (p < b.length) { - ch = b.readUInt8(p); - last |= ch << (24 - (p % 4) * 8); - p++; - } - last = util.fixup_uint32(last); - words.push(last); - } - return new WordArray(words, b.length); - }; + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } - WordArray.from_buffer_le = function(b) { - var ch, last, p, words; - words = []; - p = 0; - while ((b.length - p) >= 4) { - words.push(b.readUInt32LE(p)); - p += 4; - } - if (p < b.length) { - last = 0; - while (p < b.length) { - ch = b.readUInt8(p); - last |= ch << ((p % 4) * 8); - p++; - } - last = util.fixup_uint32(last); - words.push(last); - } - return new WordArray(words, b.length); - }; + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } - WordArray.from_utf8 = function(s) { - return WordArray.from_buffer(new Buffer(s, 'utf8')); - }; + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } - WordArray.from_utf8_le = function(s) { - return WordArray.from_buffer_le(new Buffer(s, 'utf8')); - }; + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - WordArray.from_hex = function(s) { - return WordArray.from_buffer(new Buffer(s, 'hex')); - }; + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } - WordArray.from_hex_le = function(s) { - return WordArray.from_buffer_le(new Buffer(s, 'hex')); - }; + ctx.seen.push(value); - WordArray.from_ui8a = function(v) { - return WordArray.from_buffer(ui8a_to_buffer(v)); - }; + 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); + }); + } - WordArray.from_i32a = function(v) { - return new WordArray(Array.apply([], v)); - }; + ctx.seen.pop(); - WordArray.prototype.equal = function(wa) { - var i, ret, w, _i, _len, _ref; - ret = true; - if (wa.sigBytes !== this.sigBytes) { - ret = false; - } else { - _ref = this.words; - for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { - w = _ref[i]; - if (util.fixup_uint32(w) !== util.fixup_uint32(wa.words[i])) { - ret = false; - } - } - } - return ret; - }; + return reduceToSingleString(output, base, braces); +} - WordArray.prototype.xor = function(wa2, _arg) { - var dst_offset, i, n_words, src_offset, tmp, _i; - dst_offset = _arg.dst_offset, src_offset = _arg.src_offset, n_words = _arg.n_words; - if (!dst_offset) { - dst_offset = 0; - } - if (!src_offset) { - src_offset = 0; - } - if (n_words == null) { - n_words = wa2.words.length - src_offset; - } - if (this.words.length < dst_offset + n_words) { - throw new Error("dest range exceeded (" + this.words.length + " < " + (dst_offset + n_words) + ")"); - } - if (wa2.words.length < src_offset + n_words) { - throw new Error("source range exceeded"); - } - for (i = _i = 0; 0 <= n_words ? _i < n_words : _i > n_words; i = 0 <= n_words ? ++_i : --_i) { - tmp = this.words[dst_offset + i] ^ wa2.words[src_offset + i]; - this.words[dst_offset + i] = util.fixup_uint32(tmp); - } - return this; - }; - WordArray.prototype.truncate = function(n_bytes) { - var n_words; - if (!(n_bytes <= this.sigBytes)) { - throw new Error("Cannot truncate: " + n_bytes + " > " + this.sigBytes); - } - n_words = Math.ceil(n_bytes / 4); - return new WordArray(this.words.slice(0, n_words), n_bytes); - }; +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + - WordArray.prototype.unshift = function(n_words) { - var ret; - if (this.words.length >= n_words) { - ret = this.words.splice(0, n_words); - this.sigBytes -= n_words * 4; - return new WordArray(ret); - } else { - return null; - } - }; +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} - WordArray.prototype.is_scrubbed = function() { - var w, _i, _len, _ref; - _ref = this.words; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - w = _ref[_i]; - if (w !== 0) { - return false; - } - } - return true; - }; - WordArray.prototype.scrub = function() { - return util.scrub_vec(this.words); - }; +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; +} - WordArray.prototype.slice = function(low, hi) { - var n, sb; - n = this.words.length; - if (!((low < hi) && (hi <= n))) { - throw new Error("Bad WordArray slice [" + low + "," + hi + ")] when only " + n + " avail"); + +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); } - sb = (hi - low) * 4; - if (hi === n) { - sb -= n * 4 - this.sigBytes; + 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'); + } } - return new WordArray(this.words.slice(low, hi), sb); - }; - - return WordArray; + } 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; +} - exports.X64Word = X64Word = (function() { - function X64Word(high, low) { - this.high = high; - this.low = low; - } - X64Word.prototype.clone = function() { - return new X64Word(this.high, this.low); - }; +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); - return X64Word; + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } - })(); + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} - exports.X64WordArray = X64WordArray = (function() { - function X64WordArray(words, sigBytes) { - this.sigBytes = sigBytes; - this.words = words || []; - if (!this.sigBytes) { - this.sigBytes = this.words.length * 8; - } - } - X64WordArray.prototype.toX32 = function() { - var v, w, _i, _len, _ref; - v = []; - _ref = this.words; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - w = _ref[_i]; - v.push(w.high); - v.push(w.low); - } - return new WordArray(v, this.sigBytes); - }; +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; - X64WordArray.prototype.clone = function() { - var w; - return new X64WordArray((function() { - var _i, _len, _ref, _results; - _ref = this.words; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - w = _ref[_i]; - _results.push(w.clone()); - } - return _results; - }).call(this), this.sigBytes); - }; +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - return X64WordArray; +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - })(); +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - exports.buffer_to_ui8a = buffer_to_ui8a; +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - exports.ui8a_to_buffer = ui8a_to_buffer; +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - exports.endian_reverse = endian_reverse; +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; -}).call(this); +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; -}).call(this,require("buffer").Buffer) -},{"./util":37,"buffer":1}],39:[function(require,module,exports){ -// Generated by IcedCoffeeScript 1.7.1-f -(function() { - var Generator, iced, __iced_k, __iced_k_noop; +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; - iced = require('iced-runtime'); - __iced_k = __iced_k_noop = function() {}; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; - Generator = Generator = (function() { - function Generator(opts) { - opts = opts || {}; - this.lazy_loop_delay = opts.lazy_loop_delay || 30; - this.loop_delay = opts.loop_delay || 5; - this.work_min = opts.work_min || 1; - this.auto_stop_bits = opts.auto_stop_bits || 4096; - this.max_bits_per_delta = opts.max_bits_per_delta || 4; - this.auto_stop = opts.auto_stop ? opts.auto_stop : true; - this.entropies = []; - this.running = true; - this.is_generating = false; - this.timer_race_loop(); - } +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; - Generator.prototype.generate = function(bits_wanted, cb) { - var e, harvested_bits, res, ___iced_passed_deferral, __iced_deferrals, __iced_k; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - this.is_generating = true; - if (!this.running) { - this.resume(); - } - harvested_bits = 0; - res = []; - (function(_this) { - return (function(__iced_k) { - var _results, _while; - _results = []; - _while = function(__iced_k) { - var _break, _continue, _next; - _break = function() { - return __iced_k(_results); - }; - _continue = function() { - return iced.trampoline(function() { - return _while(__iced_k); - }); - }; - _next = function(__iced_next_arg) { - _results.push(__iced_next_arg); - return _continue(); - }; - if (!(harvested_bits < bits_wanted)) { - return _break(); - } else { - (function(__iced_k) { - if (_this.entropies.length) { - e = _this.entropies.splice(0, 1)[0]; - harvested_bits += e[1]; - return __iced_k(res.push(e[0])); - } else { - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "/Users/chris/git/more-entropy/src/generator.iced", - funcname: "Generator.generate" - }); - _this.delay(__iced_deferrals.defer({ - lineno: 28 - })); - __iced_deferrals._fulfill(); - })(__iced_k); - } - })(_next); - } - }; - _while(__iced_k); - }); - })(this)((function(_this) { - return function() { - if (_this.auto_stop) { - _this.stop(); - } - _this.is_generating = false; - return cb(res); - }; - })(this)); - }; +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; - Generator.prototype.stop = function() { - return this.running = false; - }; +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; - Generator.prototype.resume = function() { - this.running = true; - return this.timer_race_loop(); - }; +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; - Generator.prototype.reset = function() { - this.entropies = []; - return this.total_bits = 0; - }; +exports.isBuffer = require('./support/isBuffer'); - Generator.prototype.count_unused_bits = function() { - var bits, e, _i, _len, _ref; - bits = 0; - _ref = this.entropies; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - e = _ref[_i]; - bits += e[1]; - } - return bits; - }; +function objectToString(o) { + return Object.prototype.toString.call(o); +} - Generator.prototype.delay = function(cb) { - var delay, ___iced_passed_deferral, __iced_deferrals, __iced_k; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - delay = this.is_generating ? this.loop_delay : this.lazy_loop_delay; - (function(_this) { - return (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "/Users/chris/git/more-entropy/src/generator.iced", - funcname: "Generator.delay" - }); - setTimeout(__iced_deferrals.defer({ - lineno: 50 - }), delay); - __iced_deferrals._fulfill(); - }); - })(this)((function(_this) { - return function() { - return cb(); - }; - })(this)); - }; - Generator.prototype.timer_race_loop = function() { - var ___iced_passed_deferral, __iced_k, _results, _while; - __iced_k = __iced_k_noop; - ___iced_passed_deferral = iced.findDeferral(arguments); - this._last_count = null; - _results = []; - _while = (function(_this) { - var count, delta, entropy, v, __iced_deferrals; - return function(__iced_k) { - var _break, _continue, _next; - _break = function() { - return __iced_k(_results); - }; - _continue = function() { - return iced.trampoline(function() { - return _while(__iced_k); - }); - }; - _next = function(__iced_next_arg) { - _results.push(__iced_next_arg); - return _continue(); - }; - if (!_this.running) { - return _break(); - } else { - if (_this.count_unused_bits() < _this.auto_stop_bits) { - count = _this.millisecond_count(); - if ((_this._last_count != null) && (delta = count - _this._last_count)) { - entropy = Math.floor(_this.log_2(Math.abs(delta))); - entropy = Math.min(_this.max_bits_per_delta, entropy); - v = [delta, entropy]; - _this.entropies.push(v); - } - _this._last_count = count; - } - (function(__iced_k) { - __iced_deferrals = new iced.Deferrals(__iced_k, { - parent: ___iced_passed_deferral, - filename: "/Users/chris/git/more-entropy/src/generator.iced", - funcname: "Generator.timer_race_loop" - }); - _this.delay(__iced_deferrals.defer({ - lineno: 64 - })); - __iced_deferrals._fulfill(); - })(_next); - } - }; - })(this); - _while(__iced_k); - }; +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} - Generator.prototype.log_2 = function(x) { - return Math.log(x) / Math.LN2; - }; - Generator.prototype.millisecond_count = function() { - var d, i, x; - d = Date.now(); - i = x = 0; - while (Date.now() < d + this.work_min + 1) { - i++; - x = Math.sin(Math.sqrt(Math.log(i + x))); - } - return i; - }; +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; - return Generator; +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} - })(); - if (typeof window !== "undefined" && window !== null) { - window.Generator = Generator; - } +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; - if (typeof exports !== "undefined" && exports !== null) { - exports.Generator = Generator; - } -}).call(this); +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); -},{"iced-runtime":13}],40:[function(require,module,exports){ -// Generated by IcedCoffeeScript 1.7.1-c -(function() { - exports.Generator = require('../lib/generator').Generator; +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; -}).call(this); + 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); +} -},{"../lib/generator":39}],41:[function(require,module,exports){ +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":38,"_process":14,"inherits":37}],40:[function(require,module,exports){ (function (Buffer){ var HMAC_SHA256, WordArray, from_utf8, generate, iced, params, pbkdf2, run, scrypt, util, __iced_k, __iced_k_noop, _ref; @@ -11742,7 +12076,7 @@ exports.run = run = function(_arg, cb) { }; }).call(this,require("buffer").Buffer) -},{"../json/params.json":42,"buffer":1,"iced-runtime":13,"keybase-bitcoin":15,"triplesec":26}],42:[function(require,module,exports){ +},{"../json/params.json":41,"buffer":2,"iced-runtime":7,"keybase-bitcoin":10,"triplesec":24}],41:[function(require,module,exports){ module.exports={ "N" : 18, "p" : 1, @@ -11751,5 +12085,5 @@ module.exports={ "pbkdf2c" : 65536 } -},{}]},{},[41])(41) +},{}]},{},[40])(40) }); \ No newline at end of file diff --git a/src/js/jquery-ui.min.js b/src/js/jquery-ui.min.js new file mode 100644 index 0000000..117cb35 --- /dev/null +++ b/src/js/jquery-ui.min.js @@ -0,0 +1,13 @@ +/*! jQuery UI - v1.12.1 - 2016-09-14 +* http://jqueryui.com +* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js +* Copyright jQuery Foundation and other contributors; Licensed MIT */ + +(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}function i(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function s(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=n(t("
"))}function n(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,o)}function o(){t.datepicker._isDisabledDatepicker(m.inline?m.dpDiv.parent()[0]:m.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function a(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function r(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.ui.version="1.12.1";var h=0,l=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],o=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),o=0,a=n.length;a>o;o++)for(i in n[o])s=n[o][i],n[o].hasOwnProperty(i)&&void 0!==s&&(e[i]=t.isPlainObject(s)?t.isPlainObject(e[i])?t.widget.extend({},e[i],s):t.widget.extend({},s):s);return e},t.widget.bridge=function(e,i){var s=i.prototype.widgetFullName||e;t.fn[e]=function(n){var o="string"==typeof n,a=l.call(arguments,1),r=this;return o?this.length||"instance"!==n?this.each(function(){var i,o=t.data(this,s);return"instance"===n?(r=o,!1):o?t.isFunction(o[n])&&"_"!==n.charAt(0)?(i=o[n].apply(o,a),i!==o&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+n+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+n+"'")}):r=void 0:(a.length&&(n=t.widget.extend.apply(null,[n].concat(a))),this.each(function(){var e=t.data(this,s);e?(e.option(n||{}),e._init&&e._init()):t.data(this,s,new i(n,this))})),r}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"
",options:{classes:{},disabled:!1,create:null},_createWidget:function(e,i){i=t(i||this.defaultElement||this)[0],this.element=t(i),this.uuid=h++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},i!==this&&(t.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===i&&this.destroy()}}),this.document=t(i.style?i.ownerDocument:i.document||i),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){function i(i,o){var a,r;for(r=0;i.length>r;r++)a=n.classesElementLookup[i[r]]||t(),a=e.add?t(t.unique(a.get().concat(e.element.get()))):t(a.not(e.element).get()),n.classesElementLookup[i[r]]=a,s.push(i[r]),o&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),this._on(e.element,{remove:"_untrackClassesElement"}),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))})},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+o.eventNamespace,c=h[2];c?n.on(l,c,r):i.on(l,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,function(){function e(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function i(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}var n,o=Math.max,a=Math.abs,r=/left|center|right/,h=/top|center|bottom/,l=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,d=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("
"),o=s.children()[0];return t("body").append(s),e=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.widthi?"left":e>0?"right":"center",vertical:0>r?"top":s>0?"bottom":"middle"};l>p&&p>a(e+i)&&(u.horizontal="center"),c>f&&f>a(s+r)&&(u.vertical="middle"),u.important=o(a(e),a(i))>o(a(s),a(r))?"horizontal":"vertical",n.using.call(this,t,u)}),h.offset(t.extend(D,{using:r}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-a-n;e.collisionWidth>a?h>0&&0>=l?(i=t.left+h+e.collisionWidth-a-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+a-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-a-n;e.collisionHeight>a?h>0&&0>=l?(i=t.top+h+e.collisionHeight-a-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+a-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,r=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,c=l-h,u=l+e.collisionWidth-r-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-r-o,(0>i||a(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||u>a(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,r=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,c=l-h,u=l+e.collisionHeight-r-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-r-o,(0>s||a(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-h,(i>0||u>a(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])}}),t.fn.extend({disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.off(".ui-disableSelection")}});var c="ui-effects-",u="ui-effects-style",d="ui-effects-animated",p=t;t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(t,o){var a,r=o.re.exec(i),h=r&&o.parse(r),l=o.space||"rgba";return h?(a=s[l](h),s[c[l].cache]=a[c[l].cache],n=s._rgba=a._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,o.transparent),s):o[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var o,a="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],l=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=l.support={},p=t("

")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),l.fn=t.extend(l.prototype,{parse:function(n,a,r,h){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(a),a=e);var u=this,d=t.type(n),p=this._rgba=[];return a!==e&&(n=[n,a,r,h],d="array"),"string"===d?this.parse(s(n)||o._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof l?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var o=s.cache;f(s.props,function(t,e){if(!u[o]&&s.to){if("alpha"===t||null==n[t])return;u[o]=s.to(u._rgba)}u[o][e.idx]=i(n[t],e,!0)}),u[o]&&0>t.inArray(null,u[o].slice(0,3))&&(u[o][3]=1,s.from&&(u._rgba=s.from(u[o])))}),this):e},is:function(t){var i=l(t),s=!0,n=this;return f(c,function(t,o){var a,r=i[o.cache];return r&&(a=n[o.cache]||o.to&&o.to(n._rgba)||[],f(o.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===a[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=l(t),n=s._space(),o=c[n],a=0===this.alpha()?l("transparent"):this,r=a[o.cache]||o.to(a._rgba),h=r.slice();return s=s[o.cache],f(o.props,function(t,n){var o=n.idx,a=r[o],l=s[o],c=u[n.type]||{};null!==l&&(null===a?h[o]=l:(c.mod&&(l-a>c.mod/2?a+=c.mod:a-l>c.mod/2&&(a-=c.mod)),h[o]=i((l-a)*e+a,n)))}),this[n](h)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(e)._rgba;return l(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,o=t[2]/255,a=t[3],r=Math.max(s,n,o),h=Math.min(s,n,o),l=r-h,c=r+h,u=.5*c;return e=h===r?0:s===r?60*(n-o)/l+360:n===r?60*(o-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=u?l/c:l/(2-c),[Math.round(e)%360,i,u,null==a?1:a]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],o=t[3],a=.5>=s?s*(1+i):s+i-s*i,r=2*s-a;return[Math.round(255*n(r,a,e+1/3)),Math.round(255*n(r,a,e)),Math.round(255*n(r,a,e-1/3)),o]},f(c,function(s,n){var o=n.props,a=n.cache,h=n.to,c=n.from;l.fn[s]=function(s){if(h&&!this[a]&&(this[a]=h(this._rgba)),s===e)return this[a].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[a].slice();return f(o,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=l(c(d)),n[a]=d,n):l(d)},f(o,function(e,i){l.fn[e]||(l.fn[e]=function(n){var o,a=t.type(n),h="alpha"===e?this._hsla?"hsla":"rgba":s,l=this[h](),c=l[i.idx];return"undefined"===a?c:("function"===a&&(n=n.call(this,c),a=t.type(n)),null==n&&i.empty?this:("string"===a&&(o=r.exec(n),o&&(n=c+parseFloat(o[2])*("+"===o[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var o,a,r="";if("transparent"!==n&&("string"!==t.type(n)||(o=s(n)))){if(n=l(o||n),!d.rgba&&1!==n._rgba[3]){for(a="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&a&&a.style;)try{r=t.css(a,"backgroundColor"),a=a.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(h){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=l(e.elem,i),e.end=l(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},l.hook(a),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},o=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(p),function(){function e(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,o={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(o[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(o[i]=n[i]);return o}function i(e,i){var s,o,a={};for(s in i)o=i[s],e[s]!==o&&(n[s]||(t.fx.step[s]||!isNaN(parseFloat(o)))&&(a[s]=o));return a}var s=["add","remove","toggle"],n={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(p.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(n,o,a,r){var h=t.speed(o,a,r);return this.queue(function(){var o,a=t(this),r=a.attr("class")||"",l=h.children?a.find("*").addBack():a;l=l.map(function(){var i=t(this);return{el:i,start:e(this)}}),o=function(){t.each(s,function(t,e){n[e]&&a[e+"Class"](n[e])})},o(),l=l.map(function(){return this.end=e(this.el[0]),this.diff=i(this.start,this.end),this}),a.attr("class",r),l=l.map(function(){var e=this,i=t.Deferred(),s=t.extend({},h,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,l.get()).done(function(){o(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),h.complete.call(a[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,o){return s?t.effects.animateClass.call(this,{add:i},s,n,o):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,o){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,o):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(e){return function(i,s,n,o,a){return"boolean"==typeof s||void 0===s?n?t.effects.animateClass.call(this,s?{add:i}:{remove:i},n,o,a):e.apply(this,arguments):t.effects.animateClass.call(this,{toggle:i},s,n,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,o){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,o)}})}(),function(){function e(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function i(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}function s(t,e){var i=e.outerWidth(),s=e.outerHeight(),n=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,o=n.exec(t)||["",0,i,s,0];return{top:parseFloat(o[1])||0,right:"auto"===o[2]?i:parseFloat(o[2]),bottom:"auto"===o[3]?s:parseFloat(o[3]),left:parseFloat(o[4])||0}}t.expr&&t.expr.filters&&t.expr.filters.animated&&(t.expr.filters.animated=function(e){return function(i){return!!t(i).data(d)||e(i)}}(t.expr.filters.animated)),t.uiBackCompat!==!1&&t.extend(t.effects,{save:function(t,e){for(var i=0,s=e.length;s>i;i++)null!==e[i]&&t.data(c+e[i],t[0].style[e[i]])},restore:function(t,e){for(var i,s=0,n=e.length;n>s;s++)null!==e[s]&&(i=t.data(c+e[s]),t.css(e[s],i))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("

").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},o=document.activeElement;try{o.id}catch(a){o=document.body}return e.wrap(s),(e[0]===o||t.contains(e[0],o))&&t(o).trigger("focus"),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).trigger("focus")),e}}),t.extend(t.effects,{version:"1.12.1",define:function(e,i,s){return s||(s=i,i="effect"),t.effects.effect[e]=s,t.effects.effect[e].mode=i,s},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,n="vertical"!==i?(e||100)/100:1;return{height:t.height()*n,width:t.width()*s,outerHeight:t.outerHeight()*n,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();e>1&&s.splice.apply(s,[1,0].concat(s.splice(e,i))),t.dequeue()},saveStyle:function(t){t.data(u,t[0].style.cssText)},restoreStyle:function(t){t[0].style.cssText=t.data(u)||"",t.removeData(u)},mode:function(t,e){var i=t.is(":hidden");return"toggle"===e&&(e=i?"show":"hide"),(i?"hide"===e:"show"===e)&&(e="none"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createPlaceholder:function(e){var i,s=e.css("position"),n=e.position();return e.css({marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()),/^(static|relative)/.test(s)&&(s="absolute",i=t("<"+e[0].nodeName+">").insertAfter(e).css({display:/^(inline|ruby)/.test(e.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight"),"float":e.css("float")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).addClass("ui-effects-placeholder"),e.data(c+"placeholder",i)),e.css({position:s,left:n.left,top:n.top}),i},removePlaceholder:function(t){var e=c+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(e){t.effects.restoreStyle(e),t.effects.removePlaceholder(e)},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var o=e.cssUnit(i);o[0]>0&&(n[i]=o[0]*s+o[1])}),n}}),t.fn.extend({effect:function(){function i(e){function i(){r.removeData(d),t.effects.cleanUp(r),"hide"===s.mode&&r.hide(),a()}function a(){t.isFunction(h)&&h.call(r[0]),t.isFunction(e)&&e()}var r=t(this);s.mode=c.shift(),t.uiBackCompat===!1||o?"none"===s.mode?(r[l](),a()):n.call(r[0],s,i):(r.is(":hidden")?"hide"===l:"show"===l)?(r[l](),a()):n.call(r[0],s,a)}var s=e.apply(this,arguments),n=t.effects.effect[s.effect],o=n.mode,a=s.queue,r=a||"fx",h=s.complete,l=s.mode,c=[],u=function(e){var i=t(this),s=t.effects.mode(i,l)||o;i.data(d,!0),c.push(s),o&&("show"===s||s===o&&"hide"===s)&&i.show(),o&&"none"===s||t.effects.saveStyle(i),t.isFunction(e)&&e()};return t.fx.off||!n?l?this[l](s.duration,h):this.each(function(){h&&h.call(this)}):a===!1?this.each(u).each(i):this.queue(r,u).queue(r,i)},show:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="show",this.effect.call(this,n) +}}(t.fn.show),hide:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(t.fn.hide),toggle:function(t){return function(s){if(i(s)||"boolean"==typeof s)return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):s(this.css("clip"),this)},transfer:function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("
").appendTo("body").addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),t.isFunction(i)&&i()})}}),t.fx.step.clip=function(e){e.clipInit||(e.start=t(e.elem).cssClip(),"string"==typeof e.end&&(e.end=s(e.end,e.elem)),e.clipInit=!0),t(e.elem).cssClip({top:e.pos*(e.end.top-e.start.top)+e.start.top,right:e.pos*(e.end.right-e.start.right)+e.start.right,bottom:e.pos*(e.end.bottom-e.start.bottom)+e.start.bottom,left:e.pos*(e.end.left-e.start.left)+e.start.left})}}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}();var f=t.effects;t.effects.define("blind","hide",function(e,i){var s={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},n=t(this),o=e.direction||"up",a=n.cssClip(),r={clip:t.extend({},a)},h=t.effects.createPlaceholder(n);r.clip[s[o][0]]=r.clip[s[o][1]],"show"===e.mode&&(n.cssClip(r.clip),h&&h.css(t.effects.clipToBox(r)),r.clip=a),h&&h.animate(t.effects.clipToBox(r),e.duration,e.easing),n.animate(r,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("bounce",function(e,i){var s,n,o,a=t(this),r=e.mode,h="hide"===r,l="show"===r,c=e.direction||"up",u=e.distance,d=e.times||5,p=2*d+(l||h?1:0),f=e.duration/p,g=e.easing,m="up"===c||"down"===c?"top":"left",_="up"===c||"left"===c,v=0,b=a.queue().length;for(t.effects.createPlaceholder(a),o=a.css(m),u||(u=a["top"===m?"outerHeight":"outerWidth"]()/3),l&&(n={opacity:1},n[m]=o,a.css("opacity",0).css(m,_?2*-u:2*u).animate(n,f,g)),h&&(u/=Math.pow(2,d-1)),n={},n[m]=o;d>v;v++)s={},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g).animate(n,f,g),u=h?2*u:u/2;h&&(s={opacity:0},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g)),a.queue(i),t.effects.unshift(a,b,p+1)}),t.effects.define("clip","hide",function(e,i){var s,n={},o=t(this),a=e.direction||"vertical",r="both"===a,h=r||"horizontal"===a,l=r||"vertical"===a;s=o.cssClip(),n.clip={top:l?(s.bottom-s.top)/2:s.top,right:h?(s.right-s.left)/2:s.right,bottom:l?(s.bottom-s.top)/2:s.bottom,left:h?(s.right-s.left)/2:s.left},t.effects.createPlaceholder(o),"show"===e.mode&&(o.cssClip(n.clip),n.clip=s),o.animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("drop","hide",function(e,i){var s,n=t(this),o=e.mode,a="show"===o,r=e.direction||"left",h="up"===r||"down"===r?"top":"left",l="up"===r||"left"===r?"-=":"+=",c="+="===l?"-=":"+=",u={opacity:0};t.effects.createPlaceholder(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,u[h]=l+s,a&&(n.css(u),u[h]=c+s,u.opacity=1),n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("explode","hide",function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=e.mode,g="show"===f,m=p.show().css("visibility","hidden").offset(),_=Math.ceil(p.outerWidth()/d),v=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*v,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*_,l=a-(d-1)/2,p.clone().appendTo("body").wrap("
").css({position:"absolute",visibility:"visible",left:-a*_,top:-o*v}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:_,height:v,left:r+(g?l*_:0),top:h+(g?c*v:0),opacity:g?0:1}).animate({left:r+(g?0:l*_),top:h+(g?0:c*v),opacity:g?1:0},e.duration||500,e.easing,s)}),t.effects.define("fade","toggle",function(e,i){var s="show"===e.mode;t(this).css("opacity",s?0:1).animate({opacity:s?1:0},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("fold","hide",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=e.size||15,h=/([0-9]+)%/.exec(r),l=!!e.horizFirst,c=l?["right","bottom"]:["bottom","right"],u=e.duration/2,d=t.effects.createPlaceholder(s),p=s.cssClip(),f={clip:t.extend({},p)},g={clip:t.extend({},p)},m=[p[c[0]],p[c[1]]],_=s.queue().length;h&&(r=parseInt(h[1],10)/100*m[a?0:1]),f.clip[c[0]]=r,g.clip[c[0]]=r,g.clip[c[1]]=0,o&&(s.cssClip(g.clip),d&&d.css(t.effects.clipToBox(g)),g.clip=p),s.queue(function(i){d&&d.animate(t.effects.clipToBox(f),u,e.easing).animate(t.effects.clipToBox(g),u,e.easing),i()}).animate(f,u,e.easing).animate(g,u,e.easing).queue(i),t.effects.unshift(s,_,4)}),t.effects.define("highlight","show",function(e,i){var s=t(this),n={backgroundColor:s.css("backgroundColor")};"hide"===e.mode&&(n.opacity=0),t.effects.saveStyle(s),s.css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("size",function(e,i){var s,n,o,a=t(this),r=["fontSize"],h=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],l=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],c=e.mode,u="effect"!==c,d=e.scale||"both",p=e.origin||["middle","center"],f=a.css("position"),g=a.position(),m=t.effects.scaledDimensions(a),_=e.from||m,v=e.to||t.effects.scaledDimensions(a,0);t.effects.createPlaceholder(a),"show"===c&&(o=_,_=v,v=o),n={from:{y:_.height/m.height,x:_.width/m.width},to:{y:v.height/m.height,x:v.width/m.width}},("box"===d||"both"===d)&&(n.from.y!==n.to.y&&(_=t.effects.setTransition(a,h,n.from.y,_),v=t.effects.setTransition(a,h,n.to.y,v)),n.from.x!==n.to.x&&(_=t.effects.setTransition(a,l,n.from.x,_),v=t.effects.setTransition(a,l,n.to.x,v))),("content"===d||"both"===d)&&n.from.y!==n.to.y&&(_=t.effects.setTransition(a,r,n.from.y,_),v=t.effects.setTransition(a,r,n.to.y,v)),p&&(s=t.effects.getBaseline(p,m),_.top=(m.outerHeight-_.outerHeight)*s.y+g.top,_.left=(m.outerWidth-_.outerWidth)*s.x+g.left,v.top=(m.outerHeight-v.outerHeight)*s.y+g.top,v.left=(m.outerWidth-v.outerWidth)*s.x+g.left),a.css(_),("content"===d||"both"===d)&&(h=h.concat(["marginTop","marginBottom"]).concat(r),l=l.concat(["marginLeft","marginRight"]),a.find("*[width]").each(function(){var i=t(this),s=t.effects.scaledDimensions(i),o={height:s.height*n.from.y,width:s.width*n.from.x,outerHeight:s.outerHeight*n.from.y,outerWidth:s.outerWidth*n.from.x},a={height:s.height*n.to.y,width:s.width*n.to.x,outerHeight:s.height*n.to.y,outerWidth:s.width*n.to.x};n.from.y!==n.to.y&&(o=t.effects.setTransition(i,h,n.from.y,o),a=t.effects.setTransition(i,h,n.to.y,a)),n.from.x!==n.to.x&&(o=t.effects.setTransition(i,l,n.from.x,o),a=t.effects.setTransition(i,l,n.to.x,a)),u&&t.effects.saveStyle(i),i.css(o),i.animate(a,e.duration,e.easing,function(){u&&t.effects.restoreStyle(i)})})),a.animate(v,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){var e=a.offset();0===v.opacity&&a.css("opacity",_.opacity),u||(a.css("position","static"===f?"relative":f).offset(e),t.effects.saveStyle(a)),i()}})}),t.effects.define("scale",function(e,i){var s=t(this),n=e.mode,o=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"effect"!==n?0:100),a=t.extend(!0,{from:t.effects.scaledDimensions(s),to:t.effects.scaledDimensions(s,o,e.direction||"both"),origin:e.origin||["middle","center"]},e);e.fade&&(a.from.opacity=1,a.to.opacity=0),t.effects.effect.size.call(this,a,i)}),t.effects.define("puff","hide",function(e,i){var s=t.extend(!0,{},e,{fade:!0,percent:parseInt(e.percent,10)||150});t.effects.effect.scale.call(this,s,i)}),t.effects.define("pulsate","show",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=o||a,h=2*(e.times||5)+(r?1:0),l=e.duration/h,c=0,u=1,d=s.queue().length;for((o||!s.is(":visible"))&&(s.css("opacity",0).show(),c=1);h>u;u++)s.animate({opacity:c},l,e.easing),c=1-c;s.animate({opacity:c},l,e.easing),s.queue(i),t.effects.unshift(s,d,h+1)}),t.effects.define("shake",function(e,i){var s=1,n=t(this),o=e.direction||"left",a=e.distance||20,r=e.times||3,h=2*r+1,l=Math.round(e.duration/h),c="up"===o||"down"===o?"top":"left",u="up"===o||"left"===o,d={},p={},f={},g=n.queue().length;for(t.effects.createPlaceholder(n),d[c]=(u?"-=":"+=")+a,p[c]=(u?"+=":"-=")+2*a,f[c]=(u?"-=":"+=")+2*a,n.animate(d,l,e.easing);r>s;s++)n.animate(p,l,e.easing).animate(f,l,e.easing);n.animate(p,l,e.easing).animate(d,l/2,e.easing).queue(i),t.effects.unshift(n,g,h+1)}),t.effects.define("slide","show",function(e,i){var s,n,o=t(this),a={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},r=e.mode,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h,u=e.distance||o["top"===l?"outerHeight":"outerWidth"](!0),d={};t.effects.createPlaceholder(o),s=o.cssClip(),n=o.position()[l],d[l]=(c?-1:1)*u+n,d.clip=o.cssClip(),d.clip[a[h][1]]=d.clip[a[h][0]],"show"===r&&(o.cssClip(d.clip),o.css(l,d[l]),d.clip=s,d[l]=n),o.animate(d,{queue:!1,duration:e.duration,easing:e.easing,complete:i})});var f;t.uiBackCompat!==!1&&(f=t.effects.define("transfer",function(e,i){t(this).transfer(e,i)})),t.ui.focusable=function(i,s){var n,o,a,r,h,l=i.nodeName.toLowerCase();return"area"===l?(n=i.parentNode,o=n.name,i.href&&o&&"map"===n.nodeName.toLowerCase()?(a=t("img[usemap='#"+o+"']"),a.length>0&&a.is(":visible")):!1):(/^(input|select|textarea|button|object)$/.test(l)?(r=!i.disabled,r&&(h=t(i).closest("fieldset")[0],h&&(r=!h.disabled))):r="a"===l?i.href||s:s,r&&t(i).is(":visible")&&e(t(i)))},t.extend(t.expr[":"],{focusable:function(e){return t.ui.focusable(e,null!=t.attr(e,"tabindex"))}}),t.ui.focusable,t.fn.form=function(){return"string"==typeof this[0].form?this.closest("form"):t(this[0].form)},t.ui.formResetMixin={_formResetHandler:function(){var e=t(this);setTimeout(function(){var i=e.data("ui-form-reset-instances");t.each(i,function(){this.refresh()})})},_bindFormResetHandler:function(){if(this.form=this.element.form(),this.form.length){var t=this.form.data("ui-form-reset-instances")||[];t.length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t)}},_unbindFormResetHandler:function(){if(this.form.length){var e=this.form.data("ui-form-reset-instances");e.splice(t.inArray(this,e),1),e.length?this.form.data("ui-form-reset-instances",e):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}},"1.7"===t.fn.jquery.substring(0,3)&&(t.each(["Width","Height"],function(e,i){function s(e,i,s,o){return t.each(n,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),o&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],o=i.toLowerCase(),a={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+i]=function(e){return void 0===e?a["inner"+i].call(this):this.each(function(){t(this).css(o,s(this,e)+"px")})},t.fn["outer"+i]=function(e,n){return"number"!=typeof e?a["outer"+i].call(this,e):this.each(function(){t(this).css(o,s(this,e,!0,n)+"px")})}}),t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},t.ui.escapeSelector=function(){var t=/([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g;return function(e){return e.replace(t,"\\$1")}}(),t.fn.labels=function(){var e,i,s,n,o;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(n=this.eq(0).parents("label"),s=this.attr("id"),s&&(e=this.eq(0).parents().last(),o=e.add(e.length?e.siblings():this.siblings()),i="label[for='"+t.ui.escapeSelector(s)+"']",n=n.add(o.find(i).addBack(i))),this.pushStack(n))},t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},t.extend(t.expr[":"],{tabbable:function(e){var i=t.attr(e,"tabindex"),s=null!=i;return(!s||i>=0)&&t.ui.focusable(e,s)}}),t.fn.extend({uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.widget("ui.accordion",{version:"1.12.1",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:!1,event:"click",header:"> li > :first-child, > :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),e.collapsible||e.active!==!1&&null!=e.active||(e.active=0),this._processPanels(),0>e.active&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t()}},_createIcons:function(){var e,i,s=this.options.icons;s&&(e=t(""),this._addClass(e,"ui-accordion-header-icon","ui-icon "+s.header),e.prependTo(this.headers),i=this.active.children(".ui-accordion-header-icon"),this._removeClass(i,s.header)._addClass(i,null,s.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||this.options.active!==!1||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons()),void 0)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),o=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:o=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:o=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:o=this.headers[0];break;case i.END:o=this.headers[s-1]}o&&(t(e.target).attr("tabIndex",-1),t(o).attr("tabIndex",0),t(o).trigger("focus"),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().trigger("focus")},refresh:function(){var e=this.options;this._processPanels(),e.active===!1&&e.collapsible===!0||!this.headers.length?(e.active=!1,this.active=t()):e.active===!1?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var e,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var e=t(this),i=e.uniqueId().attr("id"),s=e.next(),n=s.uniqueId().attr("id");e.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(e=n.height(),this.element.siblings(":visible").each(function(){var i=t(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(e-=i.outerHeight(!0))}),this.headers.each(function(){e-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,e-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===s&&(e=0,this.headers.next().each(function(){var i=t(this).is(":visible");i||t(this).show(),e=Math.max(e,t(this).css("height","").height()),i||t(this).hide()}).height(e))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(e){var i,s,n=this.options,o=this.active,a=t(e.currentTarget),r=a[0]===o[0],h=r&&n.collapsible,l=h?t():a.next(),c=o.next(),u={oldHeader:o,oldPanel:c,newHeader:h?t():a,newPanel:l};e.preventDefault(),r&&!n.collapsible||this._trigger("beforeActivate",e,u)===!1||(n.active=h?!1:this.headers.index(a),this.active=r?t():a,this._toggle(u),this._removeClass(o,"ui-accordion-header-active","ui-state-active"),n.icons&&(i=o.children(".ui-accordion-header-icon"),this._removeClass(i,null,n.icons.activeHeader)._addClass(i,null,n.icons.header)),r||(this._removeClass(a,"ui-accordion-header-collapsed")._addClass(a,"ui-accordion-header-active","ui-state-active"),n.icons&&(s=a.children(".ui-accordion-header-icon"),this._removeClass(s,null,n.icons.header)._addClass(s,null,n.icons.activeHeader)),this._addClass(a.next(),"ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(t(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,e,i){var s,n,o,a=this,r=0,h=t.css("box-sizing"),l=t.length&&(!e.length||t.index()",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(e){var i=t(e.target),s=t(t.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&s.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){if(!this.previousFilter){var i=t(e.target).closest(".ui-menu-item"),s=t(e.currentTarget);i[0]===s[0]&&(this._removeClass(s.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,s))}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){var i=!t.contains(this.element[0],t.ui.safeActiveElement(this.document[0]));i&&this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled"),i=e.children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),i.children().each(function(){var e=t(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var i,s,n,o,a=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:a=!1,s=this.previousFilter||"",o=!1,n=e.keyCode>=96&&105>=e.keyCode?""+(e.keyCode-96):String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),n===s?o=!0:n=s+n,i=this._filterMenuItems(n),i=o&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}a&&e.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i,s,n,o,a=this,r=this.options.icons.submenu,h=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),s=h.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.prev(),s=t("").data("ui-menu-submenu-caret",!0);a._addClass(s,"ui-menu-icon","ui-icon "+r),i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),this._addClass(s,"ui-menu","ui-widget ui-widget-content ui-front"),e=h.add(this.element),i=e.find(this.options.items),i.not(".ui-menu-item").each(function(){var e=t(this);a._isDivider(e)&&a._addClass(e,"ui-menu-divider","ui-widget-content")}),n=i.not(".ui-menu-item, .ui-menu-divider"),o=n.children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(n,"ui-menu-item")._addClass(o,"ui-menu-item-wrapper"),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){if("icons"===t){var i=this.element.find(".ui-menu-icon");this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)}this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t+""),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i,s,n;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children(".ui-menu-item-wrapper"),this._addClass(s,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),n=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(n,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.outerHeight(),0>n?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this._removeClass(s.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(e){return!t(e.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(e),void 0)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items).first())),void 0):(this.next(e),void 0)},_hasScroll:function(){return this.element.outerHeight()",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n; +this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("