aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIan Coleman <coleman.ian@gmail.com>2015-08-16 14:39:33 +1000
committerIan Coleman <coleman.ian@gmail.com>2015-08-16 14:41:43 +1000
commit1759e5e80dac2a43ab41d99b84abfc06f811f396 (patch)
tree098b6b1c6eae9501d45e2a9f2856440fa3a4d2e5
parent7f15cb6eb98d29aeb64ec4a4ad37b81a66eb6103 (diff)
downloadBIP39-1759e5e80dac2a43ab41d99b84abfc06f811f396.tar.gz
BIP39-1759e5e80dac2a43ab41d99b84abfc06f811f396.tar.zst
BIP39-1759e5e80dac2a43ab41d99b84abfc06f811f396.zip
bitcoinjs 1.0.0 changed to bitcoinjs 1.5.7
-rw-r--r--src/index.html2
-rw-r--r--src/js/bitcoinjs-1-0-0.js14463
-rw-r--r--src/js/bitcoinjs-1-5-7.js12683
-rw-r--r--src/js/index.js12
4 files changed, 12690 insertions, 14470 deletions
diff --git a/src/index.html b/src/index.html
index 9ab7f6d..af2b7fb 100644
--- a/src/index.html
+++ b/src/index.html
@@ -391,7 +391,7 @@
391 </script> 391 </script>
392 <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 392 <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
393 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> 393 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
394 <script src="/js/bitcoinjs-1-0-0.js"></script> 394 <script src="/js/bitcoinjs-1-5-7.js"></script>
395 <script src="/js/sjcl-bip39.js"></script> 395 <script src="/js/sjcl-bip39.js"></script>
396 <script src="/js/wordlist_english.js"></script> 396 <script src="/js/wordlist_english.js"></script>
397 <script src="/js/jsbip39.js"></script> 397 <script src="/js/jsbip39.js"></script>
diff --git a/src/js/bitcoinjs-1-0-0.js b/src/js/bitcoinjs-1-0-0.js
deleted file mode 100644
index 3f53b2c..0000000
--- a/src/js/bitcoinjs-1-0-0.js
+++ /dev/null
@@ -1,14463 +0,0 @@
1(function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Bitcoin=e()}})(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
2var assert = _dereq_('assert')
3
4module.exports = BigInteger
5
6// JavaScript engine analysis
7var canary = 0xdeadbeefcafe;
8var j_lm = ((canary&0xffffff)==0xefcafe);
9
10// (public) Constructor
11function BigInteger(a,b,c) {
12 if (!(this instanceof BigInteger)) {
13 return new BigInteger(a, b, c);
14 }
15
16 if(a != null) {
17 if("number" == typeof a) this.fromNumber(a,b,c);
18 else if(b == null && "string" != typeof a) this.fromString(a,256);
19 else this.fromString(a,b);
20 }
21}
22
23var proto = BigInteger.prototype;
24
25// return new, unset BigInteger
26function nbi() { return new BigInteger(null); }
27
28// Bits per digit
29var dbits;
30
31// am: Compute w_j += (x*this_i), propagate carries,
32// c is initial carry, returns final carry.
33// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
34// We need to select the fastest one that works in this environment.
35
36// am1: use a single mult and divide to get the high bits,
37// max digit bits should be 26 because
38// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
39function am1(i,x,w,j,c,n) {
40 while(--n >= 0) {
41 var v = x*this[i++]+w[j]+c;
42 c = Math.floor(v/0x4000000);
43 w[j++] = v&0x3ffffff;
44 }
45 return c;
46}
47// am2 avoids a big mult-and-extract completely.
48// Max digit bits should be <= 30 because we do bitwise ops
49// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
50function am2(i,x,w,j,c,n) {
51 var xl = x&0x7fff, xh = x>>15;
52 while(--n >= 0) {
53 var l = this[i]&0x7fff;
54 var h = this[i++]>>15;
55 var m = xh*l+h*xl;
56 l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
57 c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
58 w[j++] = l&0x3fffffff;
59 }
60 return c;
61}
62// Alternately, set max digit bits to 28 since some
63// browsers slow down when dealing with 32-bit numbers.
64function am3(i,x,w,j,c,n) {
65 var xl = x&0x3fff, xh = x>>14;
66 while(--n >= 0) {
67 var l = this[i]&0x3fff;
68 var h = this[i++]>>14;
69 var m = xh*l+h*xl;
70 l = xl*l+((m&0x3fff)<<14)+w[j]+c;
71 c = (l>>28)+(m>>14)+xh*h;
72 w[j++] = l&0xfffffff;
73 }
74 return c;
75}
76
77// wtf?
78BigInteger.prototype.am = am1;
79dbits = 26;
80
81/*
82if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
83 BigInteger.prototype.am = am2;
84 dbits = 30;
85}
86else if(j_lm && (navigator.appName != "Netscape")) {
87 BigInteger.prototype.am = am1;
88 dbits = 26;
89}
90else { // Mozilla/Netscape seems to prefer am3
91 BigInteger.prototype.am = am3;
92 dbits = 28;
93}
94*/
95
96BigInteger.prototype.DB = dbits;
97BigInteger.prototype.DM = ((1<<dbits)-1);
98var DV = BigInteger.prototype.DV = (1<<dbits);
99
100var BI_FP = 52;
101BigInteger.prototype.FV = Math.pow(2,BI_FP);
102BigInteger.prototype.F1 = BI_FP-dbits;
103BigInteger.prototype.F2 = 2*dbits-BI_FP;
104
105// Digit conversions
106var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
107var BI_RC = new Array();
108var rr,vv;
109rr = "0".charCodeAt(0);
110for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
111rr = "a".charCodeAt(0);
112for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
113rr = "A".charCodeAt(0);
114for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
115
116function int2char(n) { return BI_RM.charAt(n); }
117function intAt(s,i) {
118 var c = BI_RC[s.charCodeAt(i)];
119 return (c==null)?-1:c;
120}
121
122// (protected) copy this to r
123function bnpCopyTo(r) {
124 for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
125 r.t = this.t;
126 r.s = this.s;
127}
128
129// (protected) set from integer value x, -DV <= x < DV
130function bnpFromInt(x) {
131 this.t = 1;
132 this.s = (x<0)?-1:0;
133 if(x > 0) this[0] = x;
134 else if(x < -1) this[0] = x+DV;
135 else this.t = 0;
136}
137
138// return bigint initialized to value
139function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
140
141// (protected) set from string and radix
142function bnpFromString(s,b) {
143 var self = this;
144
145 var k;
146 if(b == 16) k = 4;
147 else if(b == 8) k = 3;
148 else if(b == 256) k = 8; // byte array
149 else if(b == 2) k = 1;
150 else if(b == 32) k = 5;
151 else if(b == 4) k = 2;
152 else { self.fromRadix(s,b); return; }
153 self.t = 0;
154 self.s = 0;
155 var i = s.length, mi = false, sh = 0;
156 while(--i >= 0) {
157 var x = (k==8)?s[i]&0xff:intAt(s,i);
158 if(x < 0) {
159 if(s.charAt(i) == "-") mi = true;
160 continue;
161 }
162 mi = false;
163 if(sh == 0)
164 self[self.t++] = x;
165 else if(sh+k > self.DB) {
166 self[self.t-1] |= (x&((1<<(self.DB-sh))-1))<<sh;
167 self[self.t++] = (x>>(self.DB-sh));
168 }
169 else
170 self[self.t-1] |= x<<sh;
171 sh += k;
172 if(sh >= self.DB) sh -= self.DB;
173 }
174 if(k == 8 && (s[0]&0x80) != 0) {
175 self.s = -1;
176 if(sh > 0) self[self.t-1] |= ((1<<(self.DB-sh))-1)<<sh;
177 }
178 self.clamp();
179 if(mi) BigInteger.ZERO.subTo(self,self);
180}
181
182// (protected) clamp off excess high words
183function bnpClamp() {
184 var c = this.s&this.DM;
185 while(this.t > 0 && this[this.t-1] == c) --this.t;
186}
187
188// (public) return string representation in given radix
189function bnToString(b) {
190 var self = this;
191 if(self.s < 0) return "-"+self.negate().toString(b);
192 var k;
193 if(b == 16) k = 4;
194 else if(b == 8) k = 3;
195 else if(b == 2) k = 1;
196 else if(b == 32) k = 5;
197 else if(b == 4) k = 2;
198 else return self.toRadix(b);
199 var km = (1<<k)-1, d, m = false, r = "", i = self.t;
200 var p = self.DB-(i*self.DB)%k;
201 if(i-- > 0) {
202 if(p < self.DB && (d = self[i]>>p) > 0) { m = true; r = int2char(d); }
203 while(i >= 0) {
204 if(p < k) {
205 d = (self[i]&((1<<p)-1))<<(k-p);
206 d |= self[--i]>>(p+=self.DB-k);
207 }
208 else {
209 d = (self[i]>>(p-=k))&km;
210 if(p <= 0) { p += self.DB; --i; }
211 }
212 if(d > 0) m = true;
213 if(m) r += int2char(d);
214 }
215 }
216 return m?r:"0";
217}
218
219// (public) -this
220function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
221
222// (public) |this|
223function bnAbs() { return (this.s<0)?this.negate():this; }
224
225// (public) return + if this > a, - if this < a, 0 if equal
226function bnCompareTo(a) {
227 var r = this.s-a.s;
228 if(r != 0) return r;
229 var i = this.t;
230 r = i-a.t;
231 if(r != 0) return (this.s<0)?-r:r;
232 while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
233 return 0;
234}
235
236// returns bit length of the integer x
237function nbits(x) {
238 var r = 1, t;
239 if((t=x>>>16) != 0) { x = t; r += 16; }
240 if((t=x>>8) != 0) { x = t; r += 8; }
241 if((t=x>>4) != 0) { x = t; r += 4; }
242 if((t=x>>2) != 0) { x = t; r += 2; }
243 if((t=x>>1) != 0) { x = t; r += 1; }
244 return r;
245}
246
247// (public) return the number of bits in "this"
248function bnBitLength() {
249 if(this.t <= 0) return 0;
250 return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
251}
252
253// (protected) r = this << n*DB
254function bnpDLShiftTo(n,r) {
255 var i;
256 for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
257 for(i = n-1; i >= 0; --i) r[i] = 0;
258 r.t = this.t+n;
259 r.s = this.s;
260}
261
262// (protected) r = this >> n*DB
263function bnpDRShiftTo(n,r) {
264 for(var i = n; i < this.t; ++i) r[i-n] = this[i];
265 r.t = Math.max(this.t-n,0);
266 r.s = this.s;
267}
268
269// (protected) r = this << n
270function bnpLShiftTo(n,r) {
271 var self = this;
272 var bs = n%self.DB;
273 var cbs = self.DB-bs;
274 var bm = (1<<cbs)-1;
275 var ds = Math.floor(n/self.DB), c = (self.s<<bs)&self.DM, i;
276 for(i = self.t-1; i >= 0; --i) {
277 r[i+ds+1] = (self[i]>>cbs)|c;
278 c = (self[i]&bm)<<bs;
279 }
280 for(i = ds-1; i >= 0; --i) r[i] = 0;
281 r[ds] = c;
282 r.t = self.t+ds+1;
283 r.s = self.s;
284 r.clamp();
285}
286
287// (protected) r = this >> n
288function bnpRShiftTo(n,r) {
289 var self = this;
290 r.s = self.s;
291 var ds = Math.floor(n/self.DB);
292 if(ds >= self.t) { r.t = 0; return; }
293 var bs = n%self.DB;
294 var cbs = self.DB-bs;
295 var bm = (1<<bs)-1;
296 r[0] = self[ds]>>bs;
297 for(var i = ds+1; i < self.t; ++i) {
298 r[i-ds-1] |= (self[i]&bm)<<cbs;
299 r[i-ds] = self[i]>>bs;
300 }
301 if(bs > 0) r[self.t-ds-1] |= (self.s&bm)<<cbs;
302 r.t = self.t-ds;
303 r.clamp();
304}
305
306// (protected) r = this - a
307function bnpSubTo(a,r) {
308 var self = this;
309 var i = 0, c = 0, m = Math.min(a.t,self.t);
310 while(i < m) {
311 c += self[i]-a[i];
312 r[i++] = c&self.DM;
313 c >>= self.DB;
314 }
315 if(a.t < self.t) {
316 c -= a.s;
317 while(i < self.t) {
318 c += self[i];
319 r[i++] = c&self.DM;
320 c >>= self.DB;
321 }
322 c += self.s;
323 }
324 else {
325 c += self.s;
326 while(i < a.t) {
327 c -= a[i];
328 r[i++] = c&self.DM;
329 c >>= self.DB;
330 }
331 c -= a.s;
332 }
333 r.s = (c<0)?-1:0;
334 if(c < -1) r[i++] = self.DV+c;
335 else if(c > 0) r[i++] = c;
336 r.t = i;
337 r.clamp();
338}
339
340// (protected) r = this * a, r != this,a (HAC 14.12)
341// "this" should be the larger one if appropriate.
342function bnpMultiplyTo(a,r) {
343 var x = this.abs(), y = a.abs();
344 var i = x.t;
345 r.t = i+y.t;
346 while(--i >= 0) r[i] = 0;
347 for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
348 r.s = 0;
349 r.clamp();
350 if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
351}
352
353// (protected) r = this^2, r != this (HAC 14.16)
354function bnpSquareTo(r) {
355 var x = this.abs();
356 var i = r.t = 2*x.t;
357 while(--i >= 0) r[i] = 0;
358 for(i = 0; i < x.t-1; ++i) {
359 var c = x.am(i,x[i],r,2*i,0,1);
360 if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
361 r[i+x.t] -= x.DV;
362 r[i+x.t+1] = 1;
363 }
364 }
365 if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
366 r.s = 0;
367 r.clamp();
368}
369
370// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
371// r != q, this != m. q or r may be null.
372function bnpDivRemTo(m,q,r) {
373 var self = this;
374 var pm = m.abs();
375 if(pm.t <= 0) return;
376 var pt = self.abs();
377 if(pt.t < pm.t) {
378 if(q != null) q.fromInt(0);
379 if(r != null) self.copyTo(r);
380 return;
381 }
382 if(r == null) r = nbi();
383 var y = nbi(), ts = self.s, ms = m.s;
384 var nsh = self.DB-nbits(pm[pm.t-1]); // normalize modulus
385 if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
386 else { pm.copyTo(y); pt.copyTo(r); }
387 var ys = y.t;
388 var y0 = y[ys-1];
389 if(y0 == 0) return;
390 var yt = y0*(1<<self.F1)+((ys>1)?y[ys-2]>>self.F2:0);
391 var d1 = self.FV/yt, d2 = (1<<self.F1)/yt, e = 1<<self.F2;
392 var i = r.t, j = i-ys, t = (q==null)?nbi():q;
393 y.dlShiftTo(j,t);
394 if(r.compareTo(t) >= 0) {
395 r[r.t++] = 1;
396 r.subTo(t,r);
397 }
398 BigInteger.ONE.dlShiftTo(ys,t);
399 t.subTo(y,y); // "negative" y so we can replace sub with am later
400 while(y.t < ys) y[y.t++] = 0;
401 while(--j >= 0) {
402 // Estimate quotient digit
403 var qd = (r[--i]==y0)?self.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
404 if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
405 y.dlShiftTo(j,t);
406 r.subTo(t,r);
407 while(r[i] < --qd) r.subTo(t,r);
408 }
409 }
410 if(q != null) {
411 r.drShiftTo(ys,q);
412 if(ts != ms) BigInteger.ZERO.subTo(q,q);
413 }
414 r.t = ys;
415 r.clamp();
416 if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
417 if(ts < 0) BigInteger.ZERO.subTo(r,r);
418}
419
420// (public) this mod a
421function bnMod(a) {
422 var r = nbi();
423 this.abs().divRemTo(a,null,r);
424 if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
425 return r;
426}
427
428// Modular reduction using "classic" algorithm
429function Classic(m) { this.m = m; }
430function cConvert(x) {
431 if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
432 else return x;
433}
434function cRevert(x) { return x; }
435function cReduce(x) { x.divRemTo(this.m,null,x); }
436function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
437function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
438
439Classic.prototype.convert = cConvert;
440Classic.prototype.revert = cRevert;
441Classic.prototype.reduce = cReduce;
442Classic.prototype.mulTo = cMulTo;
443Classic.prototype.sqrTo = cSqrTo;
444
445// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
446// justification:
447// xy == 1 (mod m)
448// xy = 1+km
449// xy(2-xy) = (1+km)(1-km)
450// x[y(2-xy)] = 1-k^2m^2
451// x[y(2-xy)] == 1 (mod m^2)
452// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
453// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
454// JS multiply "overflows" differently from C/C++, so care is needed here.
455function bnpInvDigit() {
456 if(this.t < 1) return 0;
457 var x = this[0];
458 if((x&1) == 0) return 0;
459 var y = x&3; // y == 1/x mod 2^2
460 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
461 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
462 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
463 // last step - calculate inverse mod DV directly;
464 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
465 y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
466 // we really want the negative inverse, and -DV < y < DV
467 return (y>0)?this.DV-y:-y;
468}
469
470// Montgomery reduction
471function Montgomery(m) {
472 this.m = m;
473 this.mp = m.invDigit();
474 this.mpl = this.mp&0x7fff;
475 this.mph = this.mp>>15;
476 this.um = (1<<(m.DB-15))-1;
477 this.mt2 = 2*m.t;
478}
479
480// xR mod m
481function montConvert(x) {
482 var r = nbi();
483 x.abs().dlShiftTo(this.m.t,r);
484 r.divRemTo(this.m,null,r);
485 if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
486 return r;
487}
488
489// x/R mod m
490function montRevert(x) {
491 var r = nbi();
492 x.copyTo(r);
493 this.reduce(r);
494 return r;
495}
496
497// x = x/R mod m (HAC 14.32)
498function montReduce(x) {
499 while(x.t <= this.mt2) // pad x so am has enough room later
500 x[x.t++] = 0;
501 for(var i = 0; i < this.m.t; ++i) {
502 // faster way of calculating u0 = x[i]*mp mod DV
503 var j = x[i]&0x7fff;
504 var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
505 // use am to combine the multiply-shift-add into one call
506 j = i+this.m.t;
507 x[j] += this.m.am(0,u0,x,i,0,this.m.t);
508 // propagate carry
509 while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
510 }
511 x.clamp();
512 x.drShiftTo(this.m.t,x);
513 if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
514}
515
516// r = "x^2/R mod m"; x != r
517function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
518
519// r = "xy/R mod m"; x,y != r
520function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
521
522Montgomery.prototype.convert = montConvert;
523Montgomery.prototype.revert = montRevert;
524Montgomery.prototype.reduce = montReduce;
525Montgomery.prototype.mulTo = montMulTo;
526Montgomery.prototype.sqrTo = montSqrTo;
527
528// (protected) true iff this is even
529function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
530
531// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
532function bnpExp(e,z) {
533 if(e > 0xffffffff || e < 1) return BigInteger.ONE;
534 var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
535 g.copyTo(r);
536 while(--i >= 0) {
537 z.sqrTo(r,r2);
538 if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
539 else { var t = r; r = r2; r2 = t; }
540 }
541 return z.revert(r);
542}
543
544// (public) this^e % m, 0 <= e < 2^32
545function bnModPowInt(e,m) {
546 var z;
547 if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
548 return this.exp(e,z);
549}
550
551// protected
552proto.copyTo = bnpCopyTo;
553proto.fromInt = bnpFromInt;
554proto.fromString = bnpFromString;
555proto.clamp = bnpClamp;
556proto.dlShiftTo = bnpDLShiftTo;
557proto.drShiftTo = bnpDRShiftTo;
558proto.lShiftTo = bnpLShiftTo;
559proto.rShiftTo = bnpRShiftTo;
560proto.subTo = bnpSubTo;
561proto.multiplyTo = bnpMultiplyTo;
562proto.squareTo = bnpSquareTo;
563proto.divRemTo = bnpDivRemTo;
564proto.invDigit = bnpInvDigit;
565proto.isEven = bnpIsEven;
566proto.exp = bnpExp;
567
568// public
569proto.toString = bnToString;
570proto.negate = bnNegate;
571proto.abs = bnAbs;
572proto.compareTo = bnCompareTo;
573proto.bitLength = bnBitLength;
574proto.mod = bnMod;
575proto.modPowInt = bnModPowInt;
576
577//// jsbn2
578
579function nbi() { return new BigInteger(null); }
580
581// (public)
582function bnClone() { var r = nbi(); this.copyTo(r); return r; }
583
584// (public) return value as integer
585function bnIntValue() {
586 if(this.s < 0) {
587 if(this.t == 1) return this[0]-this.DV;
588 else if(this.t == 0) return -1;
589 }
590 else if(this.t == 1) return this[0];
591 else if(this.t == 0) return 0;
592 // assumes 16 < DB < 32
593 return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];
594}
595
596// (public) return value as byte
597function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
598
599// (public) return value as short (assumes DB>=16)
600function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
601
602// (protected) return x s.t. r^x < DV
603function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
604
605// (public) 0 if this == 0, 1 if this > 0
606function bnSigNum() {
607 if(this.s < 0) return -1;
608 else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
609 else return 1;
610}
611
612// (protected) convert to radix string
613function bnpToRadix(b) {
614 if(b == null) b = 10;
615 if(this.signum() == 0 || b < 2 || b > 36) return "0";
616 var cs = this.chunkSize(b);
617 var a = Math.pow(b,cs);
618 var d = nbv(a), y = nbi(), z = nbi(), r = "";
619 this.divRemTo(d,y,z);
620 while(y.signum() > 0) {
621 r = (a+z.intValue()).toString(b).substr(1) + r;
622 y.divRemTo(d,y,z);
623 }
624 return z.intValue().toString(b) + r;
625}
626
627// (protected) convert from radix string
628function bnpFromRadix(s,b) {
629 var self = this;
630 self.fromInt(0);
631 if(b == null) b = 10;
632 var cs = self.chunkSize(b);
633 var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
634 for(var i = 0; i < s.length; ++i) {
635 var x = intAt(s,i);
636 if(x < 0) {
637 if(s.charAt(i) == "-" && self.signum() == 0) mi = true;
638 continue;
639 }
640 w = b*w+x;
641 if(++j >= cs) {
642 self.dMultiply(d);
643 self.dAddOffset(w,0);
644 j = 0;
645 w = 0;
646 }
647 }
648 if(j > 0) {
649 self.dMultiply(Math.pow(b,j));
650 self.dAddOffset(w,0);
651 }
652 if(mi) BigInteger.ZERO.subTo(self,self);
653}
654
655// (protected) alternate constructor
656function bnpFromNumber(a,b,c) {
657 var self = this;
658 if("number" == typeof b) {
659 // new BigInteger(int,int,RNG)
660 if(a < 2) self.fromInt(1);
661 else {
662 self.fromNumber(a,c);
663 if(!self.testBit(a-1)) // force MSB set
664 self.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,self);
665 if(self.isEven()) self.dAddOffset(1,0); // force odd
666 while(!self.isProbablePrime(b)) {
667 self.dAddOffset(2,0);
668 if(self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a-1),self);
669 }
670 }
671 }
672 else {
673 // new BigInteger(int,RNG)
674 var x = new Array(), t = a&7;
675 x.length = (a>>3)+1;
676 b.nextBytes(x);
677 if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
678 self.fromString(x,256);
679 }
680}
681
682// (public) convert to bigendian byte array
683function bnToByteArray() {
684 var self = this;
685 var i = self.t, r = new Array();
686 r[0] = self.s;
687 var p = self.DB-(i*self.DB)%8, d, k = 0;
688 if(i-- > 0) {
689 if(p < self.DB && (d = self[i]>>p) != (self.s&self.DM)>>p)
690 r[k++] = d|(self.s<<(self.DB-p));
691 while(i >= 0) {
692 if(p < 8) {
693 d = (self[i]&((1<<p)-1))<<(8-p);
694 d |= self[--i]>>(p+=self.DB-8);
695 }
696 else {
697 d = (self[i]>>(p-=8))&0xff;
698 if(p <= 0) { p += self.DB; --i; }
699 }
700 if((d&0x80) != 0) d |= -256;
701 if(k === 0 && (self.s&0x80) != (d&0x80)) ++k;
702 if(k > 0 || d != self.s) r[k++] = d;
703 }
704 }
705 return r;
706}
707
708function bnEquals(a) { return(this.compareTo(a)==0); }
709function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
710function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
711
712// (protected) r = this op a (bitwise)
713function bnpBitwiseTo(a,op,r) {
714 var self = this;
715 var i, f, m = Math.min(a.t,self.t);
716 for(i = 0; i < m; ++i) r[i] = op(self[i],a[i]);
717 if(a.t < self.t) {
718 f = a.s&self.DM;
719 for(i = m; i < self.t; ++i) r[i] = op(self[i],f);
720 r.t = self.t;
721 }
722 else {
723 f = self.s&self.DM;
724 for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
725 r.t = a.t;
726 }
727 r.s = op(self.s,a.s);
728 r.clamp();
729}
730
731// (public) this & a
732function op_and(x,y) { return x&y; }
733function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
734
735// (public) this | a
736function op_or(x,y) { return x|y; }
737function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
738
739// (public) this ^ a
740function op_xor(x,y) { return x^y; }
741function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
742
743// (public) this & ~a
744function op_andnot(x,y) { return x&~y; }
745function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
746
747// (public) ~this
748function bnNot() {
749 var r = nbi();
750 for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
751 r.t = this.t;
752 r.s = ~this.s;
753 return r;
754}
755
756// (public) this << n
757function bnShiftLeft(n) {
758 var r = nbi();
759 if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
760 return r;
761}
762
763// (public) this >> n
764function bnShiftRight(n) {
765 var r = nbi();
766 if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
767 return r;
768}
769
770// return index of lowest 1-bit in x, x < 2^31
771function lbit(x) {
772 if(x == 0) return -1;
773 var r = 0;
774 if((x&0xffff) == 0) { x >>= 16; r += 16; }
775 if((x&0xff) == 0) { x >>= 8; r += 8; }
776 if((x&0xf) == 0) { x >>= 4; r += 4; }
777 if((x&3) == 0) { x >>= 2; r += 2; }
778 if((x&1) == 0) ++r;
779 return r;
780}
781
782// (public) returns index of lowest 1-bit (or -1 if none)
783function bnGetLowestSetBit() {
784 for(var i = 0; i < this.t; ++i)
785 if(this[i] != 0) return i*this.DB+lbit(this[i]);
786 if(this.s < 0) return this.t*this.DB;
787 return -1;
788}
789
790// return number of 1 bits in x
791function cbit(x) {
792 var r = 0;
793 while(x != 0) { x &= x-1; ++r; }
794 return r;
795}
796
797// (public) return number of set bits
798function bnBitCount() {
799 var r = 0, x = this.s&this.DM;
800 for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
801 return r;
802}
803
804// (public) true iff nth bit is set
805function bnTestBit(n) {
806 var j = Math.floor(n/this.DB);
807 if(j >= this.t) return(this.s!=0);
808 return((this[j]&(1<<(n%this.DB)))!=0);
809}
810
811// (protected) this op (1<<n)
812function bnpChangeBit(n,op) {
813 var r = BigInteger.ONE.shiftLeft(n);
814 this.bitwiseTo(r,op,r);
815 return r;
816}
817
818// (public) this | (1<<n)
819function bnSetBit(n) { return this.changeBit(n,op_or); }
820
821// (public) this & ~(1<<n)
822function bnClearBit(n) { return this.changeBit(n,op_andnot); }
823
824// (public) this ^ (1<<n)
825function bnFlipBit(n) { return this.changeBit(n,op_xor); }
826
827// (protected) r = this + a
828function bnpAddTo(a,r) {
829 var self = this;
830
831 var i = 0, c = 0, m = Math.min(a.t,self.t);
832 while(i < m) {
833 c += self[i]+a[i];
834 r[i++] = c&self.DM;
835 c >>= self.DB;
836 }
837 if(a.t < self.t) {
838 c += a.s;
839 while(i < self.t) {
840 c += self[i];
841 r[i++] = c&self.DM;
842 c >>= self.DB;
843 }
844 c += self.s;
845 }
846 else {
847 c += self.s;
848 while(i < a.t) {
849 c += a[i];
850 r[i++] = c&self.DM;
851 c >>= self.DB;
852 }
853 c += a.s;
854 }
855 r.s = (c<0)?-1:0;
856 if(c > 0) r[i++] = c;
857 else if(c < -1) r[i++] = self.DV+c;
858 r.t = i;
859 r.clamp();
860}
861
862// (public) this + a
863function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
864
865// (public) this - a
866function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
867
868// (public) this * a
869function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
870
871// (public) this^2
872function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
873
874// (public) this / a
875function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
876
877// (public) this % a
878function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
879
880// (public) [this/a,this%a]
881function bnDivideAndRemainder(a) {
882 var q = nbi(), r = nbi();
883 this.divRemTo(a,q,r);
884 return new Array(q,r);
885}
886
887// (protected) this *= n, this >= 0, 1 < n < DV
888function bnpDMultiply(n) {
889 this[this.t] = this.am(0,n-1,this,0,0,this.t);
890 ++this.t;
891 this.clamp();
892}
893
894// (protected) this += n << w words, this >= 0
895function bnpDAddOffset(n,w) {
896 if(n == 0) return;
897 while(this.t <= w) this[this.t++] = 0;
898 this[w] += n;
899 while(this[w] >= this.DV) {
900 this[w] -= this.DV;
901 if(++w >= this.t) this[this.t++] = 0;
902 ++this[w];
903 }
904}
905
906// A "null" reducer
907function NullExp() {}
908function nNop(x) { return x; }
909function nMulTo(x,y,r) { x.multiplyTo(y,r); }
910function nSqrTo(x,r) { x.squareTo(r); }
911
912NullExp.prototype.convert = nNop;
913NullExp.prototype.revert = nNop;
914NullExp.prototype.mulTo = nMulTo;
915NullExp.prototype.sqrTo = nSqrTo;
916
917// (public) this^e
918function bnPow(e) { return this.exp(e,new NullExp()); }
919
920// (protected) r = lower n words of "this * a", a.t <= n
921// "this" should be the larger one if appropriate.
922function bnpMultiplyLowerTo(a,n,r) {
923 var i = Math.min(this.t+a.t,n);
924 r.s = 0; // assumes a,this >= 0
925 r.t = i;
926 while(i > 0) r[--i] = 0;
927 var j;
928 for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
929 for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
930 r.clamp();
931}
932
933// (protected) r = "this * a" without lower n words, n > 0
934// "this" should be the larger one if appropriate.
935function bnpMultiplyUpperTo(a,n,r) {
936 --n;
937 var i = r.t = this.t+a.t-n;
938 r.s = 0; // assumes a,this >= 0
939 while(--i >= 0) r[i] = 0;
940 for(i = Math.max(n-this.t,0); i < a.t; ++i)
941 r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
942 r.clamp();
943 r.drShiftTo(1,r);
944}
945
946// Barrett modular reduction
947function Barrett(m) {
948 // setup Barrett
949 this.r2 = nbi();
950 this.q3 = nbi();
951 BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
952 this.mu = this.r2.divide(m);
953 this.m = m;
954}
955
956function barrettConvert(x) {
957 if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
958 else if(x.compareTo(this.m) < 0) return x;
959 else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
960}
961
962function barrettRevert(x) { return x; }
963
964// x = x mod m (HAC 14.42)
965function barrettReduce(x) {
966 var self = this;
967 x.drShiftTo(self.m.t-1,self.r2);
968 if(x.t > self.m.t+1) { x.t = self.m.t+1; x.clamp(); }
969 self.mu.multiplyUpperTo(self.r2,self.m.t+1,self.q3);
970 self.m.multiplyLowerTo(self.q3,self.m.t+1,self.r2);
971 while(x.compareTo(self.r2) < 0) x.dAddOffset(1,self.m.t+1);
972 x.subTo(self.r2,x);
973 while(x.compareTo(self.m) >= 0) x.subTo(self.m,x);
974}
975
976// r = x^2 mod m; x != r
977function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
978
979// r = x*y mod m; x,y != r
980function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
981
982Barrett.prototype.convert = barrettConvert;
983Barrett.prototype.revert = barrettRevert;
984Barrett.prototype.reduce = barrettReduce;
985Barrett.prototype.mulTo = barrettMulTo;
986Barrett.prototype.sqrTo = barrettSqrTo;
987
988// (public) this^e % m (HAC 14.85)
989function bnModPow(e,m) {
990 var i = e.bitLength(), k, r = nbv(1), z;
991 if(i <= 0) return r;
992 else if(i < 18) k = 1;
993 else if(i < 48) k = 3;
994 else if(i < 144) k = 4;
995 else if(i < 768) k = 5;
996 else k = 6;
997 if(i < 8)
998 z = new Classic(m);
999 else if(m.isEven())
1000 z = new Barrett(m);
1001 else
1002 z = new Montgomery(m);
1003
1004 // precomputation
1005 var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
1006 g[1] = z.convert(this);
1007 if(k > 1) {
1008 var g2 = nbi();
1009 z.sqrTo(g[1],g2);
1010 while(n <= km) {
1011 g[n] = nbi();
1012 z.mulTo(g2,g[n-2],g[n]);
1013 n += 2;
1014 }
1015 }
1016
1017 var j = e.t-1, w, is1 = true, r2 = nbi(), t;
1018 i = nbits(e[j])-1;
1019 while(j >= 0) {
1020 if(i >= k1) w = (e[j]>>(i-k1))&km;
1021 else {
1022 w = (e[j]&((1<<(i+1))-1))<<(k1-i);
1023 if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
1024 }
1025
1026 n = k;
1027 while((w&1) == 0) { w >>= 1; --n; }
1028 if((i -= n) < 0) { i += this.DB; --j; }
1029 if(is1) { // ret == 1, don't bother squaring or multiplying it
1030 g[w].copyTo(r);
1031 is1 = false;
1032 }
1033 else {
1034 while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
1035 if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
1036 z.mulTo(r2,g[w],r);
1037 }
1038
1039 while(j >= 0 && (e[j]&(1<<i)) == 0) {
1040 z.sqrTo(r,r2); t = r; r = r2; r2 = t;
1041 if(--i < 0) { i = this.DB-1; --j; }
1042 }
1043 }
1044 return z.revert(r);
1045}
1046
1047// (public) gcd(this,a) (HAC 14.54)
1048function bnGCD(a) {
1049 var x = (this.s<0)?this.negate():this.clone();
1050 var y = (a.s<0)?a.negate():a.clone();
1051 if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
1052 var i = x.getLowestSetBit(), g = y.getLowestSetBit();
1053 if(g < 0) return x;
1054 if(i < g) g = i;
1055 if(g > 0) {
1056 x.rShiftTo(g,x);
1057 y.rShiftTo(g,y);
1058 }
1059 while(x.signum() > 0) {
1060 if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
1061 if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
1062 if(x.compareTo(y) >= 0) {
1063 x.subTo(y,x);
1064 x.rShiftTo(1,x);
1065 }
1066 else {
1067 y.subTo(x,y);
1068 y.rShiftTo(1,y);
1069 }
1070 }
1071 if(g > 0) y.lShiftTo(g,y);
1072 return y;
1073}
1074
1075// (protected) this % n, n < 2^26
1076function bnpModInt(n) {
1077 if(n <= 0) return 0;
1078 var d = this.DV%n, r = (this.s<0)?n-1:0;
1079 if(this.t > 0)
1080 if(d == 0) r = this[0]%n;
1081 else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
1082 return r;
1083}
1084
1085// (public) 1/this % m (HAC 14.61)
1086function bnModInverse(m) {
1087 var ac = m.isEven();
1088 if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
1089 var u = m.clone(), v = this.clone();
1090 var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
1091 while(u.signum() != 0) {
1092 while(u.isEven()) {
1093 u.rShiftTo(1,u);
1094 if(ac) {
1095 if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
1096 a.rShiftTo(1,a);
1097 }
1098 else if(!b.isEven()) b.subTo(m,b);
1099 b.rShiftTo(1,b);
1100 }
1101 while(v.isEven()) {
1102 v.rShiftTo(1,v);
1103 if(ac) {
1104 if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
1105 c.rShiftTo(1,c);
1106 }
1107 else if(!d.isEven()) d.subTo(m,d);
1108 d.rShiftTo(1,d);
1109 }
1110 if(u.compareTo(v) >= 0) {
1111 u.subTo(v,u);
1112 if(ac) a.subTo(c,a);
1113 b.subTo(d,b);
1114 }
1115 else {
1116 v.subTo(u,v);
1117 if(ac) c.subTo(a,c);
1118 d.subTo(b,d);
1119 }
1120 }
1121 if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
1122 if(d.compareTo(m) >= 0) return d.subtract(m);
1123 if(d.signum() < 0) d.addTo(m,d); else return d;
1124 if(d.signum() < 0) return d.add(m); else return d;
1125}
1126
1127// protected
1128proto.chunkSize = bnpChunkSize;
1129proto.toRadix = bnpToRadix;
1130proto.fromRadix = bnpFromRadix;
1131proto.fromNumber = bnpFromNumber;
1132proto.bitwiseTo = bnpBitwiseTo;
1133proto.changeBit = bnpChangeBit;
1134proto.addTo = bnpAddTo;
1135proto.dMultiply = bnpDMultiply;
1136proto.dAddOffset = bnpDAddOffset;
1137proto.multiplyLowerTo = bnpMultiplyLowerTo;
1138proto.multiplyUpperTo = bnpMultiplyUpperTo;
1139proto.modInt = bnpModInt;
1140
1141// public
1142proto.clone = bnClone;
1143proto.intValue = bnIntValue;
1144proto.byteValue = bnByteValue;
1145proto.shortValue = bnShortValue;
1146proto.signum = bnSigNum;
1147proto.toByteArray = bnToByteArray;
1148proto.equals = bnEquals;
1149proto.min = bnMin;
1150proto.max = bnMax;
1151proto.and = bnAnd;
1152proto.or = bnOr;
1153proto.xor = bnXor;
1154proto.andNot = bnAndNot;
1155proto.not = bnNot;
1156proto.shiftLeft = bnShiftLeft;
1157proto.shiftRight = bnShiftRight;
1158proto.getLowestSetBit = bnGetLowestSetBit;
1159proto.bitCount = bnBitCount;
1160proto.testBit = bnTestBit;
1161proto.setBit = bnSetBit;
1162proto.clearBit = bnClearBit;
1163proto.flipBit = bnFlipBit;
1164proto.add = bnAdd;
1165proto.subtract = bnSubtract;
1166proto.multiply = bnMultiply;
1167proto.divide = bnDivide;
1168proto.remainder = bnRemainder;
1169proto.divideAndRemainder = bnDivideAndRemainder;
1170proto.modPow = bnModPow;
1171proto.modInverse = bnModInverse;
1172proto.pow = bnPow;
1173proto.gcd = bnGCD;
1174
1175// JSBN-specific extension
1176proto.square = bnSquare;
1177
1178// BigInteger interfaces not implemented in jsbn:
1179
1180// BigInteger(int signum, byte[] magnitude)
1181// double doubleValue()
1182// float floatValue()
1183// int hashCode()
1184// long longValue()
1185// static BigInteger valueOf(long val)
1186
1187// "constants"
1188BigInteger.ZERO = nbv(0);
1189BigInteger.ONE = nbv(1);
1190BigInteger.valueOf = nbv;
1191
1192},{"assert":4}],2:[function(_dereq_,module,exports){
1193(function (Buffer){
1194// FIXME: Kind of a weird way to throw exceptions, consider removing
1195var assert = _dereq_('assert')
1196var BigInteger = _dereq_('./bigi')
1197
1198/**
1199 * Turns a byte array into a big integer.
1200 *
1201 * This function will interpret a byte array as a big integer in big
1202 * endian notation.
1203 */
1204BigInteger.fromByteArrayUnsigned = function(byteArray) {
1205 // BigInteger expects a DER integer conformant byte array
1206 if (byteArray[0] & 0x80) {
1207 return new BigInteger([0].concat(byteArray))
1208 }
1209
1210 return new BigInteger(byteArray)
1211}
1212
1213/**
1214 * Returns a byte array representation of the big integer.
1215 *
1216 * This returns the absolute of the contained value in big endian
1217 * form. A value of zero results in an empty array.
1218 */
1219BigInteger.prototype.toByteArrayUnsigned = function() {
1220 var byteArray = this.toByteArray()
1221 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
1222}
1223
1224BigInteger.fromDERInteger = function(byteArray) {
1225 return new BigInteger(byteArray)
1226}
1227
1228/*
1229 * Converts BigInteger to a DER integer representation.
1230 *
1231 * The format for this value uses the most significant bit as a sign
1232 * bit. If the most significant bit is already set and the integer is
1233 * positive, a 0x00 is prepended.
1234 *
1235 * Examples:
1236 *
1237 * 0 => 0x00
1238 * 1 => 0x01
1239 * -1 => 0x81
1240 * 127 => 0x7f
1241 * -127 => 0xff
1242 * 128 => 0x0080
1243 * -128 => 0x80
1244 * 255 => 0x00ff
1245 * -255 => 0xff
1246 * 16300 => 0x3fac
1247 * -16300 => 0xbfac
1248 * 62300 => 0x00f35c
1249 * -62300 => 0xf35c
1250*/
1251BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
1252
1253BigInteger.fromBuffer = function(buffer) {
1254 // BigInteger expects a DER integer conformant byte array
1255 if (buffer[0] & 0x80) {
1256 var byteArray = Array.prototype.slice.call(buffer)
1257
1258 return new BigInteger([0].concat(byteArray))
1259 }
1260
1261 return new BigInteger(buffer)
1262}
1263
1264BigInteger.fromHex = function(hex) {
1265 if (hex === '') return BigInteger.ZERO
1266
1267 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
1268 assert.equal(hex.length % 2, 0, 'Incomplete hex')
1269 return new BigInteger(hex, 16)
1270}
1271
1272BigInteger.prototype.toBuffer = function(size) {
1273 var byteArray = this.toByteArrayUnsigned()
1274 var zeros = []
1275
1276 var padding = size - byteArray.length
1277 while (zeros.length < padding) zeros.push(0)
1278
1279 return new Buffer(zeros.concat(byteArray))
1280}
1281
1282BigInteger.prototype.toHex = function(size) {
1283 return this.toBuffer(size).toString('hex')
1284}
1285
1286}).call(this,_dereq_("buffer").Buffer)
1287},{"./bigi":1,"assert":4,"buffer":8}],3:[function(_dereq_,module,exports){
1288var BigInteger = _dereq_('./bigi')
1289
1290//addons
1291_dereq_('./convert')
1292
1293module.exports = BigInteger
1294},{"./bigi":1,"./convert":2}],4:[function(_dereq_,module,exports){
1295// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
1296//
1297// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
1298//
1299// Originally from narwhal.js (http://narwhaljs.org)
1300// Copyright (c) 2009 Thomas Robinson <280north.com>
1301//
1302// Permission is hereby granted, free of charge, to any person obtaining a copy
1303// of this software and associated documentation files (the 'Software'), to
1304// deal in the Software without restriction, including without limitation the
1305// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
1306// sell copies of the Software, and to permit persons to whom the Software is
1307// furnished to do so, subject to the following conditions:
1308//
1309// The above copyright notice and this permission notice shall be included in
1310// all copies or substantial portions of the Software.
1311//
1312// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1313// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1314// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1315// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1316// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
1317// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1318
1319// when used in node, this will actually load the util module we depend on
1320// versus loading the builtin util module as happens otherwise
1321// this is a bug in node module loading as far as I am concerned
1322var util = _dereq_('util/');
1323
1324var pSlice = Array.prototype.slice;
1325var hasOwn = Object.prototype.hasOwnProperty;
1326
1327// 1. The assert module provides functions that throw
1328// AssertionError's when particular conditions are not met. The
1329// assert module must conform to the following interface.
1330
1331var assert = module.exports = ok;
1332
1333// 2. The AssertionError is defined in assert.
1334// new assert.AssertionError({ message: message,
1335// actual: actual,
1336// expected: expected })
1337
1338assert.AssertionError = function AssertionError(options) {
1339 this.name = 'AssertionError';
1340 this.actual = options.actual;
1341 this.expected = options.expected;
1342 this.operator = options.operator;
1343 if (options.message) {
1344 this.message = options.message;
1345 this.generatedMessage = false;
1346 } else {
1347 this.message = getMessage(this);
1348 this.generatedMessage = true;
1349 }
1350 var stackStartFunction = options.stackStartFunction || fail;
1351
1352 if (Error.captureStackTrace) {
1353 Error.captureStackTrace(this, stackStartFunction);
1354 }
1355 else {
1356 // non v8 browsers so we can have a stacktrace
1357 var err = new Error();
1358 if (err.stack) {
1359 var out = err.stack;
1360
1361 // try to strip useless frames
1362 var fn_name = stackStartFunction.name;
1363 var idx = out.indexOf('\n' + fn_name);
1364 if (idx >= 0) {
1365 // once we have located the function frame
1366 // we need to strip out everything before it (and its line)
1367 var next_line = out.indexOf('\n', idx + 1);
1368 out = out.substring(next_line + 1);
1369 }
1370
1371 this.stack = out;
1372 }
1373 }
1374};
1375
1376// assert.AssertionError instanceof Error
1377util.inherits(assert.AssertionError, Error);
1378
1379function replacer(key, value) {
1380 if (util.isUndefined(value)) {
1381 return '' + value;
1382 }
1383 if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) {
1384 return value.toString();
1385 }
1386 if (util.isFunction(value) || util.isRegExp(value)) {
1387 return value.toString();
1388 }
1389 return value;
1390}
1391
1392function truncate(s, n) {
1393 if (util.isString(s)) {
1394 return s.length < n ? s : s.slice(0, n);
1395 } else {
1396 return s;
1397 }
1398}
1399
1400function getMessage(self) {
1401 return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
1402 self.operator + ' ' +
1403 truncate(JSON.stringify(self.expected, replacer), 128);
1404}
1405
1406// At present only the three keys mentioned above are used and
1407// understood by the spec. Implementations or sub modules can pass
1408// other keys to the AssertionError's constructor - they will be
1409// ignored.
1410
1411// 3. All of the following functions must throw an AssertionError
1412// when a corresponding condition is not met, with a message that
1413// may be undefined if not provided. All assertion methods provide
1414// both the actual and expected values to the assertion error for
1415// display purposes.
1416
1417function fail(actual, expected, message, operator, stackStartFunction) {
1418 throw new assert.AssertionError({
1419 message: message,
1420 actual: actual,
1421 expected: expected,
1422 operator: operator,
1423 stackStartFunction: stackStartFunction
1424 });
1425}
1426
1427// EXTENSION! allows for well behaved errors defined elsewhere.
1428assert.fail = fail;
1429
1430// 4. Pure assertion tests whether a value is truthy, as determined
1431// by !!guard.
1432// assert.ok(guard, message_opt);
1433// This statement is equivalent to assert.equal(true, !!guard,
1434// message_opt);. To test strictly for the value true, use
1435// assert.strictEqual(true, guard, message_opt);.
1436
1437function ok(value, message) {
1438 if (!value) fail(value, true, message, '==', assert.ok);
1439}
1440assert.ok = ok;
1441
1442// 5. The equality assertion tests shallow, coercive equality with
1443// ==.
1444// assert.equal(actual, expected, message_opt);
1445
1446assert.equal = function equal(actual, expected, message) {
1447 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
1448};
1449
1450// 6. The non-equality assertion tests for whether two objects are not equal
1451// with != assert.notEqual(actual, expected, message_opt);
1452
1453assert.notEqual = function notEqual(actual, expected, message) {
1454 if (actual == expected) {
1455 fail(actual, expected, message, '!=', assert.notEqual);
1456 }
1457};
1458
1459// 7. The equivalence assertion tests a deep equality relation.
1460// assert.deepEqual(actual, expected, message_opt);
1461
1462assert.deepEqual = function deepEqual(actual, expected, message) {
1463 if (!_deepEqual(actual, expected)) {
1464 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
1465 }
1466};
1467
1468function _deepEqual(actual, expected) {
1469 // 7.1. All identical values are equivalent, as determined by ===.
1470 if (actual === expected) {
1471 return true;
1472
1473 } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
1474 if (actual.length != expected.length) return false;
1475
1476 for (var i = 0; i < actual.length; i++) {
1477 if (actual[i] !== expected[i]) return false;
1478 }
1479
1480 return true;
1481
1482 // 7.2. If the expected value is a Date object, the actual value is
1483 // equivalent if it is also a Date object that refers to the same time.
1484 } else if (util.isDate(actual) && util.isDate(expected)) {
1485 return actual.getTime() === expected.getTime();
1486
1487 // 7.3 If the expected value is a RegExp object, the actual value is
1488 // equivalent if it is also a RegExp object with the same source and
1489 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
1490 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
1491 return actual.source === expected.source &&
1492 actual.global === expected.global &&
1493 actual.multiline === expected.multiline &&
1494 actual.lastIndex === expected.lastIndex &&
1495 actual.ignoreCase === expected.ignoreCase;
1496
1497 // 7.4. Other pairs that do not both pass typeof value == 'object',
1498 // equivalence is determined by ==.
1499 } else if (!util.isObject(actual) && !util.isObject(expected)) {
1500 return actual == expected;
1501
1502 // 7.5 For all other Object pairs, including Array objects, equivalence is
1503 // determined by having the same number of owned properties (as verified
1504 // with Object.prototype.hasOwnProperty.call), the same set of keys
1505 // (although not necessarily the same order), equivalent values for every
1506 // corresponding key, and an identical 'prototype' property. Note: this
1507 // accounts for both named and indexed properties on Arrays.
1508 } else {
1509 return objEquiv(actual, expected);
1510 }
1511}
1512
1513function isArguments(object) {
1514 return Object.prototype.toString.call(object) == '[object Arguments]';
1515}
1516
1517function objEquiv(a, b) {
1518 if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
1519 return false;
1520 // an identical 'prototype' property.
1521 if (a.prototype !== b.prototype) return false;
1522 //~~~I've managed to break Object.keys through screwy arguments passing.
1523 // Converting to array solves the problem.
1524 if (isArguments(a)) {
1525 if (!isArguments(b)) {
1526 return false;
1527 }
1528 a = pSlice.call(a);
1529 b = pSlice.call(b);
1530 return _deepEqual(a, b);
1531 }
1532 try {
1533 var ka = objectKeys(a),
1534 kb = objectKeys(b),
1535 key, i;
1536 } catch (e) {//happens when one is a string literal and the other isn't
1537 return false;
1538 }
1539 // having the same number of owned properties (keys incorporates
1540 // hasOwnProperty)
1541 if (ka.length != kb.length)
1542 return false;
1543 //the same set of keys (although not necessarily the same order),
1544 ka.sort();
1545 kb.sort();
1546 //~~~cheap key test
1547 for (i = ka.length - 1; i >= 0; i--) {
1548 if (ka[i] != kb[i])
1549 return false;
1550 }
1551 //equivalent values for every corresponding key, and
1552 //~~~possibly expensive deep test
1553 for (i = ka.length - 1; i >= 0; i--) {
1554 key = ka[i];
1555 if (!_deepEqual(a[key], b[key])) return false;
1556 }
1557 return true;
1558}
1559
1560// 8. The non-equivalence assertion tests for any deep inequality.
1561// assert.notDeepEqual(actual, expected, message_opt);
1562
1563assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
1564 if (_deepEqual(actual, expected)) {
1565 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
1566 }
1567};
1568
1569// 9. The strict equality assertion tests strict equality, as determined by ===.
1570// assert.strictEqual(actual, expected, message_opt);
1571
1572assert.strictEqual = function strictEqual(actual, expected, message) {
1573 if (actual !== expected) {
1574 fail(actual, expected, message, '===', assert.strictEqual);
1575 }
1576};
1577
1578// 10. The strict non-equality assertion tests for strict inequality, as
1579// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
1580
1581assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
1582 if (actual === expected) {
1583 fail(actual, expected, message, '!==', assert.notStrictEqual);
1584 }
1585};
1586
1587function expectedException(actual, expected) {
1588 if (!actual || !expected) {
1589 return false;
1590 }
1591
1592 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
1593 return expected.test(actual);
1594 } else if (actual instanceof expected) {
1595 return true;
1596 } else if (expected.call({}, actual) === true) {
1597 return true;
1598 }
1599
1600 return false;
1601}
1602
1603function _throws(shouldThrow, block, expected, message) {
1604 var actual;
1605
1606 if (util.isString(expected)) {
1607 message = expected;
1608 expected = null;
1609 }
1610
1611 try {
1612 block();
1613 } catch (e) {
1614 actual = e;
1615 }
1616
1617 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
1618 (message ? ' ' + message : '.');
1619
1620 if (shouldThrow && !actual) {
1621 fail(actual, expected, 'Missing expected exception' + message);
1622 }
1623
1624 if (!shouldThrow && expectedException(actual, expected)) {
1625 fail(actual, expected, 'Got unwanted exception' + message);
1626 }
1627
1628 if ((shouldThrow && actual && expected &&
1629 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
1630 throw actual;
1631 }
1632}
1633
1634// 11. Expected to throw an error:
1635// assert.throws(block, Error_opt, message_opt);
1636
1637assert.throws = function(block, /*optional*/error, /*optional*/message) {
1638 _throws.apply(this, [true].concat(pSlice.call(arguments)));
1639};
1640
1641// EXTENSION! This is annoying to write outside this module.
1642assert.doesNotThrow = function(block, /*optional*/message) {
1643 _throws.apply(this, [false].concat(pSlice.call(arguments)));
1644};
1645
1646assert.ifError = function(err) { if (err) {throw err;}};
1647
1648var objectKeys = Object.keys || function (obj) {
1649 var keys = [];
1650 for (var key in obj) {
1651 if (hasOwn.call(obj, key)) keys.push(key);
1652 }
1653 return keys;
1654};
1655
1656},{"util/":6}],5:[function(_dereq_,module,exports){
1657module.exports = function isBuffer(arg) {
1658 return arg && typeof arg === 'object'
1659 && typeof arg.copy === 'function'
1660 && typeof arg.fill === 'function'
1661 && typeof arg.readUInt8 === 'function';
1662}
1663},{}],6:[function(_dereq_,module,exports){
1664(function (process,global){
1665// Copyright Joyent, Inc. and other Node contributors.
1666//
1667// Permission is hereby granted, free of charge, to any person obtaining a
1668// copy of this software and associated documentation files (the
1669// "Software"), to deal in the Software without restriction, including
1670// without limitation the rights to use, copy, modify, merge, publish,
1671// distribute, sublicense, and/or sell copies of the Software, and to permit
1672// persons to whom the Software is furnished to do so, subject to the
1673// following conditions:
1674//
1675// The above copyright notice and this permission notice shall be included
1676// in all copies or substantial portions of the Software.
1677//
1678// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1679// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1680// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
1681// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
1682// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
1683// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
1684// USE OR OTHER DEALINGS IN THE SOFTWARE.
1685
1686var formatRegExp = /%[sdj%]/g;
1687exports.format = function(f) {
1688 if (!isString(f)) {
1689 var objects = [];
1690 for (var i = 0; i < arguments.length; i++) {
1691 objects.push(inspect(arguments[i]));
1692 }
1693 return objects.join(' ');
1694 }
1695
1696 var i = 1;
1697 var args = arguments;
1698 var len = args.length;
1699 var str = String(f).replace(formatRegExp, function(x) {
1700 if (x === '%%') return '%';
1701 if (i >= len) return x;
1702 switch (x) {
1703 case '%s': return String(args[i++]);
1704 case '%d': return Number(args[i++]);
1705 case '%j':
1706 try {
1707 return JSON.stringify(args[i++]);
1708 } catch (_) {
1709 return '[Circular]';
1710 }
1711 default:
1712 return x;
1713 }
1714 });
1715 for (var x = args[i]; i < len; x = args[++i]) {
1716 if (isNull(x) || !isObject(x)) {
1717 str += ' ' + x;
1718 } else {
1719 str += ' ' + inspect(x);
1720 }
1721 }
1722 return str;
1723};
1724
1725
1726// Mark that a method should not be used.
1727// Returns a modified function which warns once by default.
1728// If --no-deprecation is set, then it is a no-op.
1729exports.deprecate = function(fn, msg) {
1730 // Allow for deprecating things in the process of starting up.
1731 if (isUndefined(global.process)) {
1732 return function() {
1733 return exports.deprecate(fn, msg).apply(this, arguments);
1734 };
1735 }
1736
1737 if (process.noDeprecation === true) {
1738 return fn;
1739 }
1740
1741 var warned = false;
1742 function deprecated() {
1743 if (!warned) {
1744 if (process.throwDeprecation) {
1745 throw new Error(msg);
1746 } else if (process.traceDeprecation) {
1747 console.trace(msg);
1748 } else {
1749 console.error(msg);
1750 }
1751 warned = true;
1752 }
1753 return fn.apply(this, arguments);
1754 }
1755
1756 return deprecated;
1757};
1758
1759
1760var debugs = {};
1761var debugEnviron;
1762exports.debuglog = function(set) {
1763 if (isUndefined(debugEnviron))
1764 debugEnviron = process.env.NODE_DEBUG || '';
1765 set = set.toUpperCase();
1766 if (!debugs[set]) {
1767 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
1768 var pid = process.pid;
1769 debugs[set] = function() {
1770 var msg = exports.format.apply(exports, arguments);
1771 console.error('%s %d: %s', set, pid, msg);
1772 };
1773 } else {
1774 debugs[set] = function() {};
1775 }
1776 }
1777 return debugs[set];
1778};
1779
1780
1781/**
1782 * Echos the value of a value. Trys to print the value out
1783 * in the best way possible given the different types.
1784 *
1785 * @param {Object} obj The object to print out.
1786 * @param {Object} opts Optional options object that alters the output.
1787 */
1788/* legacy: obj, showHidden, depth, colors*/
1789function inspect(obj, opts) {
1790 // default options
1791 var ctx = {
1792 seen: [],
1793 stylize: stylizeNoColor
1794 };
1795 // legacy...
1796 if (arguments.length >= 3) ctx.depth = arguments[2];
1797 if (arguments.length >= 4) ctx.colors = arguments[3];
1798 if (isBoolean(opts)) {
1799 // legacy...
1800 ctx.showHidden = opts;
1801 } else if (opts) {
1802 // got an "options" object
1803 exports._extend(ctx, opts);
1804 }
1805 // set default options
1806 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
1807 if (isUndefined(ctx.depth)) ctx.depth = 2;
1808 if (isUndefined(ctx.colors)) ctx.colors = false;
1809 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
1810 if (ctx.colors) ctx.stylize = stylizeWithColor;
1811 return formatValue(ctx, obj, ctx.depth);
1812}
1813exports.inspect = inspect;
1814
1815
1816// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
1817inspect.colors = {
1818 'bold' : [1, 22],
1819 'italic' : [3, 23],
1820 'underline' : [4, 24],
1821 'inverse' : [7, 27],
1822 'white' : [37, 39],
1823 'grey' : [90, 39],
1824 'black' : [30, 39],
1825 'blue' : [34, 39],
1826 'cyan' : [36, 39],
1827 'green' : [32, 39],
1828 'magenta' : [35, 39],
1829 'red' : [31, 39],
1830 'yellow' : [33, 39]
1831};
1832
1833// Don't use 'blue' not visible on cmd.exe
1834inspect.styles = {
1835 'special': 'cyan',
1836 'number': 'yellow',
1837 'boolean': 'yellow',
1838 'undefined': 'grey',
1839 'null': 'bold',
1840 'string': 'green',
1841 'date': 'magenta',
1842 // "name": intentionally not styling
1843 'regexp': 'red'
1844};
1845
1846
1847function stylizeWithColor(str, styleType) {
1848 var style = inspect.styles[styleType];
1849
1850 if (style) {
1851 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
1852 '\u001b[' + inspect.colors[style][1] + 'm';
1853 } else {
1854 return str;
1855 }
1856}
1857
1858
1859function stylizeNoColor(str, styleType) {
1860 return str;
1861}
1862
1863
1864function arrayToHash(array) {
1865 var hash = {};
1866
1867 array.forEach(function(val, idx) {
1868 hash[val] = true;
1869 });
1870
1871 return hash;
1872}
1873
1874
1875function formatValue(ctx, value, recurseTimes) {
1876 // Provide a hook for user-specified inspect functions.
1877 // Check that value is an object with an inspect function on it
1878 if (ctx.customInspect &&
1879 value &&
1880 isFunction(value.inspect) &&
1881 // Filter out the util module, it's inspect function is special
1882 value.inspect !== exports.inspect &&
1883 // Also filter out any prototype objects using the circular check.
1884 !(value.constructor && value.constructor.prototype === value)) {
1885 var ret = value.inspect(recurseTimes, ctx);
1886 if (!isString(ret)) {
1887 ret = formatValue(ctx, ret, recurseTimes);
1888 }
1889 return ret;
1890 }
1891
1892 // Primitive types cannot have properties
1893 var primitive = formatPrimitive(ctx, value);
1894 if (primitive) {
1895 return primitive;
1896 }
1897
1898 // Look up the keys of the object.
1899 var keys = Object.keys(value);
1900 var visibleKeys = arrayToHash(keys);
1901
1902 if (ctx.showHidden) {
1903 keys = Object.getOwnPropertyNames(value);
1904 }
1905
1906 // IE doesn't make error fields non-enumerable
1907 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
1908 if (isError(value)
1909 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
1910 return formatError(value);
1911 }
1912
1913 // Some type of object without properties can be shortcutted.
1914 if (keys.length === 0) {
1915 if (isFunction(value)) {
1916 var name = value.name ? ': ' + value.name : '';
1917 return ctx.stylize('[Function' + name + ']', 'special');
1918 }
1919 if (isRegExp(value)) {
1920 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
1921 }
1922 if (isDate(value)) {
1923 return ctx.stylize(Date.prototype.toString.call(value), 'date');
1924 }
1925 if (isError(value)) {
1926 return formatError(value);
1927 }
1928 }
1929
1930 var base = '', array = false, braces = ['{', '}'];
1931
1932 // Make Array say that they are Array
1933 if (isArray(value)) {
1934 array = true;
1935 braces = ['[', ']'];
1936 }
1937
1938 // Make functions say that they are functions
1939 if (isFunction(value)) {
1940 var n = value.name ? ': ' + value.name : '';
1941 base = ' [Function' + n + ']';
1942 }
1943
1944 // Make RegExps say that they are RegExps
1945 if (isRegExp(value)) {
1946 base = ' ' + RegExp.prototype.toString.call(value);
1947 }
1948
1949 // Make dates with properties first say the date
1950 if (isDate(value)) {
1951 base = ' ' + Date.prototype.toUTCString.call(value);
1952 }
1953
1954 // Make error with message first say the error
1955 if (isError(value)) {
1956 base = ' ' + formatError(value);
1957 }
1958
1959 if (keys.length === 0 && (!array || value.length == 0)) {
1960 return braces[0] + base + braces[1];
1961 }
1962
1963 if (recurseTimes < 0) {
1964 if (isRegExp(value)) {
1965 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
1966 } else {
1967 return ctx.stylize('[Object]', 'special');
1968 }
1969 }
1970
1971 ctx.seen.push(value);
1972
1973 var output;
1974 if (array) {
1975 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
1976 } else {
1977 output = keys.map(function(key) {
1978 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
1979 });
1980 }
1981
1982 ctx.seen.pop();
1983
1984 return reduceToSingleString(output, base, braces);
1985}
1986
1987
1988function formatPrimitive(ctx, value) {
1989 if (isUndefined(value))
1990 return ctx.stylize('undefined', 'undefined');
1991 if (isString(value)) {
1992 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
1993 .replace(/'/g, "\\'")
1994 .replace(/\\"/g, '"') + '\'';
1995 return ctx.stylize(simple, 'string');
1996 }
1997 if (isNumber(value))
1998 return ctx.stylize('' + value, 'number');
1999 if (isBoolean(value))
2000 return ctx.stylize('' + value, 'boolean');
2001 // For some reason typeof null is "object", so special case here.
2002 if (isNull(value))
2003 return ctx.stylize('null', 'null');
2004}
2005
2006
2007function formatError(value) {
2008 return '[' + Error.prototype.toString.call(value) + ']';
2009}
2010
2011
2012function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
2013 var output = [];
2014 for (var i = 0, l = value.length; i < l; ++i) {
2015 if (hasOwnProperty(value, String(i))) {
2016 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
2017 String(i), true));
2018 } else {
2019 output.push('');
2020 }
2021 }
2022 keys.forEach(function(key) {
2023 if (!key.match(/^\d+$/)) {
2024 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
2025 key, true));
2026 }
2027 });
2028 return output;
2029}
2030
2031
2032function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
2033 var name, str, desc;
2034 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
2035 if (desc.get) {
2036 if (desc.set) {
2037 str = ctx.stylize('[Getter/Setter]', 'special');
2038 } else {
2039 str = ctx.stylize('[Getter]', 'special');
2040 }
2041 } else {
2042 if (desc.set) {
2043 str = ctx.stylize('[Setter]', 'special');
2044 }
2045 }
2046 if (!hasOwnProperty(visibleKeys, key)) {
2047 name = '[' + key + ']';
2048 }
2049 if (!str) {
2050 if (ctx.seen.indexOf(desc.value) < 0) {
2051 if (isNull(recurseTimes)) {
2052 str = formatValue(ctx, desc.value, null);
2053 } else {
2054 str = formatValue(ctx, desc.value, recurseTimes - 1);
2055 }
2056 if (str.indexOf('\n') > -1) {
2057 if (array) {
2058 str = str.split('\n').map(function(line) {
2059 return ' ' + line;
2060 }).join('\n').substr(2);
2061 } else {
2062 str = '\n' + str.split('\n').map(function(line) {
2063 return ' ' + line;
2064 }).join('\n');
2065 }
2066 }
2067 } else {
2068 str = ctx.stylize('[Circular]', 'special');
2069 }
2070 }
2071 if (isUndefined(name)) {
2072 if (array && key.match(/^\d+$/)) {
2073 return str;
2074 }
2075 name = JSON.stringify('' + key);
2076 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
2077 name = name.substr(1, name.length - 2);
2078 name = ctx.stylize(name, 'name');
2079 } else {
2080 name = name.replace(/'/g, "\\'")
2081 .replace(/\\"/g, '"')
2082 .replace(/(^"|"$)/g, "'");
2083 name = ctx.stylize(name, 'string');
2084 }
2085 }
2086
2087 return name + ': ' + str;
2088}
2089
2090
2091function reduceToSingleString(output, base, braces) {
2092 var numLinesEst = 0;
2093 var length = output.reduce(function(prev, cur) {
2094 numLinesEst++;
2095 if (cur.indexOf('\n') >= 0) numLinesEst++;
2096 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
2097 }, 0);
2098
2099 if (length > 60) {
2100 return braces[0] +
2101 (base === '' ? '' : base + '\n ') +
2102 ' ' +
2103 output.join(',\n ') +
2104 ' ' +
2105 braces[1];
2106 }
2107
2108 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
2109}
2110
2111
2112// NOTE: These type checking functions intentionally don't use `instanceof`
2113// because it is fragile and can be easily faked with `Object.create()`.
2114function isArray(ar) {
2115 return Array.isArray(ar);
2116}
2117exports.isArray = isArray;
2118
2119function isBoolean(arg) {
2120 return typeof arg === 'boolean';
2121}
2122exports.isBoolean = isBoolean;
2123
2124function isNull(arg) {
2125 return arg === null;
2126}
2127exports.isNull = isNull;
2128
2129function isNullOrUndefined(arg) {
2130 return arg == null;
2131}
2132exports.isNullOrUndefined = isNullOrUndefined;
2133
2134function isNumber(arg) {
2135 return typeof arg === 'number';
2136}
2137exports.isNumber = isNumber;
2138
2139function isString(arg) {
2140 return typeof arg === 'string';
2141}
2142exports.isString = isString;
2143
2144function isSymbol(arg) {
2145 return typeof arg === 'symbol';
2146}
2147exports.isSymbol = isSymbol;
2148
2149function isUndefined(arg) {
2150 return arg === void 0;
2151}
2152exports.isUndefined = isUndefined;
2153
2154function isRegExp(re) {
2155 return isObject(re) && objectToString(re) === '[object RegExp]';
2156}
2157exports.isRegExp = isRegExp;
2158
2159function isObject(arg) {
2160 return typeof arg === 'object' && arg !== null;
2161}
2162exports.isObject = isObject;
2163
2164function isDate(d) {
2165 return isObject(d) && objectToString(d) === '[object Date]';
2166}
2167exports.isDate = isDate;
2168
2169function isError(e) {
2170 return isObject(e) &&
2171 (objectToString(e) === '[object Error]' || e instanceof Error);
2172}
2173exports.isError = isError;
2174
2175function isFunction(arg) {
2176 return typeof arg === 'function';
2177}
2178exports.isFunction = isFunction;
2179
2180function isPrimitive(arg) {
2181 return arg === null ||
2182 typeof arg === 'boolean' ||
2183 typeof arg === 'number' ||
2184 typeof arg === 'string' ||
2185 typeof arg === 'symbol' || // ES6 symbol
2186 typeof arg === 'undefined';
2187}
2188exports.isPrimitive = isPrimitive;
2189
2190exports.isBuffer = _dereq_('./support/isBuffer');
2191
2192function objectToString(o) {
2193 return Object.prototype.toString.call(o);
2194}
2195
2196
2197function pad(n) {
2198 return n < 10 ? '0' + n.toString(10) : n.toString(10);
2199}
2200
2201
2202var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
2203 'Oct', 'Nov', 'Dec'];
2204
2205// 26 Feb 16:19:34
2206function timestamp() {
2207 var d = new Date();
2208 var time = [pad(d.getHours()),
2209 pad(d.getMinutes()),
2210 pad(d.getSeconds())].join(':');
2211 return [d.getDate(), months[d.getMonth()], time].join(' ');
2212}
2213
2214
2215// log is just a thin wrapper to console.log that prepends a timestamp
2216exports.log = function() {
2217 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
2218};
2219
2220
2221/**
2222 * Inherit the prototype methods from one constructor into another.
2223 *
2224 * The Function.prototype.inherits from lang.js rewritten as a standalone
2225 * function (not on Function.prototype). NOTE: If this file is to be loaded
2226 * during bootstrapping this function needs to be rewritten using some native
2227 * functions as prototype setup using normal JavaScript does not work as
2228 * expected during bootstrapping (see mirror.js in r114903).
2229 *
2230 * @param {function} ctor Constructor function which needs to inherit the
2231 * prototype.
2232 * @param {function} superCtor Constructor function to inherit prototype from.
2233 */
2234exports.inherits = _dereq_('inherits');
2235
2236exports._extend = function(origin, add) {
2237 // Don't do anything if add isn't an object
2238 if (!add || !isObject(add)) return origin;
2239
2240 var keys = Object.keys(add);
2241 var i = keys.length;
2242 while (i--) {
2243 origin[keys[i]] = add[keys[i]];
2244 }
2245 return origin;
2246};
2247
2248function hasOwnProperty(obj, prop) {
2249 return Object.prototype.hasOwnProperty.call(obj, prop);
2250}
2251
2252}).call(this,_dereq_("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2253},{"./support/isBuffer":5,"FWaASH":12,"inherits":11}],7:[function(_dereq_,module,exports){
2254
2255},{}],8:[function(_dereq_,module,exports){
2256/*!
2257 * The buffer module from node.js, for the browser.
2258 *
2259 * at author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2260 * at license MIT
2261 */
2262
2263var base64 = _dereq_('base64-js')
2264var ieee754 = _dereq_('ieee754')
2265
2266exports.Buffer = Buffer
2267exports.SlowBuffer = Buffer
2268exports.INSPECT_MAX_BYTES = 50
2269Buffer.poolSize = 8192
2270
2271/**
2272 * If `Buffer._useTypedArrays`:
2273 * === true Use Uint8Array implementation (fastest)
2274 * === false Use Object implementation (compatible down to IE6)
2275 */
2276Buffer._useTypedArrays = (function () {
2277 // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+,
2278 // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding
2279 // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support
2280 // because we need to be able to add all the node Buffer API methods. This is an issue
2281 // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
2282 try {
2283 var buf = new ArrayBuffer(0)
2284 var arr = new Uint8Array(buf)
2285 arr.foo = function () { return 42 }
2286 return 42 === arr.foo() &&
2287 typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
2288 } catch (e) {
2289 return false
2290 }
2291})()
2292
2293/**
2294 * Class: Buffer
2295 * =============
2296 *
2297 * The Buffer constructor returns instances of `Uint8Array` that are augmented
2298 * with function properties for all the node `Buffer` API functions. We use
2299 * `Uint8Array` so that square bracket notation works as expected -- it returns
2300 * a single octet.
2301 *
2302 * By augmenting the instances, we can avoid modifying the `Uint8Array`
2303 * prototype.
2304 */
2305function Buffer (subject, encoding, noZero) {
2306 if (!(this instanceof Buffer))
2307 return new Buffer(subject, encoding, noZero)
2308
2309 var type = typeof subject
2310
2311 if (encoding === 'base64' && type === 'string') {
2312 subject = base64clean(subject)
2313 }
2314
2315 // Find the length
2316 var length
2317 if (type === 'number')
2318 length = coerce(subject)
2319 else if (type === 'string')
2320 length = Buffer.byteLength(subject, encoding)
2321 else if (type === 'object')
2322 length = coerce(subject.length) // assume that object is array-like
2323 else
2324 throw new Error('First argument needs to be a number, array or string.')
2325
2326 var buf
2327 if (Buffer._useTypedArrays) {
2328 // Preferred: Return an augmented `Uint8Array` instance for best performance
2329 buf = Buffer._augment(new Uint8Array(length))
2330 } else {
2331 // Fallback: Return THIS instance of Buffer (created by `new`)
2332 buf = this
2333 buf.length = length
2334 buf._isBuffer = true
2335 }
2336
2337 var i
2338 if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
2339 // Speed optimization -- use set if we're copying from a typed array
2340 buf._set(subject)
2341 } else if (isArrayish(subject)) {
2342 // Treat array-ish objects as a byte array
2343 if (Buffer.isBuffer(subject)) {
2344 for (i = 0; i < length; i++)
2345 buf[i] = subject.readUInt8(i)
2346 } else {
2347 for (i = 0; i < length; i++)
2348 buf[i] = ((subject[i] % 256) + 256) % 256
2349 }
2350 } else if (type === 'string') {
2351 buf.write(subject, 0, encoding)
2352 } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
2353 for (i = 0; i < length; i++) {
2354 buf[i] = 0
2355 }
2356 }
2357
2358 return buf
2359}
2360
2361// STATIC METHODS
2362// ==============
2363
2364Buffer.isEncoding = function (encoding) {
2365 switch (String(encoding).toLowerCase()) {
2366 case 'hex':
2367 case 'utf8':
2368 case 'utf-8':
2369 case 'ascii':
2370 case 'binary':
2371 case 'base64':
2372 case 'raw':
2373 case 'ucs2':
2374 case 'ucs-2':
2375 case 'utf16le':
2376 case 'utf-16le':
2377 return true
2378 default:
2379 return false
2380 }
2381}
2382
2383Buffer.isBuffer = function (b) {
2384 return !!(b !== null && b !== undefined && b._isBuffer)
2385}
2386
2387Buffer.byteLength = function (str, encoding) {
2388 var ret
2389 str = str.toString()
2390 switch (encoding || 'utf8') {
2391 case 'hex':
2392 ret = str.length / 2
2393 break
2394 case 'utf8':
2395 case 'utf-8':
2396 ret = utf8ToBytes(str).length
2397 break
2398 case 'ascii':
2399 case 'binary':
2400 case 'raw':
2401 ret = str.length
2402 break
2403 case 'base64':
2404 ret = base64ToBytes(str).length
2405 break
2406 case 'ucs2':
2407 case 'ucs-2':
2408 case 'utf16le':
2409 case 'utf-16le':
2410 ret = str.length * 2
2411 break
2412 default:
2413 throw new Error('Unknown encoding')
2414 }
2415 return ret
2416}
2417
2418Buffer.concat = function (list, totalLength) {
2419 assert(isArray(list), 'Usage: Buffer.concat(list[, length])')
2420
2421 if (list.length === 0) {
2422 return new Buffer(0)
2423 } else if (list.length === 1) {
2424 return list[0]
2425 }
2426
2427 var i
2428 if (totalLength === undefined) {
2429 totalLength = 0
2430 for (i = 0; i < list.length; i++) {
2431 totalLength += list[i].length
2432 }
2433 }
2434
2435 var buf = new Buffer(totalLength)
2436 var pos = 0
2437 for (i = 0; i < list.length; i++) {
2438 var item = list[i]
2439 item.copy(buf, pos)
2440 pos += item.length
2441 }
2442 return buf
2443}
2444
2445Buffer.compare = function (a, b) {
2446 assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers')
2447 var x = a.length
2448 var y = b.length
2449 for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
2450 if (i !== len) {
2451 x = a[i]
2452 y = b[i]
2453 }
2454 if (x < y) {
2455 return -1
2456 }
2457 if (y < x) {
2458 return 1
2459 }
2460 return 0
2461}
2462
2463// BUFFER INSTANCE METHODS
2464// =======================
2465
2466function hexWrite (buf, string, offset, length) {
2467 offset = Number(offset) || 0
2468 var remaining = buf.length - offset
2469 if (!length) {
2470 length = remaining
2471 } else {
2472 length = Number(length)
2473 if (length > remaining) {
2474 length = remaining
2475 }
2476 }
2477
2478 // must be an even number of digits
2479 var strLen = string.length
2480 assert(strLen % 2 === 0, 'Invalid hex string')
2481
2482 if (length > strLen / 2) {
2483 length = strLen / 2
2484 }
2485 for (var i = 0; i < length; i++) {
2486 var byte = parseInt(string.substr(i * 2, 2), 16)
2487 assert(!isNaN(byte), 'Invalid hex string')
2488 buf[offset + i] = byte
2489 }
2490 return i
2491}
2492
2493function utf8Write (buf, string, offset, length) {
2494 var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
2495 return charsWritten
2496}
2497
2498function asciiWrite (buf, string, offset, length) {
2499 var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
2500 return charsWritten
2501}
2502
2503function binaryWrite (buf, string, offset, length) {
2504 return asciiWrite(buf, string, offset, length)
2505}
2506
2507function base64Write (buf, string, offset, length) {
2508 var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
2509 return charsWritten
2510}
2511
2512function utf16leWrite (buf, string, offset, length) {
2513 var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
2514 return charsWritten
2515}
2516
2517Buffer.prototype.write = function (string, offset, length, encoding) {
2518 // Support both (string, offset, length, encoding)
2519 // and the legacy (string, encoding, offset, length)
2520 if (isFinite(offset)) {
2521 if (!isFinite(length)) {
2522 encoding = length
2523 length = undefined
2524 }
2525 } else { // legacy
2526 var swap = encoding
2527 encoding = offset
2528 offset = length
2529 length = swap
2530 }
2531
2532 offset = Number(offset) || 0
2533 var remaining = this.length - offset
2534 if (!length) {
2535 length = remaining
2536 } else {
2537 length = Number(length)
2538 if (length > remaining) {
2539 length = remaining
2540 }
2541 }
2542 encoding = String(encoding || 'utf8').toLowerCase()
2543
2544 var ret
2545 switch (encoding) {
2546 case 'hex':
2547 ret = hexWrite(this, string, offset, length)
2548 break
2549 case 'utf8':
2550 case 'utf-8':
2551 ret = utf8Write(this, string, offset, length)
2552 break
2553 case 'ascii':
2554 ret = asciiWrite(this, string, offset, length)
2555 break
2556 case 'binary':
2557 ret = binaryWrite(this, string, offset, length)
2558 break
2559 case 'base64':
2560 ret = base64Write(this, string, offset, length)
2561 break
2562 case 'ucs2':
2563 case 'ucs-2':
2564 case 'utf16le':
2565 case 'utf-16le':
2566 ret = utf16leWrite(this, string, offset, length)
2567 break
2568 default:
2569 throw new Error('Unknown encoding')
2570 }
2571 return ret
2572}
2573
2574Buffer.prototype.toString = function (encoding, start, end) {
2575 var self = this
2576
2577 encoding = String(encoding || 'utf8').toLowerCase()
2578 start = Number(start) || 0
2579 end = (end === undefined) ? self.length : Number(end)
2580
2581 // Fastpath empty strings
2582 if (end === start)
2583 return ''
2584
2585 var ret
2586 switch (encoding) {
2587 case 'hex':
2588 ret = hexSlice(self, start, end)
2589 break
2590 case 'utf8':
2591 case 'utf-8':
2592 ret = utf8Slice(self, start, end)
2593 break
2594 case 'ascii':
2595 ret = asciiSlice(self, start, end)
2596 break
2597 case 'binary':
2598 ret = binarySlice(self, start, end)
2599 break
2600 case 'base64':
2601 ret = base64Slice(self, start, end)
2602 break
2603 case 'ucs2':
2604 case 'ucs-2':
2605 case 'utf16le':
2606 case 'utf-16le':
2607 ret = utf16leSlice(self, start, end)
2608 break
2609 default:
2610 throw new Error('Unknown encoding')
2611 }
2612 return ret
2613}
2614
2615Buffer.prototype.toJSON = function () {
2616 return {
2617 type: 'Buffer',
2618 data: Array.prototype.slice.call(this._arr || this, 0)
2619 }
2620}
2621
2622Buffer.prototype.equals = function (b) {
2623 assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
2624 return Buffer.compare(this, b) === 0
2625}
2626
2627Buffer.prototype.compare = function (b) {
2628 assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
2629 return Buffer.compare(this, b)
2630}
2631
2632// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2633Buffer.prototype.copy = function (target, target_start, start, end) {
2634 var source = this
2635
2636 if (!start) start = 0
2637 if (!end && end !== 0) end = this.length
2638 if (!target_start) target_start = 0
2639
2640 // Copy 0 bytes; we're done
2641 if (end === start) return
2642 if (target.length === 0 || source.length === 0) return
2643
2644 // Fatal error conditions
2645 assert(end >= start, 'sourceEnd < sourceStart')
2646 assert(target_start >= 0 && target_start < target.length,
2647 'targetStart out of bounds')
2648 assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
2649 assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
2650
2651 // Are we oob?
2652 if (end > this.length)
2653 end = this.length
2654 if (target.length - target_start < end - start)
2655 end = target.length - target_start + start
2656
2657 var len = end - start
2658
2659 if (len < 100 || !Buffer._useTypedArrays) {
2660 for (var i = 0; i < len; i++) {
2661 target[i + target_start] = this[i + start]
2662 }
2663 } else {
2664 target._set(this.subarray(start, start + len), target_start)
2665 }
2666}
2667
2668function base64Slice (buf, start, end) {
2669 if (start === 0 && end === buf.length) {
2670 return base64.fromByteArray(buf)
2671 } else {
2672 return base64.fromByteArray(buf.slice(start, end))
2673 }
2674}
2675
2676function utf8Slice (buf, start, end) {
2677 var res = ''
2678 var tmp = ''
2679 end = Math.min(buf.length, end)
2680
2681 for (var i = start; i < end; i++) {
2682 if (buf[i] <= 0x7F) {
2683 res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
2684 tmp = ''
2685 } else {
2686 tmp += '%' + buf[i].toString(16)
2687 }
2688 }
2689
2690 return res + decodeUtf8Char(tmp)
2691}
2692
2693function asciiSlice (buf, start, end) {
2694 var ret = ''
2695 end = Math.min(buf.length, end)
2696
2697 for (var i = start; i < end; i++) {
2698 ret += String.fromCharCode(buf[i])
2699 }
2700 return ret
2701}
2702
2703function binarySlice (buf, start, end) {
2704 return asciiSlice(buf, start, end)
2705}
2706
2707function hexSlice (buf, start, end) {
2708 var len = buf.length
2709
2710 if (!start || start < 0) start = 0
2711 if (!end || end < 0 || end > len) end = len
2712
2713 var out = ''
2714 for (var i = start; i < end; i++) {
2715 out += toHex(buf[i])
2716 }
2717 return out
2718}
2719
2720function utf16leSlice (buf, start, end) {
2721 var bytes = buf.slice(start, end)
2722 var res = ''
2723 for (var i = 0; i < bytes.length; i += 2) {
2724 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
2725 }
2726 return res
2727}
2728
2729Buffer.prototype.slice = function (start, end) {
2730 var len = this.length
2731 start = clamp(start, len, 0)
2732 end = clamp(end, len, len)
2733
2734 if (Buffer._useTypedArrays) {
2735 return Buffer._augment(this.subarray(start, end))
2736 } else {
2737 var sliceLen = end - start
2738 var newBuf = new Buffer(sliceLen, undefined, true)
2739 for (var i = 0; i < sliceLen; i++) {
2740 newBuf[i] = this[i + start]
2741 }
2742 return newBuf
2743 }
2744}
2745
2746// `get` will be removed in Node 0.13+
2747Buffer.prototype.get = function (offset) {
2748 console.log('.get() is deprecated. Access using array indexes instead.')
2749 return this.readUInt8(offset)
2750}
2751
2752// `set` will be removed in Node 0.13+
2753Buffer.prototype.set = function (v, offset) {
2754 console.log('.set() is deprecated. Access using array indexes instead.')
2755 return this.writeUInt8(v, offset)
2756}
2757
2758Buffer.prototype.readUInt8 = function (offset, noAssert) {
2759 if (!noAssert) {
2760 assert(offset !== undefined && offset !== null, 'missing offset')
2761 assert(offset < this.length, 'Trying to read beyond buffer length')
2762 }
2763
2764 if (offset >= this.length)
2765 return
2766
2767 return this[offset]
2768}
2769
2770function readUInt16 (buf, offset, littleEndian, noAssert) {
2771 if (!noAssert) {
2772 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2773 assert(offset !== undefined && offset !== null, 'missing offset')
2774 assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
2775 }
2776
2777 var len = buf.length
2778 if (offset >= len)
2779 return
2780
2781 var val
2782 if (littleEndian) {
2783 val = buf[offset]
2784 if (offset + 1 < len)
2785 val |= buf[offset + 1] << 8
2786 } else {
2787 val = buf[offset] << 8
2788 if (offset + 1 < len)
2789 val |= buf[offset + 1]
2790 }
2791 return val
2792}
2793
2794Buffer.prototype.readUInt16LE = function (offset, noAssert) {
2795 return readUInt16(this, offset, true, noAssert)
2796}
2797
2798Buffer.prototype.readUInt16BE = function (offset, noAssert) {
2799 return readUInt16(this, offset, false, noAssert)
2800}
2801
2802function readUInt32 (buf, offset, littleEndian, noAssert) {
2803 if (!noAssert) {
2804 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2805 assert(offset !== undefined && offset !== null, 'missing offset')
2806 assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
2807 }
2808
2809 var len = buf.length
2810 if (offset >= len)
2811 return
2812
2813 var val
2814 if (littleEndian) {
2815 if (offset + 2 < len)
2816 val = buf[offset + 2] << 16
2817 if (offset + 1 < len)
2818 val |= buf[offset + 1] << 8
2819 val |= buf[offset]
2820 if (offset + 3 < len)
2821 val = val + (buf[offset + 3] << 24 >>> 0)
2822 } else {
2823 if (offset + 1 < len)
2824 val = buf[offset + 1] << 16
2825 if (offset + 2 < len)
2826 val |= buf[offset + 2] << 8
2827 if (offset + 3 < len)
2828 val |= buf[offset + 3]
2829 val = val + (buf[offset] << 24 >>> 0)
2830 }
2831 return val
2832}
2833
2834Buffer.prototype.readUInt32LE = function (offset, noAssert) {
2835 return readUInt32(this, offset, true, noAssert)
2836}
2837
2838Buffer.prototype.readUInt32BE = function (offset, noAssert) {
2839 return readUInt32(this, offset, false, noAssert)
2840}
2841
2842Buffer.prototype.readInt8 = function (offset, noAssert) {
2843 if (!noAssert) {
2844 assert(offset !== undefined && offset !== null,
2845 'missing offset')
2846 assert(offset < this.length, 'Trying to read beyond buffer length')
2847 }
2848
2849 if (offset >= this.length)
2850 return
2851
2852 var neg = this[offset] & 0x80
2853 if (neg)
2854 return (0xff - this[offset] + 1) * -1
2855 else
2856 return this[offset]
2857}
2858
2859function readInt16 (buf, offset, littleEndian, noAssert) {
2860 if (!noAssert) {
2861 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2862 assert(offset !== undefined && offset !== null, 'missing offset')
2863 assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
2864 }
2865
2866 var len = buf.length
2867 if (offset >= len)
2868 return
2869
2870 var val = readUInt16(buf, offset, littleEndian, true)
2871 var neg = val & 0x8000
2872 if (neg)
2873 return (0xffff - val + 1) * -1
2874 else
2875 return val
2876}
2877
2878Buffer.prototype.readInt16LE = function (offset, noAssert) {
2879 return readInt16(this, offset, true, noAssert)
2880}
2881
2882Buffer.prototype.readInt16BE = function (offset, noAssert) {
2883 return readInt16(this, offset, false, noAssert)
2884}
2885
2886function readInt32 (buf, offset, littleEndian, noAssert) {
2887 if (!noAssert) {
2888 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2889 assert(offset !== undefined && offset !== null, 'missing offset')
2890 assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
2891 }
2892
2893 var len = buf.length
2894 if (offset >= len)
2895 return
2896
2897 var val = readUInt32(buf, offset, littleEndian, true)
2898 var neg = val & 0x80000000
2899 if (neg)
2900 return (0xffffffff - val + 1) * -1
2901 else
2902 return val
2903}
2904
2905Buffer.prototype.readInt32LE = function (offset, noAssert) {
2906 return readInt32(this, offset, true, noAssert)
2907}
2908
2909Buffer.prototype.readInt32BE = function (offset, noAssert) {
2910 return readInt32(this, offset, false, noAssert)
2911}
2912
2913function readFloat (buf, offset, littleEndian, noAssert) {
2914 if (!noAssert) {
2915 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2916 assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
2917 }
2918
2919 return ieee754.read(buf, offset, littleEndian, 23, 4)
2920}
2921
2922Buffer.prototype.readFloatLE = function (offset, noAssert) {
2923 return readFloat(this, offset, true, noAssert)
2924}
2925
2926Buffer.prototype.readFloatBE = function (offset, noAssert) {
2927 return readFloat(this, offset, false, noAssert)
2928}
2929
2930function readDouble (buf, offset, littleEndian, noAssert) {
2931 if (!noAssert) {
2932 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2933 assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
2934 }
2935
2936 return ieee754.read(buf, offset, littleEndian, 52, 8)
2937}
2938
2939Buffer.prototype.readDoubleLE = function (offset, noAssert) {
2940 return readDouble(this, offset, true, noAssert)
2941}
2942
2943Buffer.prototype.readDoubleBE = function (offset, noAssert) {
2944 return readDouble(this, offset, false, noAssert)
2945}
2946
2947Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
2948 if (!noAssert) {
2949 assert(value !== undefined && value !== null, 'missing value')
2950 assert(offset !== undefined && offset !== null, 'missing offset')
2951 assert(offset < this.length, 'trying to write beyond buffer length')
2952 verifuint(value, 0xff)
2953 }
2954
2955 if (offset >= this.length) return
2956
2957 this[offset] = value
2958 return offset + 1
2959}
2960
2961function writeUInt16 (buf, value, offset, littleEndian, noAssert) {
2962 if (!noAssert) {
2963 assert(value !== undefined && value !== null, 'missing value')
2964 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2965 assert(offset !== undefined && offset !== null, 'missing offset')
2966 assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
2967 verifuint(value, 0xffff)
2968 }
2969
2970 var len = buf.length
2971 if (offset >= len)
2972 return
2973
2974 for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
2975 buf[offset + i] =
2976 (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
2977 (littleEndian ? i : 1 - i) * 8
2978 }
2979 return offset + 2
2980}
2981
2982Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
2983 return writeUInt16(this, value, offset, true, noAssert)
2984}
2985
2986Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
2987 return writeUInt16(this, value, offset, false, noAssert)
2988}
2989
2990function writeUInt32 (buf, value, offset, littleEndian, noAssert) {
2991 if (!noAssert) {
2992 assert(value !== undefined && value !== null, 'missing value')
2993 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2994 assert(offset !== undefined && offset !== null, 'missing offset')
2995 assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
2996 verifuint(value, 0xffffffff)
2997 }
2998
2999 var len = buf.length
3000 if (offset >= len)
3001 return
3002
3003 for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
3004 buf[offset + i] =
3005 (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
3006 }
3007 return offset + 4
3008}
3009
3010Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
3011 return writeUInt32(this, value, offset, true, noAssert)
3012}
3013
3014Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
3015 return writeUInt32(this, value, offset, false, noAssert)
3016}
3017
3018Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
3019 if (!noAssert) {
3020 assert(value !== undefined && value !== null, 'missing value')
3021 assert(offset !== undefined && offset !== null, 'missing offset')
3022 assert(offset < this.length, 'Trying to write beyond buffer length')
3023 verifsint(value, 0x7f, -0x80)
3024 }
3025
3026 if (offset >= this.length)
3027 return
3028
3029 if (value >= 0)
3030 this.writeUInt8(value, offset, noAssert)
3031 else
3032 this.writeUInt8(0xff + value + 1, offset, noAssert)
3033 return offset + 1
3034}
3035
3036function writeInt16 (buf, value, offset, littleEndian, noAssert) {
3037 if (!noAssert) {
3038 assert(value !== undefined && value !== null, 'missing value')
3039 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
3040 assert(offset !== undefined && offset !== null, 'missing offset')
3041 assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
3042 verifsint(value, 0x7fff, -0x8000)
3043 }
3044
3045 var len = buf.length
3046 if (offset >= len)
3047 return
3048
3049 if (value >= 0)
3050 writeUInt16(buf, value, offset, littleEndian, noAssert)
3051 else
3052 writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
3053 return offset + 2
3054}
3055
3056Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
3057 return writeInt16(this, value, offset, true, noAssert)
3058}
3059
3060Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
3061 return writeInt16(this, value, offset, false, noAssert)
3062}
3063
3064function writeInt32 (buf, value, offset, littleEndian, noAssert) {
3065 if (!noAssert) {
3066 assert(value !== undefined && value !== null, 'missing value')
3067 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
3068 assert(offset !== undefined && offset !== null, 'missing offset')
3069 assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
3070 verifsint(value, 0x7fffffff, -0x80000000)
3071 }
3072
3073 var len = buf.length
3074 if (offset >= len)
3075 return
3076
3077 if (value >= 0)
3078 writeUInt32(buf, value, offset, littleEndian, noAssert)
3079 else
3080 writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
3081 return offset + 4
3082}
3083
3084Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
3085 return writeInt32(this, value, offset, true, noAssert)
3086}
3087
3088Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
3089 return writeInt32(this, value, offset, false, noAssert)
3090}
3091
3092function writeFloat (buf, value, offset, littleEndian, noAssert) {
3093 if (!noAssert) {
3094 assert(value !== undefined && value !== null, 'missing value')
3095 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
3096 assert(offset !== undefined && offset !== null, 'missing offset')
3097 assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
3098 verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
3099 }
3100
3101 var len = buf.length
3102 if (offset >= len)
3103 return
3104
3105 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3106 return offset + 4
3107}
3108
3109Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
3110 return writeFloat(this, value, offset, true, noAssert)
3111}
3112
3113Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
3114 return writeFloat(this, value, offset, false, noAssert)
3115}
3116
3117function writeDouble (buf, value, offset, littleEndian, noAssert) {
3118 if (!noAssert) {
3119 assert(value !== undefined && value !== null, 'missing value')
3120 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
3121 assert(offset !== undefined && offset !== null, 'missing offset')
3122 assert(offset + 7 < buf.length,
3123 'Trying to write beyond buffer length')
3124 verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
3125 }
3126
3127 var len = buf.length
3128 if (offset >= len)
3129 return
3130
3131 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3132 return offset + 8
3133}
3134
3135Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
3136 return writeDouble(this, value, offset, true, noAssert)
3137}
3138
3139Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
3140 return writeDouble(this, value, offset, false, noAssert)
3141}
3142
3143// fill(value, start=0, end=buffer.length)
3144Buffer.prototype.fill = function (value, start, end) {
3145 if (!value) value = 0
3146 if (!start) start = 0
3147 if (!end) end = this.length
3148
3149 assert(end >= start, 'end < start')
3150
3151 // Fill 0 bytes; we're done
3152 if (end === start) return
3153 if (this.length === 0) return
3154
3155 assert(start >= 0 && start < this.length, 'start out of bounds')
3156 assert(end >= 0 && end <= this.length, 'end out of bounds')
3157
3158 var i
3159 if (typeof value === 'number') {
3160 for (i = start; i < end; i++) {
3161 this[i] = value
3162 }
3163 } else {
3164 var bytes = utf8ToBytes(value.toString())
3165 var len = bytes.length
3166 for (i = start; i < end; i++) {
3167 this[i] = bytes[i % len]
3168 }
3169 }
3170
3171 return this
3172}
3173
3174Buffer.prototype.inspect = function () {
3175 var out = []
3176 var len = this.length
3177 for (var i = 0; i < len; i++) {
3178 out[i] = toHex(this[i])
3179 if (i === exports.INSPECT_MAX_BYTES) {
3180 out[i + 1] = '...'
3181 break
3182 }
3183 }
3184 return '<Buffer ' + out.join(' ') + '>'
3185}
3186
3187/**
3188 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
3189 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
3190 */
3191Buffer.prototype.toArrayBuffer = function () {
3192 if (typeof Uint8Array !== 'undefined') {
3193 if (Buffer._useTypedArrays) {
3194 return (new Buffer(this)).buffer
3195 } else {
3196 var buf = new Uint8Array(this.length)
3197 for (var i = 0, len = buf.length; i < len; i += 1) {
3198 buf[i] = this[i]
3199 }
3200 return buf.buffer
3201 }
3202 } else {
3203 throw new Error('Buffer.toArrayBuffer not supported in this browser')
3204 }
3205}
3206
3207// HELPER FUNCTIONS
3208// ================
3209
3210var BP = Buffer.prototype
3211
3212/**
3213 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
3214 */
3215Buffer._augment = function (arr) {
3216 arr._isBuffer = true
3217
3218 // save reference to original Uint8Array get/set methods before overwriting
3219 arr._get = arr.get
3220 arr._set = arr.set
3221
3222 // deprecated, will be removed in node 0.13+
3223 arr.get = BP.get
3224 arr.set = BP.set
3225
3226 arr.write = BP.write
3227 arr.toString = BP.toString
3228 arr.toLocaleString = BP.toString
3229 arr.toJSON = BP.toJSON
3230 arr.equals = BP.equals
3231 arr.compare = BP.compare
3232 arr.copy = BP.copy
3233 arr.slice = BP.slice
3234 arr.readUInt8 = BP.readUInt8
3235 arr.readUInt16LE = BP.readUInt16LE
3236 arr.readUInt16BE = BP.readUInt16BE
3237 arr.readUInt32LE = BP.readUInt32LE
3238 arr.readUInt32BE = BP.readUInt32BE
3239 arr.readInt8 = BP.readInt8
3240 arr.readInt16LE = BP.readInt16LE
3241 arr.readInt16BE = BP.readInt16BE
3242 arr.readInt32LE = BP.readInt32LE
3243 arr.readInt32BE = BP.readInt32BE
3244 arr.readFloatLE = BP.readFloatLE
3245 arr.readFloatBE = BP.readFloatBE
3246 arr.readDoubleLE = BP.readDoubleLE
3247 arr.readDoubleBE = BP.readDoubleBE
3248 arr.writeUInt8 = BP.writeUInt8
3249 arr.writeUInt16LE = BP.writeUInt16LE
3250 arr.writeUInt16BE = BP.writeUInt16BE
3251 arr.writeUInt32LE = BP.writeUInt32LE
3252 arr.writeUInt32BE = BP.writeUInt32BE
3253 arr.writeInt8 = BP.writeInt8
3254 arr.writeInt16LE = BP.writeInt16LE
3255 arr.writeInt16BE = BP.writeInt16BE
3256 arr.writeInt32LE = BP.writeInt32LE
3257 arr.writeInt32BE = BP.writeInt32BE
3258 arr.writeFloatLE = BP.writeFloatLE
3259 arr.writeFloatBE = BP.writeFloatBE
3260 arr.writeDoubleLE = BP.writeDoubleLE
3261 arr.writeDoubleBE = BP.writeDoubleBE
3262 arr.fill = BP.fill
3263 arr.inspect = BP.inspect
3264 arr.toArrayBuffer = BP.toArrayBuffer
3265
3266 return arr
3267}
3268
3269var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
3270
3271function base64clean (str) {
3272 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3273 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
3274 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3275 while (str.length % 4 !== 0) {
3276 str = str + '='
3277 }
3278 return str
3279}
3280
3281function stringtrim (str) {
3282 if (str.trim) return str.trim()
3283 return str.replace(/^\s+|\s+$/g, '')
3284}
3285
3286// slice(start, end)
3287function clamp (index, len, defaultValue) {
3288 if (typeof index !== 'number') return defaultValue
3289 index = ~~index; // Coerce to integer.
3290 if (index >= len) return len
3291 if (index >= 0) return index
3292 index += len
3293 if (index >= 0) return index
3294 return 0
3295}
3296
3297function coerce (length) {
3298 // Coerce length to a number (possibly NaN), round up
3299 // in case it's fractional (e.g. 123.456) then do a
3300 // double negate to coerce a NaN to 0. Easy, right?
3301 length = ~~Math.ceil(+length)
3302 return length < 0 ? 0 : length
3303}
3304
3305function isArray (subject) {
3306 return (Array.isArray || function (subject) {
3307 return Object.prototype.toString.call(subject) === '[object Array]'
3308 })(subject)
3309}
3310
3311function isArrayish (subject) {
3312 return isArray(subject) || Buffer.isBuffer(subject) ||
3313 subject && typeof subject === 'object' &&
3314 typeof subject.length === 'number'
3315}
3316
3317function toHex (n) {
3318 if (n < 16) return '0' + n.toString(16)
3319 return n.toString(16)
3320}
3321
3322function utf8ToBytes (str) {
3323 var byteArray = []
3324 for (var i = 0; i < str.length; i++) {
3325 var b = str.charCodeAt(i)
3326 if (b <= 0x7F) {
3327 byteArray.push(b)
3328 } else {
3329 var start = i
3330 if (b >= 0xD800 && b <= 0xDFFF) i++
3331 var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
3332 for (var j = 0; j < h.length; j++) {
3333 byteArray.push(parseInt(h[j], 16))
3334 }
3335 }
3336 }
3337 return byteArray
3338}
3339
3340function asciiToBytes (str) {
3341 var byteArray = []
3342 for (var i = 0; i < str.length; i++) {
3343 // Node's code seems to be doing this and not & 0x7F..
3344 byteArray.push(str.charCodeAt(i) & 0xFF)
3345 }
3346 return byteArray
3347}
3348
3349function utf16leToBytes (str) {
3350 var c, hi, lo
3351 var byteArray = []
3352 for (var i = 0; i < str.length; i++) {
3353 c = str.charCodeAt(i)
3354 hi = c >> 8
3355 lo = c % 256
3356 byteArray.push(lo)
3357 byteArray.push(hi)
3358 }
3359
3360 return byteArray
3361}
3362
3363function base64ToBytes (str) {
3364 return base64.toByteArray(str)
3365}
3366
3367function blitBuffer (src, dst, offset, length) {
3368 for (var i = 0; i < length; i++) {
3369 if ((i + offset >= dst.length) || (i >= src.length))
3370 break
3371 dst[i + offset] = src[i]
3372 }
3373 return i
3374}
3375
3376function decodeUtf8Char (str) {
3377 try {
3378 return decodeURIComponent(str)
3379 } catch (err) {
3380 return String.fromCharCode(0xFFFD) // UTF 8 invalid char
3381 }
3382}
3383
3384/*
3385 * We have to make sure that the value is a valid integer. This means that it
3386 * is non-negative. It has no fractional component and that it does not
3387 * exceed the maximum allowed value.
3388 */
3389function verifuint (value, max) {
3390 assert(typeof value === 'number', 'cannot write a non-number as a number')
3391 assert(value >= 0, 'specified a negative value for writing an unsigned value')
3392 assert(value <= max, 'value is larger than maximum value for type')
3393 assert(Math.floor(value) === value, 'value has a fractional component')
3394}
3395
3396function verifsint (value, max, min) {
3397 assert(typeof value === 'number', 'cannot write a non-number as a number')
3398 assert(value <= max, 'value larger than maximum allowed value')
3399 assert(value >= min, 'value smaller than minimum allowed value')
3400 assert(Math.floor(value) === value, 'value has a fractional component')
3401}
3402
3403function verifIEEE754 (value, max, min) {
3404 assert(typeof value === 'number', 'cannot write a non-number as a number')
3405 assert(value <= max, 'value larger than maximum allowed value')
3406 assert(value >= min, 'value smaller than minimum allowed value')
3407}
3408
3409function assert (test, message) {
3410 if (!test) throw new Error(message || 'Failed assertion')
3411}
3412
3413},{"base64-js":9,"ieee754":10}],9:[function(_dereq_,module,exports){
3414var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3415
3416;(function (exports) {
3417 'use strict';
3418
3419 var Arr = (typeof Uint8Array !== 'undefined')
3420 ? Uint8Array
3421 : Array
3422
3423 var PLUS = '+'.charCodeAt(0)
3424 var SLASH = '/'.charCodeAt(0)
3425 var NUMBER = '0'.charCodeAt(0)
3426 var LOWER = 'a'.charCodeAt(0)
3427 var UPPER = 'A'.charCodeAt(0)
3428
3429 function decode (elt) {
3430 var code = elt.charCodeAt(0)
3431 if (code === PLUS)
3432 return 62 // '+'
3433 if (code === SLASH)
3434 return 63 // '/'
3435 if (code < NUMBER)
3436 return -1 //no match
3437 if (code < NUMBER + 10)
3438 return code - NUMBER + 26 + 26
3439 if (code < UPPER + 26)
3440 return code - UPPER
3441 if (code < LOWER + 26)
3442 return code - LOWER + 26
3443 }
3444
3445 function b64ToByteArray (b64) {
3446 var i, j, l, tmp, placeHolders, arr
3447
3448 if (b64.length % 4 > 0) {
3449 throw new Error('Invalid string. Length must be a multiple of 4')
3450 }
3451
3452 // the number of equal signs (place holders)
3453 // if there are two placeholders, than the two characters before it
3454 // represent one byte
3455 // if there is only one, then the three characters before it represent 2 bytes
3456 // this is just a cheap hack to not do indexOf twice
3457 var len = b64.length
3458 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
3459
3460 // base64 is 4/3 + up to two characters of the original data
3461 arr = new Arr(b64.length * 3 / 4 - placeHolders)
3462
3463 // if there are placeholders, only get up to the last complete 4 chars
3464 l = placeHolders > 0 ? b64.length - 4 : b64.length
3465
3466 var L = 0
3467
3468 function push (v) {
3469 arr[L++] = v
3470 }
3471
3472 for (i = 0, j = 0; i < l; i += 4, j += 3) {
3473 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
3474 push((tmp & 0xFF0000) >> 16)
3475 push((tmp & 0xFF00) >> 8)
3476 push(tmp & 0xFF)
3477 }
3478
3479 if (placeHolders === 2) {
3480 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
3481 push(tmp & 0xFF)
3482 } else if (placeHolders === 1) {
3483 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
3484 push((tmp >> 8) & 0xFF)
3485 push(tmp & 0xFF)
3486 }
3487
3488 return arr
3489 }
3490
3491 function uint8ToBase64 (uint8) {
3492 var i,
3493 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
3494 output = "",
3495 temp, length
3496
3497 function encode (num) {
3498 return lookup.charAt(num)
3499 }
3500
3501 function tripletToBase64 (num) {
3502 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
3503 }
3504
3505 // go through the array every three bytes, we'll deal with trailing stuff later
3506 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
3507 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
3508 output += tripletToBase64(temp)
3509 }
3510
3511 // pad the end with zeros, but make sure to not forget the extra bytes
3512 switch (extraBytes) {
3513 case 1:
3514 temp = uint8[uint8.length - 1]
3515 output += encode(temp >> 2)
3516 output += encode((temp << 4) & 0x3F)
3517 output += '=='
3518 break
3519 case 2:
3520 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
3521 output += encode(temp >> 10)
3522 output += encode((temp >> 4) & 0x3F)
3523 output += encode((temp << 2) & 0x3F)
3524 output += '='
3525 break
3526 }
3527
3528 return output
3529 }
3530
3531 exports.toByteArray = b64ToByteArray
3532 exports.fromByteArray = uint8ToBase64
3533}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
3534
3535},{}],10:[function(_dereq_,module,exports){
3536exports.read = function(buffer, offset, isLE, mLen, nBytes) {
3537 var e, m,
3538 eLen = nBytes * 8 - mLen - 1,
3539 eMax = (1 << eLen) - 1,
3540 eBias = eMax >> 1,
3541 nBits = -7,
3542 i = isLE ? (nBytes - 1) : 0,
3543 d = isLE ? -1 : 1,
3544 s = buffer[offset + i];
3545
3546 i += d;
3547
3548 e = s & ((1 << (-nBits)) - 1);
3549 s >>= (-nBits);
3550 nBits += eLen;
3551 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8){};
3552
3553 m = e & ((1 << (-nBits)) - 1);
3554 e >>= (-nBits);
3555 nBits += mLen;
3556 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8){};
3557
3558 if (e === 0) {
3559 e = 1 - eBias;
3560 } else if (e === eMax) {
3561 return m ? NaN : ((s ? -1 : 1) * Infinity);
3562 } else {
3563 m = m + Math.pow(2, mLen);
3564 e = e - eBias;
3565 }
3566 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
3567};
3568
3569exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
3570 var e, m, c,
3571 eLen = nBytes * 8 - mLen - 1,
3572 eMax = (1 << eLen) - 1,
3573 eBias = eMax >> 1,
3574 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
3575 i = isLE ? 0 : (nBytes - 1),
3576 d = isLE ? 1 : -1,
3577 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
3578
3579 value = Math.abs(value);
3580
3581 if (isNaN(value) || value === Infinity) {
3582 m = isNaN(value) ? 1 : 0;
3583 e = eMax;
3584 } else {
3585 e = Math.floor(Math.log(value) / Math.LN2);
3586 if (value * (c = Math.pow(2, -e)) < 1) {
3587 e--;
3588 c *= 2;
3589 }
3590 if (e + eBias >= 1) {
3591 value += rt / c;
3592 } else {
3593 value += rt * Math.pow(2, 1 - eBias);
3594 }
3595 if (value * c >= 2) {
3596 e++;
3597 c /= 2;
3598 }
3599
3600 if (e + eBias >= eMax) {
3601 m = 0;
3602 e = eMax;
3603 } else if (e + eBias >= 1) {
3604 m = (value * c - 1) * Math.pow(2, mLen);
3605 e = e + eBias;
3606 } else {
3607 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
3608 e = 0;
3609 }
3610 }
3611
3612 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8){};
3613
3614 e = (e << mLen) | m;
3615 eLen += mLen;
3616 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8){};
3617
3618 buffer[offset + i - d] |= s * 128;
3619};
3620
3621},{}],11:[function(_dereq_,module,exports){
3622if (typeof Object.create === 'function') {
3623 // implementation from standard node.js 'util' module
3624 module.exports = function inherits(ctor, superCtor) {
3625 ctor.super_ = superCtor
3626 ctor.prototype = Object.create(superCtor.prototype, {
3627 constructor: {
3628 value: ctor,
3629 enumerable: false,
3630 writable: true,
3631 configurable: true
3632 }
3633 });
3634 };
3635} else {
3636 // old school shim for old browsers
3637 module.exports = function inherits(ctor, superCtor) {
3638 ctor.super_ = superCtor
3639 var TempCtor = function () {}
3640 TempCtor.prototype = superCtor.prototype
3641 ctor.prototype = new TempCtor()
3642 ctor.prototype.constructor = ctor
3643 }
3644}
3645
3646},{}],12:[function(_dereq_,module,exports){
3647// shim for using process in browser
3648
3649var process = module.exports = {};
3650
3651process.nextTick = (function () {
3652 var canSetImmediate = typeof window !== 'undefined'
3653 && window.setImmediate;
3654 var canPost = typeof window !== 'undefined'
3655 && window.postMessage && window.addEventListener
3656 ;
3657
3658 if (canSetImmediate) {
3659 return function (f) { return window.setImmediate(f) };
3660 }
3661
3662 if (canPost) {
3663 var queue = [];
3664 window.addEventListener('message', function (ev) {
3665 var source = ev.source;
3666 if ((source === window || source === null) && ev.data === 'process-tick') {
3667 ev.stopPropagation();
3668 if (queue.length > 0) {
3669 var fn = queue.shift();
3670 fn();
3671 }
3672 }
3673 }, true);
3674
3675 return function nextTick(fn) {
3676 queue.push(fn);
3677 window.postMessage('process-tick', '*');
3678 };
3679 }
3680
3681 return function nextTick(fn) {
3682 setTimeout(fn, 0);
3683 };
3684})();
3685
3686process.title = 'browser';
3687process.browser = true;
3688process.env = {};
3689process.argv = [];
3690
3691function noop() {}
3692
3693process.on = noop;
3694process.addListener = noop;
3695process.once = noop;
3696process.off = noop;
3697process.removeListener = noop;
3698process.removeAllListeners = noop;
3699process.emit = noop;
3700
3701process.binding = function (name) {
3702 throw new Error('process.binding is not supported');
3703}
3704
3705// TODO(shtylman)
3706process.cwd = function () { return '/' };
3707process.chdir = function (dir) {
3708 throw new Error('process.chdir is not supported');
3709};
3710
3711},{}],13:[function(_dereq_,module,exports){
3712module.exports=_dereq_(5)
3713},{}],14:[function(_dereq_,module,exports){
3714module.exports=_dereq_(6)
3715},{"./support/isBuffer":13,"FWaASH":12,"inherits":11}],15:[function(_dereq_,module,exports){
3716(function (Buffer){
3717// Base58 encoding/decoding
3718// Originally written by Mike Hearn for BitcoinJ
3719// Copyright (c) 2011 Google Inc
3720// Ported to JavaScript by Stefan Thomas
3721// Merged Buffer refactorings from base58-native by Stephen Pair
3722// Copyright (c) 2013 BitPay Inc
3723
3724var assert = _dereq_('assert')
3725var BigInteger = _dereq_('bigi')
3726
3727var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
3728var ALPHABET_BUF = new Buffer(ALPHABET, 'ascii')
3729var ALPHABET_MAP = {}
3730for(var i = 0; i < ALPHABET.length; i++) {
3731 ALPHABET_MAP[ALPHABET.charAt(i)] = BigInteger.valueOf(i)
3732}
3733var BASE = new BigInteger('58')
3734
3735function encode(buffer) {
3736 var bi = BigInteger.fromBuffer(buffer)
3737 var result = new Buffer(buffer.length << 1)
3738
3739 var i = result.length - 1
3740 while (bi.signum() > 0) {
3741 var remainder = bi.mod(BASE)
3742 bi = bi.divide(BASE)
3743
3744 result[i] = ALPHABET_BUF[remainder.intValue()]
3745 i--
3746 }
3747
3748 // deal with leading zeros
3749 var j = 0
3750 while (buffer[j] === 0) {
3751 result[i] = ALPHABET_BUF[0]
3752 j++
3753 i--
3754 }
3755
3756 return result.slice(i + 1, result.length).toString('ascii')
3757}
3758
3759function decode(string) {
3760 if (string.length === 0) return new Buffer(0)
3761
3762 var num = BigInteger.ZERO
3763
3764 for (var i = 0; i < string.length; i++) {
3765 num = num.multiply(BASE)
3766
3767 var figure = ALPHABET_MAP[string.charAt(i)]
3768 assert.notEqual(figure, undefined, 'Non-base58 character')
3769
3770 num = num.add(figure)
3771 }
3772
3773 // deal with leading zeros
3774 var j = 0
3775 while ((j < string.length) && (string[j] === ALPHABET[0])) {
3776 j++
3777 }
3778
3779 var buffer = num.toBuffer()
3780 var leadingZeros = new Buffer(j)
3781 leadingZeros.fill(0)
3782
3783 return Buffer.concat([leadingZeros, buffer])
3784}
3785
3786module.exports = {
3787 encode: encode,
3788 decode: decode
3789}
3790
3791}).call(this,_dereq_("buffer").Buffer)
3792},{"assert":4,"bigi":3,"buffer":8}],16:[function(_dereq_,module,exports){
3793(function (Buffer){
3794var createHash = _dereq_('sha.js')
3795
3796var md5 = toConstructor(_dereq_('./md5'))
3797var rmd160 = toConstructor(_dereq_('ripemd160'))
3798
3799function toConstructor (fn) {
3800 return function () {
3801 var buffers = []
3802 var m= {
3803 update: function (data, enc) {
3804 if(!Buffer.isBuffer(data)) data = new Buffer(data, enc)
3805 buffers.push(data)
3806 return this
3807 },
3808 digest: function (enc) {
3809 var buf = Buffer.concat(buffers)
3810 var r = fn(buf)
3811 buffers = null
3812 return enc ? r.toString(enc) : r
3813 }
3814 }
3815 return m
3816 }
3817}
3818
3819module.exports = function (alg) {
3820 if('md5' === alg) return new md5()
3821 if('rmd160' === alg) return new rmd160()
3822 return createHash(alg)
3823}
3824
3825}).call(this,_dereq_("buffer").Buffer)
3826},{"./md5":20,"buffer":8,"ripemd160":21,"sha.js":23}],17:[function(_dereq_,module,exports){
3827(function (Buffer){
3828var createHash = _dereq_('./create-hash')
3829
3830var blocksize = 64
3831var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0)
3832
3833module.exports = Hmac
3834
3835function Hmac (alg, key) {
3836 if(!(this instanceof Hmac)) return new Hmac(alg, key)
3837 this._opad = opad
3838 this._alg = alg
3839
3840 key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key
3841
3842 if(key.length > blocksize) {
3843 key = createHash(alg).update(key).digest()
3844 } else if(key.length < blocksize) {
3845 key = Buffer.concat([key, zeroBuffer], blocksize)
3846 }
3847
3848 var ipad = this._ipad = new Buffer(blocksize)
3849 var opad = this._opad = new Buffer(blocksize)
3850
3851 for(var i = 0; i < blocksize; i++) {
3852 ipad[i] = key[i] ^ 0x36
3853 opad[i] = key[i] ^ 0x5C
3854 }
3855
3856 this._hash = createHash(alg).update(ipad)
3857}
3858
3859Hmac.prototype.update = function (data, enc) {
3860 this._hash.update(data, enc)
3861 return this
3862}
3863
3864Hmac.prototype.digest = function (enc) {
3865 var h = this._hash.digest()
3866 return createHash(this._alg).update(this._opad).update(h).digest(enc)
3867}
3868
3869
3870}).call(this,_dereq_("buffer").Buffer)
3871},{"./create-hash":16,"buffer":8}],18:[function(_dereq_,module,exports){
3872(function (Buffer){
3873var intSize = 4;
3874var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
3875var chrsz = 8;
3876
3877function toArray(buf, bigEndian) {
3878 if ((buf.length % intSize) !== 0) {
3879 var len = buf.length + (intSize - (buf.length % intSize));
3880 buf = Buffer.concat([buf, zeroBuffer], len);
3881 }
3882
3883 var arr = [];
3884 var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
3885 for (var i = 0; i < buf.length; i += intSize) {
3886 arr.push(fn.call(buf, i));
3887 }
3888 return arr;
3889}
3890
3891function toBuffer(arr, size, bigEndian) {
3892 var buf = new Buffer(size);
3893 var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
3894 for (var i = 0; i < arr.length; i++) {
3895 fn.call(buf, arr[i], i * 4, true);
3896 }
3897 return buf;
3898}
3899
3900function hash(buf, fn, hashSize, bigEndian) {
3901 if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
3902 var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
3903 return toBuffer(arr, hashSize, bigEndian);
3904}
3905
3906module.exports = { hash: hash };
3907
3908}).call(this,_dereq_("buffer").Buffer)
3909},{"buffer":8}],19:[function(_dereq_,module,exports){
3910(function (Buffer){
3911var rng = _dereq_('./rng')
3912
3913function error () {
3914 var m = [].slice.call(arguments).join(' ')
3915 throw new Error([
3916 m,
3917 'we accept pull requests',
3918 'http://github.com/dominictarr/crypto-browserify'
3919 ].join('\n'))
3920}
3921
3922exports.createHash = _dereq_('./create-hash')
3923
3924exports.createHmac = _dereq_('./create-hmac')
3925
3926exports.randomBytes = function(size, callback) {
3927 if (callback && callback.call) {
3928 try {
3929 callback.call(this, undefined, new Buffer(rng(size)))
3930 } catch (err) { callback(err) }
3931 } else {
3932 return new Buffer(rng(size))
3933 }
3934}
3935
3936function each(a, f) {
3937 for(var i in a)
3938 f(a[i], i)
3939}
3940
3941exports.getHashes = function () {
3942 return ['sha1', 'sha256', 'md5', 'rmd160']
3943
3944}
3945
3946var p = _dereq_('./pbkdf2')(exports.createHmac)
3947exports.pbkdf2 = p.pbkdf2
3948exports.pbkdf2Sync = p.pbkdf2Sync
3949
3950
3951// the least I can do is make error messages for the rest of the node.js/crypto api.
3952each(['createCredentials'
3953, 'createCipher'
3954, 'createCipheriv'
3955, 'createDecipher'
3956, 'createDecipheriv'
3957, 'createSign'
3958, 'createVerify'
3959, 'createDiffieHellman'
3960], function (name) {
3961 exports[name] = function () {
3962 error('sorry,', name, 'is not implemented yet')
3963 }
3964})
3965
3966}).call(this,_dereq_("buffer").Buffer)
3967},{"./create-hash":16,"./create-hmac":17,"./pbkdf2":27,"./rng":28,"buffer":8}],20:[function(_dereq_,module,exports){
3968/*
3969 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
3970 * Digest Algorithm, as defined in RFC 1321.
3971 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
3972 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
3973 * Distributed under the BSD License
3974 * See http://pajhome.org.uk/crypt/md5 for more info.
3975 */
3976
3977var helpers = _dereq_('./helpers');
3978
3979/*
3980 * Calculate the MD5 of an array of little-endian words, and a bit length
3981 */
3982function core_md5(x, len)
3983{
3984 /* append padding */
3985 x[len >> 5] |= 0x80 << ((len) % 32);
3986 x[(((len + 64) >>> 9) << 4) + 14] = len;
3987
3988 var a = 1732584193;
3989 var b = -271733879;
3990 var c = -1732584194;
3991 var d = 271733878;
3992
3993 for(var i = 0; i < x.length; i += 16)
3994 {
3995 var olda = a;
3996 var oldb = b;
3997 var oldc = c;
3998 var oldd = d;
3999
4000 a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
4001 d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
4002 c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
4003 b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
4004 a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
4005 d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
4006 c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
4007 b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
4008 a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
4009 d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
4010 c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
4011 b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
4012 a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
4013 d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
4014 c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
4015 b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
4016
4017 a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
4018 d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
4019 c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
4020 b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
4021 a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
4022 d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
4023 c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
4024 b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
4025 a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
4026 d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
4027 c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
4028 b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
4029 a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
4030 d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
4031 c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
4032 b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
4033
4034 a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
4035 d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
4036 c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
4037 b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
4038 a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
4039 d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
4040 c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
4041 b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
4042 a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
4043 d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
4044 c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
4045 b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
4046 a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
4047 d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
4048 c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
4049 b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
4050
4051 a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
4052 d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
4053 c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
4054 b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
4055 a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
4056 d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
4057 c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
4058 b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
4059 a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
4060 d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
4061 c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
4062 b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
4063 a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
4064 d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
4065 c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
4066 b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
4067
4068 a = safe_add(a, olda);
4069 b = safe_add(b, oldb);
4070 c = safe_add(c, oldc);
4071 d = safe_add(d, oldd);
4072 }
4073 return Array(a, b, c, d);
4074
4075}
4076
4077/*
4078 * These functions implement the four basic operations the algorithm uses.
4079 */
4080function md5_cmn(q, a, b, x, s, t)
4081{
4082 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
4083}
4084function md5_ff(a, b, c, d, x, s, t)
4085{
4086 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
4087}
4088function md5_gg(a, b, c, d, x, s, t)
4089{
4090 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
4091}
4092function md5_hh(a, b, c, d, x, s, t)
4093{
4094 return md5_cmn(b ^ c ^ d, a, b, x, s, t);
4095}
4096function md5_ii(a, b, c, d, x, s, t)
4097{
4098 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
4099}
4100
4101/*
4102 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
4103 * to work around bugs in some JS interpreters.
4104 */
4105function safe_add(x, y)
4106{
4107 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
4108 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
4109 return (msw << 16) | (lsw & 0xFFFF);
4110}
4111
4112/*
4113 * Bitwise rotate a 32-bit number to the left.
4114 */
4115function bit_rol(num, cnt)
4116{
4117 return (num << cnt) | (num >>> (32 - cnt));
4118}
4119
4120module.exports = function md5(buf) {
4121 return helpers.hash(buf, core_md5, 16);
4122};
4123
4124},{"./helpers":18}],21:[function(_dereq_,module,exports){
4125(function (Buffer){
4126
4127module.exports = ripemd160
4128
4129
4130
4131/*
4132CryptoJS v3.1.2
4133code.google.com/p/crypto-js
4134(c) 2009-2013 by Jeff Mott. All rights reserved.
4135code.google.com/p/crypto-js/wiki/License
4136*/
4137/** @preserve
4138(c) 2012 by Cédric Mesnil. All rights reserved.
4139
4140Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4141
4142 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
4143 - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
4144
4145THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4146*/
4147
4148// Constants table
4149var zl = [
4150 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
4151 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
4152 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
4153 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4154 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
4155var zr = [
4156 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
4157 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
4158 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
4159 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
4160 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
4161var sl = [
4162 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
4163 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
4164 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
4165 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
4166 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ];
4167var sr = [
4168 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
4169 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
4170 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
4171 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
4172 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ];
4173
4174var hl = [ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E];
4175var hr = [ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000];
4176
4177var bytesToWords = function (bytes) {
4178 var words = [];
4179 for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
4180 words[b >>> 5] |= bytes[i] << (24 - b % 32);
4181 }
4182 return words;
4183};
4184
4185var wordsToBytes = function (words) {
4186 var bytes = [];
4187 for (var b = 0; b < words.length * 32; b += 8) {
4188 bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
4189 }
4190 return bytes;
4191};
4192
4193var processBlock = function (H, M, offset) {
4194
4195 // Swap endian
4196 for (var i = 0; i < 16; i++) {
4197 var offset_i = offset + i;
4198 var M_offset_i = M[offset_i];
4199
4200 // Swap
4201 M[offset_i] = (
4202 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
4203 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
4204 );
4205 }
4206
4207 // Working variables
4208 var al, bl, cl, dl, el;
4209 var ar, br, cr, dr, er;
4210
4211 ar = al = H[0];
4212 br = bl = H[1];
4213 cr = cl = H[2];
4214 dr = dl = H[3];
4215 er = el = H[4];
4216 // Computation
4217 var t;
4218 for (var i = 0; i < 80; i += 1) {
4219 t = (al + M[offset+zl[i]])|0;
4220 if (i<16){
4221 t += f1(bl,cl,dl) + hl[0];
4222 } else if (i<32) {
4223 t += f2(bl,cl,dl) + hl[1];
4224 } else if (i<48) {
4225 t += f3(bl,cl,dl) + hl[2];
4226 } else if (i<64) {
4227 t += f4(bl,cl,dl) + hl[3];
4228 } else {// if (i<80) {
4229 t += f5(bl,cl,dl) + hl[4];
4230 }
4231 t = t|0;
4232 t = rotl(t,sl[i]);
4233 t = (t+el)|0;
4234 al = el;
4235 el = dl;
4236 dl = rotl(cl, 10);
4237 cl = bl;
4238 bl = t;
4239
4240 t = (ar + M[offset+zr[i]])|0;
4241 if (i<16){
4242 t += f5(br,cr,dr) + hr[0];
4243 } else if (i<32) {
4244 t += f4(br,cr,dr) + hr[1];
4245 } else if (i<48) {
4246 t += f3(br,cr,dr) + hr[2];
4247 } else if (i<64) {
4248 t += f2(br,cr,dr) + hr[3];
4249 } else {// if (i<80) {
4250 t += f1(br,cr,dr) + hr[4];
4251 }
4252 t = t|0;
4253 t = rotl(t,sr[i]) ;
4254 t = (t+er)|0;
4255 ar = er;
4256 er = dr;
4257 dr = rotl(cr, 10);
4258 cr = br;
4259 br = t;
4260 }
4261 // Intermediate hash value
4262 t = (H[1] + cl + dr)|0;
4263 H[1] = (H[2] + dl + er)|0;
4264 H[2] = (H[3] + el + ar)|0;
4265 H[3] = (H[4] + al + br)|0;
4266 H[4] = (H[0] + bl + cr)|0;
4267 H[0] = t;
4268};
4269
4270function f1(x, y, z) {
4271 return ((x) ^ (y) ^ (z));
4272}
4273
4274function f2(x, y, z) {
4275 return (((x)&(y)) | ((~x)&(z)));
4276}
4277
4278function f3(x, y, z) {
4279 return (((x) | (~(y))) ^ (z));
4280}
4281
4282function f4(x, y, z) {
4283 return (((x) & (z)) | ((y)&(~(z))));
4284}
4285
4286function f5(x, y, z) {
4287 return ((x) ^ ((y) |(~(z))));
4288}
4289
4290function rotl(x,n) {
4291 return (x<<n) | (x>>>(32-n));
4292}
4293
4294function ripemd160(message) {
4295 var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
4296
4297 if (typeof message == 'string')
4298 message = new Buffer(message, 'utf8');
4299
4300 var m = bytesToWords(message);
4301
4302 var nBitsLeft = message.length * 8;
4303 var nBitsTotal = message.length * 8;
4304
4305 // Add padding
4306 m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
4307 m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
4308 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
4309 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
4310 );
4311
4312 for (var i=0 ; i<m.length; i += 16) {
4313 processBlock(H, m, i);
4314 }
4315
4316 // Swap endian
4317 for (var i = 0; i < 5; i++) {
4318 // Shortcut
4319 var H_i = H[i];
4320
4321 // Swap
4322 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
4323 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
4324 }
4325
4326 var digestbytes = wordsToBytes(H);
4327 return new Buffer(digestbytes);
4328}
4329
4330
4331
4332}).call(this,_dereq_("buffer").Buffer)
4333},{"buffer":8}],22:[function(_dereq_,module,exports){
4334var u = _dereq_('./util')
4335var write = u.write
4336var fill = u.zeroFill
4337
4338module.exports = function (Buffer) {
4339
4340 //prototype class for hash functions
4341 function Hash (blockSize, finalSize) {
4342 this._block = new Buffer(blockSize) //new Uint32Array(blockSize/4)
4343 this._finalSize = finalSize
4344 this._blockSize = blockSize
4345 this._len = 0
4346 this._s = 0
4347 }
4348
4349 Hash.prototype.init = function () {
4350 this._s = 0
4351 this._len = 0
4352 }
4353
4354 function lengthOf(data, enc) {
4355 if(enc == null) return data.byteLength || data.length
4356 if(enc == 'ascii' || enc == 'binary') return data.length
4357 if(enc == 'hex') return data.length/2
4358 if(enc == 'base64') return data.length/3
4359 }
4360
4361 Hash.prototype.update = function (data, enc) {
4362 var bl = this._blockSize
4363
4364 //I'd rather do this with a streaming encoder, like the opposite of
4365 //http://nodejs.org/api/string_decoder.html
4366 var length
4367 if(!enc && 'string' === typeof data)
4368 enc = 'utf8'
4369
4370 if(enc) {
4371 if(enc === 'utf-8')
4372 enc = 'utf8'
4373
4374 if(enc === 'base64' || enc === 'utf8')
4375 data = new Buffer(data, enc), enc = null
4376
4377 length = lengthOf(data, enc)
4378 } else
4379 length = data.byteLength || data.length
4380
4381 var l = this._len += length
4382 var s = this._s = (this._s || 0)
4383 var f = 0
4384 var buffer = this._block
4385 while(s < l) {
4386 var t = Math.min(length, f + bl)
4387 write(buffer, data, enc, s%bl, f, t)
4388 var ch = (t - f);
4389 s += ch; f += ch
4390
4391 if(!(s%bl))
4392 this._update(buffer)
4393 }
4394 this._s = s
4395
4396 return this
4397
4398 }
4399
4400 Hash.prototype.digest = function (enc) {
4401 var bl = this._blockSize
4402 var fl = this._finalSize
4403 var len = this._len*8
4404
4405 var x = this._block
4406
4407 var bits = len % (bl*8)
4408
4409 //add end marker, so that appending 0's creats a different hash.
4410 x[this._len % bl] = 0x80
4411 fill(this._block, this._len % bl + 1)
4412
4413 if(bits >= fl*8) {
4414 this._update(this._block)
4415 u.zeroFill(this._block, 0)
4416 }
4417
4418 //TODO: handle case where the bit length is > Math.pow(2, 29)
4419 x.writeInt32BE(len, fl + 4) //big endian
4420
4421 var hash = this._update(this._block) || this._hash()
4422 if(enc == null) return hash
4423 return hash.toString(enc)
4424 }
4425
4426 Hash.prototype._update = function () {
4427 throw new Error('_update must be implemented by subclass')
4428 }
4429
4430 return Hash
4431}
4432
4433},{"./util":26}],23:[function(_dereq_,module,exports){
4434var exports = module.exports = function (alg) {
4435 var Alg = exports[alg]
4436 if(!Alg) throw new Error(alg + ' is not supported (we accept pull requests)')
4437 return new Alg()
4438}
4439
4440var Buffer = _dereq_('buffer').Buffer
4441var Hash = _dereq_('./hash')(Buffer)
4442
4443exports.sha =
4444exports.sha1 = _dereq_('./sha1')(Buffer, Hash)
4445exports.sha256 = _dereq_('./sha256')(Buffer, Hash)
4446
4447},{"./hash":22,"./sha1":24,"./sha256":25,"buffer":8}],24:[function(_dereq_,module,exports){
4448/*
4449 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
4450 * in FIPS PUB 180-1
4451 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
4452 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
4453 * Distributed under the BSD License
4454 * See http://pajhome.org.uk/crypt/md5 for details.
4455 */
4456module.exports = function (Buffer, Hash) {
4457
4458 var inherits = _dereq_('util').inherits
4459
4460 inherits(Sha1, Hash)
4461
4462 var A = 0|0
4463 var B = 4|0
4464 var C = 8|0
4465 var D = 12|0
4466 var E = 16|0
4467
4468 var BE = false
4469 var LE = true
4470
4471 var W = new Int32Array(80)
4472
4473 var POOL = []
4474
4475 function Sha1 () {
4476 if(POOL.length)
4477 return POOL.pop().init()
4478
4479 if(!(this instanceof Sha1)) return new Sha1()
4480 this._w = W
4481 Hash.call(this, 16*4, 14*4)
4482
4483 this._h = null
4484 this.init()
4485 }
4486
4487 Sha1.prototype.init = function () {
4488 this._a = 0x67452301
4489 this._b = 0xefcdab89
4490 this._c = 0x98badcfe
4491 this._d = 0x10325476
4492 this._e = 0xc3d2e1f0
4493
4494 Hash.prototype.init.call(this)
4495 return this
4496 }
4497
4498 Sha1.prototype._POOL = POOL
4499
4500 // assume that array is a Uint32Array with length=16,
4501 // and that if it is the last block, it already has the length and the 1 bit appended.
4502
4503
4504 var isDV = new Buffer(1) instanceof DataView
4505 function readInt32BE (X, i) {
4506 return isDV
4507 ? X.getInt32(i, false)
4508 : X.readInt32BE(i)
4509 }
4510
4511 Sha1.prototype._update = function (array) {
4512
4513 var X = this._block
4514 var h = this._h
4515 var a, b, c, d, e, _a, _b, _c, _d, _e
4516
4517 a = _a = this._a
4518 b = _b = this._b
4519 c = _c = this._c
4520 d = _d = this._d
4521 e = _e = this._e
4522
4523 var w = this._w
4524
4525 for(var j = 0; j < 80; j++) {
4526 var W = w[j]
4527 = j < 16
4528 //? X.getInt32(j*4, false)
4529 //? readInt32BE(X, j*4) //*/ X.readInt32BE(j*4) //*/
4530 ? X.readInt32BE(j*4)
4531 : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)
4532
4533 var t =
4534 add(
4535 add(rol(a, 5), sha1_ft(j, b, c, d)),
4536 add(add(e, W), sha1_kt(j))
4537 );
4538
4539 e = d
4540 d = c
4541 c = rol(b, 30)
4542 b = a
4543 a = t
4544 }
4545
4546 this._a = add(a, _a)
4547 this._b = add(b, _b)
4548 this._c = add(c, _c)
4549 this._d = add(d, _d)
4550 this._e = add(e, _e)
4551 }
4552
4553 Sha1.prototype._hash = function () {
4554 if(POOL.length < 100) POOL.push(this)
4555 var H = new Buffer(20)
4556 //console.log(this._a|0, this._b|0, this._c|0, this._d|0, this._e|0)
4557 H.writeInt32BE(this._a|0, A)
4558 H.writeInt32BE(this._b|0, B)
4559 H.writeInt32BE(this._c|0, C)
4560 H.writeInt32BE(this._d|0, D)
4561 H.writeInt32BE(this._e|0, E)
4562 return H
4563 }
4564
4565 /*
4566 * Perform the appropriate triplet combination function for the current
4567 * iteration
4568 */
4569 function sha1_ft(t, b, c, d) {
4570 if(t < 20) return (b & c) | ((~b) & d);
4571 if(t < 40) return b ^ c ^ d;
4572 if(t < 60) return (b & c) | (b & d) | (c & d);
4573 return b ^ c ^ d;
4574 }
4575
4576 /*
4577 * Determine the appropriate additive constant for the current iteration
4578 */
4579 function sha1_kt(t) {
4580 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
4581 (t < 60) ? -1894007588 : -899497514;
4582 }
4583
4584 /*
4585 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
4586 * to work around bugs in some JS interpreters.
4587 * //dominictarr: this is 10 years old, so maybe this can be dropped?)
4588 *
4589 */
4590 function add(x, y) {
4591 return (x + y ) | 0
4592 //lets see how this goes on testling.
4593 // var lsw = (x & 0xFFFF) + (y & 0xFFFF);
4594 // var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
4595 // return (msw << 16) | (lsw & 0xFFFF);
4596 }
4597
4598 /*
4599 * Bitwise rotate a 32-bit number to the left.
4600 */
4601 function rol(num, cnt) {
4602 return (num << cnt) | (num >>> (32 - cnt));
4603 }
4604
4605 return Sha1
4606}
4607
4608},{"util":14}],25:[function(_dereq_,module,exports){
4609
4610/**
4611 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
4612 * in FIPS 180-2
4613 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
4614 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
4615 *
4616 */
4617
4618var inherits = _dereq_('util').inherits
4619var BE = false
4620var LE = true
4621var u = _dereq_('./util')
4622
4623module.exports = function (Buffer, Hash) {
4624
4625 var K = [
4626 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
4627 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
4628 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
4629 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
4630 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
4631 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
4632 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
4633 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
4634 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
4635 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
4636 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
4637 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
4638 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
4639 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
4640 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
4641 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
4642 ]
4643
4644 inherits(Sha256, Hash)
4645 var W = new Array(64)
4646 var POOL = []
4647 function Sha256() {
4648 // Closure compiler warning - this code lacks side effects - thus commented out
4649 // if(POOL.length) {
4650 // return POOL.shift().init()
4651 // }
4652 //this._data = new Buffer(32)
4653
4654 this.init()
4655
4656 this._w = W //new Array(64)
4657
4658 Hash.call(this, 16*4, 14*4)
4659 };
4660
4661 Sha256.prototype.init = function () {
4662
4663 this._a = 0x6a09e667|0
4664 this._b = 0xbb67ae85|0
4665 this._c = 0x3c6ef372|0
4666 this._d = 0xa54ff53a|0
4667 this._e = 0x510e527f|0
4668 this._f = 0x9b05688c|0
4669 this._g = 0x1f83d9ab|0
4670 this._h = 0x5be0cd19|0
4671
4672 this._len = this._s = 0
4673
4674 return this
4675 }
4676
4677 var safe_add = function(x, y) {
4678 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
4679 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
4680 return (msw << 16) | (lsw & 0xFFFF);
4681 }
4682
4683 function S (X, n) {
4684 return (X >>> n) | (X << (32 - n));
4685 }
4686
4687 function R (X, n) {
4688 return (X >>> n);
4689 }
4690
4691 function Ch (x, y, z) {
4692 return ((x & y) ^ ((~x) & z));
4693 }
4694
4695 function Maj (x, y, z) {
4696 return ((x & y) ^ (x & z) ^ (y & z));
4697 }
4698
4699 function Sigma0256 (x) {
4700 return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
4701 }
4702
4703 function Sigma1256 (x) {
4704 return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
4705 }
4706
4707 function Gamma0256 (x) {
4708 return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
4709 }
4710
4711 function Gamma1256 (x) {
4712 return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
4713 }
4714
4715 Sha256.prototype._update = function(m) {
4716 var M = this._block
4717 var W = this._w
4718 var a, b, c, d, e, f, g, h
4719 var T1, T2
4720
4721 a = this._a | 0
4722 b = this._b | 0
4723 c = this._c | 0
4724 d = this._d | 0
4725 e = this._e | 0
4726 f = this._f | 0
4727 g = this._g | 0
4728 h = this._h | 0
4729
4730 for (var j = 0; j < 64; j++) {
4731 var w = W[j] = j < 16
4732 ? M.readInt32BE(j * 4)
4733 : Gamma1256(W[j - 2]) + W[j - 7] + Gamma0256(W[j - 15]) + W[j - 16]
4734
4735 T1 = h + Sigma1256(e) + Ch(e, f, g) + K[j] + w
4736
4737 T2 = Sigma0256(a) + Maj(a, b, c);
4738 h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2;
4739 }
4740
4741 this._a = (a + this._a) | 0
4742 this._b = (b + this._b) | 0
4743 this._c = (c + this._c) | 0
4744 this._d = (d + this._d) | 0
4745 this._e = (e + this._e) | 0
4746 this._f = (f + this._f) | 0
4747 this._g = (g + this._g) | 0
4748 this._h = (h + this._h) | 0
4749
4750 };
4751
4752 Sha256.prototype._hash = function () {
4753 if(POOL.length < 10)
4754 POOL.push(this)
4755
4756 var H = new Buffer(32)
4757
4758 H.writeInt32BE(this._a, 0)
4759 H.writeInt32BE(this._b, 4)
4760 H.writeInt32BE(this._c, 8)
4761 H.writeInt32BE(this._d, 12)
4762 H.writeInt32BE(this._e, 16)
4763 H.writeInt32BE(this._f, 20)
4764 H.writeInt32BE(this._g, 24)
4765 H.writeInt32BE(this._h, 28)
4766
4767 return H
4768 }
4769
4770 return Sha256
4771
4772}
4773
4774},{"./util":26,"util":14}],26:[function(_dereq_,module,exports){
4775exports.write = write
4776exports.zeroFill = zeroFill
4777
4778exports.toString = toString
4779
4780function write (buffer, string, enc, start, from, to, LE) {
4781 var l = (to - from)
4782 if(enc === 'ascii' || enc === 'binary') {
4783 for( var i = 0; i < l; i++) {
4784 buffer[start + i] = string.charCodeAt(i + from)
4785 }
4786 }
4787 else if(enc == null) {
4788 for( var i = 0; i < l; i++) {
4789 buffer[start + i] = string[i + from]
4790 }
4791 }
4792 else if(enc === 'hex') {
4793 for(var i = 0; i < l; i++) {
4794 var j = from + i
4795 buffer[start + i] = parseInt(string[j*2] + string[(j*2)+1], 16)
4796 }
4797 }
4798 else if(enc === 'base64') {
4799 throw new Error('base64 encoding not yet supported')
4800 }
4801 else
4802 throw new Error(enc +' encoding not yet supported')
4803}
4804
4805//always fill to the end!
4806function zeroFill(buf, from) {
4807 for(var i = from; i < buf.length; i++)
4808 buf[i] = 0
4809}
4810
4811
4812},{}],27:[function(_dereq_,module,exports){
4813(function (Buffer){
4814// JavaScript PBKDF2 Implementation
4815// Based on http://git.io/qsv2zw
4816// Licensed under LGPL v3
4817// Copyright (c) 2013 jduncanator
4818
4819var blocksize = 64
4820var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0)
4821
4822module.exports = function (createHmac, exports) {
4823 exports = exports || {}
4824
4825 exports.pbkdf2 = function(password, salt, iterations, keylen, cb) {
4826 if('function' !== typeof cb)
4827 throw new Error('No callback provided to pbkdf2');
4828 setTimeout(function () {
4829 cb(null, exports.pbkdf2Sync(password, salt, iterations, keylen))
4830 })
4831 }
4832
4833 exports.pbkdf2Sync = function(key, salt, iterations, keylen) {
4834 if('number' !== typeof iterations)
4835 throw new TypeError('Iterations not a number')
4836 if(iterations < 0)
4837 throw new TypeError('Bad iterations')
4838 if('number' !== typeof keylen)
4839 throw new TypeError('Key length not a number')
4840 if(keylen < 0)
4841 throw new TypeError('Bad key length')
4842
4843 //stretch key to the correct length that hmac wants it,
4844 //otherwise this will happen every time hmac is called
4845 //twice per iteration.
4846 var key = !Buffer.isBuffer(key) ? new Buffer(key) : key
4847
4848 if(key.length > blocksize) {
4849 key = createHash(alg).update(key).digest()
4850 } else if(key.length < blocksize) {
4851 key = Buffer.concat([key, zeroBuffer], blocksize)
4852 }
4853
4854 var HMAC;
4855 var cplen, p = 0, i = 1, itmp = new Buffer(4), digtmp;
4856 var out = new Buffer(keylen);
4857 out.fill(0);
4858 while(keylen) {
4859 if(keylen > 20)
4860 cplen = 20;
4861 else
4862 cplen = keylen;
4863
4864 /* We are unlikely to ever use more than 256 blocks (5120 bits!)
4865 * but just in case...
4866 */
4867 itmp[0] = (i >> 24) & 0xff;
4868 itmp[1] = (i >> 16) & 0xff;
4869 itmp[2] = (i >> 8) & 0xff;
4870 itmp[3] = i & 0xff;
4871
4872 HMAC = createHmac('sha1', key);
4873 HMAC.update(salt)
4874 HMAC.update(itmp);
4875 digtmp = HMAC.digest();
4876 digtmp.copy(out, p, 0, cplen);
4877
4878 for(var j = 1; j < iterations; j++) {
4879 HMAC = createHmac('sha1', key);
4880 HMAC.update(digtmp);
4881 digtmp = HMAC.digest();
4882 for(var k = 0; k < cplen; k++) {
4883 out[k] ^= digtmp[k];
4884 }
4885 }
4886 keylen -= cplen;
4887 i++;
4888 p += cplen;
4889 }
4890
4891 return out;
4892 }
4893
4894 return exports
4895}
4896
4897}).call(this,_dereq_("buffer").Buffer)
4898},{"buffer":8}],28:[function(_dereq_,module,exports){
4899(function (Buffer){
4900// Original code adapted from Robert Kieffer.
4901// details at https://github.com/broofa/node-uuid
4902
4903
4904(function() {
4905 var _global = this;
4906
4907 var mathRNG, whatwgRNG;
4908
4909 // NOTE: Math.random() does not guarantee "cryptographic quality"
4910 mathRNG = function(size) {
4911 var bytes = new Buffer(size);
4912 var r;
4913
4914 for (var i = 0, r; i < size; i++) {
4915 if ((i & 0x03) == 0) r = Math.random() * 0x100000000;
4916 bytes[i] = r >>> ((i & 0x03) << 3) & 0xff;
4917 }
4918
4919 return bytes;
4920 }
4921
4922 if (_global.crypto && crypto.getRandomValues) {
4923 whatwgRNG = function(size) {
4924 var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
4925 crypto.getRandomValues(bytes);
4926 return bytes;
4927 }
4928 }
4929
4930 module.exports = whatwgRNG || mathRNG;
4931
4932}())
4933
4934}).call(this,_dereq_("buffer").Buffer)
4935},{"buffer":8}],29:[function(_dereq_,module,exports){
4936;(function (root, factory, undef) {
4937 if (typeof exports === "object") {
4938 // CommonJS
4939 module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
4940 }
4941 else if (typeof define === "function" && define.amd) {
4942 // AMD
4943 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
4944 }
4945 else {
4946 // Global (browser)
4947 factory(root.CryptoJS);
4948 }
4949}(this, function (CryptoJS) {
4950
4951 (function () {
4952 // Shortcuts
4953 var C = CryptoJS;
4954 var C_lib = C.lib;
4955 var BlockCipher = C_lib.BlockCipher;
4956 var C_algo = C.algo;
4957
4958 // Lookup tables
4959 var SBOX = [];
4960 var INV_SBOX = [];
4961 var SUB_MIX_0 = [];
4962 var SUB_MIX_1 = [];
4963 var SUB_MIX_2 = [];
4964 var SUB_MIX_3 = [];
4965 var INV_SUB_MIX_0 = [];
4966 var INV_SUB_MIX_1 = [];
4967 var INV_SUB_MIX_2 = [];
4968 var INV_SUB_MIX_3 = [];
4969
4970 // Compute lookup tables
4971 (function () {
4972 // Compute double table
4973 var d = [];
4974 for (var i = 0; i < 256; i++) {
4975 if (i < 128) {
4976 d[i] = i << 1;
4977 } else {
4978 d[i] = (i << 1) ^ 0x11b;
4979 }
4980 }
4981
4982 // Walk GF(2^8)
4983 var x = 0;
4984 var xi = 0;
4985 for (var i = 0; i < 256; i++) {
4986 // Compute sbox
4987 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
4988 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
4989 SBOX[x] = sx;
4990 INV_SBOX[sx] = x;
4991
4992 // Compute multiplication
4993 var x2 = d[x];
4994 var x4 = d[x2];
4995 var x8 = d[x4];
4996
4997 // Compute sub bytes, mix columns tables
4998 var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
4999 SUB_MIX_0[x] = (t << 24) | (t >>> 8);
5000 SUB_MIX_1[x] = (t << 16) | (t >>> 16);
5001 SUB_MIX_2[x] = (t << 8) | (t >>> 24);
5002 SUB_MIX_3[x] = t;
5003
5004 // Compute inv sub bytes, inv mix columns tables
5005 var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
5006 INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
5007 INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
5008 INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
5009 INV_SUB_MIX_3[sx] = t;
5010
5011 // Compute next counter
5012 if (!x) {
5013 x = xi = 1;
5014 } else {
5015 x = x2 ^ d[d[d[x8 ^ x2]]];
5016 xi ^= d[d[xi]];
5017 }
5018 }
5019 }());
5020
5021 // Precomputed Rcon lookup
5022 var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
5023
5024 /**
5025 * AES block cipher algorithm.
5026 */
5027 var AES = C_algo.AES = BlockCipher.extend({
5028 _doReset: function () {
5029 // Shortcuts
5030 var key = this._key;
5031 var keyWords = key.words;
5032 var keySize = key.sigBytes / 4;
5033
5034 // Compute number of rounds
5035 var nRounds = this._nRounds = keySize + 6
5036
5037 // Compute number of key schedule rows
5038 var ksRows = (nRounds + 1) * 4;
5039
5040 // Compute key schedule
5041 var keySchedule = this._keySchedule = [];
5042 for (var ksRow = 0; ksRow < ksRows; ksRow++) {
5043 if (ksRow < keySize) {
5044 keySchedule[ksRow] = keyWords[ksRow];
5045 } else {
5046 var t = keySchedule[ksRow - 1];
5047
5048 if (!(ksRow % keySize)) {
5049 // Rot word
5050 t = (t << 8) | (t >>> 24);
5051
5052 // Sub word
5053 t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
5054
5055 // Mix Rcon
5056 t ^= RCON[(ksRow / keySize) | 0] << 24;
5057 } else if (keySize > 6 && ksRow % keySize == 4) {
5058 // Sub word
5059 t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
5060 }
5061
5062 keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
5063 }
5064 }
5065
5066 // Compute inv key schedule
5067 var invKeySchedule = this._invKeySchedule = [];
5068 for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
5069 var ksRow = ksRows - invKsRow;
5070
5071 if (invKsRow % 4) {
5072 var t = keySchedule[ksRow];
5073 } else {
5074 var t = keySchedule[ksRow - 4];
5075 }
5076
5077 if (invKsRow < 4 || ksRow <= 4) {
5078 invKeySchedule[invKsRow] = t;
5079 } else {
5080 invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
5081 INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
5082 }
5083 }
5084 },
5085
5086 encryptBlock: function (M, offset) {
5087 this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
5088 },
5089
5090 decryptBlock: function (M, offset) {
5091 // Swap 2nd and 4th rows
5092 var t = M[offset + 1];
5093 M[offset + 1] = M[offset + 3];
5094 M[offset + 3] = t;
5095
5096 this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
5097
5098 // Inv swap 2nd and 4th rows
5099 var t = M[offset + 1];
5100 M[offset + 1] = M[offset + 3];
5101 M[offset + 3] = t;
5102 },
5103
5104 _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
5105 // Shortcut
5106 var nRounds = this._nRounds;
5107
5108 // Get input, add round key
5109 var s0 = M[offset] ^ keySchedule[0];
5110 var s1 = M[offset + 1] ^ keySchedule[1];
5111 var s2 = M[offset + 2] ^ keySchedule[2];
5112 var s3 = M[offset + 3] ^ keySchedule[3];
5113
5114 // Key schedule row counter
5115 var ksRow = 4;
5116
5117 // Rounds
5118 for (var round = 1; round < nRounds; round++) {
5119 // Shift rows, sub bytes, mix columns, add round key
5120 var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
5121 var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
5122 var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
5123 var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
5124
5125 // Update state
5126 s0 = t0;
5127 s1 = t1;
5128 s2 = t2;
5129 s3 = t3;
5130 }
5131
5132 // Shift rows, sub bytes, add round key
5133 var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
5134 var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
5135 var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
5136 var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
5137
5138 // Set output
5139 M[offset] = t0;
5140 M[offset + 1] = t1;
5141 M[offset + 2] = t2;
5142 M[offset + 3] = t3;
5143 },
5144
5145 keySize: 256/32
5146 });
5147
5148 /**
5149 * Shortcut functions to the cipher's object interface.
5150 *
5151 * @example
5152 *
5153 * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
5154 * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
5155 */
5156 C.AES = BlockCipher._createHelper(AES);
5157 }());
5158
5159
5160 return CryptoJS.AES;
5161
5162}));
5163},{"./cipher-core":30,"./core":31,"./enc-base64":32,"./evpkdf":34,"./md5":39}],30:[function(_dereq_,module,exports){
5164;(function (root, factory) {
5165 if (typeof exports === "object") {
5166 // CommonJS
5167 module.exports = exports = factory(_dereq_("./core"));
5168 }
5169 else if (typeof define === "function" && define.amd) {
5170 // AMD
5171 define(["./core"], factory);
5172 }
5173 else {
5174 // Global (browser)
5175 factory(root.CryptoJS);
5176 }
5177}(this, function (CryptoJS) {
5178
5179 /**
5180 * Cipher core components.
5181 */
5182 CryptoJS.lib.Cipher || (function (undefined) {
5183 // Shortcuts
5184 var C = CryptoJS;
5185 var C_lib = C.lib;
5186 var Base = C_lib.Base;
5187 var WordArray = C_lib.WordArray;
5188 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
5189 var C_enc = C.enc;
5190 var Utf8 = C_enc.Utf8;
5191 var Base64 = C_enc.Base64;
5192 var C_algo = C.algo;
5193 var EvpKDF = C_algo.EvpKDF;
5194
5195 /**
5196 * Abstract base cipher template.
5197 *
5198 * @property {number} keySize This cipher's key size. Default: 4 (128 bits)
5199 * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
5200 * @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
5201 * @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
5202 */
5203 var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
5204 /**
5205 * Configuration options.
5206 *
5207 * @property {WordArray} iv The IV to use for this operation.
5208 */
5209 cfg: Base.extend(),
5210
5211 /**
5212 * Creates this cipher in encryption mode.
5213 *
5214 * @param {WordArray} key The key.
5215 * @param {Object} cfg (Optional) The configuration options to use for this operation.
5216 *
5217 * @return {Cipher} A cipher instance.
5218 *
5219 * @static
5220 *
5221 * @example
5222 *
5223 * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
5224 */
5225 createEncryptor: function (key, cfg) {
5226 return this.create(this._ENC_XFORM_MODE, key, cfg);
5227 },
5228
5229 /**
5230 * Creates this cipher in decryption mode.
5231 *
5232 * @param {WordArray} key The key.
5233 * @param {Object} cfg (Optional) The configuration options to use for this operation.
5234 *
5235 * @return {Cipher} A cipher instance.
5236 *
5237 * @static
5238 *
5239 * @example
5240 *
5241 * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
5242 */
5243 createDecryptor: function (key, cfg) {
5244 return this.create(this._DEC_XFORM_MODE, key, cfg);
5245 },
5246
5247 /**
5248 * Initializes a newly created cipher.
5249 *
5250 * @param {number} xformMode Either the encryption or decryption transormation mode constant.
5251 * @param {WordArray} key The key.
5252 * @param {Object} cfg (Optional) The configuration options to use for this operation.
5253 *
5254 * @example
5255 *
5256 * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
5257 */
5258 init: function (xformMode, key, cfg) {
5259 // Apply config defaults
5260 this.cfg = this.cfg.extend(cfg);
5261
5262 // Store transform mode and key
5263 this._xformMode = xformMode;
5264 this._key = key;
5265
5266 // Set initial values
5267 this.reset();
5268 },
5269
5270 /**
5271 * Resets this cipher to its initial state.
5272 *
5273 * @example
5274 *
5275 * cipher.reset();
5276 */
5277 reset: function () {
5278 // Reset data buffer
5279 BufferedBlockAlgorithm.reset.call(this);
5280
5281 // Perform concrete-cipher logic
5282 this._doReset();
5283 },
5284
5285 /**
5286 * Adds data to be encrypted or decrypted.
5287 *
5288 * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
5289 *
5290 * @return {WordArray} The data after processing.
5291 *
5292 * @example
5293 *
5294 * var encrypted = cipher.process('data');
5295 * var encrypted = cipher.process(wordArray);
5296 */
5297 process: function (dataUpdate) {
5298 // Append
5299 this._append(dataUpdate);
5300
5301 // Process available blocks
5302 return this._process();
5303 },
5304
5305 /**
5306 * Finalizes the encryption or decryption process.
5307 * Note that the finalize operation is effectively a destructive, read-once operation.
5308 *
5309 * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
5310 *
5311 * @return {WordArray} The data after final processing.
5312 *
5313 * @example
5314 *
5315 * var encrypted = cipher.finalize();
5316 * var encrypted = cipher.finalize('data');
5317 * var encrypted = cipher.finalize(wordArray);
5318 */
5319 finalize: function (dataUpdate) {
5320 // Final data update
5321 if (dataUpdate) {
5322 this._append(dataUpdate);
5323 }
5324
5325 // Perform concrete-cipher logic
5326 var finalProcessedData = this._doFinalize();
5327
5328 return finalProcessedData;
5329 },
5330
5331 keySize: 128/32,
5332
5333 ivSize: 128/32,
5334
5335 _ENC_XFORM_MODE: 1,
5336
5337 _DEC_XFORM_MODE: 2,
5338
5339 /**
5340 * Creates shortcut functions to a cipher's object interface.
5341 *
5342 * @param {Cipher} cipher The cipher to create a helper for.
5343 *
5344 * @return {Object} An object with encrypt and decrypt shortcut functions.
5345 *
5346 * @static
5347 *
5348 * @example
5349 *
5350 * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
5351 */
5352 _createHelper: (function () {
5353 function selectCipherStrategy(key) {
5354 if (typeof key == 'string') {
5355 return PasswordBasedCipher;
5356 } else {
5357 return SerializableCipher;
5358 }
5359 }
5360
5361 return function (cipher) {
5362 return {
5363 encrypt: function (message, key, cfg) {
5364 return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
5365 },
5366
5367 decrypt: function (ciphertext, key, cfg) {
5368 return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
5369 }
5370 };
5371 };
5372 }())
5373 });
5374
5375 /**
5376 * Abstract base stream cipher template.
5377 *
5378 * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
5379 */
5380 var StreamCipher = C_lib.StreamCipher = Cipher.extend({
5381 _doFinalize: function () {
5382 // Process partial blocks
5383 var finalProcessedBlocks = this._process(!!'flush');
5384
5385 return finalProcessedBlocks;
5386 },
5387
5388 blockSize: 1
5389 });
5390
5391 /**
5392 * Mode namespace.
5393 */
5394 var C_mode = C.mode = {};
5395
5396 /**
5397 * Abstract base block cipher mode template.
5398 */
5399 var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
5400 /**
5401 * Creates this mode for encryption.
5402 *
5403 * @param {Cipher} cipher A block cipher instance.
5404 * @param {Array} iv The IV words.
5405 *
5406 * @static
5407 *
5408 * @example
5409 *
5410 * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
5411 */
5412 createEncryptor: function (cipher, iv) {
5413 return this.Encryptor.create(cipher, iv);
5414 },
5415
5416 /**
5417 * Creates this mode for decryption.
5418 *
5419 * @param {Cipher} cipher A block cipher instance.
5420 * @param {Array} iv The IV words.
5421 *
5422 * @static
5423 *
5424 * @example
5425 *
5426 * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
5427 */
5428 createDecryptor: function (cipher, iv) {
5429 return this.Decryptor.create(cipher, iv);
5430 },
5431
5432 /**
5433 * Initializes a newly created mode.
5434 *
5435 * @param {Cipher} cipher A block cipher instance.
5436 * @param {Array} iv The IV words.
5437 *
5438 * @example
5439 *
5440 * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
5441 */
5442 init: function (cipher, iv) {
5443 this._cipher = cipher;
5444 this._iv = iv;
5445 }
5446 });
5447
5448 /**
5449 * Cipher Block Chaining mode.
5450 */
5451 var CBC = C_mode.CBC = (function () {
5452 /**
5453 * Abstract base CBC mode.
5454 */
5455 var CBC = BlockCipherMode.extend();
5456
5457 /**
5458 * CBC encryptor.
5459 */
5460 CBC.Encryptor = CBC.extend({
5461 /**
5462 * Processes the data block at offset.
5463 *
5464 * @param {Array} words The data words to operate on.
5465 * @param {number} offset The offset where the block starts.
5466 *
5467 * @example
5468 *
5469 * mode.processBlock(data.words, offset);
5470 */
5471 processBlock: function (words, offset) {
5472 // Shortcuts
5473 var cipher = this._cipher;
5474 var blockSize = cipher.blockSize;
5475
5476 // XOR and encrypt
5477 xorBlock.call(this, words, offset, blockSize);
5478 cipher.encryptBlock(words, offset);
5479
5480 // Remember this block to use with next block
5481 this._prevBlock = words.slice(offset, offset + blockSize);
5482 }
5483 });
5484
5485 /**
5486 * CBC decryptor.
5487 */
5488 CBC.Decryptor = CBC.extend({
5489 /**
5490 * Processes the data block at offset.
5491 *
5492 * @param {Array} words The data words to operate on.
5493 * @param {number} offset The offset where the block starts.
5494 *
5495 * @example
5496 *
5497 * mode.processBlock(data.words, offset);
5498 */
5499 processBlock: function (words, offset) {
5500 // Shortcuts
5501 var cipher = this._cipher;
5502 var blockSize = cipher.blockSize;
5503
5504 // Remember this block to use with next block
5505 var thisBlock = words.slice(offset, offset + blockSize);
5506
5507 // Decrypt and XOR
5508 cipher.decryptBlock(words, offset);
5509 xorBlock.call(this, words, offset, blockSize);
5510
5511 // This block becomes the previous block
5512 this._prevBlock = thisBlock;
5513 }
5514 });
5515
5516 function xorBlock(words, offset, blockSize) {
5517 // Shortcut
5518 var iv = this._iv;
5519
5520 // Choose mixing block
5521 if (iv) {
5522 var block = iv;
5523
5524 // Remove IV for subsequent blocks
5525 this._iv = undefined;
5526 } else {
5527 var block = this._prevBlock;
5528 }
5529
5530 // XOR blocks
5531 for (var i = 0; i < blockSize; i++) {
5532 words[offset + i] ^= block[i];
5533 }
5534 }
5535
5536 return CBC;
5537 }());
5538
5539 /**
5540 * Padding namespace.
5541 */
5542 var C_pad = C.pad = {};
5543
5544 /**
5545 * PKCS #5/7 padding strategy.
5546 */
5547 var Pkcs7 = C_pad.Pkcs7 = {
5548 /**
5549 * Pads data using the algorithm defined in PKCS #5/7.
5550 *
5551 * @param {WordArray} data The data to pad.
5552 * @param {number} blockSize The multiple that the data should be padded to.
5553 *
5554 * @static
5555 *
5556 * @example
5557 *
5558 * CryptoJS.pad.Pkcs7.pad(wordArray, 4);
5559 */
5560 pad: function (data, blockSize) {
5561 // Shortcut
5562 var blockSizeBytes = blockSize * 4;
5563
5564 // Count padding bytes
5565 var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
5566
5567 // Create padding word
5568 var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
5569
5570 // Create padding
5571 var paddingWords = [];
5572 for (var i = 0; i < nPaddingBytes; i += 4) {
5573 paddingWords.push(paddingWord);
5574 }
5575 var padding = WordArray.create(paddingWords, nPaddingBytes);
5576
5577 // Add padding
5578 data.concat(padding);
5579 },
5580
5581 /**
5582 * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
5583 *
5584 * @param {WordArray} data The data to unpad.
5585 *
5586 * @static
5587 *
5588 * @example
5589 *
5590 * CryptoJS.pad.Pkcs7.unpad(wordArray);
5591 */
5592 unpad: function (data) {
5593 // Get number of padding bytes from last byte
5594 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
5595
5596 // Remove padding
5597 data.sigBytes -= nPaddingBytes;
5598 }
5599 };
5600
5601 /**
5602 * Abstract base block cipher template.
5603 *
5604 * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
5605 */
5606 var BlockCipher = C_lib.BlockCipher = Cipher.extend({
5607 /**
5608 * Configuration options.
5609 *
5610 * @property {Mode} mode The block mode to use. Default: CBC
5611 * @property {Padding} padding The padding strategy to use. Default: Pkcs7
5612 */
5613 cfg: Cipher.cfg.extend({
5614 mode: CBC,
5615 padding: Pkcs7
5616 }),
5617
5618 reset: function () {
5619 // Reset cipher
5620 Cipher.reset.call(this);
5621
5622 // Shortcuts
5623 var cfg = this.cfg;
5624 var iv = cfg.iv;
5625 var mode = cfg.mode;
5626
5627 // Reset block mode
5628 if (this._xformMode == this._ENC_XFORM_MODE) {
5629 var modeCreator = mode.createEncryptor;
5630 } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
5631 var modeCreator = mode.createDecryptor;
5632
5633 // Keep at least one block in the buffer for unpadding
5634 this._minBufferSize = 1;
5635 }
5636 this._mode = modeCreator.call(mode, this, iv && iv.words);
5637 },
5638
5639 _doProcessBlock: function (words, offset) {
5640 this._mode.processBlock(words, offset);
5641 },
5642
5643 _doFinalize: function () {
5644 // Shortcut
5645 var padding = this.cfg.padding;
5646
5647 // Finalize
5648 if (this._xformMode == this._ENC_XFORM_MODE) {
5649 // Pad data
5650 padding.pad(this._data, this.blockSize);
5651
5652 // Process final blocks
5653 var finalProcessedBlocks = this._process(!!'flush');
5654 } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
5655 // Process final blocks
5656 var finalProcessedBlocks = this._process(!!'flush');
5657
5658 // Unpad data
5659 padding.unpad(finalProcessedBlocks);
5660 }
5661
5662 return finalProcessedBlocks;
5663 },
5664
5665 blockSize: 128/32
5666 });
5667
5668 /**
5669 * A collection of cipher parameters.
5670 *
5671 * @property {WordArray} ciphertext The raw ciphertext.
5672 * @property {WordArray} key The key to this ciphertext.
5673 * @property {WordArray} iv The IV used in the ciphering operation.
5674 * @property {WordArray} salt The salt used with a key derivation function.
5675 * @property {Cipher} algorithm The cipher algorithm.
5676 * @property {Mode} mode The block mode used in the ciphering operation.
5677 * @property {Padding} padding The padding scheme used in the ciphering operation.
5678 * @property {number} blockSize The block size of the cipher.
5679 * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
5680 */
5681 var CipherParams = C_lib.CipherParams = Base.extend({
5682 /**
5683 * Initializes a newly created cipher params object.
5684 *
5685 * @param {Object} cipherParams An object with any of the possible cipher parameters.
5686 *
5687 * @example
5688 *
5689 * var cipherParams = CryptoJS.lib.CipherParams.create({
5690 * ciphertext: ciphertextWordArray,
5691 * key: keyWordArray,
5692 * iv: ivWordArray,
5693 * salt: saltWordArray,
5694 * algorithm: CryptoJS.algo.AES,
5695 * mode: CryptoJS.mode.CBC,
5696 * padding: CryptoJS.pad.PKCS7,
5697 * blockSize: 4,
5698 * formatter: CryptoJS.format.OpenSSL
5699 * });
5700 */
5701 init: function (cipherParams) {
5702 this.mixIn(cipherParams);
5703 },
5704
5705 /**
5706 * Converts this cipher params object to a string.
5707 *
5708 * @param {Format} formatter (Optional) The formatting strategy to use.
5709 *
5710 * @return {string} The stringified cipher params.
5711 *
5712 * @throws Error If neither the formatter nor the default formatter is set.
5713 *
5714 * @example
5715 *
5716 * var string = cipherParams + '';
5717 * var string = cipherParams.toString();
5718 * var string = cipherParams.toString(CryptoJS.format.OpenSSL);
5719 */
5720 toString: function (formatter) {
5721 return (formatter || this.formatter).stringify(this);
5722 }
5723 });
5724
5725 /**
5726 * Format namespace.
5727 */
5728 var C_format = C.format = {};
5729
5730 /**
5731 * OpenSSL formatting strategy.
5732 */
5733 var OpenSSLFormatter = C_format.OpenSSL = {
5734 /**
5735 * Converts a cipher params object to an OpenSSL-compatible string.
5736 *
5737 * @param {CipherParams} cipherParams The cipher params object.
5738 *
5739 * @return {string} The OpenSSL-compatible string.
5740 *
5741 * @static
5742 *
5743 * @example
5744 *
5745 * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
5746 */
5747 stringify: function (cipherParams) {
5748 // Shortcuts
5749 var ciphertext = cipherParams.ciphertext;
5750 var salt = cipherParams.salt;
5751
5752 // Format
5753 if (salt) {
5754 var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
5755 } else {
5756 var wordArray = ciphertext;
5757 }
5758
5759 return wordArray.toString(Base64);
5760 },
5761
5762 /**
5763 * Converts an OpenSSL-compatible string to a cipher params object.
5764 *
5765 * @param {string} openSSLStr The OpenSSL-compatible string.
5766 *
5767 * @return {CipherParams} The cipher params object.
5768 *
5769 * @static
5770 *
5771 * @example
5772 *
5773 * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
5774 */
5775 parse: function (openSSLStr) {
5776 // Parse base64
5777 var ciphertext = Base64.parse(openSSLStr);
5778
5779 // Shortcut
5780 var ciphertextWords = ciphertext.words;
5781
5782 // Test for salt
5783 if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
5784 // Extract salt
5785 var salt = WordArray.create(ciphertextWords.slice(2, 4));
5786
5787 // Remove salt from ciphertext
5788 ciphertextWords.splice(0, 4);
5789 ciphertext.sigBytes -= 16;
5790 }
5791
5792 return CipherParams.create({ ciphertext: ciphertext, salt: salt });
5793 }
5794 };
5795
5796 /**
5797 * A cipher wrapper that returns ciphertext as a serializable cipher params object.
5798 */
5799 var SerializableCipher = C_lib.SerializableCipher = Base.extend({
5800 /**
5801 * Configuration options.
5802 *
5803 * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
5804 */
5805 cfg: Base.extend({
5806 format: OpenSSLFormatter
5807 }),
5808
5809 /**
5810 * Encrypts a message.
5811 *
5812 * @param {Cipher} cipher The cipher algorithm to use.
5813 * @param {WordArray|string} message The message to encrypt.
5814 * @param {WordArray} key The key.
5815 * @param {Object} cfg (Optional) The configuration options to use for this operation.
5816 *
5817 * @return {CipherParams} A cipher params object.
5818 *
5819 * @static
5820 *
5821 * @example
5822 *
5823 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
5824 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
5825 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
5826 */
5827 encrypt: function (cipher, message, key, cfg) {
5828 // Apply config defaults
5829 cfg = this.cfg.extend(cfg);
5830
5831 // Encrypt
5832 var encryptor = cipher.createEncryptor(key, cfg);
5833 var ciphertext = encryptor.finalize(message);
5834
5835 // Shortcut
5836 var cipherCfg = encryptor.cfg;
5837
5838 // Create and return serializable cipher params
5839 return CipherParams.create({
5840 ciphertext: ciphertext,
5841 key: key,
5842 iv: cipherCfg.iv,
5843 algorithm: cipher,
5844 mode: cipherCfg.mode,
5845 padding: cipherCfg.padding,
5846 blockSize: cipher.blockSize,
5847 formatter: cfg.format
5848 });
5849 },
5850
5851 /**
5852 * Decrypts serialized ciphertext.
5853 *
5854 * @param {Cipher} cipher The cipher algorithm to use.
5855 * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
5856 * @param {WordArray} key The key.
5857 * @param {Object} cfg (Optional) The configuration options to use for this operation.
5858 *
5859 * @return {WordArray} The plaintext.
5860 *
5861 * @static
5862 *
5863 * @example
5864 *
5865 * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
5866 * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
5867 */
5868 decrypt: function (cipher, ciphertext, key, cfg) {
5869 // Apply config defaults
5870 cfg = this.cfg.extend(cfg);
5871
5872 // Convert string to CipherParams
5873 ciphertext = this._parse(ciphertext, cfg.format);
5874
5875 // Decrypt
5876 var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
5877
5878 return plaintext;
5879 },
5880
5881 /**
5882 * Converts serialized ciphertext to CipherParams,
5883 * else assumed CipherParams already and returns ciphertext unchanged.
5884 *
5885 * @param {CipherParams|string} ciphertext The ciphertext.
5886 * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
5887 *
5888 * @return {CipherParams} The unserialized ciphertext.
5889 *
5890 * @static
5891 *
5892 * @example
5893 *
5894 * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
5895 */
5896 _parse: function (ciphertext, format) {
5897 if (typeof ciphertext == 'string') {
5898 return format.parse(ciphertext, this);
5899 } else {
5900 return ciphertext;
5901 }
5902 }
5903 });
5904
5905 /**
5906 * Key derivation function namespace.
5907 */
5908 var C_kdf = C.kdf = {};
5909
5910 /**
5911 * OpenSSL key derivation function.
5912 */
5913 var OpenSSLKdf = C_kdf.OpenSSL = {
5914 /**
5915 * Derives a key and IV from a password.
5916 *
5917 * @param {string} password The password to derive from.
5918 * @param {number} keySize The size in words of the key to generate.
5919 * @param {number} ivSize The size in words of the IV to generate.
5920 * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
5921 *
5922 * @return {CipherParams} A cipher params object with the key, IV, and salt.
5923 *
5924 * @static
5925 *
5926 * @example
5927 *
5928 * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
5929 * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
5930 */
5931 execute: function (password, keySize, ivSize, salt) {
5932 // Generate random salt
5933 if (!salt) {
5934 salt = WordArray.random(64/8);
5935 }
5936
5937 // Derive key and IV
5938 var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
5939
5940 // Separate key and IV
5941 var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
5942 key.sigBytes = keySize * 4;
5943
5944 // Return params
5945 return CipherParams.create({ key: key, iv: iv, salt: salt });
5946 }
5947 };
5948
5949 /**
5950 * A serializable cipher wrapper that derives the key from a password,
5951 * and returns ciphertext as a serializable cipher params object.
5952 */
5953 var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
5954 /**
5955 * Configuration options.
5956 *
5957 * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
5958 */
5959 cfg: SerializableCipher.cfg.extend({
5960 kdf: OpenSSLKdf
5961 }),
5962
5963 /**
5964 * Encrypts a message using a password.
5965 *
5966 * @param {Cipher} cipher The cipher algorithm to use.
5967 * @param {WordArray|string} message The message to encrypt.
5968 * @param {string} password The password.
5969 * @param {Object} cfg (Optional) The configuration options to use for this operation.
5970 *
5971 * @return {CipherParams} A cipher params object.
5972 *
5973 * @static
5974 *
5975 * @example
5976 *
5977 * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
5978 * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
5979 */
5980 encrypt: function (cipher, message, password, cfg) {
5981 // Apply config defaults
5982 cfg = this.cfg.extend(cfg);
5983
5984 // Derive key and other params
5985 var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
5986
5987 // Add IV to config
5988 cfg.iv = derivedParams.iv;
5989
5990 // Encrypt
5991 var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
5992
5993 // Mix in derived params
5994 ciphertext.mixIn(derivedParams);
5995
5996 return ciphertext;
5997 },
5998
5999 /**
6000 * Decrypts serialized ciphertext using a password.
6001 *
6002 * @param {Cipher} cipher The cipher algorithm to use.
6003 * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
6004 * @param {string} password The password.
6005 * @param {Object} cfg (Optional) The configuration options to use for this operation.
6006 *
6007 * @return {WordArray} The plaintext.
6008 *
6009 * @static
6010 *
6011 * @example
6012 *
6013 * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
6014 * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
6015 */
6016 decrypt: function (cipher, ciphertext, password, cfg) {
6017 // Apply config defaults
6018 cfg = this.cfg.extend(cfg);
6019
6020 // Convert string to CipherParams
6021 ciphertext = this._parse(ciphertext, cfg.format);
6022
6023 // Derive key and other params
6024 var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
6025
6026 // Add IV to config
6027 cfg.iv = derivedParams.iv;
6028
6029 // Decrypt
6030 var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
6031
6032 return plaintext;
6033 }
6034 });
6035 }());
6036
6037
6038}));
6039},{"./core":31}],31:[function(_dereq_,module,exports){
6040;(function (root, factory) {
6041 if (typeof exports === "object") {
6042 // CommonJS
6043 module.exports = exports = factory();
6044 }
6045 else if (typeof define === "function" && define.amd) {
6046 // AMD
6047 define([], factory);
6048 }
6049 else {
6050 // Global (browser)
6051 root.CryptoJS = factory();
6052 }
6053}(this, function () {
6054
6055 /**
6056 * CryptoJS core components.
6057 */
6058 var CryptoJS = CryptoJS || (function (Math, undefined) {
6059 /**
6060 * CryptoJS namespace.
6061 */
6062 var C = {};
6063
6064 /**
6065 * Library namespace.
6066 */
6067 var C_lib = C.lib = {};
6068
6069 /**
6070 * Base object for prototypal inheritance.
6071 */
6072 var Base = C_lib.Base = (function () {
6073 function F() {}
6074
6075 return {
6076 /**
6077 * Creates a new object that inherits from this object.
6078 *
6079 * @param {Object} overrides Properties to copy into the new object.
6080 *
6081 * @return {Object} The new object.
6082 *
6083 * @static
6084 *
6085 * @example
6086 *
6087 * var MyType = CryptoJS.lib.Base.extend({
6088 * field: 'value',
6089 *
6090 * method: function () {
6091 * }
6092 * });
6093 */
6094 extend: function (overrides) {
6095 // Spawn
6096 F.prototype = this;
6097 var subtype = new F();
6098
6099 // Augment
6100 if (overrides) {
6101 subtype.mixIn(overrides);
6102 }
6103
6104 // Create default initializer
6105 if (!subtype.hasOwnProperty('init')) {
6106 subtype.init = function () {
6107 subtype.$super.init.apply(this, arguments);
6108 };
6109 }
6110
6111 // Initializer's prototype is the subtype object
6112 subtype.init.prototype = subtype;
6113
6114 // Reference supertype
6115 subtype.$super = this;
6116
6117 return subtype;
6118 },
6119
6120 /**
6121 * Extends this object and runs the init method.
6122 * Arguments to create() will be passed to init().
6123 *
6124 * @return {Object} The new object.
6125 *
6126 * @static
6127 *
6128 * @example
6129 *
6130 * var instance = MyType.create();
6131 */
6132 create: function () {
6133 var instance = this.extend();
6134 instance.init.apply(instance, arguments);
6135
6136 return instance;
6137 },
6138
6139 /**
6140 * Initializes a newly created object.
6141 * Override this method to add some logic when your objects are created.
6142 *
6143 * @example
6144 *
6145 * var MyType = CryptoJS.lib.Base.extend({
6146 * init: function () {
6147 * // ...
6148 * }
6149 * });
6150 */
6151 init: function () {
6152 },
6153
6154 /**
6155 * Copies properties into this object.
6156 *
6157 * @param {Object} properties The properties to mix in.
6158 *
6159 * @example
6160 *
6161 * MyType.mixIn({
6162 * field: 'value'
6163 * });
6164 */
6165 mixIn: function (properties) {
6166 for (var propertyName in properties) {
6167 if (properties.hasOwnProperty(propertyName)) {
6168 this[propertyName] = properties[propertyName];
6169 }
6170 }
6171
6172 // IE won't copy toString using the loop above
6173 if (properties.hasOwnProperty('toString')) {
6174 this.toString = properties.toString;
6175 }
6176 },
6177
6178 /**
6179 * Creates a copy of this object.
6180 *
6181 * @return {Object} The clone.
6182 *
6183 * @example
6184 *
6185 * var clone = instance.clone();
6186 */
6187 clone: function () {
6188 return this.init.prototype.extend(this);
6189 }
6190 };
6191 }());
6192
6193 /**
6194 * An array of 32-bit words.
6195 *
6196 * @property {Array} words The array of 32-bit words.
6197 * @property {number} sigBytes The number of significant bytes in this word array.
6198 */
6199 var WordArray = C_lib.WordArray = Base.extend({
6200 /**
6201 * Initializes a newly created word array.
6202 *
6203 * @param {Array} words (Optional) An array of 32-bit words.
6204 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
6205 *
6206 * @example
6207 *
6208 * var wordArray = CryptoJS.lib.WordArray.create();
6209 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
6210 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
6211 */
6212 init: function (words, sigBytes) {
6213 words = this.words = words || [];
6214
6215 if (sigBytes != undefined) {
6216 this.sigBytes = sigBytes;
6217 } else {
6218 this.sigBytes = words.length * 4;
6219 }
6220 },
6221
6222 /**
6223 * Converts this word array to a string.
6224 *
6225 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
6226 *
6227 * @return {string} The stringified word array.
6228 *
6229 * @example
6230 *
6231 * var string = wordArray + '';
6232 * var string = wordArray.toString();
6233 * var string = wordArray.toString(CryptoJS.enc.Utf8);
6234 */
6235 toString: function (encoder) {
6236 return (encoder || Hex).stringify(this);
6237 },
6238
6239 /**
6240 * Concatenates a word array to this word array.
6241 *
6242 * @param {WordArray} wordArray The word array to append.
6243 *
6244 * @return {WordArray} This word array.
6245 *
6246 * @example
6247 *
6248 * wordArray1.concat(wordArray2);
6249 */
6250 concat: function (wordArray) {
6251 // Shortcuts
6252 var thisWords = this.words;
6253 var thatWords = wordArray.words;
6254 var thisSigBytes = this.sigBytes;
6255 var thatSigBytes = wordArray.sigBytes;
6256
6257 // Clamp excess bits
6258 this.clamp();
6259
6260 // Concat
6261 if (thisSigBytes % 4) {
6262 // Copy one byte at a time
6263 for (var i = 0; i < thatSigBytes; i++) {
6264 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
6265 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
6266 }
6267 } else if (thatWords.length > 0xffff) {
6268 // Copy one word at a time
6269 for (var i = 0; i < thatSigBytes; i += 4) {
6270 thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
6271 }
6272 } else {
6273 // Copy all words at once
6274 thisWords.push.apply(thisWords, thatWords);
6275 }
6276 this.sigBytes += thatSigBytes;
6277
6278 // Chainable
6279 return this;
6280 },
6281
6282 /**
6283 * Removes insignificant bits.
6284 *
6285 * @example
6286 *
6287 * wordArray.clamp();
6288 */
6289 clamp: function () {
6290 // Shortcuts
6291 var words = this.words;
6292 var sigBytes = this.sigBytes;
6293
6294 // Clamp
6295 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
6296 words.length = Math.ceil(sigBytes / 4);
6297 },
6298
6299 /**
6300 * Creates a copy of this word array.
6301 *
6302 * @return {WordArray} The clone.
6303 *
6304 * @example
6305 *
6306 * var clone = wordArray.clone();
6307 */
6308 clone: function () {
6309 var clone = Base.clone.call(this);
6310 clone.words = this.words.slice(0);
6311
6312 return clone;
6313 },
6314
6315 /**
6316 * Creates a word array filled with random bytes.
6317 *
6318 * @param {number} nBytes The number of random bytes to generate.
6319 *
6320 * @return {WordArray} The random word array.
6321 *
6322 * @static
6323 *
6324 * @example
6325 *
6326 * var wordArray = CryptoJS.lib.WordArray.random(16);
6327 */
6328 random: function (nBytes) {
6329 var words = [];
6330 for (var i = 0; i < nBytes; i += 4) {
6331 words.push((Math.random() * 0x100000000) | 0);
6332 }
6333
6334 return new WordArray.init(words, nBytes);
6335 }
6336 });
6337
6338 /**
6339 * Encoder namespace.
6340 */
6341 var C_enc = C.enc = {};
6342
6343 /**
6344 * Hex encoding strategy.
6345 */
6346 var Hex = C_enc.Hex = {
6347 /**
6348 * Converts a word array to a hex string.
6349 *
6350 * @param {WordArray} wordArray The word array.
6351 *
6352 * @return {string} The hex string.
6353 *
6354 * @static
6355 *
6356 * @example
6357 *
6358 * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
6359 */
6360 stringify: function (wordArray) {
6361 // Shortcuts
6362 var words = wordArray.words;
6363 var sigBytes = wordArray.sigBytes;
6364
6365 // Convert
6366 var hexChars = [];
6367 for (var i = 0; i < sigBytes; i++) {
6368 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
6369 hexChars.push((bite >>> 4).toString(16));
6370 hexChars.push((bite & 0x0f).toString(16));
6371 }
6372
6373 return hexChars.join('');
6374 },
6375
6376 /**
6377 * Converts a hex string to a word array.
6378 *
6379 * @param {string} hexStr The hex string.
6380 *
6381 * @return {WordArray} The word array.
6382 *
6383 * @static
6384 *
6385 * @example
6386 *
6387 * var wordArray = CryptoJS.enc.Hex.parse(hexString);
6388 */
6389 parse: function (hexStr) {
6390 // Shortcut
6391 var hexStrLength = hexStr.length;
6392
6393 // Convert
6394 var words = [];
6395 for (var i = 0; i < hexStrLength; i += 2) {
6396 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
6397 }
6398
6399 return new WordArray.init(words, hexStrLength / 2);
6400 }
6401 };
6402
6403 /**
6404 * Latin1 encoding strategy.
6405 */
6406 var Latin1 = C_enc.Latin1 = {
6407 /**
6408 * Converts a word array to a Latin1 string.
6409 *
6410 * @param {WordArray} wordArray The word array.
6411 *
6412 * @return {string} The Latin1 string.
6413 *
6414 * @static
6415 *
6416 * @example
6417 *
6418 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
6419 */
6420 stringify: function (wordArray) {
6421 // Shortcuts
6422 var words = wordArray.words;
6423 var sigBytes = wordArray.sigBytes;
6424
6425 // Convert
6426 var latin1Chars = [];
6427 for (var i = 0; i < sigBytes; i++) {
6428 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
6429 latin1Chars.push(String.fromCharCode(bite));
6430 }
6431
6432 return latin1Chars.join('');
6433 },
6434
6435 /**
6436 * Converts a Latin1 string to a word array.
6437 *
6438 * @param {string} latin1Str The Latin1 string.
6439 *
6440 * @return {WordArray} The word array.
6441 *
6442 * @static
6443 *
6444 * @example
6445 *
6446 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
6447 */
6448 parse: function (latin1Str) {
6449 // Shortcut
6450 var latin1StrLength = latin1Str.length;
6451
6452 // Convert
6453 var words = [];
6454 for (var i = 0; i < latin1StrLength; i++) {
6455 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
6456 }
6457
6458 return new WordArray.init(words, latin1StrLength);
6459 }
6460 };
6461
6462 /**
6463 * UTF-8 encoding strategy.
6464 */
6465 var Utf8 = C_enc.Utf8 = {
6466 /**
6467 * Converts a word array to a UTF-8 string.
6468 *
6469 * @param {WordArray} wordArray The word array.
6470 *
6471 * @return {string} The UTF-8 string.
6472 *
6473 * @static
6474 *
6475 * @example
6476 *
6477 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
6478 */
6479 stringify: function (wordArray) {
6480 try {
6481 return decodeURIComponent(escape(Latin1.stringify(wordArray)));
6482 } catch (e) {
6483 throw new Error('Malformed UTF-8 data');
6484 }
6485 },
6486
6487 /**
6488 * Converts a UTF-8 string to a word array.
6489 *
6490 * @param {string} utf8Str The UTF-8 string.
6491 *
6492 * @return {WordArray} The word array.
6493 *
6494 * @static
6495 *
6496 * @example
6497 *
6498 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
6499 */
6500 parse: function (utf8Str) {
6501 return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
6502 }
6503 };
6504
6505 /**
6506 * Abstract buffered block algorithm template.
6507 *
6508 * The property blockSize must be implemented in a concrete subtype.
6509 *
6510 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
6511 */
6512 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
6513 /**
6514 * Resets this block algorithm's data buffer to its initial state.
6515 *
6516 * @example
6517 *
6518 * bufferedBlockAlgorithm.reset();
6519 */
6520 reset: function () {
6521 // Initial values
6522 this._data = new WordArray.init();
6523 this._nDataBytes = 0;
6524 },
6525
6526 /**
6527 * Adds new data to this block algorithm's buffer.
6528 *
6529 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
6530 *
6531 * @example
6532 *
6533 * bufferedBlockAlgorithm._append('data');
6534 * bufferedBlockAlgorithm._append(wordArray);
6535 */
6536 _append: function (data) {
6537 // Convert string to WordArray, else assume WordArray already
6538 if (typeof data == 'string') {
6539 data = Utf8.parse(data);
6540 }
6541
6542 // Append
6543 this._data.concat(data);
6544 this._nDataBytes += data.sigBytes;
6545 },
6546
6547 /**
6548 * Processes available data blocks.
6549 *
6550 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
6551 *
6552 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
6553 *
6554 * @return {WordArray} The processed data.
6555 *
6556 * @example
6557 *
6558 * var processedData = bufferedBlockAlgorithm._process();
6559 * var processedData = bufferedBlockAlgorithm._process(!!'flush');
6560 */
6561 _process: function (doFlush) {
6562 // Shortcuts
6563 var data = this._data;
6564 var dataWords = data.words;
6565 var dataSigBytes = data.sigBytes;
6566 var blockSize = this.blockSize;
6567 var blockSizeBytes = blockSize * 4;
6568
6569 // Count blocks ready
6570 var nBlocksReady = dataSigBytes / blockSizeBytes;
6571 if (doFlush) {
6572 // Round up to include partial blocks
6573 nBlocksReady = Math.ceil(nBlocksReady);
6574 } else {
6575 // Round down to include only full blocks,
6576 // less the number of blocks that must remain in the buffer
6577 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
6578 }
6579
6580 // Count words ready
6581 var nWordsReady = nBlocksReady * blockSize;
6582
6583 // Count bytes ready
6584 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
6585
6586 // Process blocks
6587 if (nWordsReady) {
6588 for (var offset = 0; offset < nWordsReady; offset += blockSize) {
6589 // Perform concrete-algorithm logic
6590 this._doProcessBlock(dataWords, offset);
6591 }
6592
6593 // Remove processed words
6594 var processedWords = dataWords.splice(0, nWordsReady);
6595 data.sigBytes -= nBytesReady;
6596 }
6597
6598 // Return processed words
6599 return new WordArray.init(processedWords, nBytesReady);
6600 },
6601
6602 /**
6603 * Creates a copy of this object.
6604 *
6605 * @return {Object} The clone.
6606 *
6607 * @example
6608 *
6609 * var clone = bufferedBlockAlgorithm.clone();
6610 */
6611 clone: function () {
6612 var clone = Base.clone.call(this);
6613 clone._data = this._data.clone();
6614
6615 return clone;
6616 },
6617
6618 _minBufferSize: 0
6619 });
6620
6621 /**
6622 * Abstract hasher template.
6623 *
6624 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
6625 */
6626 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
6627 /**
6628 * Configuration options.
6629 */
6630 cfg: Base.extend(),
6631
6632 /**
6633 * Initializes a newly created hasher.
6634 *
6635 * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
6636 *
6637 * @example
6638 *
6639 * var hasher = CryptoJS.algo.SHA256.create();
6640 */
6641 init: function (cfg) {
6642 // Apply config defaults
6643 this.cfg = this.cfg.extend(cfg);
6644
6645 // Set initial values
6646 this.reset();
6647 },
6648
6649 /**
6650 * Resets this hasher to its initial state.
6651 *
6652 * @example
6653 *
6654 * hasher.reset();
6655 */
6656 reset: function () {
6657 // Reset data buffer
6658 BufferedBlockAlgorithm.reset.call(this);
6659
6660 // Perform concrete-hasher logic
6661 this._doReset();
6662 },
6663
6664 /**
6665 * Updates this hasher with a message.
6666 *
6667 * @param {WordArray|string} messageUpdate The message to append.
6668 *
6669 * @return {Hasher} This hasher.
6670 *
6671 * @example
6672 *
6673 * hasher.update('message');
6674 * hasher.update(wordArray);
6675 */
6676 update: function (messageUpdate) {
6677 // Append
6678 this._append(messageUpdate);
6679
6680 // Update the hash
6681 this._process();
6682
6683 // Chainable
6684 return this;
6685 },
6686
6687 /**
6688 * Finalizes the hash computation.
6689 * Note that the finalize operation is effectively a destructive, read-once operation.
6690 *
6691 * @param {WordArray|string} messageUpdate (Optional) A final message update.
6692 *
6693 * @return {WordArray} The hash.
6694 *
6695 * @example
6696 *
6697 * var hash = hasher.finalize();
6698 * var hash = hasher.finalize('message');
6699 * var hash = hasher.finalize(wordArray);
6700 */
6701 finalize: function (messageUpdate) {
6702 // Final message update
6703 if (messageUpdate) {
6704 this._append(messageUpdate);
6705 }
6706
6707 // Perform concrete-hasher logic
6708 var hash = this._doFinalize();
6709
6710 return hash;
6711 },
6712
6713 blockSize: 512/32,
6714
6715 /**
6716 * Creates a shortcut function to a hasher's object interface.
6717 *
6718 * @param {Hasher} hasher The hasher to create a helper for.
6719 *
6720 * @return {Function} The shortcut function.
6721 *
6722 * @static
6723 *
6724 * @example
6725 *
6726 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
6727 */
6728 _createHelper: function (hasher) {
6729 return function (message, cfg) {
6730 return new hasher.init(cfg).finalize(message);
6731 };
6732 },
6733
6734 /**
6735 * Creates a shortcut function to the HMAC's object interface.
6736 *
6737 * @param {Hasher} hasher The hasher to use in this HMAC helper.
6738 *
6739 * @return {Function} The shortcut function.
6740 *
6741 * @static
6742 *
6743 * @example
6744 *
6745 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
6746 */
6747 _createHmacHelper: function (hasher) {
6748 return function (message, key) {
6749 return new C_algo.HMAC.init(hasher, key).finalize(message);
6750 };
6751 }
6752 });
6753
6754 /**
6755 * Algorithm namespace.
6756 */
6757 var C_algo = C.algo = {};
6758
6759 return C;
6760 }(Math));
6761
6762
6763 return CryptoJS;
6764
6765}));
6766},{}],32:[function(_dereq_,module,exports){
6767;(function (root, factory) {
6768 if (typeof exports === "object") {
6769 // CommonJS
6770 module.exports = exports = factory(_dereq_("./core"));
6771 }
6772 else if (typeof define === "function" && define.amd) {
6773 // AMD
6774 define(["./core"], factory);
6775 }
6776 else {
6777 // Global (browser)
6778 factory(root.CryptoJS);
6779 }
6780}(this, function (CryptoJS) {
6781
6782 (function () {
6783 // Shortcuts
6784 var C = CryptoJS;
6785 var C_lib = C.lib;
6786 var WordArray = C_lib.WordArray;
6787 var C_enc = C.enc;
6788
6789 /**
6790 * Base64 encoding strategy.
6791 */
6792 var Base64 = C_enc.Base64 = {
6793 /**
6794 * Converts a word array to a Base64 string.
6795 *
6796 * @param {WordArray} wordArray The word array.
6797 *
6798 * @return {string} The Base64 string.
6799 *
6800 * @static
6801 *
6802 * @example
6803 *
6804 * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
6805 */
6806 stringify: function (wordArray) {
6807 // Shortcuts
6808 var words = wordArray.words;
6809 var sigBytes = wordArray.sigBytes;
6810 var map = this._map;
6811
6812 // Clamp excess bits
6813 wordArray.clamp();
6814
6815 // Convert
6816 var base64Chars = [];
6817 for (var i = 0; i < sigBytes; i += 3) {
6818 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
6819 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
6820 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
6821
6822 var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
6823
6824 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
6825 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
6826 }
6827 }
6828
6829 // Add padding
6830 var paddingChar = map.charAt(64);
6831 if (paddingChar) {
6832 while (base64Chars.length % 4) {
6833 base64Chars.push(paddingChar);
6834 }
6835 }
6836
6837 return base64Chars.join('');
6838 },
6839
6840 /**
6841 * Converts a Base64 string to a word array.
6842 *
6843 * @param {string} base64Str The Base64 string.
6844 *
6845 * @return {WordArray} The word array.
6846 *
6847 * @static
6848 *
6849 * @example
6850 *
6851 * var wordArray = CryptoJS.enc.Base64.parse(base64String);
6852 */
6853 parse: function (base64Str) {
6854 // Shortcuts
6855 var base64StrLength = base64Str.length;
6856 var map = this._map;
6857
6858 // Ignore padding
6859 var paddingChar = map.charAt(64);
6860 if (paddingChar) {
6861 var paddingIndex = base64Str.indexOf(paddingChar);
6862 if (paddingIndex != -1) {
6863 base64StrLength = paddingIndex;
6864 }
6865 }
6866
6867 // Convert
6868 var words = [];
6869 var nBytes = 0;
6870 for (var i = 0; i < base64StrLength; i++) {
6871 if (i % 4) {
6872 var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
6873 var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
6874 words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
6875 nBytes++;
6876 }
6877 }
6878
6879 return WordArray.create(words, nBytes);
6880 },
6881
6882 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
6883 };
6884 }());
6885
6886
6887 return CryptoJS.enc.Base64;
6888
6889}));
6890},{"./core":31}],33:[function(_dereq_,module,exports){
6891;(function (root, factory) {
6892 if (typeof exports === "object") {
6893 // CommonJS
6894 module.exports = exports = factory(_dereq_("./core"));
6895 }
6896 else if (typeof define === "function" && define.amd) {
6897 // AMD
6898 define(["./core"], factory);
6899 }
6900 else {
6901 // Global (browser)
6902 factory(root.CryptoJS);
6903 }
6904}(this, function (CryptoJS) {
6905
6906 (function () {
6907 // Shortcuts
6908 var C = CryptoJS;
6909 var C_lib = C.lib;
6910 var WordArray = C_lib.WordArray;
6911 var C_enc = C.enc;
6912
6913 /**
6914 * UTF-16 BE encoding strategy.
6915 */
6916 var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
6917 /**
6918 * Converts a word array to a UTF-16 BE string.
6919 *
6920 * @param {WordArray} wordArray The word array.
6921 *
6922 * @return {string} The UTF-16 BE string.
6923 *
6924 * @static
6925 *
6926 * @example
6927 *
6928 * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
6929 */
6930 stringify: function (wordArray) {
6931 // Shortcuts
6932 var words = wordArray.words;
6933 var sigBytes = wordArray.sigBytes;
6934
6935 // Convert
6936 var utf16Chars = [];
6937 for (var i = 0; i < sigBytes; i += 2) {
6938 var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
6939 utf16Chars.push(String.fromCharCode(codePoint));
6940 }
6941
6942 return utf16Chars.join('');
6943 },
6944
6945 /**
6946 * Converts a UTF-16 BE string to a word array.
6947 *
6948 * @param {string} utf16Str The UTF-16 BE string.
6949 *
6950 * @return {WordArray} The word array.
6951 *
6952 * @static
6953 *
6954 * @example
6955 *
6956 * var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
6957 */
6958 parse: function (utf16Str) {
6959 // Shortcut
6960 var utf16StrLength = utf16Str.length;
6961
6962 // Convert
6963 var words = [];
6964 for (var i = 0; i < utf16StrLength; i++) {
6965 words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
6966 }
6967
6968 return WordArray.create(words, utf16StrLength * 2);
6969 }
6970 };
6971
6972 /**
6973 * UTF-16 LE encoding strategy.
6974 */
6975 C_enc.Utf16LE = {
6976 /**
6977 * Converts a word array to a UTF-16 LE string.
6978 *
6979 * @param {WordArray} wordArray The word array.
6980 *
6981 * @return {string} The UTF-16 LE string.
6982 *
6983 * @static
6984 *
6985 * @example
6986 *
6987 * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
6988 */
6989 stringify: function (wordArray) {
6990 // Shortcuts
6991 var words = wordArray.words;
6992 var sigBytes = wordArray.sigBytes;
6993
6994 // Convert
6995 var utf16Chars = [];
6996 for (var i = 0; i < sigBytes; i += 2) {
6997 var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
6998 utf16Chars.push(String.fromCharCode(codePoint));
6999 }
7000
7001 return utf16Chars.join('');
7002 },
7003
7004 /**
7005 * Converts a UTF-16 LE string to a word array.
7006 *
7007 * @param {string} utf16Str The UTF-16 LE string.
7008 *
7009 * @return {WordArray} The word array.
7010 *
7011 * @static
7012 *
7013 * @example
7014 *
7015 * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
7016 */
7017 parse: function (utf16Str) {
7018 // Shortcut
7019 var utf16StrLength = utf16Str.length;
7020
7021 // Convert
7022 var words = [];
7023 for (var i = 0; i < utf16StrLength; i++) {
7024 words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
7025 }
7026
7027 return WordArray.create(words, utf16StrLength * 2);
7028 }
7029 };
7030
7031 function swapEndian(word) {
7032 return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
7033 }
7034 }());
7035
7036
7037 return CryptoJS.enc.Utf16;
7038
7039}));
7040},{"./core":31}],34:[function(_dereq_,module,exports){
7041;(function (root, factory, undef) {
7042 if (typeof exports === "object") {
7043 // CommonJS
7044 module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
7045 }
7046 else if (typeof define === "function" && define.amd) {
7047 // AMD
7048 define(["./core", "./sha1", "./hmac"], factory);
7049 }
7050 else {
7051 // Global (browser)
7052 factory(root.CryptoJS);
7053 }
7054}(this, function (CryptoJS) {
7055
7056 (function () {
7057 // Shortcuts
7058 var C = CryptoJS;
7059 var C_lib = C.lib;
7060 var Base = C_lib.Base;
7061 var WordArray = C_lib.WordArray;
7062 var C_algo = C.algo;
7063 var MD5 = C_algo.MD5;
7064
7065 /**
7066 * This key derivation function is meant to conform with EVP_BytesToKey.
7067 * www.openssl.org/docs/crypto/EVP_BytesToKey.html
7068 */
7069 var EvpKDF = C_algo.EvpKDF = Base.extend({
7070 /**
7071 * Configuration options.
7072 *
7073 * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
7074 * @property {Hasher} hasher The hash algorithm to use. Default: MD5
7075 * @property {number} iterations The number of iterations to perform. Default: 1
7076 */
7077 cfg: Base.extend({
7078 keySize: 128/32,
7079 hasher: MD5,
7080 iterations: 1
7081 }),
7082
7083 /**
7084 * Initializes a newly created key derivation function.
7085 *
7086 * @param {Object} cfg (Optional) The configuration options to use for the derivation.
7087 *
7088 * @example
7089 *
7090 * var kdf = CryptoJS.algo.EvpKDF.create();
7091 * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
7092 * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
7093 */
7094 init: function (cfg) {
7095 this.cfg = this.cfg.extend(cfg);
7096 },
7097
7098 /**
7099 * Derives a key from a password.
7100 *
7101 * @param {WordArray|string} password The password.
7102 * @param {WordArray|string} salt A salt.
7103 *
7104 * @return {WordArray} The derived key.
7105 *
7106 * @example
7107 *
7108 * var key = kdf.compute(password, salt);
7109 */
7110 compute: function (password, salt) {
7111 // Shortcut
7112 var cfg = this.cfg;
7113
7114 // Init hasher
7115 var hasher = cfg.hasher.create();
7116
7117 // Initial values
7118 var derivedKey = WordArray.create();
7119
7120 // Shortcuts
7121 var derivedKeyWords = derivedKey.words;
7122 var keySize = cfg.keySize;
7123 var iterations = cfg.iterations;
7124
7125 // Generate key
7126 while (derivedKeyWords.length < keySize) {
7127 if (block) {
7128 hasher.update(block);
7129 }
7130 var block = hasher.update(password).finalize(salt);
7131 hasher.reset();
7132
7133 // Iterations
7134 for (var i = 1; i < iterations; i++) {
7135 block = hasher.finalize(block);
7136 hasher.reset();
7137 }
7138
7139 derivedKey.concat(block);
7140 }
7141 derivedKey.sigBytes = keySize * 4;
7142
7143 return derivedKey;
7144 }
7145 });
7146
7147 /**
7148 * Derives a key from a password.
7149 *
7150 * @param {WordArray|string} password The password.
7151 * @param {WordArray|string} salt A salt.
7152 * @param {Object} cfg (Optional) The configuration options to use for this computation.
7153 *
7154 * @return {WordArray} The derived key.
7155 *
7156 * @static
7157 *
7158 * @example
7159 *
7160 * var key = CryptoJS.EvpKDF(password, salt);
7161 * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
7162 * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
7163 */
7164 C.EvpKDF = function (password, salt, cfg) {
7165 return EvpKDF.create(cfg).compute(password, salt);
7166 };
7167 }());
7168
7169
7170 return CryptoJS.EvpKDF;
7171
7172}));
7173},{"./core":31,"./hmac":36,"./sha1":55}],35:[function(_dereq_,module,exports){
7174;(function (root, factory, undef) {
7175 if (typeof exports === "object") {
7176 // CommonJS
7177 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
7178 }
7179 else if (typeof define === "function" && define.amd) {
7180 // AMD
7181 define(["./core", "./cipher-core"], factory);
7182 }
7183 else {
7184 // Global (browser)
7185 factory(root.CryptoJS);
7186 }
7187}(this, function (CryptoJS) {
7188
7189 (function (undefined) {
7190 // Shortcuts
7191 var C = CryptoJS;
7192 var C_lib = C.lib;
7193 var CipherParams = C_lib.CipherParams;
7194 var C_enc = C.enc;
7195 var Hex = C_enc.Hex;
7196 var C_format = C.format;
7197
7198 var HexFormatter = C_format.Hex = {
7199 /**
7200 * Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
7201 *
7202 * @param {CipherParams} cipherParams The cipher params object.
7203 *
7204 * @return {string} The hexadecimally encoded string.
7205 *
7206 * @static
7207 *
7208 * @example
7209 *
7210 * var hexString = CryptoJS.format.Hex.stringify(cipherParams);
7211 */
7212 stringify: function (cipherParams) {
7213 return cipherParams.ciphertext.toString(Hex);
7214 },
7215
7216 /**
7217 * Converts a hexadecimally encoded ciphertext string to a cipher params object.
7218 *
7219 * @param {string} input The hexadecimally encoded string.
7220 *
7221 * @return {CipherParams} The cipher params object.
7222 *
7223 * @static
7224 *
7225 * @example
7226 *
7227 * var cipherParams = CryptoJS.format.Hex.parse(hexString);
7228 */
7229 parse: function (input) {
7230 var ciphertext = Hex.parse(input);
7231 return CipherParams.create({ ciphertext: ciphertext });
7232 }
7233 };
7234 }());
7235
7236
7237 return CryptoJS.format.Hex;
7238
7239}));
7240},{"./cipher-core":30,"./core":31}],36:[function(_dereq_,module,exports){
7241;(function (root, factory) {
7242 if (typeof exports === "object") {
7243 // CommonJS
7244 module.exports = exports = factory(_dereq_("./core"));
7245 }
7246 else if (typeof define === "function" && define.amd) {
7247 // AMD
7248 define(["./core"], factory);
7249 }
7250 else {
7251 // Global (browser)
7252 factory(root.CryptoJS);
7253 }
7254}(this, function (CryptoJS) {
7255
7256 (function () {
7257 // Shortcuts
7258 var C = CryptoJS;
7259 var C_lib = C.lib;
7260 var Base = C_lib.Base;
7261 var C_enc = C.enc;
7262 var Utf8 = C_enc.Utf8;
7263 var C_algo = C.algo;
7264
7265 /**
7266 * HMAC algorithm.
7267 */
7268 var HMAC = C_algo.HMAC = Base.extend({
7269 /**
7270 * Initializes a newly created HMAC.
7271 *
7272 * @param {Hasher} hasher The hash algorithm to use.
7273 * @param {WordArray|string} key The secret key.
7274 *
7275 * @example
7276 *
7277 * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
7278 */
7279 init: function (hasher, key) {
7280 // Init hasher
7281 hasher = this._hasher = new hasher.init();
7282
7283 // Convert string to WordArray, else assume WordArray already
7284 if (typeof key == 'string') {
7285 key = Utf8.parse(key);
7286 }
7287
7288 // Shortcuts
7289 var hasherBlockSize = hasher.blockSize;
7290 var hasherBlockSizeBytes = hasherBlockSize * 4;
7291
7292 // Allow arbitrary length keys
7293 if (key.sigBytes > hasherBlockSizeBytes) {
7294 key = hasher.finalize(key);
7295 }
7296
7297 // Clamp excess bits
7298 key.clamp();
7299
7300 // Clone key for inner and outer pads
7301 var oKey = this._oKey = key.clone();
7302 var iKey = this._iKey = key.clone();
7303
7304 // Shortcuts
7305 var oKeyWords = oKey.words;
7306 var iKeyWords = iKey.words;
7307
7308 // XOR keys with pad constants
7309 for (var i = 0; i < hasherBlockSize; i++) {
7310 oKeyWords[i] ^= 0x5c5c5c5c;
7311 iKeyWords[i] ^= 0x36363636;
7312 }
7313 oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
7314
7315 // Set initial values
7316 this.reset();
7317 },
7318
7319 /**
7320 * Resets this HMAC to its initial state.
7321 *
7322 * @example
7323 *
7324 * hmacHasher.reset();
7325 */
7326 reset: function () {
7327 // Shortcut
7328 var hasher = this._hasher;
7329
7330 // Reset
7331 hasher.reset();
7332 hasher.update(this._iKey);
7333 },
7334
7335 /**
7336 * Updates this HMAC with a message.
7337 *
7338 * @param {WordArray|string} messageUpdate The message to append.
7339 *
7340 * @return {HMAC} This HMAC instance.
7341 *
7342 * @example
7343 *
7344 * hmacHasher.update('message');
7345 * hmacHasher.update(wordArray);
7346 */
7347 update: function (messageUpdate) {
7348 this._hasher.update(messageUpdate);
7349
7350 // Chainable
7351 return this;
7352 },
7353
7354 /**
7355 * Finalizes the HMAC computation.
7356 * Note that the finalize operation is effectively a destructive, read-once operation.
7357 *
7358 * @param {WordArray|string} messageUpdate (Optional) A final message update.
7359 *
7360 * @return {WordArray} The HMAC.
7361 *
7362 * @example
7363 *
7364 * var hmac = hmacHasher.finalize();
7365 * var hmac = hmacHasher.finalize('message');
7366 * var hmac = hmacHasher.finalize(wordArray);
7367 */
7368 finalize: function (messageUpdate) {
7369 // Shortcut
7370 var hasher = this._hasher;
7371
7372 // Compute HMAC
7373 var innerHash = hasher.finalize(messageUpdate);
7374 hasher.reset();
7375 var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
7376
7377 return hmac;
7378 }
7379 });
7380 }());
7381
7382
7383}));
7384},{"./core":31}],37:[function(_dereq_,module,exports){
7385;(function (root, factory, undef) {
7386 if (typeof exports === "object") {
7387 // CommonJS
7388 module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
7389 }
7390 else if (typeof define === "function" && define.amd) {
7391 // AMD
7392 define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
7393 }
7394 else {
7395 // Global (browser)
7396 factory(root.CryptoJS);
7397 }
7398}(this, function (CryptoJS) {
7399
7400 return CryptoJS;
7401
7402}));
7403},{"./aes":29,"./cipher-core":30,"./core":31,"./enc-base64":32,"./enc-utf16":33,"./evpkdf":34,"./format-hex":35,"./hmac":36,"./lib-typedarrays":38,"./md5":39,"./mode-cfb":40,"./mode-ctr":42,"./mode-ctr-gladman":41,"./mode-ecb":43,"./mode-ofb":44,"./pad-ansix923":45,"./pad-iso10126":46,"./pad-iso97971":47,"./pad-nopadding":48,"./pad-zeropadding":49,"./pbkdf2":50,"./rabbit":52,"./rabbit-legacy":51,"./rc4":53,"./ripemd160":54,"./sha1":55,"./sha224":56,"./sha256":57,"./sha3":58,"./sha384":59,"./sha512":60,"./tripledes":61,"./x64-core":62}],38:[function(_dereq_,module,exports){
7404;(function (root, factory) {
7405 if (typeof exports === "object") {
7406 // CommonJS
7407 module.exports = exports = factory(_dereq_("./core"));
7408 }
7409 else if (typeof define === "function" && define.amd) {
7410 // AMD
7411 define(["./core"], factory);
7412 }
7413 else {
7414 // Global (browser)
7415 factory(root.CryptoJS);
7416 }
7417}(this, function (CryptoJS) {
7418
7419 (function () {
7420 // Check if typed arrays are supported
7421 if (typeof ArrayBuffer != 'function') {
7422 return;
7423 }
7424
7425 // Shortcuts
7426 var C = CryptoJS;
7427 var C_lib = C.lib;
7428 var WordArray = C_lib.WordArray;
7429
7430 // Reference original init
7431 var superInit = WordArray.init;
7432
7433 // Augment WordArray.init to handle typed arrays
7434 var subInit = WordArray.init = function (typedArray) {
7435 // Convert buffers to uint8
7436 if (typedArray instanceof ArrayBuffer) {
7437 typedArray = new Uint8Array(typedArray);
7438 }
7439
7440 // Convert other array views to uint8
7441 if (
7442 typedArray instanceof Int8Array ||
7443 typedArray instanceof Uint8ClampedArray ||
7444 typedArray instanceof Int16Array ||
7445 typedArray instanceof Uint16Array ||
7446 typedArray instanceof Int32Array ||
7447 typedArray instanceof Uint32Array ||
7448 typedArray instanceof Float32Array ||
7449 typedArray instanceof Float64Array
7450 ) {
7451 typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
7452 }
7453
7454 // Handle Uint8Array
7455 if (typedArray instanceof Uint8Array) {
7456 // Shortcut
7457 var typedArrayByteLength = typedArray.byteLength;
7458
7459 // Extract bytes
7460 var words = [];
7461 for (var i = 0; i < typedArrayByteLength; i++) {
7462 words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
7463 }
7464
7465 // Initialize this word array
7466 superInit.call(this, words, typedArrayByteLength);
7467 } else {
7468 // Else call normal init
7469 superInit.apply(this, arguments);
7470 }
7471 };
7472
7473 subInit.prototype = WordArray;
7474 }());
7475
7476
7477 return CryptoJS.lib.WordArray;
7478
7479}));
7480},{"./core":31}],39:[function(_dereq_,module,exports){
7481;(function (root, factory) {
7482 if (typeof exports === "object") {
7483 // CommonJS
7484 module.exports = exports = factory(_dereq_("./core"));
7485 }
7486 else if (typeof define === "function" && define.amd) {
7487 // AMD
7488 define(["./core"], factory);
7489 }
7490 else {
7491 // Global (browser)
7492 factory(root.CryptoJS);
7493 }
7494}(this, function (CryptoJS) {
7495
7496 (function (Math) {
7497 // Shortcuts
7498 var C = CryptoJS;
7499 var C_lib = C.lib;
7500 var WordArray = C_lib.WordArray;
7501 var Hasher = C_lib.Hasher;
7502 var C_algo = C.algo;
7503
7504 // Constants table
7505 var T = [];
7506
7507 // Compute constants
7508 (function () {
7509 for (var i = 0; i < 64; i++) {
7510 T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
7511 }
7512 }());
7513
7514 /**
7515 * MD5 hash algorithm.
7516 */
7517 var MD5 = C_algo.MD5 = Hasher.extend({
7518 _doReset: function () {
7519 this._hash = new WordArray.init([
7520 0x67452301, 0xefcdab89,
7521 0x98badcfe, 0x10325476
7522 ]);
7523 },
7524
7525 _doProcessBlock: function (M, offset) {
7526 // Swap endian
7527 for (var i = 0; i < 16; i++) {
7528 // Shortcuts
7529 var offset_i = offset + i;
7530 var M_offset_i = M[offset_i];
7531
7532 M[offset_i] = (
7533 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
7534 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
7535 );
7536 }
7537
7538 // Shortcuts
7539 var H = this._hash.words;
7540
7541 var M_offset_0 = M[offset + 0];
7542 var M_offset_1 = M[offset + 1];
7543 var M_offset_2 = M[offset + 2];
7544 var M_offset_3 = M[offset + 3];
7545 var M_offset_4 = M[offset + 4];
7546 var M_offset_5 = M[offset + 5];
7547 var M_offset_6 = M[offset + 6];
7548 var M_offset_7 = M[offset + 7];
7549 var M_offset_8 = M[offset + 8];
7550 var M_offset_9 = M[offset + 9];
7551 var M_offset_10 = M[offset + 10];
7552 var M_offset_11 = M[offset + 11];
7553 var M_offset_12 = M[offset + 12];
7554 var M_offset_13 = M[offset + 13];
7555 var M_offset_14 = M[offset + 14];
7556 var M_offset_15 = M[offset + 15];
7557
7558 // Working varialbes
7559 var a = H[0];
7560 var b = H[1];
7561 var c = H[2];
7562 var d = H[3];
7563
7564 // Computation
7565 a = FF(a, b, c, d, M_offset_0, 7, T[0]);
7566 d = FF(d, a, b, c, M_offset_1, 12, T[1]);
7567 c = FF(c, d, a, b, M_offset_2, 17, T[2]);
7568 b = FF(b, c, d, a, M_offset_3, 22, T[3]);
7569 a = FF(a, b, c, d, M_offset_4, 7, T[4]);
7570 d = FF(d, a, b, c, M_offset_5, 12, T[5]);
7571 c = FF(c, d, a, b, M_offset_6, 17, T[6]);
7572 b = FF(b, c, d, a, M_offset_7, 22, T[7]);
7573 a = FF(a, b, c, d, M_offset_8, 7, T[8]);
7574 d = FF(d, a, b, c, M_offset_9, 12, T[9]);
7575 c = FF(c, d, a, b, M_offset_10, 17, T[10]);
7576 b = FF(b, c, d, a, M_offset_11, 22, T[11]);
7577 a = FF(a, b, c, d, M_offset_12, 7, T[12]);
7578 d = FF(d, a, b, c, M_offset_13, 12, T[13]);
7579 c = FF(c, d, a, b, M_offset_14, 17, T[14]);
7580 b = FF(b, c, d, a, M_offset_15, 22, T[15]);
7581
7582 a = GG(a, b, c, d, M_offset_1, 5, T[16]);
7583 d = GG(d, a, b, c, M_offset_6, 9, T[17]);
7584 c = GG(c, d, a, b, M_offset_11, 14, T[18]);
7585 b = GG(b, c, d, a, M_offset_0, 20, T[19]);
7586 a = GG(a, b, c, d, M_offset_5, 5, T[20]);
7587 d = GG(d, a, b, c, M_offset_10, 9, T[21]);
7588 c = GG(c, d, a, b, M_offset_15, 14, T[22]);
7589 b = GG(b, c, d, a, M_offset_4, 20, T[23]);
7590 a = GG(a, b, c, d, M_offset_9, 5, T[24]);
7591 d = GG(d, a, b, c, M_offset_14, 9, T[25]);
7592 c = GG(c, d, a, b, M_offset_3, 14, T[26]);
7593 b = GG(b, c, d, a, M_offset_8, 20, T[27]);
7594 a = GG(a, b, c, d, M_offset_13, 5, T[28]);
7595 d = GG(d, a, b, c, M_offset_2, 9, T[29]);
7596 c = GG(c, d, a, b, M_offset_7, 14, T[30]);
7597 b = GG(b, c, d, a, M_offset_12, 20, T[31]);
7598
7599 a = HH(a, b, c, d, M_offset_5, 4, T[32]);
7600 d = HH(d, a, b, c, M_offset_8, 11, T[33]);
7601 c = HH(c, d, a, b, M_offset_11, 16, T[34]);
7602 b = HH(b, c, d, a, M_offset_14, 23, T[35]);
7603 a = HH(a, b, c, d, M_offset_1, 4, T[36]);
7604 d = HH(d, a, b, c, M_offset_4, 11, T[37]);
7605 c = HH(c, d, a, b, M_offset_7, 16, T[38]);
7606 b = HH(b, c, d, a, M_offset_10, 23, T[39]);
7607 a = HH(a, b, c, d, M_offset_13, 4, T[40]);
7608 d = HH(d, a, b, c, M_offset_0, 11, T[41]);
7609 c = HH(c, d, a, b, M_offset_3, 16, T[42]);
7610 b = HH(b, c, d, a, M_offset_6, 23, T[43]);
7611 a = HH(a, b, c, d, M_offset_9, 4, T[44]);
7612 d = HH(d, a, b, c, M_offset_12, 11, T[45]);
7613 c = HH(c, d, a, b, M_offset_15, 16, T[46]);
7614 b = HH(b, c, d, a, M_offset_2, 23, T[47]);
7615
7616 a = II(a, b, c, d, M_offset_0, 6, T[48]);
7617 d = II(d, a, b, c, M_offset_7, 10, T[49]);
7618 c = II(c, d, a, b, M_offset_14, 15, T[50]);
7619 b = II(b, c, d, a, M_offset_5, 21, T[51]);
7620 a = II(a, b, c, d, M_offset_12, 6, T[52]);
7621 d = II(d, a, b, c, M_offset_3, 10, T[53]);
7622 c = II(c, d, a, b, M_offset_10, 15, T[54]);
7623 b = II(b, c, d, a, M_offset_1, 21, T[55]);
7624 a = II(a, b, c, d, M_offset_8, 6, T[56]);
7625 d = II(d, a, b, c, M_offset_15, 10, T[57]);
7626 c = II(c, d, a, b, M_offset_6, 15, T[58]);
7627 b = II(b, c, d, a, M_offset_13, 21, T[59]);
7628 a = II(a, b, c, d, M_offset_4, 6, T[60]);
7629 d = II(d, a, b, c, M_offset_11, 10, T[61]);
7630 c = II(c, d, a, b, M_offset_2, 15, T[62]);
7631 b = II(b, c, d, a, M_offset_9, 21, T[63]);
7632
7633 // Intermediate hash value
7634 H[0] = (H[0] + a) | 0;
7635 H[1] = (H[1] + b) | 0;
7636 H[2] = (H[2] + c) | 0;
7637 H[3] = (H[3] + d) | 0;
7638 },
7639
7640 _doFinalize: function () {
7641 // Shortcuts
7642 var data = this._data;
7643 var dataWords = data.words;
7644
7645 var nBitsTotal = this._nDataBytes * 8;
7646 var nBitsLeft = data.sigBytes * 8;
7647
7648 // Add padding
7649 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
7650
7651 var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
7652 var nBitsTotalL = nBitsTotal;
7653 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
7654 (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
7655 (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
7656 );
7657 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
7658 (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
7659 (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
7660 );
7661
7662 data.sigBytes = (dataWords.length + 1) * 4;
7663
7664 // Hash final blocks
7665 this._process();
7666
7667 // Shortcuts
7668 var hash = this._hash;
7669 var H = hash.words;
7670
7671 // Swap endian
7672 for (var i = 0; i < 4; i++) {
7673 // Shortcut
7674 var H_i = H[i];
7675
7676 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
7677 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
7678 }
7679
7680 // Return final computed hash
7681 return hash;
7682 },
7683
7684 clone: function () {
7685 var clone = Hasher.clone.call(this);
7686 clone._hash = this._hash.clone();
7687
7688 return clone;
7689 }
7690 });
7691
7692 function FF(a, b, c, d, x, s, t) {
7693 var n = a + ((b & c) | (~b & d)) + x + t;
7694 return ((n << s) | (n >>> (32 - s))) + b;
7695 }
7696
7697 function GG(a, b, c, d, x, s, t) {
7698 var n = a + ((b & d) | (c & ~d)) + x + t;
7699 return ((n << s) | (n >>> (32 - s))) + b;
7700 }
7701
7702 function HH(a, b, c, d, x, s, t) {
7703 var n = a + (b ^ c ^ d) + x + t;
7704 return ((n << s) | (n >>> (32 - s))) + b;
7705 }
7706
7707 function II(a, b, c, d, x, s, t) {
7708 var n = a + (c ^ (b | ~d)) + x + t;
7709 return ((n << s) | (n >>> (32 - s))) + b;
7710 }
7711
7712 /**
7713 * Shortcut function to the hasher's object interface.
7714 *
7715 * @param {WordArray|string} message The message to hash.
7716 *
7717 * @return {WordArray} The hash.
7718 *
7719 * @static
7720 *
7721 * @example
7722 *
7723 * var hash = CryptoJS.MD5('message');
7724 * var hash = CryptoJS.MD5(wordArray);
7725 */
7726 C.MD5 = Hasher._createHelper(MD5);
7727
7728 /**
7729 * Shortcut function to the HMAC's object interface.
7730 *
7731 * @param {WordArray|string} message The message to hash.
7732 * @param {WordArray|string} key The secret key.
7733 *
7734 * @return {WordArray} The HMAC.
7735 *
7736 * @static
7737 *
7738 * @example
7739 *
7740 * var hmac = CryptoJS.HmacMD5(message, key);
7741 */
7742 C.HmacMD5 = Hasher._createHmacHelper(MD5);
7743 }(Math));
7744
7745
7746 return CryptoJS.MD5;
7747
7748}));
7749},{"./core":31}],40:[function(_dereq_,module,exports){
7750;(function (root, factory, undef) {
7751 if (typeof exports === "object") {
7752 // CommonJS
7753 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
7754 }
7755 else if (typeof define === "function" && define.amd) {
7756 // AMD
7757 define(["./core", "./cipher-core"], factory);
7758 }
7759 else {
7760 // Global (browser)
7761 factory(root.CryptoJS);
7762 }
7763}(this, function (CryptoJS) {
7764
7765 /**
7766 * Cipher Feedback block mode.
7767 */
7768 CryptoJS.mode.CFB = (function () {
7769 var CFB = CryptoJS.lib.BlockCipherMode.extend();
7770
7771 CFB.Encryptor = CFB.extend({
7772 processBlock: function (words, offset) {
7773 // Shortcuts
7774 var cipher = this._cipher;
7775 var blockSize = cipher.blockSize;
7776
7777 generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
7778
7779 // Remember this block to use with next block
7780 this._prevBlock = words.slice(offset, offset + blockSize);
7781 }
7782 });
7783
7784 CFB.Decryptor = CFB.extend({
7785 processBlock: function (words, offset) {
7786 // Shortcuts
7787 var cipher = this._cipher;
7788 var blockSize = cipher.blockSize;
7789
7790 // Remember this block to use with next block
7791 var thisBlock = words.slice(offset, offset + blockSize);
7792
7793 generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
7794
7795 // This block becomes the previous block
7796 this._prevBlock = thisBlock;
7797 }
7798 });
7799
7800 function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
7801 // Shortcut
7802 var iv = this._iv;
7803
7804 // Generate keystream
7805 if (iv) {
7806 var keystream = iv.slice(0);
7807
7808 // Remove IV for subsequent blocks
7809 this._iv = undefined;
7810 } else {
7811 var keystream = this._prevBlock;
7812 }
7813 cipher.encryptBlock(keystream, 0);
7814
7815 // Encrypt
7816 for (var i = 0; i < blockSize; i++) {
7817 words[offset + i] ^= keystream[i];
7818 }
7819 }
7820
7821 return CFB;
7822 }());
7823
7824
7825 return CryptoJS.mode.CFB;
7826
7827}));
7828},{"./cipher-core":30,"./core":31}],41:[function(_dereq_,module,exports){
7829;(function (root, factory, undef) {
7830 if (typeof exports === "object") {
7831 // CommonJS
7832 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
7833 }
7834 else if (typeof define === "function" && define.amd) {
7835 // AMD
7836 define(["./core", "./cipher-core"], factory);
7837 }
7838 else {
7839 // Global (browser)
7840 factory(root.CryptoJS);
7841 }
7842}(this, function (CryptoJS) {
7843
7844 /** @preserve
7845 * Counter block mode compatible with Dr Brian Gladman fileenc.c
7846 * derived from CryptoJS.mode.CTR
7847 * Jan Hruby jhruby.web@gmail.com
7848 */
7849 CryptoJS.mode.CTRGladman = (function () {
7850 var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
7851
7852 function incWord(word)
7853 {
7854 if (((word >> 24) & 0xff) === 0xff) { //overflow
7855 var b1 = (word >> 16)&0xff;
7856 var b2 = (word >> 8)&0xff;
7857 var b3 = word & 0xff;
7858
7859 if (b1 === 0xff) // overflow b1
7860 {
7861 b1 = 0;
7862 if (b2 === 0xff)
7863 {
7864 b2 = 0;
7865 if (b3 === 0xff)
7866 {
7867 b3 = 0;
7868 }
7869 else
7870 {
7871 ++b3;
7872 }
7873 }
7874 else
7875 {
7876 ++b2;
7877 }
7878 }
7879 else
7880 {
7881 ++b1;
7882 }
7883
7884 word = 0;
7885 word += (b1 << 16);
7886 word += (b2 << 8);
7887 word += b3;
7888 }
7889 else
7890 {
7891 word += (0x01 << 24);
7892 }
7893 return word;
7894 }
7895
7896 function incCounter(counter)
7897 {
7898 if ((counter[0] = incWord(counter[0])) === 0)
7899 {
7900 // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
7901 counter[1] = incWord(counter[1]);
7902 }
7903 return counter;
7904 }
7905
7906 var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
7907 processBlock: function (words, offset) {
7908 // Shortcuts
7909 var cipher = this._cipher
7910 var blockSize = cipher.blockSize;
7911 var iv = this._iv;
7912 var counter = this._counter;
7913
7914 // Generate keystream
7915 if (iv) {
7916 counter = this._counter = iv.slice(0);
7917
7918 // Remove IV for subsequent blocks
7919 this._iv = undefined;
7920 }
7921
7922 incCounter(counter);
7923
7924 var keystream = counter.slice(0);
7925 cipher.encryptBlock(keystream, 0);
7926
7927 // Encrypt
7928 for (var i = 0; i < blockSize; i++) {
7929 words[offset + i] ^= keystream[i];
7930 }
7931 }
7932 });
7933
7934 CTRGladman.Decryptor = Encryptor;
7935
7936 return CTRGladman;
7937 }());
7938
7939
7940
7941
7942 return CryptoJS.mode.CTRGladman;
7943
7944}));
7945},{"./cipher-core":30,"./core":31}],42:[function(_dereq_,module,exports){
7946;(function (root, factory, undef) {
7947 if (typeof exports === "object") {
7948 // CommonJS
7949 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
7950 }
7951 else if (typeof define === "function" && define.amd) {
7952 // AMD
7953 define(["./core", "./cipher-core"], factory);
7954 }
7955 else {
7956 // Global (browser)
7957 factory(root.CryptoJS);
7958 }
7959}(this, function (CryptoJS) {
7960
7961 /**
7962 * Counter block mode.
7963 */
7964 CryptoJS.mode.CTR = (function () {
7965 var CTR = CryptoJS.lib.BlockCipherMode.extend();
7966
7967 var Encryptor = CTR.Encryptor = CTR.extend({
7968 processBlock: function (words, offset) {
7969 // Shortcuts
7970 var cipher = this._cipher
7971 var blockSize = cipher.blockSize;
7972 var iv = this._iv;
7973 var counter = this._counter;
7974
7975 // Generate keystream
7976 if (iv) {
7977 counter = this._counter = iv.slice(0);
7978
7979 // Remove IV for subsequent blocks
7980 this._iv = undefined;
7981 }
7982 var keystream = counter.slice(0);
7983 cipher.encryptBlock(keystream, 0);
7984
7985 // Increment counter
7986 counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
7987
7988 // Encrypt
7989 for (var i = 0; i < blockSize; i++) {
7990 words[offset + i] ^= keystream[i];
7991 }
7992 }
7993 });
7994
7995 CTR.Decryptor = Encryptor;
7996
7997 return CTR;
7998 }());
7999
8000
8001 return CryptoJS.mode.CTR;
8002
8003}));
8004},{"./cipher-core":30,"./core":31}],43:[function(_dereq_,module,exports){
8005;(function (root, factory, undef) {
8006 if (typeof exports === "object") {
8007 // CommonJS
8008 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
8009 }
8010 else if (typeof define === "function" && define.amd) {
8011 // AMD
8012 define(["./core", "./cipher-core"], factory);
8013 }
8014 else {
8015 // Global (browser)
8016 factory(root.CryptoJS);
8017 }
8018}(this, function (CryptoJS) {
8019
8020 /**
8021 * Electronic Codebook block mode.
8022 */
8023 CryptoJS.mode.ECB = (function () {
8024 var ECB = CryptoJS.lib.BlockCipherMode.extend();
8025
8026 ECB.Encryptor = ECB.extend({
8027 processBlock: function (words, offset) {
8028 this._cipher.encryptBlock(words, offset);
8029 }
8030 });
8031
8032 ECB.Decryptor = ECB.extend({
8033 processBlock: function (words, offset) {
8034 this._cipher.decryptBlock(words, offset);
8035 }
8036 });
8037
8038 return ECB;
8039 }());
8040
8041
8042 return CryptoJS.mode.ECB;
8043
8044}));
8045},{"./cipher-core":30,"./core":31}],44:[function(_dereq_,module,exports){
8046;(function (root, factory, undef) {
8047 if (typeof exports === "object") {
8048 // CommonJS
8049 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
8050 }
8051 else if (typeof define === "function" && define.amd) {
8052 // AMD
8053 define(["./core", "./cipher-core"], factory);
8054 }
8055 else {
8056 // Global (browser)
8057 factory(root.CryptoJS);
8058 }
8059}(this, function (CryptoJS) {
8060
8061 /**
8062 * Output Feedback block mode.
8063 */
8064 CryptoJS.mode.OFB = (function () {
8065 var OFB = CryptoJS.lib.BlockCipherMode.extend();
8066
8067 var Encryptor = OFB.Encryptor = OFB.extend({
8068 processBlock: function (words, offset) {
8069 // Shortcuts
8070 var cipher = this._cipher
8071 var blockSize = cipher.blockSize;
8072 var iv = this._iv;
8073 var keystream = this._keystream;
8074
8075 // Generate keystream
8076 if (iv) {
8077 keystream = this._keystream = iv.slice(0);
8078
8079 // Remove IV for subsequent blocks
8080 this._iv = undefined;
8081 }
8082 cipher.encryptBlock(keystream, 0);
8083
8084 // Encrypt
8085 for (var i = 0; i < blockSize; i++) {
8086 words[offset + i] ^= keystream[i];
8087 }
8088 }
8089 });
8090
8091 OFB.Decryptor = Encryptor;
8092
8093 return OFB;
8094 }());
8095
8096
8097 return CryptoJS.mode.OFB;
8098
8099}));
8100},{"./cipher-core":30,"./core":31}],45:[function(_dereq_,module,exports){
8101;(function (root, factory, undef) {
8102 if (typeof exports === "object") {
8103 // CommonJS
8104 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
8105 }
8106 else if (typeof define === "function" && define.amd) {
8107 // AMD
8108 define(["./core", "./cipher-core"], factory);
8109 }
8110 else {
8111 // Global (browser)
8112 factory(root.CryptoJS);
8113 }
8114}(this, function (CryptoJS) {
8115
8116 /**
8117 * ANSI X.923 padding strategy.
8118 */
8119 CryptoJS.pad.AnsiX923 = {
8120 pad: function (data, blockSize) {
8121 // Shortcuts
8122 var dataSigBytes = data.sigBytes;
8123 var blockSizeBytes = blockSize * 4;
8124
8125 // Count padding bytes
8126 var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
8127
8128 // Compute last byte position
8129 var lastBytePos = dataSigBytes + nPaddingBytes - 1;
8130
8131 // Pad
8132 data.clamp();
8133 data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
8134 data.sigBytes += nPaddingBytes;
8135 },
8136
8137 unpad: function (data) {
8138 // Get number of padding bytes from last byte
8139 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
8140
8141 // Remove padding
8142 data.sigBytes -= nPaddingBytes;
8143 }
8144 };
8145
8146
8147 return CryptoJS.pad.Ansix923;
8148
8149}));
8150},{"./cipher-core":30,"./core":31}],46:[function(_dereq_,module,exports){
8151;(function (root, factory, undef) {
8152 if (typeof exports === "object") {
8153 // CommonJS
8154 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
8155 }
8156 else if (typeof define === "function" && define.amd) {
8157 // AMD
8158 define(["./core", "./cipher-core"], factory);
8159 }
8160 else {
8161 // Global (browser)
8162 factory(root.CryptoJS);
8163 }
8164}(this, function (CryptoJS) {
8165
8166 /**
8167 * ISO 10126 padding strategy.
8168 */
8169 CryptoJS.pad.Iso10126 = {
8170 pad: function (data, blockSize) {
8171 // Shortcut
8172 var blockSizeBytes = blockSize * 4;
8173
8174 // Count padding bytes
8175 var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
8176
8177 // Pad
8178 data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
8179 concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
8180 },
8181
8182 unpad: function (data) {
8183 // Get number of padding bytes from last byte
8184 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
8185
8186 // Remove padding
8187 data.sigBytes -= nPaddingBytes;
8188 }
8189 };
8190
8191
8192 return CryptoJS.pad.Iso10126;
8193
8194}));
8195},{"./cipher-core":30,"./core":31}],47:[function(_dereq_,module,exports){
8196;(function (root, factory, undef) {
8197 if (typeof exports === "object") {
8198 // CommonJS
8199 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
8200 }
8201 else if (typeof define === "function" && define.amd) {
8202 // AMD
8203 define(["./core", "./cipher-core"], factory);
8204 }
8205 else {
8206 // Global (browser)
8207 factory(root.CryptoJS);
8208 }
8209}(this, function (CryptoJS) {
8210
8211 /**
8212 * ISO/IEC 9797-1 Padding Method 2.
8213 */
8214 CryptoJS.pad.Iso97971 = {
8215 pad: function (data, blockSize) {
8216 // Add 0x80 byte
8217 data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
8218
8219 // Zero pad the rest
8220 CryptoJS.pad.ZeroPadding.pad(data, blockSize);
8221 },
8222
8223 unpad: function (data) {
8224 // Remove zero padding
8225 CryptoJS.pad.ZeroPadding.unpad(data);
8226
8227 // Remove one more byte -- the 0x80 byte
8228 data.sigBytes--;
8229 }
8230 };
8231
8232
8233 return CryptoJS.pad.Iso97971;
8234
8235}));
8236},{"./cipher-core":30,"./core":31}],48:[function(_dereq_,module,exports){
8237;(function (root, factory, undef) {
8238 if (typeof exports === "object") {
8239 // CommonJS
8240 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
8241 }
8242 else if (typeof define === "function" && define.amd) {
8243 // AMD
8244 define(["./core", "./cipher-core"], factory);
8245 }
8246 else {
8247 // Global (browser)
8248 factory(root.CryptoJS);
8249 }
8250}(this, function (CryptoJS) {
8251
8252 /**
8253 * A noop padding strategy.
8254 */
8255 CryptoJS.pad.NoPadding = {
8256 pad: function () {
8257 },
8258
8259 unpad: function () {
8260 }
8261 };
8262
8263
8264 return CryptoJS.pad.NoPadding;
8265
8266}));
8267},{"./cipher-core":30,"./core":31}],49:[function(_dereq_,module,exports){
8268;(function (root, factory, undef) {
8269 if (typeof exports === "object") {
8270 // CommonJS
8271 module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
8272 }
8273 else if (typeof define === "function" && define.amd) {
8274 // AMD
8275 define(["./core", "./cipher-core"], factory);
8276 }
8277 else {
8278 // Global (browser)
8279 factory(root.CryptoJS);
8280 }
8281}(this, function (CryptoJS) {
8282
8283 /**
8284 * Zero padding strategy.
8285 */
8286 CryptoJS.pad.ZeroPadding = {
8287 pad: function (data, blockSize) {
8288 // Shortcut
8289 var blockSizeBytes = blockSize * 4;
8290
8291 // Pad
8292 data.clamp();
8293 data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
8294 },
8295
8296 unpad: function (data) {
8297 // Shortcut
8298 var dataWords = data.words;
8299
8300 // Unpad
8301 var i = data.sigBytes - 1;
8302 while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
8303 i--;
8304 }
8305 data.sigBytes = i + 1;
8306 }
8307 };
8308
8309
8310 return CryptoJS.pad.ZeroPadding;
8311
8312}));
8313},{"./cipher-core":30,"./core":31}],50:[function(_dereq_,module,exports){
8314;(function (root, factory, undef) {
8315 if (typeof exports === "object") {
8316 // CommonJS
8317 module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
8318 }
8319 else if (typeof define === "function" && define.amd) {
8320 // AMD
8321 define(["./core", "./sha1", "./hmac"], factory);
8322 }
8323 else {
8324 // Global (browser)
8325 factory(root.CryptoJS);
8326 }
8327}(this, function (CryptoJS) {
8328
8329 (function () {
8330 // Shortcuts
8331 var C = CryptoJS;
8332 var C_lib = C.lib;
8333 var Base = C_lib.Base;
8334 var WordArray = C_lib.WordArray;
8335 var C_algo = C.algo;
8336 var SHA1 = C_algo.SHA1;
8337 var HMAC = C_algo.HMAC;
8338
8339 /**
8340 * Password-Based Key Derivation Function 2 algorithm.
8341 */
8342 var PBKDF2 = C_algo.PBKDF2 = Base.extend({
8343 /**
8344 * Configuration options.
8345 *
8346 * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
8347 * @property {Hasher} hasher The hasher to use. Default: SHA1
8348 * @property {number} iterations The number of iterations to perform. Default: 1
8349 */
8350 cfg: Base.extend({
8351 keySize: 128/32,
8352 hasher: SHA1,
8353 iterations: 1
8354 }),
8355
8356 /**
8357 * Initializes a newly created key derivation function.
8358 *
8359 * @param {Object} cfg (Optional) The configuration options to use for the derivation.
8360 *
8361 * @example
8362 *
8363 * var kdf = CryptoJS.algo.PBKDF2.create();
8364 * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
8365 * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
8366 */
8367 init: function (cfg) {
8368 this.cfg = this.cfg.extend(cfg);
8369 },
8370
8371 /**
8372 * Computes the Password-Based Key Derivation Function 2.
8373 *
8374 * @param {WordArray|string} password The password.
8375 * @param {WordArray|string} salt A salt.
8376 *
8377 * @return {WordArray} The derived key.
8378 *
8379 * @example
8380 *
8381 * var key = kdf.compute(password, salt);
8382 */
8383 compute: function (password, salt) {
8384 // Shortcut
8385 var cfg = this.cfg;
8386
8387 // Init HMAC
8388 var hmac = HMAC.create(cfg.hasher, password);
8389
8390 // Initial values
8391 var derivedKey = WordArray.create();
8392 var blockIndex = WordArray.create([0x00000001]);
8393
8394 // Shortcuts
8395 var derivedKeyWords = derivedKey.words;
8396 var blockIndexWords = blockIndex.words;
8397 var keySize = cfg.keySize;
8398 var iterations = cfg.iterations;
8399
8400 // Generate key
8401 while (derivedKeyWords.length < keySize) {
8402 var block = hmac.update(salt).finalize(blockIndex);
8403 hmac.reset();
8404
8405 // Shortcuts
8406 var blockWords = block.words;
8407 var blockWordsLength = blockWords.length;
8408
8409 // Iterations
8410 var intermediate = block;
8411 for (var i = 1; i < iterations; i++) {
8412 intermediate = hmac.finalize(intermediate);
8413 hmac.reset();
8414
8415 // Shortcut
8416 var intermediateWords = intermediate.words;
8417
8418 // XOR intermediate with block
8419 for (var j = 0; j < blockWordsLength; j++) {
8420 blockWords[j] ^= intermediateWords[j];
8421 }
8422 }
8423
8424 derivedKey.concat(block);
8425 blockIndexWords[0]++;
8426 }
8427 derivedKey.sigBytes = keySize * 4;
8428
8429 return derivedKey;
8430 }
8431 });
8432
8433 /**
8434 * Computes the Password-Based Key Derivation Function 2.
8435 *
8436 * @param {WordArray|string} password The password.
8437 * @param {WordArray|string} salt A salt.
8438 * @param {Object} cfg (Optional) The configuration options to use for this computation.
8439 *
8440 * @return {WordArray} The derived key.
8441 *
8442 * @static
8443 *
8444 * @example
8445 *
8446 * var key = CryptoJS.PBKDF2(password, salt);
8447 * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
8448 * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
8449 */
8450 C.PBKDF2 = function (password, salt, cfg) {
8451 return PBKDF2.create(cfg).compute(password, salt);
8452 };
8453 }());
8454
8455
8456 return CryptoJS.PBKDF2;
8457
8458}));
8459},{"./core":31,"./hmac":36,"./sha1":55}],51:[function(_dereq_,module,exports){
8460;(function (root, factory, undef) {
8461 if (typeof exports === "object") {
8462 // CommonJS
8463 module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
8464 }
8465 else if (typeof define === "function" && define.amd) {
8466 // AMD
8467 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
8468 }
8469 else {
8470 // Global (browser)
8471 factory(root.CryptoJS);
8472 }
8473}(this, function (CryptoJS) {
8474
8475 (function () {
8476 // Shortcuts
8477 var C = CryptoJS;
8478 var C_lib = C.lib;
8479 var StreamCipher = C_lib.StreamCipher;
8480 var C_algo = C.algo;
8481
8482 // Reusable objects
8483 var S = [];
8484 var C_ = [];
8485 var G = [];
8486
8487 /**
8488 * Rabbit stream cipher algorithm.
8489 *
8490 * This is a legacy version that neglected to convert the key to little-endian.
8491 * This error doesn't affect the cipher's security,
8492 * but it does affect its compatibility with other implementations.
8493 */
8494 var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
8495 _doReset: function () {
8496 // Shortcuts
8497 var K = this._key.words;
8498 var iv = this.cfg.iv;
8499
8500 // Generate initial state values
8501 var X = this._X = [
8502 K[0], (K[3] << 16) | (K[2] >>> 16),
8503 K[1], (K[0] << 16) | (K[3] >>> 16),
8504 K[2], (K[1] << 16) | (K[0] >>> 16),
8505 K[3], (K[2] << 16) | (K[1] >>> 16)
8506 ];
8507
8508 // Generate initial counter values
8509 var C = this._C = [
8510 (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
8511 (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
8512 (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
8513 (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
8514 ];
8515
8516 // Carry bit
8517 this._b = 0;
8518
8519 // Iterate the system four times
8520 for (var i = 0; i < 4; i++) {
8521 nextState.call(this);
8522 }
8523
8524 // Modify the counters
8525 for (var i = 0; i < 8; i++) {
8526 C[i] ^= X[(i + 4) & 7];
8527 }
8528
8529 // IV setup
8530 if (iv) {
8531 // Shortcuts
8532 var IV = iv.words;
8533 var IV_0 = IV[0];
8534 var IV_1 = IV[1];
8535
8536 // Generate four subvectors
8537 var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
8538 var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
8539 var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
8540 var i3 = (i2 << 16) | (i0 & 0x0000ffff);
8541
8542 // Modify counter values
8543 C[0] ^= i0;
8544 C[1] ^= i1;
8545 C[2] ^= i2;
8546 C[3] ^= i3;
8547 C[4] ^= i0;
8548 C[5] ^= i1;
8549 C[6] ^= i2;
8550 C[7] ^= i3;
8551
8552 // Iterate the system four times
8553 for (var i = 0; i < 4; i++) {
8554 nextState.call(this);
8555 }
8556 }
8557 },
8558
8559 _doProcessBlock: function (M, offset) {
8560 // Shortcut
8561 var X = this._X;
8562
8563 // Iterate the system
8564 nextState.call(this);
8565
8566 // Generate four keystream words
8567 S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
8568 S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
8569 S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
8570 S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
8571
8572 for (var i = 0; i < 4; i++) {
8573 // Swap endian
8574 S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
8575 (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
8576
8577 // Encrypt
8578 M[offset + i] ^= S[i];
8579 }
8580 },
8581
8582 blockSize: 128/32,
8583
8584 ivSize: 64/32
8585 });
8586
8587 function nextState() {
8588 // Shortcuts
8589 var X = this._X;
8590 var C = this._C;
8591
8592 // Save old counter values
8593 for (var i = 0; i < 8; i++) {
8594 C_[i] = C[i];
8595 }
8596
8597 // Calculate new counter values
8598 C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
8599 C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
8600 C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
8601 C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
8602 C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
8603 C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
8604 C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
8605 C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
8606 this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
8607
8608 // Calculate the g-values
8609 for (var i = 0; i < 8; i++) {
8610 var gx = X[i] + C[i];
8611
8612 // Construct high and low argument for squaring
8613 var ga = gx & 0xffff;
8614 var gb = gx >>> 16;
8615
8616 // Calculate high and low result of squaring
8617 var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
8618 var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
8619
8620 // High XOR low
8621 G[i] = gh ^ gl;
8622 }
8623
8624 // Calculate new state values
8625 X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
8626 X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
8627 X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
8628 X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
8629 X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
8630 X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
8631 X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
8632 X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
8633 }
8634
8635 /**
8636 * Shortcut functions to the cipher's object interface.
8637 *
8638 * @example
8639 *
8640 * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
8641 * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
8642 */
8643 C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
8644 }());
8645
8646
8647 return CryptoJS.RabbitLegacy;
8648
8649}));
8650},{"./cipher-core":30,"./core":31,"./enc-base64":32,"./evpkdf":34,"./md5":39}],52:[function(_dereq_,module,exports){
8651;(function (root, factory, undef) {
8652 if (typeof exports === "object") {
8653 // CommonJS
8654 module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
8655 }
8656 else if (typeof define === "function" && define.amd) {
8657 // AMD
8658 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
8659 }
8660 else {
8661 // Global (browser)
8662 factory(root.CryptoJS);
8663 }
8664}(this, function (CryptoJS) {
8665
8666 (function () {
8667 // Shortcuts
8668 var C = CryptoJS;
8669 var C_lib = C.lib;
8670 var StreamCipher = C_lib.StreamCipher;
8671 var C_algo = C.algo;
8672
8673 // Reusable objects
8674 var S = [];
8675 var C_ = [];
8676 var G = [];
8677
8678 /**
8679 * Rabbit stream cipher algorithm
8680 */
8681 var Rabbit = C_algo.Rabbit = StreamCipher.extend({
8682 _doReset: function () {
8683 // Shortcuts
8684 var K = this._key.words;
8685 var iv = this.cfg.iv;
8686
8687 // Swap endian
8688 for (var i = 0; i < 4; i++) {
8689 K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
8690 (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
8691 }
8692
8693 // Generate initial state values
8694 var X = this._X = [
8695 K[0], (K[3] << 16) | (K[2] >>> 16),
8696 K[1], (K[0] << 16) | (K[3] >>> 16),
8697 K[2], (K[1] << 16) | (K[0] >>> 16),
8698 K[3], (K[2] << 16) | (K[1] >>> 16)
8699 ];
8700
8701 // Generate initial counter values
8702 var C = this._C = [
8703 (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
8704 (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
8705 (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
8706 (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
8707 ];
8708
8709 // Carry bit
8710 this._b = 0;
8711
8712 // Iterate the system four times
8713 for (var i = 0; i < 4; i++) {
8714 nextState.call(this);
8715 }
8716
8717 // Modify the counters
8718 for (var i = 0; i < 8; i++) {
8719 C[i] ^= X[(i + 4) & 7];
8720 }
8721
8722 // IV setup
8723 if (iv) {
8724 // Shortcuts
8725 var IV = iv.words;
8726 var IV_0 = IV[0];
8727 var IV_1 = IV[1];
8728
8729 // Generate four subvectors
8730 var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
8731 var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
8732 var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
8733 var i3 = (i2 << 16) | (i0 & 0x0000ffff);
8734
8735 // Modify counter values
8736 C[0] ^= i0;
8737 C[1] ^= i1;
8738 C[2] ^= i2;
8739 C[3] ^= i3;
8740 C[4] ^= i0;
8741 C[5] ^= i1;
8742 C[6] ^= i2;
8743 C[7] ^= i3;
8744
8745 // Iterate the system four times
8746 for (var i = 0; i < 4; i++) {
8747 nextState.call(this);
8748 }
8749 }
8750 },
8751
8752 _doProcessBlock: function (M, offset) {
8753 // Shortcut
8754 var X = this._X;
8755
8756 // Iterate the system
8757 nextState.call(this);
8758
8759 // Generate four keystream words
8760 S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
8761 S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
8762 S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
8763 S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
8764
8765 for (var i = 0; i < 4; i++) {
8766 // Swap endian
8767 S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
8768 (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
8769
8770 // Encrypt
8771 M[offset + i] ^= S[i];
8772 }
8773 },
8774
8775 blockSize: 128/32,
8776
8777 ivSize: 64/32
8778 });
8779
8780 function nextState() {
8781 // Shortcuts
8782 var X = this._X;
8783 var C = this._C;
8784
8785 // Save old counter values
8786 for (var i = 0; i < 8; i++) {
8787 C_[i] = C[i];
8788 }
8789
8790 // Calculate new counter values
8791 C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
8792 C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
8793 C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
8794 C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
8795 C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
8796 C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
8797 C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
8798 C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
8799 this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
8800
8801 // Calculate the g-values
8802 for (var i = 0; i < 8; i++) {
8803 var gx = X[i] + C[i];
8804
8805 // Construct high and low argument for squaring
8806 var ga = gx & 0xffff;
8807 var gb = gx >>> 16;
8808
8809 // Calculate high and low result of squaring
8810 var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
8811 var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
8812
8813 // High XOR low
8814 G[i] = gh ^ gl;
8815 }
8816
8817 // Calculate new state values
8818 X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
8819 X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
8820 X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
8821 X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
8822 X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
8823 X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
8824 X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
8825 X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
8826 }
8827
8828 /**
8829 * Shortcut functions to the cipher's object interface.
8830 *
8831 * @example
8832 *
8833 * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
8834 * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
8835 */
8836 C.Rabbit = StreamCipher._createHelper(Rabbit);
8837 }());
8838
8839
8840 return CryptoJS.Rabbit;
8841
8842}));
8843},{"./cipher-core":30,"./core":31,"./enc-base64":32,"./evpkdf":34,"./md5":39}],53:[function(_dereq_,module,exports){
8844;(function (root, factory, undef) {
8845 if (typeof exports === "object") {
8846 // CommonJS
8847 module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
8848 }
8849 else if (typeof define === "function" && define.amd) {
8850 // AMD
8851 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
8852 }
8853 else {
8854 // Global (browser)
8855 factory(root.CryptoJS);
8856 }
8857}(this, function (CryptoJS) {
8858
8859 (function () {
8860 // Shortcuts
8861 var C = CryptoJS;
8862 var C_lib = C.lib;
8863 var StreamCipher = C_lib.StreamCipher;
8864 var C_algo = C.algo;
8865
8866 /**
8867 * RC4 stream cipher algorithm.
8868 */
8869 var RC4 = C_algo.RC4 = StreamCipher.extend({
8870 _doReset: function () {
8871 // Shortcuts
8872 var key = this._key;
8873 var keyWords = key.words;
8874 var keySigBytes = key.sigBytes;
8875
8876 // Init sbox
8877 var S = this._S = [];
8878 for (var i = 0; i < 256; i++) {
8879 S[i] = i;
8880 }
8881
8882 // Key setup
8883 for (var i = 0, j = 0; i < 256; i++) {
8884 var keyByteIndex = i % keySigBytes;
8885 var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
8886
8887 j = (j + S[i] + keyByte) % 256;
8888
8889 // Swap
8890 var t = S[i];
8891 S[i] = S[j];
8892 S[j] = t;
8893 }
8894
8895 // Counters
8896 this._i = this._j = 0;
8897 },
8898
8899 _doProcessBlock: function (M, offset) {
8900 M[offset] ^= generateKeystreamWord.call(this);
8901 },
8902
8903 keySize: 256/32,
8904
8905 ivSize: 0
8906 });
8907
8908 function generateKeystreamWord() {
8909 // Shortcuts
8910 var S = this._S;
8911 var i = this._i;
8912 var j = this._j;
8913
8914 // Generate keystream word
8915 var keystreamWord = 0;
8916 for (var n = 0; n < 4; n++) {
8917 i = (i + 1) % 256;
8918 j = (j + S[i]) % 256;
8919
8920 // Swap
8921 var t = S[i];
8922 S[i] = S[j];
8923 S[j] = t;
8924
8925 keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
8926 }
8927
8928 // Update counters
8929 this._i = i;
8930 this._j = j;
8931
8932 return keystreamWord;
8933 }
8934
8935 /**
8936 * Shortcut functions to the cipher's object interface.
8937 *
8938 * @example
8939 *
8940 * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
8941 * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
8942 */
8943 C.RC4 = StreamCipher._createHelper(RC4);
8944
8945 /**
8946 * Modified RC4 stream cipher algorithm.
8947 */
8948 var RC4Drop = C_algo.RC4Drop = RC4.extend({
8949 /**
8950 * Configuration options.
8951 *
8952 * @property {number} drop The number of keystream words to drop. Default 192
8953 */
8954 cfg: RC4.cfg.extend({
8955 drop: 192
8956 }),
8957
8958 _doReset: function () {
8959 RC4._doReset.call(this);
8960
8961 // Drop
8962 for (var i = this.cfg.drop; i > 0; i--) {
8963 generateKeystreamWord.call(this);
8964 }
8965 }
8966 });
8967
8968 /**
8969 * Shortcut functions to the cipher's object interface.
8970 *
8971 * @example
8972 *
8973 * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
8974 * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
8975 */
8976 C.RC4Drop = StreamCipher._createHelper(RC4Drop);
8977 }());
8978
8979
8980 return CryptoJS.RC4;
8981
8982}));
8983},{"./cipher-core":30,"./core":31,"./enc-base64":32,"./evpkdf":34,"./md5":39}],54:[function(_dereq_,module,exports){
8984;(function (root, factory) {
8985 if (typeof exports === "object") {
8986 // CommonJS
8987 module.exports = exports = factory(_dereq_("./core"));
8988 }
8989 else if (typeof define === "function" && define.amd) {
8990 // AMD
8991 define(["./core"], factory);
8992 }
8993 else {
8994 // Global (browser)
8995 factory(root.CryptoJS);
8996 }
8997}(this, function (CryptoJS) {
8998
8999 /** @preserve
9000 (c) 2012 by Cédric Mesnil. All rights reserved.
9001
9002 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
9003
9004 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
9005 - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9006
9007 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9008 */
9009
9010 (function (Math) {
9011 // Shortcuts
9012 var C = CryptoJS;
9013 var C_lib = C.lib;
9014 var WordArray = C_lib.WordArray;
9015 var Hasher = C_lib.Hasher;
9016 var C_algo = C.algo;
9017
9018 // Constants table
9019 var _zl = WordArray.create([
9020 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
9021 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
9022 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
9023 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
9024 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
9025 var _zr = WordArray.create([
9026 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
9027 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
9028 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
9029 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
9030 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
9031 var _sl = WordArray.create([
9032 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
9033 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
9034 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
9035 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9036 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
9037 var _sr = WordArray.create([
9038 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9039 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9040 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
9041 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
9042 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
9043
9044 var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
9045 var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
9046
9047 /**
9048 * RIPEMD160 hash algorithm.
9049 */
9050 var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
9051 _doReset: function () {
9052 this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
9053 },
9054
9055 _doProcessBlock: function (M, offset) {
9056
9057 // Swap endian
9058 for (var i = 0; i < 16; i++) {
9059 // Shortcuts
9060 var offset_i = offset + i;
9061 var M_offset_i = M[offset_i];
9062
9063 // Swap
9064 M[offset_i] = (
9065 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
9066 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
9067 );
9068 }
9069 // Shortcut
9070 var H = this._hash.words;
9071 var hl = _hl.words;
9072 var hr = _hr.words;
9073 var zl = _zl.words;
9074 var zr = _zr.words;
9075 var sl = _sl.words;
9076 var sr = _sr.words;
9077
9078 // Working variables
9079 var al, bl, cl, dl, el;
9080 var ar, br, cr, dr, er;
9081
9082 ar = al = H[0];
9083 br = bl = H[1];
9084 cr = cl = H[2];
9085 dr = dl = H[3];
9086 er = el = H[4];
9087 // Computation
9088 var t;
9089 for (var i = 0; i < 80; i += 1) {
9090 t = (al + M[offset+zl[i]])|0;
9091 if (i<16){
9092 t += f1(bl,cl,dl) + hl[0];
9093 } else if (i<32) {
9094 t += f2(bl,cl,dl) + hl[1];
9095 } else if (i<48) {
9096 t += f3(bl,cl,dl) + hl[2];
9097 } else if (i<64) {
9098 t += f4(bl,cl,dl) + hl[3];
9099 } else {// if (i<80) {
9100 t += f5(bl,cl,dl) + hl[4];
9101 }
9102 t = t|0;
9103 t = rotl(t,sl[i]);
9104 t = (t+el)|0;
9105 al = el;
9106 el = dl;
9107 dl = rotl(cl, 10);
9108 cl = bl;
9109 bl = t;
9110
9111 t = (ar + M[offset+zr[i]])|0;
9112 if (i<16){
9113 t += f5(br,cr,dr) + hr[0];
9114 } else if (i<32) {
9115 t += f4(br,cr,dr) + hr[1];
9116 } else if (i<48) {
9117 t += f3(br,cr,dr) + hr[2];
9118 } else if (i<64) {
9119 t += f2(br,cr,dr) + hr[3];
9120 } else {// if (i<80) {
9121 t += f1(br,cr,dr) + hr[4];
9122 }
9123 t = t|0;
9124 t = rotl(t,sr[i]) ;
9125 t = (t+er)|0;
9126 ar = er;
9127 er = dr;
9128 dr = rotl(cr, 10);
9129 cr = br;
9130 br = t;
9131 }
9132 // Intermediate hash value
9133 t = (H[1] + cl + dr)|0;
9134 H[1] = (H[2] + dl + er)|0;
9135 H[2] = (H[3] + el + ar)|0;
9136 H[3] = (H[4] + al + br)|0;
9137 H[4] = (H[0] + bl + cr)|0;
9138 H[0] = t;
9139 },
9140
9141 _doFinalize: function () {
9142 // Shortcuts
9143 var data = this._data;
9144 var dataWords = data.words;
9145
9146 var nBitsTotal = this._nDataBytes * 8;
9147 var nBitsLeft = data.sigBytes * 8;
9148
9149 // Add padding
9150 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
9151 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
9152 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
9153 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
9154 );
9155 data.sigBytes = (dataWords.length + 1) * 4;
9156
9157 // Hash final blocks
9158 this._process();
9159
9160 // Shortcuts
9161 var hash = this._hash;
9162 var H = hash.words;
9163
9164 // Swap endian
9165 for (var i = 0; i < 5; i++) {
9166 // Shortcut
9167 var H_i = H[i];
9168
9169 // Swap
9170 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
9171 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
9172 }
9173
9174 // Return final computed hash
9175 return hash;
9176 },
9177
9178 clone: function () {
9179 var clone = Hasher.clone.call(this);
9180 clone._hash = this._hash.clone();
9181
9182 return clone;
9183 }
9184 });
9185
9186
9187 function f1(x, y, z) {
9188 return ((x) ^ (y) ^ (z));
9189
9190 }
9191
9192 function f2(x, y, z) {
9193 return (((x)&(y)) | ((~x)&(z)));
9194 }
9195
9196 function f3(x, y, z) {
9197 return (((x) | (~(y))) ^ (z));
9198 }
9199
9200 function f4(x, y, z) {
9201 return (((x) & (z)) | ((y)&(~(z))));
9202 }
9203
9204 function f5(x, y, z) {
9205 return ((x) ^ ((y) |(~(z))));
9206
9207 }
9208
9209 function rotl(x,n) {
9210 return (x<<n) | (x>>>(32-n));
9211 }
9212
9213
9214 /**
9215 * Shortcut function to the hasher's object interface.
9216 *
9217 * @param {WordArray|string} message The message to hash.
9218 *
9219 * @return {WordArray} The hash.
9220 *
9221 * @static
9222 *
9223 * @example
9224 *
9225 * var hash = CryptoJS.RIPEMD160('message');
9226 * var hash = CryptoJS.RIPEMD160(wordArray);
9227 */
9228 C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
9229
9230 /**
9231 * Shortcut function to the HMAC's object interface.
9232 *
9233 * @param {WordArray|string} message The message to hash.
9234 * @param {WordArray|string} key The secret key.
9235 *
9236 * @return {WordArray} The HMAC.
9237 *
9238 * @static
9239 *
9240 * @example
9241 *
9242 * var hmac = CryptoJS.HmacRIPEMD160(message, key);
9243 */
9244 C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
9245 }(Math));
9246
9247
9248 return CryptoJS.RIPEMD160;
9249
9250}));
9251},{"./core":31}],55:[function(_dereq_,module,exports){
9252;(function (root, factory) {
9253 if (typeof exports === "object") {
9254 // CommonJS
9255 module.exports = exports = factory(_dereq_("./core"));
9256 }
9257 else if (typeof define === "function" && define.amd) {
9258 // AMD
9259 define(["./core"], factory);
9260 }
9261 else {
9262 // Global (browser)
9263 factory(root.CryptoJS);
9264 }
9265}(this, function (CryptoJS) {
9266
9267 (function () {
9268 // Shortcuts
9269 var C = CryptoJS;
9270 var C_lib = C.lib;
9271 var WordArray = C_lib.WordArray;
9272 var Hasher = C_lib.Hasher;
9273 var C_algo = C.algo;
9274
9275 // Reusable object
9276 var W = [];
9277
9278 /**
9279 * SHA-1 hash algorithm.
9280 */
9281 var SHA1 = C_algo.SHA1 = Hasher.extend({
9282 _doReset: function () {
9283 this._hash = new WordArray.init([
9284 0x67452301, 0xefcdab89,
9285 0x98badcfe, 0x10325476,
9286 0xc3d2e1f0
9287 ]);
9288 },
9289
9290 _doProcessBlock: function (M, offset) {
9291 // Shortcut
9292 var H = this._hash.words;
9293
9294 // Working variables
9295 var a = H[0];
9296 var b = H[1];
9297 var c = H[2];
9298 var d = H[3];
9299 var e = H[4];
9300
9301 // Computation
9302 for (var i = 0; i < 80; i++) {
9303 if (i < 16) {
9304 W[i] = M[offset + i] | 0;
9305 } else {
9306 var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
9307 W[i] = (n << 1) | (n >>> 31);
9308 }
9309
9310 var t = ((a << 5) | (a >>> 27)) + e + W[i];
9311 if (i < 20) {
9312 t += ((b & c) | (~b & d)) + 0x5a827999;
9313 } else if (i < 40) {
9314 t += (b ^ c ^ d) + 0x6ed9eba1;
9315 } else if (i < 60) {
9316 t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
9317 } else /* if (i < 80) */ {
9318 t += (b ^ c ^ d) - 0x359d3e2a;
9319 }
9320
9321 e = d;
9322 d = c;
9323 c = (b << 30) | (b >>> 2);
9324 b = a;
9325 a = t;
9326 }
9327
9328 // Intermediate hash value
9329 H[0] = (H[0] + a) | 0;
9330 H[1] = (H[1] + b) | 0;
9331 H[2] = (H[2] + c) | 0;
9332 H[3] = (H[3] + d) | 0;
9333 H[4] = (H[4] + e) | 0;
9334 },
9335
9336 _doFinalize: function () {
9337 // Shortcuts
9338 var data = this._data;
9339 var dataWords = data.words;
9340
9341 var nBitsTotal = this._nDataBytes * 8;
9342 var nBitsLeft = data.sigBytes * 8;
9343
9344 // Add padding
9345 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
9346 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
9347 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
9348 data.sigBytes = dataWords.length * 4;
9349
9350 // Hash final blocks
9351 this._process();
9352
9353 // Return final computed hash
9354 return this._hash;
9355 },
9356
9357 clone: function () {
9358 var clone = Hasher.clone.call(this);
9359 clone._hash = this._hash.clone();
9360
9361 return clone;
9362 }
9363 });
9364
9365 /**
9366 * Shortcut function to the hasher's object interface.
9367 *
9368 * @param {WordArray|string} message The message to hash.
9369 *
9370 * @return {WordArray} The hash.
9371 *
9372 * @static
9373 *
9374 * @example
9375 *
9376 * var hash = CryptoJS.SHA1('message');
9377 * var hash = CryptoJS.SHA1(wordArray);
9378 */
9379 C.SHA1 = Hasher._createHelper(SHA1);
9380
9381 /**
9382 * Shortcut function to the HMAC's object interface.
9383 *
9384 * @param {WordArray|string} message The message to hash.
9385 * @param {WordArray|string} key The secret key.
9386 *
9387 * @return {WordArray} The HMAC.
9388 *
9389 * @static
9390 *
9391 * @example
9392 *
9393 * var hmac = CryptoJS.HmacSHA1(message, key);
9394 */
9395 C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
9396 }());
9397
9398
9399 return CryptoJS.SHA1;
9400
9401}));
9402},{"./core":31}],56:[function(_dereq_,module,exports){
9403;(function (root, factory, undef) {
9404 if (typeof exports === "object") {
9405 // CommonJS
9406 module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
9407 }
9408 else if (typeof define === "function" && define.amd) {
9409 // AMD
9410 define(["./core", "./sha256"], factory);
9411 }
9412 else {
9413 // Global (browser)
9414 factory(root.CryptoJS);
9415 }
9416}(this, function (CryptoJS) {
9417
9418 (function () {
9419 // Shortcuts
9420 var C = CryptoJS;
9421 var C_lib = C.lib;
9422 var WordArray = C_lib.WordArray;
9423 var C_algo = C.algo;
9424 var SHA256 = C_algo.SHA256;
9425
9426 /**
9427 * SHA-224 hash algorithm.
9428 */
9429 var SHA224 = C_algo.SHA224 = SHA256.extend({
9430 _doReset: function () {
9431 this._hash = new WordArray.init([
9432 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
9433 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
9434 ]);
9435 },
9436
9437 _doFinalize: function () {
9438 var hash = SHA256._doFinalize.call(this);
9439
9440 hash.sigBytes -= 4;
9441
9442 return hash;
9443 }
9444 });
9445
9446 /**
9447 * Shortcut function to the hasher's object interface.
9448 *
9449 * @param {WordArray|string} message The message to hash.
9450 *
9451 * @return {WordArray} The hash.
9452 *
9453 * @static
9454 *
9455 * @example
9456 *
9457 * var hash = CryptoJS.SHA224('message');
9458 * var hash = CryptoJS.SHA224(wordArray);
9459 */
9460 C.SHA224 = SHA256._createHelper(SHA224);
9461
9462 /**
9463 * Shortcut function to the HMAC's object interface.
9464 *
9465 * @param {WordArray|string} message The message to hash.
9466 * @param {WordArray|string} key The secret key.
9467 *
9468 * @return {WordArray} The HMAC.
9469 *
9470 * @static
9471 *
9472 * @example
9473 *
9474 * var hmac = CryptoJS.HmacSHA224(message, key);
9475 */
9476 C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
9477 }());
9478
9479
9480 return CryptoJS.SHA224;
9481
9482}));
9483},{"./core":31,"./sha256":57}],57:[function(_dereq_,module,exports){
9484;(function (root, factory) {
9485 if (typeof exports === "object") {
9486 // CommonJS
9487 module.exports = exports = factory(_dereq_("./core"));
9488 }
9489 else if (typeof define === "function" && define.amd) {
9490 // AMD
9491 define(["./core"], factory);
9492 }
9493 else {
9494 // Global (browser)
9495 factory(root.CryptoJS);
9496 }
9497}(this, function (CryptoJS) {
9498
9499 (function (Math) {
9500 // Shortcuts
9501 var C = CryptoJS;
9502 var C_lib = C.lib;
9503 var WordArray = C_lib.WordArray;
9504 var Hasher = C_lib.Hasher;
9505 var C_algo = C.algo;
9506
9507 // Initialization and round constants tables
9508 var H = [];
9509 var K = [];
9510
9511 // Compute constants
9512 (function () {
9513 function isPrime(n) {
9514 var sqrtN = Math.sqrt(n);
9515 for (var factor = 2; factor <= sqrtN; factor++) {
9516 if (!(n % factor)) {
9517 return false;
9518 }
9519 }
9520
9521 return true;
9522 }
9523
9524 function getFractionalBits(n) {
9525 return ((n - (n | 0)) * 0x100000000) | 0;
9526 }
9527
9528 var n = 2;
9529 var nPrime = 0;
9530 while (nPrime < 64) {
9531 if (isPrime(n)) {
9532 if (nPrime < 8) {
9533 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
9534 }
9535 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
9536
9537 nPrime++;
9538 }
9539
9540 n++;
9541 }
9542 }());
9543
9544 // Reusable object
9545 var W = [];
9546
9547 /**
9548 * SHA-256 hash algorithm.
9549 */
9550 var SHA256 = C_algo.SHA256 = Hasher.extend({
9551 _doReset: function () {
9552 this._hash = new WordArray.init(H.slice(0));
9553 },
9554
9555 _doProcessBlock: function (M, offset) {
9556 // Shortcut
9557 var H = this._hash.words;
9558
9559 // Working variables
9560 var a = H[0];
9561 var b = H[1];
9562 var c = H[2];
9563 var d = H[3];
9564 var e = H[4];
9565 var f = H[5];
9566 var g = H[6];
9567 var h = H[7];
9568
9569 // Computation
9570 for (var i = 0; i < 64; i++) {
9571 if (i < 16) {
9572 W[i] = M[offset + i] | 0;
9573 } else {
9574 var gamma0x = W[i - 15];
9575 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
9576 ((gamma0x << 14) | (gamma0x >>> 18)) ^
9577 (gamma0x >>> 3);
9578
9579 var gamma1x = W[i - 2];
9580 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
9581 ((gamma1x << 13) | (gamma1x >>> 19)) ^
9582 (gamma1x >>> 10);
9583
9584 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
9585 }
9586
9587 var ch = (e & f) ^ (~e & g);
9588 var maj = (a & b) ^ (a & c) ^ (b & c);
9589
9590 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
9591 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
9592
9593 var t1 = h + sigma1 + ch + K[i] + W[i];
9594 var t2 = sigma0 + maj;
9595
9596 h = g;
9597 g = f;
9598 f = e;
9599 e = (d + t1) | 0;
9600 d = c;
9601 c = b;
9602 b = a;
9603 a = (t1 + t2) | 0;
9604 }
9605
9606 // Intermediate hash value
9607 H[0] = (H[0] + a) | 0;
9608 H[1] = (H[1] + b) | 0;
9609 H[2] = (H[2] + c) | 0;
9610 H[3] = (H[3] + d) | 0;
9611 H[4] = (H[4] + e) | 0;
9612 H[5] = (H[5] + f) | 0;
9613 H[6] = (H[6] + g) | 0;
9614 H[7] = (H[7] + h) | 0;
9615 },
9616
9617 _doFinalize: function () {
9618 // Shortcuts
9619 var data = this._data;
9620 var dataWords = data.words;
9621
9622 var nBitsTotal = this._nDataBytes * 8;
9623 var nBitsLeft = data.sigBytes * 8;
9624
9625 // Add padding
9626 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
9627 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
9628 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
9629 data.sigBytes = dataWords.length * 4;
9630
9631 // Hash final blocks
9632 this._process();
9633
9634 // Return final computed hash
9635 return this._hash;
9636 },
9637
9638 clone: function () {
9639 var clone = Hasher.clone.call(this);
9640 clone._hash = this._hash.clone();
9641
9642 return clone;
9643 }
9644 });
9645
9646 /**
9647 * Shortcut function to the hasher's object interface.
9648 *
9649 * @param {WordArray|string} message The message to hash.
9650 *
9651 * @return {WordArray} The hash.
9652 *
9653 * @static
9654 *
9655 * @example
9656 *
9657 * var hash = CryptoJS.SHA256('message');
9658 * var hash = CryptoJS.SHA256(wordArray);
9659 */
9660 C.SHA256 = Hasher._createHelper(SHA256);
9661
9662 /**
9663 * Shortcut function to the HMAC's object interface.
9664 *
9665 * @param {WordArray|string} message The message to hash.
9666 * @param {WordArray|string} key The secret key.
9667 *
9668 * @return {WordArray} The HMAC.
9669 *
9670 * @static
9671 *
9672 * @example
9673 *
9674 * var hmac = CryptoJS.HmacSHA256(message, key);
9675 */
9676 C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
9677 }(Math));
9678
9679
9680 return CryptoJS.SHA256;
9681
9682}));
9683},{"./core":31}],58:[function(_dereq_,module,exports){
9684;(function (root, factory, undef) {
9685 if (typeof exports === "object") {
9686 // CommonJS
9687 module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
9688 }
9689 else if (typeof define === "function" && define.amd) {
9690 // AMD
9691 define(["./core", "./x64-core"], factory);
9692 }
9693 else {
9694 // Global (browser)
9695 factory(root.CryptoJS);
9696 }
9697}(this, function (CryptoJS) {
9698
9699 (function (Math) {
9700 // Shortcuts
9701 var C = CryptoJS;
9702 var C_lib = C.lib;
9703 var WordArray = C_lib.WordArray;
9704 var Hasher = C_lib.Hasher;
9705 var C_x64 = C.x64;
9706 var X64Word = C_x64.Word;
9707 var C_algo = C.algo;
9708
9709 // Constants tables
9710 var RHO_OFFSETS = [];
9711 var PI_INDEXES = [];
9712 var ROUND_CONSTANTS = [];
9713
9714 // Compute Constants
9715 (function () {
9716 // Compute rho offset constants
9717 var x = 1, y = 0;
9718 for (var t = 0; t < 24; t++) {
9719 RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
9720
9721 var newX = y % 5;
9722 var newY = (2 * x + 3 * y) % 5;
9723 x = newX;
9724 y = newY;
9725 }
9726
9727 // Compute pi index constants
9728 for (var x = 0; x < 5; x++) {
9729 for (var y = 0; y < 5; y++) {
9730 PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
9731 }
9732 }
9733
9734 // Compute round constants
9735 var LFSR = 0x01;
9736 for (var i = 0; i < 24; i++) {
9737 var roundConstantMsw = 0;
9738 var roundConstantLsw = 0;
9739
9740 for (var j = 0; j < 7; j++) {
9741 if (LFSR & 0x01) {
9742 var bitPosition = (1 << j) - 1;
9743 if (bitPosition < 32) {
9744 roundConstantLsw ^= 1 << bitPosition;
9745 } else /* if (bitPosition >= 32) */ {
9746 roundConstantMsw ^= 1 << (bitPosition - 32);
9747 }
9748 }
9749
9750 // Compute next LFSR
9751 if (LFSR & 0x80) {
9752 // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
9753 LFSR = (LFSR << 1) ^ 0x71;
9754 } else {
9755 LFSR <<= 1;
9756 }
9757 }
9758
9759 ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
9760 }
9761 }());
9762
9763 // Reusable objects for temporary values
9764 var T = [];
9765 (function () {
9766 for (var i = 0; i < 25; i++) {
9767 T[i] = X64Word.create();
9768 }
9769 }());
9770
9771 /**
9772 * SHA-3 hash algorithm.
9773 */
9774 var SHA3 = C_algo.SHA3 = Hasher.extend({
9775 /**
9776 * Configuration options.
9777 *
9778 * @property {number} outputLength
9779 * The desired number of bits in the output hash.
9780 * Only values permitted are: 224, 256, 384, 512.
9781 * Default: 512
9782 */
9783 cfg: Hasher.cfg.extend({
9784 outputLength: 512
9785 }),
9786
9787 _doReset: function () {
9788 var state = this._state = []
9789 for (var i = 0; i < 25; i++) {
9790 state[i] = new X64Word.init();
9791 }
9792
9793 this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
9794 },
9795
9796 _doProcessBlock: function (M, offset) {
9797 // Shortcuts
9798 var state = this._state;
9799 var nBlockSizeLanes = this.blockSize / 2;
9800
9801 // Absorb
9802 for (var i = 0; i < nBlockSizeLanes; i++) {
9803 // Shortcuts
9804 var M2i = M[offset + 2 * i];
9805 var M2i1 = M[offset + 2 * i + 1];
9806
9807 // Swap endian
9808 M2i = (
9809 (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
9810 (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
9811 );
9812 M2i1 = (
9813 (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
9814 (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
9815 );
9816
9817 // Absorb message into state
9818 var lane = state[i];
9819 lane.high ^= M2i1;
9820 lane.low ^= M2i;
9821 }
9822
9823 // Rounds
9824 for (var round = 0; round < 24; round++) {
9825 // Theta
9826 for (var x = 0; x < 5; x++) {
9827 // Mix column lanes
9828 var tMsw = 0, tLsw = 0;
9829 for (var y = 0; y < 5; y++) {
9830 var lane = state[x + 5 * y];
9831 tMsw ^= lane.high;
9832 tLsw ^= lane.low;
9833 }
9834
9835 // Temporary values
9836 var Tx = T[x];
9837 Tx.high = tMsw;
9838 Tx.low = tLsw;
9839 }
9840 for (var x = 0; x < 5; x++) {
9841 // Shortcuts
9842 var Tx4 = T[(x + 4) % 5];
9843 var Tx1 = T[(x + 1) % 5];
9844 var Tx1Msw = Tx1.high;
9845 var Tx1Lsw = Tx1.low;
9846
9847 // Mix surrounding columns
9848 var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
9849 var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
9850 for (var y = 0; y < 5; y++) {
9851 var lane = state[x + 5 * y];
9852 lane.high ^= tMsw;
9853 lane.low ^= tLsw;
9854 }
9855 }
9856
9857 // Rho Pi
9858 for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
9859 // Shortcuts
9860 var lane = state[laneIndex];
9861 var laneMsw = lane.high;
9862 var laneLsw = lane.low;
9863 var rhoOffset = RHO_OFFSETS[laneIndex];
9864
9865 // Rotate lanes
9866 if (rhoOffset < 32) {
9867 var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
9868 var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
9869 } else /* if (rhoOffset >= 32) */ {
9870 var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
9871 var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
9872 }
9873
9874 // Transpose lanes
9875 var TPiLane = T[PI_INDEXES[laneIndex]];
9876 TPiLane.high = tMsw;
9877 TPiLane.low = tLsw;
9878 }
9879
9880 // Rho pi at x = y = 0
9881 var T0 = T[0];
9882 var state0 = state[0];
9883 T0.high = state0.high;
9884 T0.low = state0.low;
9885
9886 // Chi
9887 for (var x = 0; x < 5; x++) {
9888 for (var y = 0; y < 5; y++) {
9889 // Shortcuts
9890 var laneIndex = x + 5 * y;
9891 var lane = state[laneIndex];
9892 var TLane = T[laneIndex];
9893 var Tx1Lane = T[((x + 1) % 5) + 5 * y];
9894 var Tx2Lane = T[((x + 2) % 5) + 5 * y];
9895
9896 // Mix rows
9897 lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
9898 lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
9899 }
9900 }
9901
9902 // Iota
9903 var lane = state[0];
9904 var roundConstant = ROUND_CONSTANTS[round];
9905 lane.high ^= roundConstant.high;
9906 lane.low ^= roundConstant.low;;
9907 }
9908 },
9909
9910 _doFinalize: function () {
9911 // Shortcuts
9912 var data = this._data;
9913 var dataWords = data.words;
9914 var nBitsTotal = this._nDataBytes * 8;
9915 var nBitsLeft = data.sigBytes * 8;
9916 var blockSizeBits = this.blockSize * 32;
9917
9918 // Add padding
9919 dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
9920 dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
9921 data.sigBytes = dataWords.length * 4;
9922
9923 // Hash final blocks
9924 this._process();
9925
9926 // Shortcuts
9927 var state = this._state;
9928 var outputLengthBytes = this.cfg.outputLength / 8;
9929 var outputLengthLanes = outputLengthBytes / 8;
9930
9931 // Squeeze
9932 var hashWords = [];
9933 for (var i = 0; i < outputLengthLanes; i++) {
9934 // Shortcuts
9935 var lane = state[i];
9936 var laneMsw = lane.high;
9937 var laneLsw = lane.low;
9938
9939 // Swap endian
9940 laneMsw = (
9941 (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
9942 (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
9943 );
9944 laneLsw = (
9945 (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
9946 (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
9947 );
9948
9949 // Squeeze state to retrieve hash
9950 hashWords.push(laneLsw);
9951 hashWords.push(laneMsw);
9952 }
9953
9954 // Return final computed hash
9955 return new WordArray.init(hashWords, outputLengthBytes);
9956 },
9957
9958 clone: function () {
9959 var clone = Hasher.clone.call(this);
9960
9961 var state = clone._state = this._state.slice(0);
9962 for (var i = 0; i < 25; i++) {
9963 state[i] = state[i].clone();
9964 }
9965
9966 return clone;
9967 }
9968 });
9969
9970 /**
9971 * Shortcut function to the hasher's object interface.
9972 *
9973 * @param {WordArray|string} message The message to hash.
9974 *
9975 * @return {WordArray} The hash.
9976 *
9977 * @static
9978 *
9979 * @example
9980 *
9981 * var hash = CryptoJS.SHA3('message');
9982 * var hash = CryptoJS.SHA3(wordArray);
9983 */
9984 C.SHA3 = Hasher._createHelper(SHA3);
9985
9986 /**
9987 * Shortcut function to the HMAC's object interface.
9988 *
9989 * @param {WordArray|string} message The message to hash.
9990 * @param {WordArray|string} key The secret key.
9991 *
9992 * @return {WordArray} The HMAC.
9993 *
9994 * @static
9995 *
9996 * @example
9997 *
9998 * var hmac = CryptoJS.HmacSHA3(message, key);
9999 */
10000 C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
10001 }(Math));
10002
10003
10004 return CryptoJS.SHA3;
10005
10006}));
10007},{"./core":31,"./x64-core":62}],59:[function(_dereq_,module,exports){
10008;(function (root, factory, undef) {
10009 if (typeof exports === "object") {
10010 // CommonJS
10011 module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
10012 }
10013 else if (typeof define === "function" && define.amd) {
10014 // AMD
10015 define(["./core", "./x64-core", "./sha512"], factory);
10016 }
10017 else {
10018 // Global (browser)
10019 factory(root.CryptoJS);
10020 }
10021}(this, function (CryptoJS) {
10022
10023 (function () {
10024 // Shortcuts
10025 var C = CryptoJS;
10026 var C_x64 = C.x64;
10027 var X64Word = C_x64.Word;
10028 var X64WordArray = C_x64.WordArray;
10029 var C_algo = C.algo;
10030 var SHA512 = C_algo.SHA512;
10031
10032 /**
10033 * SHA-384 hash algorithm.
10034 */
10035 var SHA384 = C_algo.SHA384 = SHA512.extend({
10036 _doReset: function () {
10037 this._hash = new X64WordArray.init([
10038 new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
10039 new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
10040 new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
10041 new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
10042 ]);
10043 },
10044
10045 _doFinalize: function () {
10046 var hash = SHA512._doFinalize.call(this);
10047
10048 hash.sigBytes -= 16;
10049
10050 return hash;
10051 }
10052 });
10053
10054 /**
10055 * Shortcut function to the hasher's object interface.
10056 *
10057 * @param {WordArray|string} message The message to hash.
10058 *
10059 * @return {WordArray} The hash.
10060 *
10061 * @static
10062 *
10063 * @example
10064 *
10065 * var hash = CryptoJS.SHA384('message');
10066 * var hash = CryptoJS.SHA384(wordArray);
10067 */
10068 C.SHA384 = SHA512._createHelper(SHA384);
10069
10070 /**
10071 * Shortcut function to the HMAC's object interface.
10072 *
10073 * @param {WordArray|string} message The message to hash.
10074 * @param {WordArray|string} key The secret key.
10075 *
10076 * @return {WordArray} The HMAC.
10077 *
10078 * @static
10079 *
10080 * @example
10081 *
10082 * var hmac = CryptoJS.HmacSHA384(message, key);
10083 */
10084 C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
10085 }());
10086
10087
10088 return CryptoJS.SHA384;
10089
10090}));
10091},{"./core":31,"./sha512":60,"./x64-core":62}],60:[function(_dereq_,module,exports){
10092;(function (root, factory, undef) {
10093 if (typeof exports === "object") {
10094 // CommonJS
10095 module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
10096 }
10097 else if (typeof define === "function" && define.amd) {
10098 // AMD
10099 define(["./core", "./x64-core"], factory);
10100 }
10101 else {
10102 // Global (browser)
10103 factory(root.CryptoJS);
10104 }
10105}(this, function (CryptoJS) {
10106
10107 (function () {
10108 // Shortcuts
10109 var C = CryptoJS;
10110 var C_lib = C.lib;
10111 var Hasher = C_lib.Hasher;
10112 var C_x64 = C.x64;
10113 var X64Word = C_x64.Word;
10114 var X64WordArray = C_x64.WordArray;
10115 var C_algo = C.algo;
10116
10117 function X64Word_create() {
10118 return X64Word.create.apply(X64Word, arguments);
10119 }
10120
10121 // Constants
10122 var K = [
10123 X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
10124 X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
10125 X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
10126 X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
10127 X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
10128 X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
10129 X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
10130 X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
10131 X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
10132 X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
10133 X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
10134 X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
10135 X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
10136 X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
10137 X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
10138 X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
10139 X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
10140 X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
10141 X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
10142 X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
10143 X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
10144 X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
10145 X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
10146 X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
10147 X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
10148 X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
10149 X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
10150 X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
10151 X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
10152 X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
10153 X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
10154 X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
10155 X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
10156 X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
10157 X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
10158 X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
10159 X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
10160 X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
10161 X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
10162 X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
10163 ];
10164
10165 // Reusable objects
10166 var W = [];
10167 (function () {
10168 for (var i = 0; i < 80; i++) {
10169 W[i] = X64Word_create();
10170 }
10171 }());
10172
10173 /**
10174 * SHA-512 hash algorithm.
10175 */
10176 var SHA512 = C_algo.SHA512 = Hasher.extend({
10177 _doReset: function () {
10178 this._hash = new X64WordArray.init([
10179 new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
10180 new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
10181 new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
10182 new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
10183 ]);
10184 },
10185
10186 _doProcessBlock: function (M, offset) {
10187 // Shortcuts
10188 var H = this._hash.words;
10189
10190 var H0 = H[0];
10191 var H1 = H[1];
10192 var H2 = H[2];
10193 var H3 = H[3];
10194 var H4 = H[4];
10195 var H5 = H[5];
10196 var H6 = H[6];
10197 var H7 = H[7];
10198
10199 var H0h = H0.high;
10200 var H0l = H0.low;
10201 var H1h = H1.high;
10202 var H1l = H1.low;
10203 var H2h = H2.high;
10204 var H2l = H2.low;
10205 var H3h = H3.high;
10206 var H3l = H3.low;
10207 var H4h = H4.high;
10208 var H4l = H4.low;
10209 var H5h = H5.high;
10210 var H5l = H5.low;
10211 var H6h = H6.high;
10212 var H6l = H6.low;
10213 var H7h = H7.high;
10214 var H7l = H7.low;
10215
10216 // Working variables
10217 var ah = H0h;
10218 var al = H0l;
10219 var bh = H1h;
10220 var bl = H1l;
10221 var ch = H2h;
10222 var cl = H2l;
10223 var dh = H3h;
10224 var dl = H3l;
10225 var eh = H4h;
10226 var el = H4l;
10227 var fh = H5h;
10228 var fl = H5l;
10229 var gh = H6h;
10230 var gl = H6l;
10231 var hh = H7h;
10232 var hl = H7l;
10233
10234 // Rounds
10235 for (var i = 0; i < 80; i++) {
10236 // Shortcut
10237 var Wi = W[i];
10238
10239 // Extend message
10240 if (i < 16) {
10241 var Wih = Wi.high = M[offset + i * 2] | 0;
10242 var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
10243 } else {
10244 // Gamma0
10245 var gamma0x = W[i - 15];
10246 var gamma0xh = gamma0x.high;
10247 var gamma0xl = gamma0x.low;
10248 var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
10249 var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
10250
10251 // Gamma1
10252 var gamma1x = W[i - 2];
10253 var gamma1xh = gamma1x.high;
10254 var gamma1xl = gamma1x.low;
10255 var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
10256 var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
10257
10258 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
10259 var Wi7 = W[i - 7];
10260 var Wi7h = Wi7.high;
10261 var Wi7l = Wi7.low;
10262
10263 var Wi16 = W[i - 16];
10264 var Wi16h = Wi16.high;
10265 var Wi16l = Wi16.low;
10266
10267 var Wil = gamma0l + Wi7l;
10268 var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
10269 var Wil = Wil + gamma1l;
10270 var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
10271 var Wil = Wil + Wi16l;
10272 var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
10273
10274 Wi.high = Wih;
10275 Wi.low = Wil;
10276 }
10277
10278 var chh = (eh & fh) ^ (~eh & gh);
10279 var chl = (el & fl) ^ (~el & gl);
10280 var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
10281 var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
10282
10283 var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
10284 var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
10285 var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
10286 var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
10287
10288 // t1 = h + sigma1 + ch + K[i] + W[i]
10289 var Ki = K[i];
10290 var Kih = Ki.high;
10291 var Kil = Ki.low;
10292
10293 var t1l = hl + sigma1l;
10294 var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
10295 var t1l = t1l + chl;
10296 var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
10297 var t1l = t1l + Kil;
10298 var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
10299 var t1l = t1l + Wil;
10300 var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
10301
10302 // t2 = sigma0 + maj
10303 var t2l = sigma0l + majl;
10304 var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
10305
10306 // Update working variables
10307 hh = gh;
10308 hl = gl;
10309 gh = fh;
10310 gl = fl;
10311 fh = eh;
10312 fl = el;
10313 el = (dl + t1l) | 0;
10314 eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
10315 dh = ch;
10316 dl = cl;
10317 ch = bh;
10318 cl = bl;
10319 bh = ah;
10320 bl = al;
10321 al = (t1l + t2l) | 0;
10322 ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
10323 }
10324
10325 // Intermediate hash value
10326 H0l = H0.low = (H0l + al);
10327 H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
10328 H1l = H1.low = (H1l + bl);
10329 H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
10330 H2l = H2.low = (H2l + cl);
10331 H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
10332 H3l = H3.low = (H3l + dl);
10333 H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
10334 H4l = H4.low = (H4l + el);
10335 H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
10336 H5l = H5.low = (H5l + fl);
10337 H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
10338 H6l = H6.low = (H6l + gl);
10339 H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
10340 H7l = H7.low = (H7l + hl);
10341 H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
10342 },
10343
10344 _doFinalize: function () {
10345 // Shortcuts
10346 var data = this._data;
10347 var dataWords = data.words;
10348
10349 var nBitsTotal = this._nDataBytes * 8;
10350 var nBitsLeft = data.sigBytes * 8;
10351
10352 // Add padding
10353 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
10354 dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
10355 dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
10356 data.sigBytes = dataWords.length * 4;
10357
10358 // Hash final blocks
10359 this._process();
10360
10361 // Convert hash to 32-bit word array before returning
10362 var hash = this._hash.toX32();
10363
10364 // Return final computed hash
10365 return hash;
10366 },
10367
10368 clone: function () {
10369 var clone = Hasher.clone.call(this);
10370 clone._hash = this._hash.clone();
10371
10372 return clone;
10373 },
10374
10375 blockSize: 1024/32
10376 });
10377
10378 /**
10379 * Shortcut function to the hasher's object interface.
10380 *
10381 * @param {WordArray|string} message The message to hash.
10382 *
10383 * @return {WordArray} The hash.
10384 *
10385 * @static
10386 *
10387 * @example
10388 *
10389 * var hash = CryptoJS.SHA512('message');
10390 * var hash = CryptoJS.SHA512(wordArray);
10391 */
10392 C.SHA512 = Hasher._createHelper(SHA512);
10393
10394 /**
10395 * Shortcut function to the HMAC's object interface.
10396 *
10397 * @param {WordArray|string} message The message to hash.
10398 * @param {WordArray|string} key The secret key.
10399 *
10400 * @return {WordArray} The HMAC.
10401 *
10402 * @static
10403 *
10404 * @example
10405 *
10406 * var hmac = CryptoJS.HmacSHA512(message, key);
10407 */
10408 C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
10409 }());
10410
10411
10412 return CryptoJS.SHA512;
10413
10414}));
10415},{"./core":31,"./x64-core":62}],61:[function(_dereq_,module,exports){
10416;(function (root, factory, undef) {
10417 if (typeof exports === "object") {
10418 // CommonJS
10419 module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
10420 }
10421 else if (typeof define === "function" && define.amd) {
10422 // AMD
10423 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
10424 }
10425 else {
10426 // Global (browser)
10427 factory(root.CryptoJS);
10428 }
10429}(this, function (CryptoJS) {
10430
10431 (function () {
10432 // Shortcuts
10433 var C = CryptoJS;
10434 var C_lib = C.lib;
10435 var WordArray = C_lib.WordArray;
10436 var BlockCipher = C_lib.BlockCipher;
10437 var C_algo = C.algo;
10438
10439 // Permuted Choice 1 constants
10440 var PC1 = [
10441 57, 49, 41, 33, 25, 17, 9, 1,
10442 58, 50, 42, 34, 26, 18, 10, 2,
10443 59, 51, 43, 35, 27, 19, 11, 3,
10444 60, 52, 44, 36, 63, 55, 47, 39,
10445 31, 23, 15, 7, 62, 54, 46, 38,
10446 30, 22, 14, 6, 61, 53, 45, 37,
10447 29, 21, 13, 5, 28, 20, 12, 4
10448 ];
10449
10450 // Permuted Choice 2 constants
10451 var PC2 = [
10452 14, 17, 11, 24, 1, 5,
10453 3, 28, 15, 6, 21, 10,
10454 23, 19, 12, 4, 26, 8,
10455 16, 7, 27, 20, 13, 2,
10456 41, 52, 31, 37, 47, 55,
10457 30, 40, 51, 45, 33, 48,
10458 44, 49, 39, 56, 34, 53,
10459 46, 42, 50, 36, 29, 32
10460 ];
10461
10462 // Cumulative bit shift constants
10463 var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
10464
10465 // SBOXes and round permutation constants
10466 var SBOX_P = [
10467 {
10468 0x0: 0x808200,
10469 0x10000000: 0x8000,
10470 0x20000000: 0x808002,
10471 0x30000000: 0x2,
10472 0x40000000: 0x200,
10473 0x50000000: 0x808202,
10474 0x60000000: 0x800202,
10475 0x70000000: 0x800000,
10476 0x80000000: 0x202,
10477 0x90000000: 0x800200,
10478 0xa0000000: 0x8200,
10479 0xb0000000: 0x808000,
10480 0xc0000000: 0x8002,
10481 0xd0000000: 0x800002,
10482 0xe0000000: 0x0,
10483 0xf0000000: 0x8202,
10484 0x8000000: 0x0,
10485 0x18000000: 0x808202,
10486 0x28000000: 0x8202,
10487 0x38000000: 0x8000,
10488 0x48000000: 0x808200,
10489 0x58000000: 0x200,
10490 0x68000000: 0x808002,
10491 0x78000000: 0x2,
10492 0x88000000: 0x800200,
10493 0x98000000: 0x8200,
10494 0xa8000000: 0x808000,
10495 0xb8000000: 0x800202,
10496 0xc8000000: 0x800002,
10497 0xd8000000: 0x8002,
10498 0xe8000000: 0x202,
10499 0xf8000000: 0x800000,
10500 0x1: 0x8000,
10501 0x10000001: 0x2,
10502 0x20000001: 0x808200,
10503 0x30000001: 0x800000,
10504 0x40000001: 0x808002,
10505 0x50000001: 0x8200,
10506 0x60000001: 0x200,
10507 0x70000001: 0x800202,
10508 0x80000001: 0x808202,
10509 0x90000001: 0x808000,
10510 0xa0000001: 0x800002,
10511 0xb0000001: 0x8202,
10512 0xc0000001: 0x202,
10513 0xd0000001: 0x800200,
10514 0xe0000001: 0x8002,
10515 0xf0000001: 0x0,
10516 0x8000001: 0x808202,
10517 0x18000001: 0x808000,
10518 0x28000001: 0x800000,
10519 0x38000001: 0x200,
10520 0x48000001: 0x8000,
10521 0x58000001: 0x800002,
10522 0x68000001: 0x2,
10523 0x78000001: 0x8202,
10524 0x88000001: 0x8002,
10525 0x98000001: 0x800202,
10526 0xa8000001: 0x202,
10527 0xb8000001: 0x808200,
10528 0xc8000001: 0x800200,
10529 0xd8000001: 0x0,
10530 0xe8000001: 0x8200,
10531 0xf8000001: 0x808002
10532 },
10533 {
10534 0x0: 0x40084010,
10535 0x1000000: 0x4000,
10536 0x2000000: 0x80000,
10537 0x3000000: 0x40080010,
10538 0x4000000: 0x40000010,
10539 0x5000000: 0x40084000,
10540 0x6000000: 0x40004000,
10541 0x7000000: 0x10,
10542 0x8000000: 0x84000,
10543 0x9000000: 0x40004010,
10544 0xa000000: 0x40000000,
10545 0xb000000: 0x84010,
10546 0xc000000: 0x80010,
10547 0xd000000: 0x0,
10548 0xe000000: 0x4010,
10549 0xf000000: 0x40080000,
10550 0x800000: 0x40004000,
10551 0x1800000: 0x84010,
10552 0x2800000: 0x10,
10553 0x3800000: 0x40004010,
10554 0x4800000: 0x40084010,
10555 0x5800000: 0x40000000,
10556 0x6800000: 0x80000,
10557 0x7800000: 0x40080010,
10558 0x8800000: 0x80010,
10559 0x9800000: 0x0,
10560 0xa800000: 0x4000,
10561 0xb800000: 0x40080000,
10562 0xc800000: 0x40000010,
10563 0xd800000: 0x84000,
10564 0xe800000: 0x40084000,
10565 0xf800000: 0x4010,
10566 0x10000000: 0x0,
10567 0x11000000: 0x40080010,
10568 0x12000000: 0x40004010,
10569 0x13000000: 0x40084000,
10570 0x14000000: 0x40080000,
10571 0x15000000: 0x10,
10572 0x16000000: 0x84010,
10573 0x17000000: 0x4000,
10574 0x18000000: 0x4010,
10575 0x19000000: 0x80000,
10576 0x1a000000: 0x80010,
10577 0x1b000000: 0x40000010,
10578 0x1c000000: 0x84000,
10579 0x1d000000: 0x40004000,
10580 0x1e000000: 0x40000000,
10581 0x1f000000: 0x40084010,
10582 0x10800000: 0x84010,
10583 0x11800000: 0x80000,
10584 0x12800000: 0x40080000,
10585 0x13800000: 0x4000,
10586 0x14800000: 0x40004000,
10587 0x15800000: 0x40084010,
10588 0x16800000: 0x10,
10589 0x17800000: 0x40000000,
10590 0x18800000: 0x40084000,
10591 0x19800000: 0x40000010,
10592 0x1a800000: 0x40004010,
10593 0x1b800000: 0x80010,
10594 0x1c800000: 0x0,
10595 0x1d800000: 0x4010,
10596 0x1e800000: 0x40080010,
10597 0x1f800000: 0x84000
10598 },
10599 {
10600 0x0: 0x104,
10601 0x100000: 0x0,
10602 0x200000: 0x4000100,
10603 0x300000: 0x10104,
10604 0x400000: 0x10004,
10605 0x500000: 0x4000004,
10606 0x600000: 0x4010104,
10607 0x700000: 0x4010000,
10608 0x800000: 0x4000000,
10609 0x900000: 0x4010100,
10610 0xa00000: 0x10100,
10611 0xb00000: 0x4010004,
10612 0xc00000: 0x4000104,
10613 0xd00000: 0x10000,
10614 0xe00000: 0x4,
10615 0xf00000: 0x100,
10616 0x80000: 0x4010100,
10617 0x180000: 0x4010004,
10618 0x280000: 0x0,
10619 0x380000: 0x4000100,
10620 0x480000: 0x4000004,
10621 0x580000: 0x10000,
10622 0x680000: 0x10004,
10623 0x780000: 0x104,
10624 0x880000: 0x4,
10625 0x980000: 0x100,
10626 0xa80000: 0x4010000,
10627 0xb80000: 0x10104,
10628 0xc80000: 0x10100,
10629 0xd80000: 0x4000104,
10630 0xe80000: 0x4010104,
10631 0xf80000: 0x4000000,
10632 0x1000000: 0x4010100,
10633 0x1100000: 0x10004,
10634 0x1200000: 0x10000,
10635 0x1300000: 0x4000100,
10636 0x1400000: 0x100,
10637 0x1500000: 0x4010104,
10638 0x1600000: 0x4000004,
10639 0x1700000: 0x0,
10640 0x1800000: 0x4000104,
10641 0x1900000: 0x4000000,
10642 0x1a00000: 0x4,
10643 0x1b00000: 0x10100,
10644 0x1c00000: 0x4010000,
10645 0x1d00000: 0x104,
10646 0x1e00000: 0x10104,
10647 0x1f00000: 0x4010004,
10648 0x1080000: 0x4000000,
10649 0x1180000: 0x104,
10650 0x1280000: 0x4010100,
10651 0x1380000: 0x0,
10652 0x1480000: 0x10004,
10653 0x1580000: 0x4000100,
10654 0x1680000: 0x100,
10655 0x1780000: 0x4010004,
10656 0x1880000: 0x10000,
10657 0x1980000: 0x4010104,
10658 0x1a80000: 0x10104,
10659 0x1b80000: 0x4000004,
10660 0x1c80000: 0x4000104,
10661 0x1d80000: 0x4010000,
10662 0x1e80000: 0x4,
10663 0x1f80000: 0x10100
10664 },
10665 {
10666 0x0: 0x80401000,
10667 0x10000: 0x80001040,
10668 0x20000: 0x401040,
10669 0x30000: 0x80400000,
10670 0x40000: 0x0,
10671 0x50000: 0x401000,
10672 0x60000: 0x80000040,
10673 0x70000: 0x400040,
10674 0x80000: 0x80000000,
10675 0x90000: 0x400000,
10676 0xa0000: 0x40,
10677 0xb0000: 0x80001000,
10678 0xc0000: 0x80400040,
10679 0xd0000: 0x1040,
10680 0xe0000: 0x1000,
10681 0xf0000: 0x80401040,
10682 0x8000: 0x80001040,
10683 0x18000: 0x40,
10684 0x28000: 0x80400040,
10685 0x38000: 0x80001000,
10686 0x48000: 0x401000,
10687 0x58000: 0x80401040,
10688 0x68000: 0x0,
10689 0x78000: 0x80400000,
10690 0x88000: 0x1000,
10691 0x98000: 0x80401000,
10692 0xa8000: 0x400000,
10693 0xb8000: 0x1040,
10694 0xc8000: 0x80000000,
10695 0xd8000: 0x400040,
10696 0xe8000: 0x401040,
10697 0xf8000: 0x80000040,
10698 0x100000: 0x400040,
10699 0x110000: 0x401000,
10700 0x120000: 0x80000040,
10701 0x130000: 0x0,
10702 0x140000: 0x1040,
10703 0x150000: 0x80400040,
10704 0x160000: 0x80401000,
10705 0x170000: 0x80001040,
10706 0x180000: 0x80401040,
10707 0x190000: 0x80000000,
10708 0x1a0000: 0x80400000,
10709 0x1b0000: 0x401040,
10710 0x1c0000: 0x80001000,
10711 0x1d0000: 0x400000,
10712 0x1e0000: 0x40,
10713 0x1f0000: 0x1000,
10714 0x108000: 0x80400000,
10715 0x118000: 0x80401040,
10716 0x128000: 0x0,
10717 0x138000: 0x401000,
10718 0x148000: 0x400040,
10719 0x158000: 0x80000000,
10720 0x168000: 0x80001040,
10721 0x178000: 0x40,
10722 0x188000: 0x80000040,
10723 0x198000: 0x1000,
10724 0x1a8000: 0x80001000,
10725 0x1b8000: 0x80400040,
10726 0x1c8000: 0x1040,
10727 0x1d8000: 0x80401000,
10728 0x1e8000: 0x400000,
10729 0x1f8000: 0x401040
10730 },
10731 {
10732 0x0: 0x80,
10733 0x1000: 0x1040000,
10734 0x2000: 0x40000,
10735 0x3000: 0x20000000,
10736 0x4000: 0x20040080,
10737 0x5000: 0x1000080,
10738 0x6000: 0x21000080,
10739 0x7000: 0x40080,
10740 0x8000: 0x1000000,
10741 0x9000: 0x20040000,
10742 0xa000: 0x20000080,
10743 0xb000: 0x21040080,
10744 0xc000: 0x21040000,
10745 0xd000: 0x0,
10746 0xe000: 0x1040080,
10747 0xf000: 0x21000000,
10748 0x800: 0x1040080,
10749 0x1800: 0x21000080,
10750 0x2800: 0x80,
10751 0x3800: 0x1040000,
10752 0x4800: 0x40000,
10753 0x5800: 0x20040080,
10754 0x6800: 0x21040000,
10755 0x7800: 0x20000000,
10756 0x8800: 0x20040000,
10757 0x9800: 0x0,
10758 0xa800: 0x21040080,
10759 0xb800: 0x1000080,
10760 0xc800: 0x20000080,
10761 0xd800: 0x21000000,
10762 0xe800: 0x1000000,
10763 0xf800: 0x40080,
10764 0x10000: 0x40000,
10765 0x11000: 0x80,
10766 0x12000: 0x20000000,
10767 0x13000: 0x21000080,
10768 0x14000: 0x1000080,
10769 0x15000: 0x21040000,
10770 0x16000: 0x20040080,
10771 0x17000: 0x1000000,
10772 0x18000: 0x21040080,
10773 0x19000: 0x21000000,
10774 0x1a000: 0x1040000,
10775 0x1b000: 0x20040000,
10776 0x1c000: 0x40080,
10777 0x1d000: 0x20000080,
10778 0x1e000: 0x0,
10779 0x1f000: 0x1040080,
10780 0x10800: 0x21000080,
10781 0x11800: 0x1000000,
10782 0x12800: 0x1040000,
10783 0x13800: 0x20040080,
10784 0x14800: 0x20000000,
10785 0x15800: 0x1040080,
10786 0x16800: 0x80,
10787 0x17800: 0x21040000,
10788 0x18800: 0x40080,
10789 0x19800: 0x21040080,
10790 0x1a800: 0x0,
10791 0x1b800: 0x21000000,
10792 0x1c800: 0x1000080,
10793 0x1d800: 0x40000,
10794 0x1e800: 0x20040000,
10795 0x1f800: 0x20000080
10796 },
10797 {
10798 0x0: 0x10000008,
10799 0x100: 0x2000,
10800 0x200: 0x10200000,
10801 0x300: 0x10202008,
10802 0x400: 0x10002000,
10803 0x500: 0x200000,
10804 0x600: 0x200008,
10805 0x700: 0x10000000,
10806 0x800: 0x0,
10807 0x900: 0x10002008,
10808 0xa00: 0x202000,
10809 0xb00: 0x8,
10810 0xc00: 0x10200008,
10811 0xd00: 0x202008,
10812 0xe00: 0x2008,
10813 0xf00: 0x10202000,
10814 0x80: 0x10200000,
10815 0x180: 0x10202008,
10816 0x280: 0x8,
10817 0x380: 0x200000,
10818 0x480: 0x202008,
10819 0x580: 0x10000008,
10820 0x680: 0x10002000,
10821 0x780: 0x2008,
10822 0x880: 0x200008,
10823 0x980: 0x2000,
10824 0xa80: 0x10002008,
10825 0xb80: 0x10200008,
10826 0xc80: 0x0,
10827 0xd80: 0x10202000,
10828 0xe80: 0x202000,
10829 0xf80: 0x10000000,
10830 0x1000: 0x10002000,
10831 0x1100: 0x10200008,
10832 0x1200: 0x10202008,
10833 0x1300: 0x2008,
10834 0x1400: 0x200000,
10835 0x1500: 0x10000000,
10836 0x1600: 0x10000008,
10837 0x1700: 0x202000,
10838 0x1800: 0x202008,
10839 0x1900: 0x0,
10840 0x1a00: 0x8,
10841 0x1b00: 0x10200000,
10842 0x1c00: 0x2000,
10843 0x1d00: 0x10002008,
10844 0x1e00: 0x10202000,
10845 0x1f00: 0x200008,
10846 0x1080: 0x8,
10847 0x1180: 0x202000,
10848 0x1280: 0x200000,
10849 0x1380: 0x10000008,
10850 0x1480: 0x10002000,
10851 0x1580: 0x2008,
10852 0x1680: 0x10202008,
10853 0x1780: 0x10200000,
10854 0x1880: 0x10202000,
10855 0x1980: 0x10200008,
10856 0x1a80: 0x2000,
10857 0x1b80: 0x202008,
10858 0x1c80: 0x200008,
10859 0x1d80: 0x0,
10860 0x1e80: 0x10000000,
10861 0x1f80: 0x10002008
10862 },
10863 {
10864 0x0: 0x100000,
10865 0x10: 0x2000401,
10866 0x20: 0x400,
10867 0x30: 0x100401,
10868 0x40: 0x2100401,
10869 0x50: 0x0,
10870 0x60: 0x1,
10871 0x70: 0x2100001,
10872 0x80: 0x2000400,
10873 0x90: 0x100001,
10874 0xa0: 0x2000001,
10875 0xb0: 0x2100400,
10876 0xc0: 0x2100000,
10877 0xd0: 0x401,
10878 0xe0: 0x100400,
10879 0xf0: 0x2000000,
10880 0x8: 0x2100001,
10881 0x18: 0x0,
10882 0x28: 0x2000401,
10883 0x38: 0x2100400,
10884 0x48: 0x100000,
10885 0x58: 0x2000001,
10886 0x68: 0x2000000,
10887 0x78: 0x401,
10888 0x88: 0x100401,
10889 0x98: 0x2000400,
10890 0xa8: 0x2100000,
10891 0xb8: 0x100001,
10892 0xc8: 0x400,
10893 0xd8: 0x2100401,
10894 0xe8: 0x1,
10895 0xf8: 0x100400,
10896 0x100: 0x2000000,
10897 0x110: 0x100000,
10898 0x120: 0x2000401,
10899 0x130: 0x2100001,
10900 0x140: 0x100001,
10901 0x150: 0x2000400,
10902 0x160: 0x2100400,
10903 0x170: 0x100401,
10904 0x180: 0x401,
10905 0x190: 0x2100401,
10906 0x1a0: 0x100400,
10907 0x1b0: 0x1,
10908 0x1c0: 0x0,
10909 0x1d0: 0x2100000,
10910 0x1e0: 0x2000001,
10911 0x1f0: 0x400,
10912 0x108: 0x100400,
10913 0x118: 0x2000401,
10914 0x128: 0x2100001,
10915 0x138: 0x1,
10916 0x148: 0x2000000,
10917 0x158: 0x100000,
10918 0x168: 0x401,
10919 0x178: 0x2100400,
10920 0x188: 0x2000001,
10921 0x198: 0x2100000,
10922 0x1a8: 0x0,
10923 0x1b8: 0x2100401,
10924 0x1c8: 0x100401,
10925 0x1d8: 0x400,
10926 0x1e8: 0x2000400,
10927 0x1f8: 0x100001
10928 },
10929 {
10930 0x0: 0x8000820,
10931 0x1: 0x20000,
10932 0x2: 0x8000000,
10933 0x3: 0x20,
10934 0x4: 0x20020,
10935 0x5: 0x8020820,
10936 0x6: 0x8020800,
10937 0x7: 0x800,
10938 0x8: 0x8020000,
10939 0x9: 0x8000800,
10940 0xa: 0x20800,
10941 0xb: 0x8020020,
10942 0xc: 0x820,
10943 0xd: 0x0,
10944 0xe: 0x8000020,
10945 0xf: 0x20820,
10946 0x80000000: 0x800,
10947 0x80000001: 0x8020820,
10948 0x80000002: 0x8000820,
10949 0x80000003: 0x8000000,
10950 0x80000004: 0x8020000,
10951 0x80000005: 0x20800,
10952 0x80000006: 0x20820,
10953 0x80000007: 0x20,
10954 0x80000008: 0x8000020,
10955 0x80000009: 0x820,
10956 0x8000000a: 0x20020,
10957 0x8000000b: 0x8020800,
10958 0x8000000c: 0x0,
10959 0x8000000d: 0x8020020,
10960 0x8000000e: 0x8000800,
10961 0x8000000f: 0x20000,
10962 0x10: 0x20820,
10963 0x11: 0x8020800,
10964 0x12: 0x20,
10965 0x13: 0x800,
10966 0x14: 0x8000800,
10967 0x15: 0x8000020,
10968 0x16: 0x8020020,
10969 0x17: 0x20000,
10970 0x18: 0x0,
10971 0x19: 0x20020,
10972 0x1a: 0x8020000,
10973 0x1b: 0x8000820,
10974 0x1c: 0x8020820,
10975 0x1d: 0x20800,
10976 0x1e: 0x820,
10977 0x1f: 0x8000000,
10978 0x80000010: 0x20000,
10979 0x80000011: 0x800,
10980 0x80000012: 0x8020020,
10981 0x80000013: 0x20820,
10982 0x80000014: 0x20,
10983 0x80000015: 0x8020000,
10984 0x80000016: 0x8000000,
10985 0x80000017: 0x8000820,
10986 0x80000018: 0x8020820,
10987 0x80000019: 0x8000020,
10988 0x8000001a: 0x8000800,
10989 0x8000001b: 0x0,
10990 0x8000001c: 0x20800,
10991 0x8000001d: 0x820,
10992 0x8000001e: 0x20020,
10993 0x8000001f: 0x8020800
10994 }
10995 ];
10996
10997 // Masks that select the SBOX input
10998 var SBOX_MASK = [
10999 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
11000 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
11001 ];
11002
11003 /**
11004 * DES block cipher algorithm.
11005 */
11006 var DES = C_algo.DES = BlockCipher.extend({
11007 _doReset: function () {
11008 // Shortcuts
11009 var key = this._key;
11010 var keyWords = key.words;
11011
11012 // Select 56 bits according to PC1
11013 var keyBits = [];
11014 for (var i = 0; i < 56; i++) {
11015 var keyBitPos = PC1[i] - 1;
11016 keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
11017 }
11018
11019 // Assemble 16 subkeys
11020 var subKeys = this._subKeys = [];
11021 for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
11022 // Create subkey
11023 var subKey = subKeys[nSubKey] = [];
11024
11025 // Shortcut
11026 var bitShift = BIT_SHIFTS[nSubKey];
11027
11028 // Select 48 bits according to PC2
11029 for (var i = 0; i < 24; i++) {
11030 // Select from the left 28 key bits
11031 subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
11032
11033 // Select from the right 28 key bits
11034 subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
11035 }
11036
11037 // Since each subkey is applied to an expanded 32-bit input,
11038 // the subkey can be broken into 8 values scaled to 32-bits,
11039 // which allows the key to be used without expansion
11040 subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
11041 for (var i = 1; i < 7; i++) {
11042 subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
11043 }
11044 subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
11045 }
11046
11047 // Compute inverse subkeys
11048 var invSubKeys = this._invSubKeys = [];
11049 for (var i = 0; i < 16; i++) {
11050 invSubKeys[i] = subKeys[15 - i];
11051 }
11052 },
11053
11054 encryptBlock: function (M, offset) {
11055 this._doCryptBlock(M, offset, this._subKeys);
11056 },
11057
11058 decryptBlock: function (M, offset) {
11059 this._doCryptBlock(M, offset, this._invSubKeys);
11060 },
11061
11062 _doCryptBlock: function (M, offset, subKeys) {
11063 // Get input
11064 this._lBlock = M[offset];
11065 this._rBlock = M[offset + 1];
11066
11067 // Initial permutation
11068 exchangeLR.call(this, 4, 0x0f0f0f0f);
11069 exchangeLR.call(this, 16, 0x0000ffff);
11070 exchangeRL.call(this, 2, 0x33333333);
11071 exchangeRL.call(this, 8, 0x00ff00ff);
11072 exchangeLR.call(this, 1, 0x55555555);
11073
11074 // Rounds
11075 for (var round = 0; round < 16; round++) {
11076 // Shortcuts
11077 var subKey = subKeys[round];
11078 var lBlock = this._lBlock;
11079 var rBlock = this._rBlock;
11080
11081 // Feistel function
11082 var f = 0;
11083 for (var i = 0; i < 8; i++) {
11084 f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
11085 }
11086 this._lBlock = rBlock;
11087 this._rBlock = lBlock ^ f;
11088 }
11089
11090 // Undo swap from last round
11091 var t = this._lBlock;
11092 this._lBlock = this._rBlock;
11093 this._rBlock = t;
11094
11095 // Final permutation
11096 exchangeLR.call(this, 1, 0x55555555);
11097 exchangeRL.call(this, 8, 0x00ff00ff);
11098 exchangeRL.call(this, 2, 0x33333333);
11099 exchangeLR.call(this, 16, 0x0000ffff);
11100 exchangeLR.call(this, 4, 0x0f0f0f0f);
11101
11102 // Set output
11103 M[offset] = this._lBlock;
11104 M[offset + 1] = this._rBlock;
11105 },
11106
11107 keySize: 64/32,
11108
11109 ivSize: 64/32,
11110
11111 blockSize: 64/32
11112 });
11113
11114 // Swap bits across the left and right words
11115 function exchangeLR(offset, mask) {
11116 var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
11117 this._rBlock ^= t;
11118 this._lBlock ^= t << offset;
11119 }
11120
11121 function exchangeRL(offset, mask) {
11122 var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
11123 this._lBlock ^= t;
11124 this._rBlock ^= t << offset;
11125 }
11126
11127 /**
11128 * Shortcut functions to the cipher's object interface.
11129 *
11130 * @example
11131 *
11132 * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
11133 * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
11134 */
11135 C.DES = BlockCipher._createHelper(DES);
11136
11137 /**
11138 * Triple-DES block cipher algorithm.
11139 */
11140 var TripleDES = C_algo.TripleDES = BlockCipher.extend({
11141 _doReset: function () {
11142 // Shortcuts
11143 var key = this._key;
11144 var keyWords = key.words;
11145
11146 // Create DES instances
11147 this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
11148 this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
11149 this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
11150 },
11151
11152 encryptBlock: function (M, offset) {
11153 this._des1.encryptBlock(M, offset);
11154 this._des2.decryptBlock(M, offset);
11155 this._des3.encryptBlock(M, offset);
11156 },
11157
11158 decryptBlock: function (M, offset) {
11159 this._des3.decryptBlock(M, offset);
11160 this._des2.encryptBlock(M, offset);
11161 this._des1.decryptBlock(M, offset);
11162 },
11163
11164 keySize: 192/32,
11165
11166 ivSize: 64/32,
11167
11168 blockSize: 64/32
11169 });
11170
11171 /**
11172 * Shortcut functions to the cipher's object interface.
11173 *
11174 * @example
11175 *
11176 * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
11177 * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
11178 */
11179 C.TripleDES = BlockCipher._createHelper(TripleDES);
11180 }());
11181
11182
11183 return CryptoJS.TripleDES;
11184
11185}));
11186},{"./cipher-core":30,"./core":31,"./enc-base64":32,"./evpkdf":34,"./md5":39}],62:[function(_dereq_,module,exports){
11187;(function (root, factory) {
11188 if (typeof exports === "object") {
11189 // CommonJS
11190 module.exports = exports = factory(_dereq_("./core"));
11191 }
11192 else if (typeof define === "function" && define.amd) {
11193 // AMD
11194 define(["./core"], factory);
11195 }
11196 else {
11197 // Global (browser)
11198 factory(root.CryptoJS);
11199 }
11200}(this, function (CryptoJS) {
11201
11202 (function (undefined) {
11203 // Shortcuts
11204 var C = CryptoJS;
11205 var C_lib = C.lib;
11206 var Base = C_lib.Base;
11207 var X32WordArray = C_lib.WordArray;
11208
11209 /**
11210 * x64 namespace.
11211 */
11212 var C_x64 = C.x64 = {};
11213
11214 /**
11215 * A 64-bit word.
11216 */
11217 var X64Word = C_x64.Word = Base.extend({
11218 /**
11219 * Initializes a newly created 64-bit word.
11220 *
11221 * @param {number} high The high 32 bits.
11222 * @param {number} low The low 32 bits.
11223 *
11224 * @example
11225 *
11226 * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
11227 */
11228 init: function (high, low) {
11229 this.high = high;
11230 this.low = low;
11231 }
11232
11233 /**
11234 * Bitwise NOTs this word.
11235 *
11236 * @return {X64Word} A new x64-Word object after negating.
11237 *
11238 * @example
11239 *
11240 * var negated = x64Word.not();
11241 */
11242 // not: function () {
11243 // var high = ~this.high;
11244 // var low = ~this.low;
11245
11246 // return X64Word.create(high, low);
11247 // },
11248
11249 /**
11250 * Bitwise ANDs this word with the passed word.
11251 *
11252 * @param {X64Word} word The x64-Word to AND with this word.
11253 *
11254 * @return {X64Word} A new x64-Word object after ANDing.
11255 *
11256 * @example
11257 *
11258 * var anded = x64Word.and(anotherX64Word);
11259 */
11260 // and: function (word) {
11261 // var high = this.high & word.high;
11262 // var low = this.low & word.low;
11263
11264 // return X64Word.create(high, low);
11265 // },
11266
11267 /**
11268 * Bitwise ORs this word with the passed word.
11269 *
11270 * @param {X64Word} word The x64-Word to OR with this word.
11271 *
11272 * @return {X64Word} A new x64-Word object after ORing.
11273 *
11274 * @example
11275 *
11276 * var ored = x64Word.or(anotherX64Word);
11277 */
11278 // or: function (word) {
11279 // var high = this.high | word.high;
11280 // var low = this.low | word.low;
11281
11282 // return X64Word.create(high, low);
11283 // },
11284
11285 /**
11286 * Bitwise XORs this word with the passed word.
11287 *
11288 * @param {X64Word} word The x64-Word to XOR with this word.
11289 *
11290 * @return {X64Word} A new x64-Word object after XORing.
11291 *
11292 * @example
11293 *
11294 * var xored = x64Word.xor(anotherX64Word);
11295 */
11296 // xor: function (word) {
11297 // var high = this.high ^ word.high;
11298 // var low = this.low ^ word.low;
11299
11300 // return X64Word.create(high, low);
11301 // },
11302
11303 /**
11304 * Shifts this word n bits to the left.
11305 *
11306 * @param {number} n The number of bits to shift.
11307 *
11308 * @return {X64Word} A new x64-Word object after shifting.
11309 *
11310 * @example
11311 *
11312 * var shifted = x64Word.shiftL(25);
11313 */
11314 // shiftL: function (n) {
11315 // if (n < 32) {
11316 // var high = (this.high << n) | (this.low >>> (32 - n));
11317 // var low = this.low << n;
11318 // } else {
11319 // var high = this.low << (n - 32);
11320 // var low = 0;
11321 // }
11322
11323 // return X64Word.create(high, low);
11324 // },
11325
11326 /**
11327 * Shifts this word n bits to the right.
11328 *
11329 * @param {number} n The number of bits to shift.
11330 *
11331 * @return {X64Word} A new x64-Word object after shifting.
11332 *
11333 * @example
11334 *
11335 * var shifted = x64Word.shiftR(7);
11336 */
11337 // shiftR: function (n) {
11338 // if (n < 32) {
11339 // var low = (this.low >>> n) | (this.high << (32 - n));
11340 // var high = this.high >>> n;
11341 // } else {
11342 // var low = this.high >>> (n - 32);
11343 // var high = 0;
11344 // }
11345
11346 // return X64Word.create(high, low);
11347 // },
11348
11349 /**
11350 * Rotates this word n bits to the left.
11351 *
11352 * @param {number} n The number of bits to rotate.
11353 *
11354 * @return {X64Word} A new x64-Word object after rotating.
11355 *
11356 * @example
11357 *
11358 * var rotated = x64Word.rotL(25);
11359 */
11360 // rotL: function (n) {
11361 // return this.shiftL(n).or(this.shiftR(64 - n));
11362 // },
11363
11364 /**
11365 * Rotates this word n bits to the right.
11366 *
11367 * @param {number} n The number of bits to rotate.
11368 *
11369 * @return {X64Word} A new x64-Word object after rotating.
11370 *
11371 * @example
11372 *
11373 * var rotated = x64Word.rotR(7);
11374 */
11375 // rotR: function (n) {
11376 // return this.shiftR(n).or(this.shiftL(64 - n));
11377 // },
11378
11379 /**
11380 * Adds this word with the passed word.
11381 *
11382 * @param {X64Word} word The x64-Word to add with this word.
11383 *
11384 * @return {X64Word} A new x64-Word object after adding.
11385 *
11386 * @example
11387 *
11388 * var added = x64Word.add(anotherX64Word);
11389 */
11390 // add: function (word) {
11391 // var low = (this.low + word.low) | 0;
11392 // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
11393 // var high = (this.high + word.high + carry) | 0;
11394
11395 // return X64Word.create(high, low);
11396 // }
11397 });
11398
11399 /**
11400 * An array of 64-bit words.
11401 *
11402 * @property {Array} words The array of CryptoJS.x64.Word objects.
11403 * @property {number} sigBytes The number of significant bytes in this word array.
11404 */
11405 var X64WordArray = C_x64.WordArray = Base.extend({
11406 /**
11407 * Initializes a newly created word array.
11408 *
11409 * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
11410 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
11411 *
11412 * @example
11413 *
11414 * var wordArray = CryptoJS.x64.WordArray.create();
11415 *
11416 * var wordArray = CryptoJS.x64.WordArray.create([
11417 * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
11418 * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
11419 * ]);
11420 *
11421 * var wordArray = CryptoJS.x64.WordArray.create([
11422 * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
11423 * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
11424 * ], 10);
11425 */
11426 init: function (words, sigBytes) {
11427 words = this.words = words || [];
11428
11429 if (sigBytes != undefined) {
11430 this.sigBytes = sigBytes;
11431 } else {
11432 this.sigBytes = words.length * 8;
11433 }
11434 },
11435
11436 /**
11437 * Converts this 64-bit word array to a 32-bit word array.
11438 *
11439 * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
11440 *
11441 * @example
11442 *
11443 * var x32WordArray = x64WordArray.toX32();
11444 */
11445 toX32: function () {
11446 // Shortcuts
11447 var x64Words = this.words;
11448 var x64WordsLength = x64Words.length;
11449
11450 // Convert
11451 var x32Words = [];
11452 for (var i = 0; i < x64WordsLength; i++) {
11453 var x64Word = x64Words[i];
11454 x32Words.push(x64Word.high);
11455 x32Words.push(x64Word.low);
11456 }
11457
11458 return X32WordArray.create(x32Words, this.sigBytes);
11459 },
11460
11461 /**
11462 * Creates a copy of this word array.
11463 *
11464 * @return {X64WordArray} The clone.
11465 *
11466 * @example
11467 *
11468 * var clone = x64WordArray.clone();
11469 */
11470 clone: function () {
11471 var clone = Base.clone.call(this);
11472
11473 // Clone "words" array
11474 var words = clone.words = this.words.slice(0);
11475
11476 // Clone each X64Word object
11477 var wordsLength = words.length;
11478 for (var i = 0; i < wordsLength; i++) {
11479 words[i] = words[i].clone();
11480 }
11481
11482 return clone;
11483 }
11484 });
11485 }());
11486
11487
11488 return CryptoJS;
11489
11490}));
11491},{"./core":31}],63:[function(_dereq_,module,exports){
11492var assert = _dereq_('assert')
11493var BigInteger = _dereq_('bigi')
11494
11495var Point = _dereq_('./point')
11496
11497function Curve(p, a, b, Gx, Gy, n, h) {
11498 this.p = p
11499 this.a = a
11500 this.b = b
11501 this.G = Point.fromAffine(this, Gx, Gy)
11502 this.n = n
11503 this.h = h
11504
11505 this.infinity = new Point(this, null, null, BigInteger.ZERO)
11506
11507 // result caching
11508 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
11509}
11510
11511Curve.prototype.pointFromX = function(isOdd, x) {
11512 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
11513 var beta = alpha.modPow(this.pOverFour, this.p)
11514
11515 var y = beta
11516 if (beta.isEven() ^ !isOdd) {
11517 y = this.p.subtract(y) // -y % p
11518 }
11519
11520 return Point.fromAffine(this, x, y)
11521}
11522
11523Curve.prototype.isInfinity = function(Q) {
11524 if (Q === this.infinity) return true
11525
11526 return Q.z.signum() === 0 && Q.y.signum() !== 0
11527}
11528
11529Curve.prototype.isOnCurve = function(Q) {
11530 if (this.isInfinity(Q)) return true
11531
11532 var x = Q.affineX
11533 var y = Q.affineY
11534 var a = this.a
11535 var b = this.b
11536 var p = this.p
11537
11538 // Check that xQ and yQ are integers in the interval [0, p - 1]
11539 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
11540 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
11541
11542 // and check that y^2 = x^3 + ax + b (mod p)
11543 var lhs = y.square().mod(p)
11544 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
11545 return lhs.equals(rhs)
11546}
11547
11548/**
11549 * Validate an elliptic curve point.
11550 *
11551 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
11552 */
11553Curve.prototype.validate = function(Q) {
11554 // Check Q != O
11555 assert(!this.isInfinity(Q), 'Point is at infinity')
11556 assert(this.isOnCurve(Q), 'Point is not on the curve')
11557
11558 // Check nQ = O (where Q is a scalar multiple of G)
11559 var nQ = Q.multiply(this.n)
11560 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
11561
11562 return true
11563}
11564
11565module.exports = Curve
11566
11567},{"./point":67,"assert":4,"bigi":3}],64:[function(_dereq_,module,exports){
11568module.exports={
11569 "secp128r1": {
11570 "p": "fffffffdffffffffffffffffffffffff",
11571 "a": "fffffffdfffffffffffffffffffffffc",
11572 "b": "e87579c11079f43dd824993c2cee5ed3",
11573 "n": "fffffffe0000000075a30d1b9038a115",
11574 "h": "01",
11575 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
11576 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
11577 },
11578 "secp160k1": {
11579 "p": "fffffffffffffffffffffffffffffffeffffac73",
11580 "a": "00",
11581 "b": "07",
11582 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
11583 "h": "01",
11584 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
11585 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
11586 },
11587 "secp160r1": {
11588 "p": "ffffffffffffffffffffffffffffffff7fffffff",
11589 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
11590 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
11591 "n": "0100000000000000000001f4c8f927aed3ca752257",
11592 "h": "01",
11593 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
11594 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
11595 },
11596 "secp192k1": {
11597 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
11598 "a": "00",
11599 "b": "03",
11600 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
11601 "h": "01",
11602 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
11603 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
11604 },
11605 "secp192r1": {
11606 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
11607 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
11608 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
11609 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
11610 "h": "01",
11611 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
11612 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
11613 },
11614 "secp224r1": {
11615 "p": "ffffffffffffffffffffffffffffffff000000000000000000000001",
11616 "a": "fffffffffffffffffffffffffffffffefffffffffffffffffffffffe",
11617 "b": "b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4",
11618 "n": "ffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d",
11619 "h": "01",
11620 "Gx": "b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21",
11621 "Gy": "bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34"
11622 },
11623 "secp256k1": {
11624 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
11625 "a": "00",
11626 "b": "07",
11627 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
11628 "h": "01",
11629 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
11630 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
11631 },
11632 "secp256r1": {
11633 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
11634 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
11635 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
11636 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
11637 "h": "01",
11638 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
11639 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
11640 }
11641}
11642
11643},{}],65:[function(_dereq_,module,exports){
11644var Point = _dereq_('./point')
11645var Curve = _dereq_('./curve')
11646
11647var getCurveByName = _dereq_('./names')
11648
11649module.exports = {
11650 Curve: Curve,
11651 Point: Point,
11652 getCurveByName: getCurveByName
11653}
11654
11655},{"./curve":63,"./names":66,"./point":67}],66:[function(_dereq_,module,exports){
11656var BigInteger = _dereq_('bigi')
11657
11658var curves = _dereq_('./curves')
11659var Curve = _dereq_('./curve')
11660
11661function getCurveByName(name) {
11662 var curve = curves[name]
11663 if (!curve) return null
11664
11665 var p = new BigInteger(curve.p, 16)
11666 var a = new BigInteger(curve.a, 16)
11667 var b = new BigInteger(curve.b, 16)
11668 var n = new BigInteger(curve.n, 16)
11669 var h = new BigInteger(curve.h, 16)
11670 var Gx = new BigInteger(curve.Gx, 16)
11671 var Gy = new BigInteger(curve.Gy, 16)
11672
11673 return new Curve(p, a, b, Gx, Gy, n, h)
11674}
11675
11676module.exports = getCurveByName
11677
11678},{"./curve":63,"./curves":64,"bigi":3}],67:[function(_dereq_,module,exports){
11679(function (Buffer){
11680var assert = _dereq_('assert')
11681var BigInteger = _dereq_('bigi')
11682
11683var THREE = BigInteger.valueOf(3)
11684
11685function Point(curve, x, y, z) {
11686 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
11687
11688 this.curve = curve
11689 this.x = x
11690 this.y = y
11691 this.z = z
11692 this._zInv = null
11693
11694 this.compressed = true
11695}
11696
11697Object.defineProperty(Point.prototype, 'zInv', {
11698 get: function() {
11699 if (this._zInv === null) {
11700 this._zInv = this.z.modInverse(this.curve.p)
11701 }
11702
11703 return this._zInv
11704 }
11705})
11706
11707Object.defineProperty(Point.prototype, 'affineX', {
11708 get: function() {
11709 return this.x.multiply(this.zInv).mod(this.curve.p)
11710 }
11711})
11712
11713Object.defineProperty(Point.prototype, 'affineY', {
11714 get: function() {
11715 return this.y.multiply(this.zInv).mod(this.curve.p)
11716 }
11717})
11718
11719Point.fromAffine = function(curve, x, y) {
11720 return new Point(curve, x, y, BigInteger.ONE)
11721}
11722
11723Point.prototype.equals = function(other) {
11724 if (other === this) return true
11725 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
11726 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
11727
11728 // u = Y2 * Z1 - Y1 * Z2
11729 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
11730
11731 if (u.signum() !== 0) return false
11732
11733 // v = X2 * Z1 - X1 * Z2
11734 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
11735
11736 return v.signum() === 0
11737}
11738
11739Point.prototype.negate = function() {
11740 var y = this.curve.p.subtract(this.y)
11741
11742 return new Point(this.curve, this.x, y, this.z)
11743}
11744
11745Point.prototype.add = function(b) {
11746 if (this.curve.isInfinity(this)) return b
11747 if (this.curve.isInfinity(b)) return this
11748
11749 var x1 = this.x
11750 var y1 = this.y
11751 var x2 = b.x
11752 var y2 = b.y
11753
11754 // u = Y2 * Z1 - Y1 * Z2
11755 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
11756 // v = X2 * Z1 - X1 * Z2
11757 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
11758
11759 if (v.signum() === 0) {
11760 if (u.signum() === 0) {
11761 return this.twice() // this == b, so double
11762 }
11763
11764 return this.curve.infinity // this = -b, so infinity
11765 }
11766
11767 var v2 = v.square()
11768 var v3 = v2.multiply(v)
11769 var x1v2 = x1.multiply(v2)
11770 var zu2 = u.square().multiply(this.z)
11771
11772 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
11773 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
11774 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
11775 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p)
11776 // z3 = v^3 * z1 * z2
11777 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
11778
11779 return new Point(this.curve, x3, y3, z3)
11780}
11781
11782Point.prototype.twice = function() {
11783 if (this.curve.isInfinity(this)) return this
11784 if (this.y.signum() === 0) return this.curve.infinity
11785
11786 var x1 = this.x
11787 var y1 = this.y
11788
11789 var y1z1 = y1.multiply(this.z)
11790 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
11791 var a = this.curve.a
11792
11793 // w = 3 * x1^2 + a * z1^2
11794 var w = x1.square().multiply(THREE)
11795
11796 if (a.signum() !== 0) {
11797 w = w.add(this.z.square().multiply(a))
11798 }
11799
11800 w = w.mod(this.curve.p)
11801 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
11802 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
11803 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
11804 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
11805 // z3 = 8 * (y1 * z1)^3
11806 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
11807
11808 return new Point(this.curve, x3, y3, z3)
11809}
11810
11811// Simple NAF (Non-Adjacent Form) multiplication algorithm
11812// TODO: modularize the multiplication algorithm
11813Point.prototype.multiply = function(k) {
11814 if (this.curve.isInfinity(this)) return this
11815 if (k.signum() === 0) return this.curve.infinity
11816
11817 var e = k
11818 var h = e.multiply(THREE)
11819
11820 var neg = this.negate()
11821 var R = this
11822
11823 for (var i = h.bitLength() - 2; i > 0; --i) {
11824 R = R.twice()
11825
11826 var hBit = h.testBit(i)
11827 var eBit = e.testBit(i)
11828
11829 if (hBit != eBit) {
11830 R = R.add(hBit ? this : neg)
11831 }
11832 }
11833
11834 return R
11835}
11836
11837// Compute this*j + x*k (simultaneous multiplication)
11838Point.prototype.multiplyTwo = function(j, x, k) {
11839 var i
11840
11841 if (j.bitLength() > k.bitLength())
11842 i = j.bitLength() - 1
11843 else
11844 i = k.bitLength() - 1
11845
11846 var R = this.curve.infinity
11847 var both = this.add(x)
11848
11849 while (i >= 0) {
11850 R = R.twice()
11851
11852 var jBit = j.testBit(i)
11853 var kBit = k.testBit(i)
11854
11855 if (jBit) {
11856 if (kBit) {
11857 R = R.add(both)
11858
11859 } else {
11860 R = R.add(this)
11861 }
11862
11863 } else {
11864 if (kBit) {
11865 R = R.add(x)
11866 }
11867 }
11868 --i
11869 }
11870
11871 return R
11872}
11873
11874Point.prototype.getEncoded = function(compressed) {
11875 if (compressed == undefined) compressed = this.compressed
11876 if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00'
11877
11878 var x = this.affineX
11879 var y = this.affineY
11880
11881 var buffer
11882
11883 // Determine size of q in bytes
11884 var byteLength = Math.floor((this.curve.p.bitLength() + 7) / 8)
11885
11886 // 0x02/0x03 | X
11887 if (compressed) {
11888 buffer = new Buffer(1 + byteLength)
11889 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
11890
11891 // 0x04 | X | Y
11892 } else {
11893 buffer = new Buffer(1 + byteLength + byteLength)
11894 buffer.writeUInt8(0x04, 0)
11895
11896 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
11897 }
11898
11899 x.toBuffer(byteLength).copy(buffer, 1)
11900
11901 return buffer
11902}
11903
11904Point.decodeFrom = function(curve, buffer) {
11905 var type = buffer.readUInt8(0)
11906 var compressed = (type !== 4)
11907
11908 var x = BigInteger.fromBuffer(buffer.slice(1, 33))
11909 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
11910
11911 var Q
11912 if (compressed) {
11913 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
11914 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
11915
11916 var isOdd = (type === 0x03)
11917 Q = curve.pointFromX(isOdd, x)
11918
11919 } else {
11920 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
11921
11922 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
11923 Q = Point.fromAffine(curve, x, y)
11924 }
11925
11926 Q.compressed = compressed
11927 return Q
11928}
11929
11930Point.prototype.toString = function () {
11931 if (this.curve.isInfinity(this)) return '(INFINITY)'
11932
11933 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
11934}
11935
11936module.exports = Point
11937
11938}).call(this,_dereq_("buffer").Buffer)
11939},{"assert":4,"bigi":3,"buffer":8}],68:[function(_dereq_,module,exports){
11940(function (process,Buffer){
11941// Closure compiler error - result of 'not' operator not being used
11942//!function(globals){
11943(function(globals){
11944'use strict'
11945
11946//*** UMD BEGIN
11947if (typeof define !== 'undefined' && define.amd) { //require.js / AMD
11948 define([], function() {
11949 return secureRandom
11950 })
11951} else if (typeof module !== 'undefined' && module.exports) { //CommonJS
11952 module.exports = secureRandom
11953} else { //script / browser
11954 globals.secureRandom = secureRandom
11955}
11956//*** UMD END
11957
11958//options.type is the only valid option
11959function secureRandom(count, options) {
11960 options = options || {type: 'Array'}
11961 //we check for process.pid to prevent browserify from tricking us
11962 if (typeof process != 'undefined' && typeof process.pid == 'number') {
11963 return nodeRandom(count, options)
11964 } else {
11965 var crypto = window.crypto || window.msCrypto
11966 if (!crypto) throw new Error("Your browser does not support window.crypto.")
11967 return browserRandom(count, options)
11968 }
11969}
11970
11971function nodeRandom(count, options) {
11972 var crypto = _dereq_('crypto')
11973 var buf = crypto.randomBytes(count)
11974
11975 switch (options.type) {
11976 case 'Array':
11977 return [].slice.call(buf)
11978 case 'Buffer':
11979 return buf
11980 case 'Uint8Array':
11981 var arr = new Uint8Array(count)
11982 for (var i = 0; i < count; ++i) { arr[i] = buf.readUInt8(i) }
11983 return arr
11984 default:
11985 throw new Error(options.type + " is unsupported.")
11986 }
11987}
11988
11989function browserRandom(count, options) {
11990 var nativeArr = new Uint8Array(count)
11991 var crypto = window.crypto || window.msCrypto
11992 crypto.getRandomValues(nativeArr)
11993
11994 switch (options.type) {
11995 case 'Array':
11996 return [].slice.call(nativeArr)
11997 case 'Buffer':
11998 try { var b = new Buffer(1) } catch(e) { throw new Error('Buffer not supported in this environment. Use Node.js or Browserify for browser support.')}
11999 return new Buffer(nativeArr)
12000 case 'Uint8Array':
12001 return nativeArr
12002 default:
12003 throw new Error(options.type + " is unsupported.")
12004 }
12005}
12006
12007secureRandom.randomArray = function(byteCount) {
12008 return secureRandom(byteCount, {type: 'Array'})
12009}
12010
12011secureRandom.randomUint8Array = function(byteCount) {
12012 return secureRandom(byteCount, {type: 'Uint8Array'})
12013}
12014
12015secureRandom.randomBuffer = function(byteCount) {
12016 return secureRandom(byteCount, {type: 'Buffer'})
12017}
12018
12019
12020})(this);
12021
12022}).call(this,_dereq_("FWaASH"),_dereq_("buffer").Buffer)
12023},{"FWaASH":12,"buffer":8,"crypto":7}],69:[function(_dereq_,module,exports){
12024(function (Buffer){
12025var assert = _dereq_('assert')
12026var base58check = _dereq_('./base58check')
12027var networks = _dereq_('./networks')
12028var scripts = _dereq_('./scripts')
12029
12030function findScriptTypeByVersion(version) {
12031 for (var networkName in networks) {
12032 var network = networks[networkName]
12033
12034 if (version === network.pubKeyHash) return 'pubkeyhash'
12035 if (version === network.scriptHash) return 'scripthash'
12036 }
12037}
12038
12039function Address(hash, version) {
12040 assert(Buffer.isBuffer(hash), 'Expected Buffer, got ' + hash)
12041 assert.strictEqual(hash.length, 20, 'Invalid hash length')
12042 assert.strictEqual(version & 0xff, version, 'Invalid version byte')
12043
12044 this.hash = hash
12045 this.version = version
12046}
12047
12048// Import functions
12049Address.fromBase58Check = function(string) {
12050 var payload = base58check.decode(string)
12051 var version = payload.readUInt8(0)
12052 var hash = payload.slice(1)
12053
12054 return new Address(hash, version)
12055}
12056
12057Address.fromOutputScript = function(script, network) {
12058 network = network || networks.bitcoin
12059
12060 var type = scripts.classifyOutput(script)
12061
12062 if (type === 'pubkeyhash') return new Address(script.chunks[2], network.pubKeyHash)
12063 if (type === 'scripthash') return new Address(script.chunks[1], network.scriptHash)
12064
12065 assert(false, type + ' has no matching Address')
12066}
12067
12068// Export functions
12069Address.prototype.toBase58Check = function () {
12070 var payload = new Buffer(21)
12071 payload.writeUInt8(this.version, 0)
12072 this.hash.copy(payload, 1)
12073
12074 return base58check.encode(payload)
12075}
12076
12077Address.prototype.toOutputScript = function() {
12078 var scriptType = findScriptTypeByVersion(this.version)
12079
12080 if (scriptType === 'pubkeyhash') return scripts.pubKeyHashOutput(this.hash)
12081 if (scriptType === 'scripthash') return scripts.scriptHashOutput(this.hash)
12082
12083 assert(false, this.toString() + ' has no matching Script')
12084}
12085
12086Address.prototype.toString = Address.prototype.toBase58Check
12087
12088module.exports = Address
12089
12090}).call(this,_dereq_("buffer").Buffer)
12091},{"./base58check":70,"./networks":81,"./scripts":84,"assert":4,"buffer":8}],70:[function(_dereq_,module,exports){
12092(function (Buffer){
12093// https://en.bitcoin.it/wiki/Base58Check_encoding
12094var assert = _dereq_('assert')
12095var base58 = _dereq_('bs58')
12096var crypto = _dereq_('./crypto')
12097
12098// Encode a buffer as a base58-check-encoded string
12099function encode(payload) {
12100 var checksum = crypto.hash256(payload).slice(0, 4)
12101
12102 return base58.encode(Buffer.concat([
12103 payload,
12104 checksum
12105 ]))
12106}
12107
12108// Decode a base58-check-encoded string to a buffer
12109function decode(string) {
12110 var buffer = base58.decode(string)
12111
12112 var payload = buffer.slice(0, -4)
12113 var checksum = buffer.slice(-4)
12114 var newChecksum = crypto.hash256(payload).slice(0, 4)
12115
12116 assert.deepEqual(newChecksum, checksum, 'Invalid checksum')
12117
12118 return payload
12119}
12120
12121module.exports = {
12122 encode: encode,
12123 decode: decode
12124}
12125
12126}).call(this,_dereq_("buffer").Buffer)
12127},{"./crypto":73,"assert":4,"bs58":15,"buffer":8}],71:[function(_dereq_,module,exports){
12128var assert = _dereq_('assert')
12129var opcodes = _dereq_('./opcodes')
12130
12131// https://github.com/feross/buffer/blob/master/index.js#L1127
12132function verifuint(value, max) {
12133 assert(typeof value === 'number', 'cannot write a non-number as a number')
12134 assert(value >= 0, 'specified a negative value for writing an unsigned value')
12135 assert(value <= max, 'value is larger than maximum value for type')
12136 assert(Math.floor(value) === value, 'value has a fractional component')
12137}
12138
12139function pushDataSize(i) {
12140 return i < opcodes.OP_PUSHDATA1 ? 1
12141 : i < 0xff ? 2
12142 : i < 0xffff ? 3
12143 : 5
12144}
12145
12146function readPushDataInt(buffer, offset) {
12147 var opcode = buffer.readUInt8(offset)
12148 var number, size
12149
12150 // ~6 bit
12151 if (opcode < opcodes.OP_PUSHDATA1) {
12152 number = opcode
12153 size = 1
12154
12155 // 8 bit
12156 } else if (opcode === opcodes.OP_PUSHDATA1) {
12157 number = buffer.readUInt8(offset + 1)
12158 size = 2
12159
12160 // 16 bit
12161 } else if (opcode === opcodes.OP_PUSHDATA2) {
12162 number = buffer.readUInt16LE(offset + 1)
12163 size = 3
12164
12165 // 32 bit
12166 } else {
12167 assert.equal(opcode, opcodes.OP_PUSHDATA4, 'Unexpected opcode')
12168
12169 number = buffer.readUInt32LE(offset + 1)
12170 size = 5
12171
12172 }
12173
12174 return {
12175 opcode: opcode,
12176 number: number,
12177 size: size
12178 }
12179}
12180
12181function readUInt64LE(buffer, offset) {
12182 var a = buffer.readUInt32LE(offset)
12183 var b = buffer.readUInt32LE(offset + 4)
12184 b *= 0x100000000
12185
12186 verifuint(b + a, 0x001fffffffffffff)
12187
12188 return b + a
12189}
12190
12191function readVarInt(buffer, offset) {
12192 var t = buffer.readUInt8(offset)
12193 var number, size
12194
12195 // 8 bit
12196 if (t < 253) {
12197 number = t
12198 size = 1
12199
12200 // 16 bit
12201 } else if (t < 254) {
12202 number = buffer.readUInt16LE(offset + 1)
12203 size = 3
12204
12205 // 32 bit
12206 } else if (t < 255) {
12207 number = buffer.readUInt32LE(offset + 1)
12208 size = 5
12209
12210 // 64 bit
12211 } else {
12212 number = readUInt64LE(buffer, offset + 1)
12213 size = 9
12214 }
12215
12216 return {
12217 number: number,
12218 size: size
12219 }
12220}
12221
12222function writePushDataInt(buffer, number, offset) {
12223 var size = pushDataSize(number)
12224
12225 // ~6 bit
12226 if (size === 1) {
12227 buffer.writeUInt8(number, offset)
12228
12229 // 8 bit
12230 } else if (size === 2) {
12231 buffer.writeUInt8(opcodes.OP_PUSHDATA1, offset)
12232 buffer.writeUInt8(number, offset + 1)
12233
12234 // 16 bit
12235 } else if (size === 3) {
12236 buffer.writeUInt8(opcodes.OP_PUSHDATA2, offset)
12237 buffer.writeUInt16LE(number, offset + 1)
12238
12239 // 32 bit
12240 } else {
12241 buffer.writeUInt8(opcodes.OP_PUSHDATA4, offset)
12242 buffer.writeUInt32LE(number, offset + 1)
12243
12244 }
12245
12246 return size
12247}
12248
12249function writeUInt64LE(buffer, value, offset) {
12250 verifuint(value, 0x001fffffffffffff)
12251
12252 buffer.writeInt32LE(value & -1, offset)
12253 buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4)
12254}
12255
12256function varIntSize(i) {
12257 return i < 253 ? 1
12258 : i < 0x10000 ? 3
12259 : i < 0x100000000 ? 5
12260 : 9
12261}
12262
12263function writeVarInt(buffer, number, offset) {
12264 var size = varIntSize(number)
12265
12266 // 8 bit
12267 if (size === 1) {
12268 buffer.writeUInt8(number, offset)
12269
12270 // 16 bit
12271 } else if (size === 3) {
12272 buffer.writeUInt8(253, offset)
12273 buffer.writeUInt16LE(number, offset + 1)
12274
12275 // 32 bit
12276 } else if (size === 5) {
12277 buffer.writeUInt8(254, offset)
12278 buffer.writeUInt32LE(number, offset + 1)
12279
12280 // 64 bit
12281 } else {
12282 buffer.writeUInt8(255, offset)
12283 writeUInt64LE(buffer, number, offset + 1)
12284 }
12285
12286 return size
12287}
12288
12289module.exports = {
12290 pushDataSize: pushDataSize,
12291 readPushDataInt: readPushDataInt,
12292 readUInt64LE: readUInt64LE,
12293 readVarInt: readVarInt,
12294 varIntSize: varIntSize,
12295 writePushDataInt: writePushDataInt,
12296 writeUInt64LE: writeUInt64LE,
12297 writeVarInt: writeVarInt
12298}
12299
12300},{"./opcodes":82,"assert":4}],72:[function(_dereq_,module,exports){
12301(function (Buffer){
12302var assert = _dereq_('assert')
12303var Crypto = _dereq_('crypto-js')
12304var WordArray = Crypto.lib.WordArray
12305
12306function bufferToWordArray(buffer) {
12307 assert(Buffer.isBuffer(buffer), 'Expected Buffer, got', buffer)
12308
12309 var words = []
12310 for (var i = 0, b = 0; i < buffer.length; i++, b += 8) {
12311 words[b >>> 5] |= buffer[i] << (24 - b % 32)
12312 }
12313
12314 return new WordArray.init(words, buffer.length)
12315}
12316
12317function wordArrayToBuffer(wordArray) {
12318 assert(Array.isArray(wordArray.words), 'Expected WordArray, got' + wordArray)
12319
12320 var words = wordArray.words
12321 var buffer = new Buffer(words.length * 4)
12322
12323 words.forEach(function(value, i) {
12324 buffer.writeInt32BE(value & -1, i * 4)
12325 })
12326
12327 return buffer
12328}
12329
12330module.exports = {
12331 bufferToWordArray: bufferToWordArray,
12332 wordArrayToBuffer: wordArrayToBuffer
12333}
12334
12335}).call(this,_dereq_("buffer").Buffer)
12336},{"assert":4,"buffer":8,"crypto-js":37}],73:[function(_dereq_,module,exports){
12337(function (Buffer){
12338// Crypto, crypto, where art thou crypto
12339var assert = _dereq_('assert')
12340var CryptoJS = _dereq_('crypto-js')
12341var crypto = _dereq_('crypto')
12342var convert = _dereq_('./convert')
12343
12344function hash160(buffer) {
12345 return ripemd160(sha256(buffer))
12346}
12347
12348function hash256(buffer) {
12349 return sha256(sha256(buffer))
12350}
12351
12352function ripemd160(buffer) {
12353 return crypto.createHash('rmd160').update(buffer).digest()
12354}
12355
12356function sha1(buffer) {
12357 return crypto.createHash('sha1').update(buffer).digest()
12358}
12359
12360function sha256(buffer) {
12361 return crypto.createHash('sha256').update(buffer).digest()
12362}
12363
12364// FIXME: Name not consistent with others
12365function HmacSHA256(buffer, secret) {
12366 return crypto.createHmac('sha256', secret).update(buffer).digest()
12367}
12368
12369function HmacSHA512(data, secret) {
12370 assert(Buffer.isBuffer(data), 'Expected Buffer for data, got ' + data)
12371 assert(Buffer.isBuffer(secret), 'Expected Buffer for secret, got ' + secret)
12372
12373 var dataWords = convert.bufferToWordArray(data)
12374 var secretWords = convert.bufferToWordArray(secret)
12375
12376 var hash = CryptoJS.HmacSHA512(dataWords, secretWords)
12377
12378 return convert.wordArrayToBuffer(hash)
12379}
12380
12381module.exports = {
12382 ripemd160: ripemd160,
12383 sha1: sha1,
12384 sha256: sha256,
12385 hash160: hash160,
12386 hash256: hash256,
12387 HmacSHA256: HmacSHA256,
12388 HmacSHA512: HmacSHA512
12389}
12390
12391}).call(this,_dereq_("buffer").Buffer)
12392},{"./convert":72,"assert":4,"buffer":8,"crypto":19,"crypto-js":37}],74:[function(_dereq_,module,exports){
12393(function (Buffer){
12394var assert = _dereq_('assert')
12395var crypto = _dereq_('./crypto')
12396
12397var BigInteger = _dereq_('bigi')
12398var ECSignature = _dereq_('./ecsignature')
12399var Point = _dereq_('ecurve').Point
12400
12401// https://tools.ietf.org/html/rfc6979#section-3.2
12402function deterministicGenerateK(curve, hash, d) {
12403 assert(Buffer.isBuffer(hash), 'Hash must be a Buffer, not ' + hash)
12404 assert.equal(hash.length, 32, 'Hash must be 256 bit')
12405 assert(d instanceof BigInteger, 'Private key must be a BigInteger')
12406
12407 var x = d.toBuffer(32)
12408 var k = new Buffer(32)
12409 var v = new Buffer(32)
12410
12411 // Step B
12412 v.fill(1)
12413
12414 // Step C
12415 k.fill(0)
12416
12417 // Step D
12418 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k)
12419
12420 // Step E
12421 v = crypto.HmacSHA256(v, k)
12422
12423 // Step F
12424 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k)
12425
12426 // Step G
12427 v = crypto.HmacSHA256(v, k)
12428
12429 // Step H1/H2a, ignored as tlen === qlen (256 bit)
12430 // Step H2b
12431 v = crypto.HmacSHA256(v, k)
12432
12433 var T = BigInteger.fromBuffer(v)
12434
12435 // Step H3, repeat until T is within the interval [1, n - 1]
12436 while ((T.signum() <= 0) || (T.compareTo(curve.n) >= 0)) {
12437 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0])]), k)
12438 v = crypto.HmacSHA256(v, k)
12439
12440 T = BigInteger.fromBuffer(v)
12441 }
12442
12443 return T
12444}
12445
12446function sign(curve, hash, d) {
12447 var k = deterministicGenerateK(curve, hash, d)
12448
12449 var n = curve.n
12450 var G = curve.G
12451 var Q = G.multiply(k)
12452 var e = BigInteger.fromBuffer(hash)
12453
12454 var r = Q.affineX.mod(n)
12455 assert.notEqual(r.signum(), 0, 'Invalid R value')
12456
12457 var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
12458 assert.notEqual(s.signum(), 0, 'Invalid S value')
12459
12460 var N_OVER_TWO = n.shiftRight(1)
12461
12462 // enforce low S values, see bip62: 'low s values in signatures'
12463 if (s.compareTo(N_OVER_TWO) > 0) {
12464 s = n.subtract(s)
12465 }
12466
12467 return new ECSignature(r, s)
12468}
12469
12470function verify(curve, hash, signature, Q) {
12471 var e = BigInteger.fromBuffer(hash)
12472
12473 return verifyRaw(curve, e, signature, Q)
12474}
12475
12476function verifyRaw(curve, e, signature, Q) {
12477 var n = curve.n
12478 var G = curve.G
12479
12480 var r = signature.r
12481 var s = signature.s
12482
12483 if (r.signum() === 0 || r.compareTo(n) >= 0) return false
12484 if (s.signum() === 0 || s.compareTo(n) >= 0) return false
12485
12486 var c = s.modInverse(n)
12487
12488 var u1 = e.multiply(c).mod(n)
12489 var u2 = r.multiply(c).mod(n)
12490
12491 var point = G.multiplyTwo(u1, Q, u2)
12492 var v = point.affineX.mod(n)
12493
12494 return v.equals(r)
12495}
12496
12497/**
12498 * Recover a public key from a signature.
12499 *
12500 * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
12501 * Key Recovery Operation".
12502 *
12503 * http://www.secg.org/download/aid-780/sec1-v2.pdf
12504 */
12505function recoverPubKey(curve, e, signature, i) {
12506 assert.strictEqual(i & 3, i, 'Recovery param is more than two bits')
12507
12508 var r = signature.r
12509 var s = signature.s
12510
12511 // A set LSB signifies that the y-coordinate is odd
12512 var isYOdd = i & 1
12513
12514 // The more significant bit specifies whether we should use the
12515 // first or second candidate key.
12516 var isSecondKey = i >> 1
12517
12518 var n = curve.n
12519 var G = curve.G
12520
12521 // 1.1 Let x = r + jn
12522 var x = isSecondKey ? r.add(n) : r
12523 var R = curve.pointFromX(isYOdd, x)
12524
12525 // 1.4 Check that nR is at infinity
12526 var nR = R.multiply(n)
12527 assert(curve.isInfinity(nR), 'nR is not a valid curve point')
12528
12529 // Compute -e from e
12530 var eNeg = e.negate().mod(n)
12531
12532 // 1.6.1 Compute Q = r^-1 (sR - eG)
12533 // Q = r^-1 (sR + -eG)
12534 var rInv = r.modInverse(n)
12535
12536 var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv)
12537 curve.validate(Q)
12538
12539 return Q
12540}
12541
12542/**
12543 * Calculate pubkey extraction parameter.
12544 *
12545 * When extracting a pubkey from a signature, we have to
12546 * distinguish four different cases. Rather than putting this
12547 * burden on the verifier, Bitcoin includes a 2-bit value with the
12548 * signature.
12549 *
12550 * This function simply tries all four cases and returns the value
12551 * that resulted in a successful pubkey recovery.
12552 */
12553function calcPubKeyRecoveryParam(curve, e, signature, Q) {
12554 for (var i = 0; i < 4; i++) {
12555 var Qprime = recoverPubKey(curve, e, signature, i)
12556
12557 // 1.6.2 Verify Q
12558 if (Qprime.equals(Q)) {
12559 return i
12560 }
12561 }
12562
12563 throw new Error('Unable to find valid recovery factor')
12564}
12565
12566module.exports = {
12567 calcPubKeyRecoveryParam: calcPubKeyRecoveryParam,
12568 deterministicGenerateK: deterministicGenerateK,
12569 recoverPubKey: recoverPubKey,
12570 sign: sign,
12571 verify: verify,
12572 verifyRaw: verifyRaw
12573}
12574
12575}).call(this,_dereq_("buffer").Buffer)
12576},{"./crypto":73,"./ecsignature":77,"assert":4,"bigi":3,"buffer":8,"ecurve":65}],75:[function(_dereq_,module,exports){
12577(function (Buffer){
12578var assert = _dereq_('assert')
12579var base58check = _dereq_('./base58check')
12580var ecdsa = _dereq_('./ecdsa')
12581var networks = _dereq_('./networks')
12582var secureRandom = _dereq_('secure-random')
12583
12584var BigInteger = _dereq_('bigi')
12585var ECPubKey = _dereq_('./ecpubkey')
12586
12587var ecurve = _dereq_('ecurve')
12588var curve = ecurve.getCurveByName('secp256k1')
12589
12590function ECKey(d, compressed) {
12591 assert(d.signum() > 0, 'Private key must be greater than 0')
12592 assert(d.compareTo(curve.n) < 0, 'Private key must be less than the curve order')
12593
12594 var Q = curve.G.multiply(d)
12595
12596 this.d = d
12597 this.pub = new ECPubKey(Q, compressed)
12598}
12599
12600// Static constructors
12601ECKey.fromWIF = function(string) {
12602 var payload = base58check.decode(string)
12603 var compressed = false
12604
12605 // Ignore the version byte
12606 payload = payload.slice(1)
12607
12608 if (payload.length === 33) {
12609 assert.strictEqual(payload[32], 0x01, 'Invalid compression flag')
12610
12611 // Truncate the compression flag
12612 payload = payload.slice(0, -1)
12613 compressed = true
12614 }
12615
12616 assert.equal(payload.length, 32, 'Invalid WIF payload length')
12617
12618 var d = BigInteger.fromBuffer(payload)
12619 return new ECKey(d, compressed)
12620}
12621
12622ECKey.makeRandom = function(compressed, rng) {
12623 rng = rng || secureRandom.randomBuffer
12624
12625 var buffer = rng(32)
12626 assert(Buffer.isBuffer(buffer), 'Expected Buffer, got ' + buffer)
12627
12628 var d = BigInteger.fromBuffer(buffer)
12629 d = d.mod(curve.n)
12630
12631 return new ECKey(d, compressed)
12632}
12633
12634// Export functions
12635ECKey.prototype.toWIF = function(network) {
12636 network = network || networks.bitcoin
12637
12638 var bufferLen = this.pub.compressed ? 34 : 33
12639 var buffer = new Buffer(bufferLen)
12640
12641 buffer.writeUInt8(network.wif, 0)
12642 this.d.toBuffer(32).copy(buffer, 1)
12643
12644 if (this.pub.compressed) {
12645 buffer.writeUInt8(0x01, 33)
12646 }
12647
12648 return base58check.encode(buffer)
12649}
12650
12651// Operations
12652ECKey.prototype.sign = function(hash) {
12653 return ecdsa.sign(curve, hash, this.d)
12654}
12655
12656module.exports = ECKey
12657
12658}).call(this,_dereq_("buffer").Buffer)
12659},{"./base58check":70,"./ecdsa":74,"./ecpubkey":76,"./networks":81,"assert":4,"bigi":3,"buffer":8,"ecurve":65,"secure-random":68}],76:[function(_dereq_,module,exports){
12660(function (Buffer){
12661var assert = _dereq_('assert')
12662var crypto = _dereq_('./crypto')
12663var ecdsa = _dereq_('./ecdsa')
12664var networks = _dereq_('./networks')
12665
12666var Address = _dereq_('./address')
12667
12668var ecurve = _dereq_('ecurve')
12669var curve = ecurve.getCurveByName('secp256k1')
12670
12671function ECPubKey(Q, compressed) {
12672 assert(Q instanceof ecurve.Point, 'Expected Point, got ' + Q)
12673
12674 if (compressed == undefined) compressed = true
12675 assert.strictEqual(typeof compressed, 'boolean', 'Expected boolean, got ' + compressed)
12676
12677 this.compressed = compressed
12678 this.Q = Q
12679}
12680
12681// Static constructors
12682ECPubKey.fromBuffer = function(buffer) {
12683 var Q = ecurve.Point.decodeFrom(curve, buffer)
12684 return new ECPubKey(Q, Q.compressed)
12685}
12686
12687ECPubKey.fromHex = function(hex) {
12688 return ECPubKey.fromBuffer(new Buffer(hex, 'hex'))
12689}
12690
12691// Operations
12692ECPubKey.prototype.getAddress = function(network) {
12693 network = network || networks.bitcoin
12694
12695 return new Address(crypto.hash160(this.toBuffer()), network.pubKeyHash)
12696}
12697
12698ECPubKey.prototype.verify = function(hash, signature) {
12699 return ecdsa.verify(curve, hash, signature, this.Q)
12700}
12701
12702// Export functions
12703ECPubKey.prototype.toBuffer = function() {
12704 return this.Q.getEncoded(this.compressed)
12705}
12706
12707ECPubKey.prototype.toHex = function() {
12708 return this.toBuffer().toString('hex')
12709}
12710
12711module.exports = ECPubKey
12712
12713}).call(this,_dereq_("buffer").Buffer)
12714},{"./address":69,"./crypto":73,"./ecdsa":74,"./networks":81,"assert":4,"buffer":8,"ecurve":65}],77:[function(_dereq_,module,exports){
12715(function (Buffer){
12716var assert = _dereq_('assert')
12717var BigInteger = _dereq_('bigi')
12718
12719function ECSignature(r, s) {
12720 assert(r instanceof BigInteger, 'Expected BigInteger, got ' + r)
12721 assert(s instanceof BigInteger, 'Expected BigInteger, got ' + s)
12722 this.r = r
12723 this.s = s
12724}
12725
12726// Import operations
12727ECSignature.parseCompact = function(buffer) {
12728 assert.equal(buffer.length, 65, 'Invalid signature length')
12729 var i = buffer.readUInt8(0) - 27
12730
12731 // At most 3 bits
12732 assert.equal(i, i & 7, 'Invalid signature parameter')
12733 var compressed = !!(i & 4)
12734
12735 // Recovery param only
12736 i = i & 3
12737
12738 var r = BigInteger.fromBuffer(buffer.slice(1, 33))
12739 var s = BigInteger.fromBuffer(buffer.slice(33))
12740
12741 return {
12742 compressed: compressed,
12743 i: i,
12744 signature: new ECSignature(r, s)
12745 }
12746}
12747
12748ECSignature.fromDER = function(buffer) {
12749 assert.equal(buffer.readUInt8(0), 0x30, 'Not a DER sequence')
12750 assert.equal(buffer.readUInt8(1), buffer.length - 2, 'Invalid sequence length')
12751 assert.equal(buffer.readUInt8(2), 0x02, 'Expected a DER integer')
12752
12753 var rLen = buffer.readUInt8(3)
12754 assert(rLen > 0, 'R length is zero')
12755
12756 var offset = 4 + rLen
12757 assert.equal(buffer.readUInt8(offset), 0x02, 'Expected a DER integer (2)')
12758
12759 var sLen = buffer.readUInt8(offset + 1)
12760 assert(sLen > 0, 'S length is zero')
12761
12762 var rB = buffer.slice(4, offset)
12763 var sB = buffer.slice(offset + 2)
12764 offset += 2 + sLen
12765
12766 if (rLen > 1 && rB.readUInt8(0) === 0x00) {
12767 assert(rB.readUInt8(1) & 0x80, 'R value excessively padded')
12768 }
12769
12770 if (sLen > 1 && sB.readUInt8(0) === 0x00) {
12771 assert(sB.readUInt8(1) & 0x80, 'S value excessively padded')
12772 }
12773
12774 assert.equal(offset, buffer.length, 'Invalid DER encoding')
12775 var r = BigInteger.fromDERInteger(rB)
12776 var s = BigInteger.fromDERInteger(sB)
12777
12778 assert(r.signum() >= 0, 'R value is negative')
12779 assert(s.signum() >= 0, 'S value is negative')
12780
12781 return new ECSignature(r, s)
12782}
12783
12784// FIXME: 0x00, 0x04, 0x80 are SIGHASH_* boundary constants, importing Transaction causes a circular dependency
12785ECSignature.parseScriptSignature = function(buffer) {
12786 var hashType = buffer.readUInt8(buffer.length - 1)
12787 var hashTypeMod = hashType & ~0x80
12788
12789 assert(hashTypeMod > 0x00 && hashTypeMod < 0x04, 'Invalid hashType')
12790
12791 return {
12792 signature: ECSignature.fromDER(buffer.slice(0, -1)),
12793 hashType: hashType
12794 }
12795}
12796
12797// Export operations
12798ECSignature.prototype.toCompact = function(i, compressed) {
12799 if (compressed) i += 4
12800 i += 27
12801
12802 var buffer = new Buffer(65)
12803 buffer.writeUInt8(i, 0)
12804
12805 this.r.toBuffer(32).copy(buffer, 1)
12806 this.s.toBuffer(32).copy(buffer, 33)
12807
12808 return buffer
12809}
12810
12811ECSignature.prototype.toDER = function() {
12812 var rBa = this.r.toDERInteger()
12813 var sBa = this.s.toDERInteger()
12814
12815 var sequence = []
12816 sequence.push(0x02) // INTEGER
12817 sequence.push(rBa.length)
12818 sequence = sequence.concat(rBa)
12819
12820 sequence.push(0x02) // INTEGER
12821 sequence.push(sBa.length)
12822 sequence = sequence.concat(sBa)
12823
12824 sequence.unshift(sequence.length)
12825 sequence.unshift(0x30) // SEQUENCE
12826
12827 return new Buffer(sequence)
12828}
12829
12830ECSignature.prototype.toScriptSignature = function(hashType) {
12831 var hashTypeBuffer = new Buffer(1)
12832 hashTypeBuffer.writeUInt8(hashType, 0)
12833
12834 return Buffer.concat([this.toDER(), hashTypeBuffer])
12835}
12836
12837module.exports = ECSignature
12838
12839}).call(this,_dereq_("buffer").Buffer)
12840},{"assert":4,"bigi":3,"buffer":8}],78:[function(_dereq_,module,exports){
12841(function (Buffer){
12842var assert = _dereq_('assert')
12843var base58check = _dereq_('./base58check')
12844var crypto = _dereq_('./crypto')
12845var networks = _dereq_('./networks')
12846
12847var BigInteger = _dereq_('bigi')
12848var ECKey = _dereq_('./eckey')
12849var ECPubKey = _dereq_('./ecpubkey')
12850
12851var ecurve = _dereq_('ecurve')
12852var curve = ecurve.getCurveByName('secp256k1')
12853
12854function findBIP32ParamsByVersion(version) {
12855 for (var name in networks) {
12856 var network = networks[name]
12857
12858 for (var type in network.bip32) {
12859 if (version != network.bip32[type]) continue
12860
12861 return {
12862 isPrivate: (type === 'private'),
12863 network: network
12864 }
12865 }
12866 }
12867
12868 assert(false, 'Could not find version ' + version.toString(16))
12869}
12870
12871function HDNode(K, chainCode, network) {
12872 network = network || networks.bitcoin
12873
12874 assert(Buffer.isBuffer(chainCode), 'Expected Buffer, got ' + chainCode)
12875 assert(network.bip32, 'Unknown BIP32 constants for network')
12876
12877 this.chainCode = chainCode
12878 this.depth = 0
12879 this.index = 0
12880 this.network = network
12881
12882 if (K instanceof BigInteger) {
12883 this.privKey = new ECKey(K, true)
12884 this.pubKey = this.privKey.pub
12885 } else {
12886 this.pubKey = new ECPubKey(K, true)
12887 }
12888}
12889
12890HDNode.MASTER_SECRET = new Buffer('Bitcoin seed')
12891HDNode.HIGHEST_BIT = 0x80000000
12892HDNode.LENGTH = 78
12893
12894HDNode.fromSeedBuffer = function(seed, network) {
12895 var I = crypto.HmacSHA512(seed, HDNode.MASTER_SECRET)
12896 var IL = I.slice(0, 32)
12897 var IR = I.slice(32)
12898
12899 // In case IL is 0 or >= n, the master key is invalid
12900 // This is handled by `new ECKey` in the HDNode constructor
12901 var pIL = BigInteger.fromBuffer(IL)
12902
12903 return new HDNode(pIL, IR, network)
12904}
12905
12906HDNode.fromSeedHex = function(hex, network) {
12907 return HDNode.fromSeedBuffer(new Buffer(hex, 'hex'), network)
12908}
12909
12910HDNode.fromBase58 = function(string) {
12911 return HDNode.fromBuffer(base58check.decode(string))
12912}
12913
12914HDNode.fromBuffer = function(buffer) {
12915 assert.strictEqual(buffer.length, HDNode.LENGTH, 'Invalid buffer length')
12916
12917 // 4 byte: version bytes
12918 var version = buffer.readUInt32BE(0)
12919 var params = findBIP32ParamsByVersion(version)
12920
12921 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
12922 var depth = buffer.readUInt8(4)
12923
12924 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
12925 var parentFingerprint = buffer.readUInt32BE(5)
12926 if (depth === 0) {
12927 assert.strictEqual(parentFingerprint, 0x00000000, 'Invalid parent fingerprint')
12928 }
12929
12930 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
12931 // This is encoded in MSB order. (0x00000000 if master key)
12932 var index = buffer.readUInt32BE(9)
12933 assert(depth > 0 || index === 0, 'Invalid index')
12934
12935 // 32 bytes: the chain code
12936 var chainCode = buffer.slice(13, 45)
12937 var hd
12938
12939 // 33 bytes: private key data (0x00 + k)
12940 if (params.isPrivate) {
12941 assert.strictEqual(buffer.readUInt8(45), 0x00, 'Invalid private key')
12942 var data = buffer.slice(46, 78)
12943 var d = BigInteger.fromBuffer(data)
12944 hd = new HDNode(d, chainCode, params.network)
12945
12946 // 33 bytes: public key data (0x02 + X or 0x03 + X)
12947 } else {
12948 var data = buffer.slice(45, 78)
12949 var Q = ecurve.Point.decodeFrom(curve, data)
12950 assert.equal(Q.compressed, true, 'Invalid public key')
12951
12952 // Verify that the X coordinate in the public point corresponds to a point on the curve.
12953 // If not, the extended public key is invalid.
12954 curve.validate(Q)
12955
12956 hd = new HDNode(Q, chainCode, params.network)
12957 }
12958
12959 hd.depth = depth
12960 hd.index = index
12961 hd.parentFingerprint = parentFingerprint
12962
12963 return hd
12964}
12965
12966HDNode.fromHex = function(hex) {
12967 return HDNode.fromBuffer(new Buffer(hex, 'hex'))
12968}
12969
12970HDNode.prototype.getIdentifier = function() {
12971 return crypto.hash160(this.pubKey.toBuffer())
12972}
12973
12974HDNode.prototype.getFingerprint = function() {
12975 return this.getIdentifier().slice(0, 4)
12976}
12977
12978HDNode.prototype.getAddress = function() {
12979 return this.pubKey.getAddress(this.network)
12980}
12981
12982HDNode.prototype.toBase58 = function(isPrivate) {
12983 return base58check.encode(this.toBuffer(isPrivate))
12984}
12985
12986HDNode.prototype.toBuffer = function(isPrivate) {
12987 if (isPrivate == undefined) isPrivate = !!this.privKey
12988
12989 // Version
12990 var version = isPrivate ? this.network.bip32.private : this.network.bip32.public
12991 var buffer = new Buffer(HDNode.LENGTH)
12992
12993 // 4 bytes: version bytes
12994 buffer.writeUInt32BE(version, 0)
12995
12996 // Depth
12997 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
12998 buffer.writeUInt8(this.depth, 4)
12999
13000 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
13001 var fingerprint = (this.depth === 0) ? 0x00000000 : this.parentFingerprint
13002 buffer.writeUInt32BE(fingerprint, 5)
13003
13004 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
13005 // This is encoded in Big endian. (0x00000000 if master key)
13006 buffer.writeUInt32BE(this.index, 9)
13007
13008 // 32 bytes: the chain code
13009 this.chainCode.copy(buffer, 13)
13010
13011 // 33 bytes: the public key or private key data
13012 if (isPrivate) {
13013 assert(this.privKey, 'Missing private key')
13014
13015 // 0x00 + k for private keys
13016 buffer.writeUInt8(0, 45)
13017 this.privKey.d.toBuffer(32).copy(buffer, 46)
13018 } else {
13019
13020 // X9.62 encoding for public keys
13021 this.pubKey.toBuffer().copy(buffer, 45)
13022 }
13023
13024 return buffer
13025}
13026
13027HDNode.prototype.toHex = function(isPrivate) {
13028 return this.toBuffer(isPrivate).toString('hex')
13029}
13030
13031// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
13032HDNode.prototype.derive = function(index) {
13033 var isHardened = index >= HDNode.HIGHEST_BIT
13034 var indexBuffer = new Buffer(4)
13035 indexBuffer.writeUInt32BE(index, 0)
13036
13037 var data
13038
13039 // Hardened child
13040 if (isHardened) {
13041 assert(this.privKey, 'Could not derive hardened child key')
13042
13043 // data = 0x00 || ser256(kpar) || ser32(index)
13044 data = Buffer.concat([
13045 this.privKey.d.toBuffer(33),
13046 indexBuffer
13047 ])
13048
13049 // Normal child
13050 } else {
13051 // data = serP(point(kpar)) || ser32(index)
13052 // = serP(Kpar) || ser32(index)
13053 data = Buffer.concat([
13054 this.pubKey.toBuffer(),
13055 indexBuffer
13056 ])
13057 }
13058
13059 var I = crypto.HmacSHA512(data, this.chainCode)
13060 var IL = I.slice(0, 32)
13061 var IR = I.slice(32)
13062
13063 var pIL = BigInteger.fromBuffer(IL)
13064
13065 // In case parse256(IL) >= n, proceed with the next value for i
13066 if (pIL.compareTo(curve.n) >= 0) {
13067 return this.derive(index + 1)
13068 }
13069
13070 // Private parent key -> private child key
13071 var hd
13072 if (this.privKey) {
13073 // ki = parse256(IL) + kpar (mod n)
13074 var ki = pIL.add(this.privKey.d).mod(curve.n)
13075
13076 // In case ki == 0, proceed with the next value for i
13077 if (ki.signum() === 0) {
13078 return this.derive(index + 1)
13079 }
13080
13081 hd = new HDNode(ki, IR, this.network)
13082
13083 // Public parent key -> public child key
13084 } else {
13085 // Ki = point(parse256(IL)) + Kpar
13086 // = G*IL + Kpar
13087 var Ki = curve.G.multiply(pIL).add(this.pubKey.Q)
13088
13089 // In case Ki is the point at infinity, proceed with the next value for i
13090 if (curve.isInfinity(Ki)) {
13091 return this.derive(index + 1)
13092 }
13093
13094 hd = new HDNode(Ki, IR, this.network)
13095 }
13096
13097 hd.depth = this.depth + 1
13098 hd.index = index
13099 hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)
13100
13101 return hd
13102}
13103
13104HDNode.prototype.deriveHardened = function(index) {
13105 // Only derives hardened private keys by default
13106 return this.derive(index + HDNode.HIGHEST_BIT)
13107}
13108
13109HDNode.prototype.toString = HDNode.prototype.toBase58
13110
13111module.exports = HDNode
13112
13113}).call(this,_dereq_("buffer").Buffer)
13114},{"./base58check":70,"./crypto":73,"./eckey":75,"./ecpubkey":76,"./networks":81,"assert":4,"bigi":3,"buffer":8,"ecurve":65}],79:[function(_dereq_,module,exports){
13115module.exports = {
13116 Address: _dereq_('./address'),
13117 base58check: _dereq_('./base58check'),
13118 bufferutils: _dereq_('./bufferutils'),
13119 convert: _dereq_('./convert'),
13120 crypto: _dereq_('./crypto'),
13121 ecdsa: _dereq_('./ecdsa'),
13122 ECKey: _dereq_('./eckey'),
13123 ECPubKey: _dereq_('./ecpubkey'),
13124 ECSignature: _dereq_('./ecsignature'),
13125 Message: _dereq_('./message'),
13126 opcodes: _dereq_('./opcodes'),
13127 HDNode: _dereq_('./hdnode'),
13128 Script: _dereq_('./script'),
13129 scripts: _dereq_('./scripts'),
13130 Transaction: _dereq_('./transaction'),
13131 networks: _dereq_('./networks'),
13132 Wallet: _dereq_('./wallet')
13133}
13134
13135},{"./address":69,"./base58check":70,"./bufferutils":71,"./convert":72,"./crypto":73,"./ecdsa":74,"./eckey":75,"./ecpubkey":76,"./ecsignature":77,"./hdnode":78,"./message":80,"./networks":81,"./opcodes":82,"./script":83,"./scripts":84,"./transaction":85,"./wallet":86}],80:[function(_dereq_,module,exports){
13136(function (Buffer){
13137/// Implements Bitcoin's feature for signing arbitrary messages.
13138var Address = _dereq_('./address')
13139var BigInteger = _dereq_('bigi')
13140var bufferutils = _dereq_('./bufferutils')
13141var crypto = _dereq_('./crypto')
13142var ecdsa = _dereq_('./ecdsa')
13143var networks = _dereq_('./networks')
13144
13145var Address = _dereq_('./address')
13146var ECPubKey = _dereq_('./ecpubkey')
13147var ECSignature = _dereq_('./ecsignature')
13148
13149var ecurve = _dereq_('ecurve')
13150var ecparams = ecurve.getCurveByName('secp256k1')
13151
13152function magicHash(message, network) {
13153 var magicPrefix = new Buffer(network.magicPrefix)
13154 var messageBuffer = new Buffer(message)
13155 var lengthBuffer = new Buffer(bufferutils.varIntSize(messageBuffer.length))
13156 bufferutils.writeVarInt(lengthBuffer, messageBuffer.length, 0)
13157
13158 var buffer = Buffer.concat([magicPrefix, lengthBuffer, messageBuffer])
13159 return crypto.hash256(buffer)
13160}
13161
13162function sign(privKey, message, network) {
13163 network = network || networks.bitcoin
13164
13165 var hash = magicHash(message, network)
13166 var signature = privKey.sign(hash)
13167 var e = BigInteger.fromBuffer(hash)
13168 var i = ecdsa.calcPubKeyRecoveryParam(ecparams, e, signature, privKey.pub.Q)
13169
13170 return signature.toCompact(i, privKey.pub.compressed)
13171}
13172
13173// TODO: network could be implied from address
13174function verify(address, signatureBuffer, message, network) {
13175 if (address instanceof Address) {
13176 address = address.toString()
13177 }
13178 network = network || networks.bitcoin
13179
13180 var hash = magicHash(message, network)
13181 var parsed = ECSignature.parseCompact(signatureBuffer)
13182 var e = BigInteger.fromBuffer(hash)
13183 var Q = ecdsa.recoverPubKey(ecparams, e, parsed.signature, parsed.i)
13184
13185 var pubKey = new ECPubKey(Q, parsed.compressed)
13186 return pubKey.getAddress(network).toString() === address
13187}
13188
13189module.exports = {
13190 magicHash: magicHash,
13191 sign: sign,
13192 verify: verify
13193}
13194
13195}).call(this,_dereq_("buffer").Buffer)
13196},{"./address":69,"./bufferutils":71,"./crypto":73,"./ecdsa":74,"./ecpubkey":76,"./ecsignature":77,"./networks":81,"bigi":3,"buffer":8,"ecurve":65}],81:[function(_dereq_,module,exports){
13197// https://en.bitcoin.it/wiki/List_of_address_prefixes
13198// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
13199
13200var networks = {
13201 bitcoin: {
13202 magicPrefix: '\x18Bitcoin Signed Message:\n',
13203 bip32: {
13204 public: 0x0488b21e,
13205 private: 0x0488ade4
13206 },
13207 pubKeyHash: 0x00,
13208 scriptHash: 0x05,
13209 wif: 0x80,
13210 dustThreshold: 546, // https://github.com/bitcoin/bitcoin/blob/v0.9.2/src/core.h#L151-L162
13211 feePerKb: 10000, // https://github.com/bitcoin/bitcoin/blob/v0.9.2/src/main.cpp#L53
13212 estimateFee: estimateFee('bitcoin')
13213 },
13214 dogecoin: {
13215 magicPrefix: '\x19Dogecoin Signed Message:\n',
13216 bip32: {
13217 public: 0x02facafd,
13218 private: 0x02fac398
13219 },
13220 pubKeyHash: 0x1e,
13221 scriptHash: 0x16,
13222 wif: 0x9e,
13223 dustThreshold: 0, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/core.h#L155-L160
13224 dustSoftThreshold: 100000000, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/main.h#L62
13225 feePerKb: 100000000, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/main.cpp#L58
13226 estimateFee: estimateFee('dogecoin')
13227 },
13228 litecoin: {
13229 magicPrefix: '\x19Litecoin Signed Message:\n',
13230 bip32: {
13231 public: 0x019da462,
13232 private: 0x019d9cfe
13233 },
13234 pubKeyHash: 0x30,
13235 scriptHash: 0x05,
13236 wif: 0xb0,
13237 dustThreshold: 0, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.cpp#L360-L365
13238 dustSoftThreshold: 100000, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.h#L53
13239 feePerKb: 100000, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.cpp#L56
13240 estimateFee: estimateFee('litecoin')
13241 },
13242 testnet: {
13243 magicPrefix: '\x18Bitcoin Signed Message:\n',
13244 bip32: {
13245 public: 0x043587cf,
13246 private: 0x04358394
13247 },
13248 pubKeyHash: 0x6f,
13249 scriptHash: 0xc4,
13250 wif: 0xef,
13251 dustThreshold: 546,
13252 feePerKb: 10000,
13253 estimateFee: estimateFee('testnet')
13254 }
13255}
13256
13257function estimateFee(type) {
13258 return function(tx) {
13259 var network = networks[type]
13260 var baseFee = network.feePerKb
13261 var byteSize = tx.toBuffer().length
13262
13263 var fee = baseFee * Math.ceil(byteSize / 1000)
13264 if (network.dustSoftThreshold == undefined) return fee
13265
13266 tx.outs.forEach(function(e){
13267 if (e.value < network.dustSoftThreshold) {
13268 fee += baseFee
13269 }
13270 })
13271
13272 return fee
13273 }
13274}
13275
13276module.exports = networks
13277
13278},{}],82:[function(_dereq_,module,exports){
13279module.exports = {
13280 // push value
13281 OP_FALSE : 0,
13282 OP_0 : 0,
13283 OP_PUSHDATA1 : 76,
13284 OP_PUSHDATA2 : 77,
13285 OP_PUSHDATA4 : 78,
13286 OP_1NEGATE : 79,
13287 OP_RESERVED : 80,
13288 OP_1 : 81,
13289 OP_TRUE : 81,
13290 OP_2 : 82,
13291 OP_3 : 83,
13292 OP_4 : 84,
13293 OP_5 : 85,
13294 OP_6 : 86,
13295 OP_7 : 87,
13296 OP_8 : 88,
13297 OP_9 : 89,
13298 OP_10 : 90,
13299 OP_11 : 91,
13300 OP_12 : 92,
13301 OP_13 : 93,
13302 OP_14 : 94,
13303 OP_15 : 95,
13304 OP_16 : 96,
13305
13306 // control
13307 OP_NOP : 97,
13308 OP_VER : 98,
13309 OP_IF : 99,
13310 OP_NOTIF : 100,
13311 OP_VERIF : 101,
13312 OP_VERNOTIF : 102,
13313 OP_ELSE : 103,
13314 OP_ENDIF : 104,
13315 OP_VERIFY : 105,
13316 OP_RETURN : 106,
13317
13318 // stack ops
13319 OP_TOALTSTACK : 107,
13320 OP_FROMALTSTACK : 108,
13321 OP_2DROP : 109,
13322 OP_2DUP : 110,
13323 OP_3DUP : 111,
13324 OP_2OVER : 112,
13325 OP_2ROT : 113,
13326 OP_2SWAP : 114,
13327 OP_IFDUP : 115,
13328 OP_DEPTH : 116,
13329 OP_DROP : 117,
13330 OP_DUP : 118,
13331 OP_NIP : 119,
13332 OP_OVER : 120,
13333 OP_PICK : 121,
13334 OP_ROLL : 122,
13335 OP_ROT : 123,
13336 OP_SWAP : 124,
13337 OP_TUCK : 125,
13338
13339 // splice ops
13340 OP_CAT : 126,
13341 OP_SUBSTR : 127,
13342 OP_LEFT : 128,
13343 OP_RIGHT : 129,
13344 OP_SIZE : 130,
13345
13346 // bit logic
13347 OP_INVERT : 131,
13348 OP_AND : 132,
13349 OP_OR : 133,
13350 OP_XOR : 134,
13351 OP_EQUAL : 135,
13352 OP_EQUALVERIFY : 136,
13353 OP_RESERVED1 : 137,
13354 OP_RESERVED2 : 138,
13355
13356 // numeric
13357 OP_1ADD : 139,
13358 OP_1SUB : 140,
13359 OP_2MUL : 141,
13360 OP_2DIV : 142,
13361 OP_NEGATE : 143,
13362 OP_ABS : 144,
13363 OP_NOT : 145,
13364 OP_0NOTEQUAL : 146,
13365
13366 OP_ADD : 147,
13367 OP_SUB : 148,
13368 OP_MUL : 149,
13369 OP_DIV : 150,
13370 OP_MOD : 151,
13371 OP_LSHIFT : 152,
13372 OP_RSHIFT : 153,
13373
13374 OP_BOOLAND : 154,
13375 OP_BOOLOR : 155,
13376 OP_NUMEQUAL : 156,
13377 OP_NUMEQUALVERIFY : 157,
13378 OP_NUMNOTEQUAL : 158,
13379 OP_LESSTHAN : 159,
13380 OP_GREATERTHAN : 160,
13381 OP_LESSTHANOREQUAL : 161,
13382 OP_GREATERTHANOREQUAL : 162,
13383 OP_MIN : 163,
13384 OP_MAX : 164,
13385
13386 OP_WITHIN : 165,
13387
13388 // crypto
13389 OP_RIPEMD160 : 166,
13390 OP_SHA1 : 167,
13391 OP_SHA256 : 168,
13392 OP_HASH160 : 169,
13393 OP_HASH256 : 170,
13394 OP_CODESEPARATOR : 171,
13395 OP_CHECKSIG : 172,
13396 OP_CHECKSIGVERIFY : 173,
13397 OP_CHECKMULTISIG : 174,
13398 OP_CHECKMULTISIGVERIFY : 175,
13399
13400 // expansion
13401 OP_NOP1 : 176,
13402 OP_NOP2 : 177,
13403 OP_NOP3 : 178,
13404 OP_NOP4 : 179,
13405 OP_NOP5 : 180,
13406 OP_NOP6 : 181,
13407 OP_NOP7 : 182,
13408 OP_NOP8 : 183,
13409 OP_NOP9 : 184,
13410 OP_NOP10 : 185,
13411
13412 // template matching params
13413 OP_PUBKEYHASH : 253,
13414 OP_PUBKEY : 254,
13415 OP_INVALIDOPCODE : 255
13416}
13417
13418},{}],83:[function(_dereq_,module,exports){
13419(function (Buffer){
13420var assert = _dereq_('assert')
13421var bufferutils = _dereq_('./bufferutils')
13422var crypto = _dereq_('./crypto')
13423var opcodes = _dereq_('./opcodes')
13424
13425function Script(buffer, chunks) {
13426 assert(Buffer.isBuffer(buffer), 'Expected Buffer, got ' + buffer)
13427 assert(Array.isArray(chunks), 'Expected Array, got ' + chunks)
13428
13429 this.buffer = buffer
13430 this.chunks = chunks
13431}
13432
13433// Import operations
13434Script.fromASM = function(asm) {
13435 var strChunks = asm.split(' ')
13436
13437 var chunks = strChunks.map(function(strChunk) {
13438 if (strChunk in opcodes) {
13439 return opcodes[strChunk]
13440
13441 } else {
13442 return new Buffer(strChunk, 'hex')
13443 }
13444 })
13445
13446 return Script.fromChunks(chunks)
13447}
13448
13449Script.fromBuffer = function(buffer) {
13450 var chunks = []
13451
13452 var i = 0
13453
13454 while (i < buffer.length) {
13455 var opcode = buffer.readUInt8(i)
13456
13457 if ((opcode > opcodes.OP_0) && (opcode <= opcodes.OP_PUSHDATA4)) {
13458 var d = bufferutils.readPushDataInt(buffer, i)
13459 i += d.size
13460
13461 var data = buffer.slice(i, i + d.number)
13462 i += d.number
13463
13464 chunks.push(data)
13465
13466 } else {
13467 chunks.push(opcode)
13468
13469 i += 1
13470 }
13471 }
13472
13473 return new Script(buffer, chunks)
13474}
13475
13476Script.fromChunks = function(chunks) {
13477 assert(Array.isArray(chunks), 'Expected Array, got ' + chunks)
13478
13479 var bufferSize = chunks.reduce(function(accum, chunk) {
13480 if (Buffer.isBuffer(chunk)) {
13481 return accum + bufferutils.pushDataSize(chunk.length) + chunk.length
13482 }
13483
13484 return accum + 1
13485 }, 0.0)
13486
13487 var buffer = new Buffer(bufferSize)
13488 var offset = 0
13489
13490 chunks.forEach(function(chunk) {
13491 if (Buffer.isBuffer(chunk)) {
13492 offset += bufferutils.writePushDataInt(buffer, chunk.length, offset)
13493
13494 chunk.copy(buffer, offset)
13495 offset += chunk.length
13496
13497 } else {
13498 buffer.writeUInt8(chunk, offset)
13499 offset += 1
13500 }
13501 })
13502
13503 assert.equal(offset, buffer.length, 'Could not decode chunks')
13504 return new Script(buffer, chunks)
13505}
13506
13507Script.fromHex = function(hex) {
13508 return Script.fromBuffer(new Buffer(hex, 'hex'))
13509}
13510
13511// Constants
13512Script.EMPTY = Script.fromChunks([])
13513
13514// Operations
13515Script.prototype.getHash = function() {
13516 return crypto.hash160(this.buffer)
13517}
13518
13519// FIXME: doesn't work for data chunks, maybe time to use buffertools.compare...
13520Script.prototype.without = function(needle) {
13521 return Script.fromChunks(this.chunks.filter(function(op) {
13522 return op !== needle
13523 }))
13524}
13525
13526// Export operations
13527var reverseOps = []
13528for (var op in opcodes) {
13529 var code = opcodes[op]
13530 reverseOps[code] = op
13531}
13532
13533Script.prototype.toASM = function() {
13534 return this.chunks.map(function(chunk) {
13535 if (Buffer.isBuffer(chunk)) {
13536 return chunk.toString('hex')
13537
13538 } else {
13539 return reverseOps[chunk]
13540 }
13541 }).join(' ')
13542}
13543
13544Script.prototype.toBuffer = function() {
13545 return this.buffer
13546}
13547
13548Script.prototype.toHex = function() {
13549 return this.toBuffer().toString('hex')
13550}
13551
13552module.exports = Script
13553
13554}).call(this,_dereq_("buffer").Buffer)
13555},{"./bufferutils":71,"./crypto":73,"./opcodes":82,"assert":4,"buffer":8}],84:[function(_dereq_,module,exports){
13556(function (Buffer){
13557var assert = _dereq_('assert')
13558var opcodes = _dereq_('./opcodes')
13559
13560// FIXME: use ECPubKey, currently the circular dependency breaks everything.
13561//
13562// Solutions:
13563// * Remove ECPubKey.getAddress
13564// - Minimal change, but likely unpopular
13565// * Move all script related functionality out of Address
13566// - Means a lot of changes to Transaction/Wallet
13567// * Ignore it (existing solution)
13568// * Some form of hackery with commonjs
13569//
13570var ecurve = _dereq_('ecurve')
13571var curve = ecurve.getCurveByName('secp256k1')
13572
13573var ECSignature = _dereq_('./ecsignature')
13574var Script = _dereq_('./script')
13575
13576function classifyOutput(script) {
13577 assert(script instanceof Script, 'Expected Script, got ', script)
13578
13579 if (isPubKeyHashOutput.call(script)) {
13580 return 'pubkeyhash'
13581 } else if (isScriptHashOutput.call(script)) {
13582 return 'scripthash'
13583 } else if (isMultisigOutput.call(script)) {
13584 return 'multisig'
13585 } else if (isPubKeyOutput.call(script)) {
13586 return 'pubkey'
13587 } else if (isNulldataOutput.call(script)) {
13588 return 'nulldata'
13589 } else {
13590 return 'nonstandard'
13591 }
13592}
13593
13594function classifyInput(script) {
13595 assert(script instanceof Script, 'Expected Script, got ', script)
13596
13597 if (isPubKeyHashInput.call(script)) {
13598 return 'pubkeyhash'
13599 } else if (isScriptHashInput.call(script)) {
13600 return 'scripthash'
13601 } else if (isMultisigInput.call(script)) {
13602 return 'multisig'
13603 } else if (isPubKeyInput.call(script)) {
13604 return 'pubkey'
13605 } else {
13606 return 'nonstandard'
13607 }
13608}
13609
13610function isCanonicalPubKey(buffer) {
13611 if (!Buffer.isBuffer(buffer)) return false
13612
13613 try {
13614 // FIXME: boo
13615 ecurve.Point.decodeFrom(curve, buffer)
13616 } catch (e) {
13617 if (!(e.message.match(/Invalid sequence (length|tag)/))) throw e
13618
13619 return false
13620 }
13621
13622 return true
13623}
13624
13625function isCanonicalSignature(buffer) {
13626 if (!Buffer.isBuffer(buffer)) return false
13627
13628 try {
13629 ECSignature.parseScriptSignature(buffer)
13630 } catch(e) {
13631 if (!(e.message.match(/Not a DER sequence|Invalid sequence length|Expected a DER integer|R length is zero|S length is zero|R value excessively padded|S value excessively padded|R value is negative|S value is negative|Invalid hashType/))) throw e
13632
13633 return false
13634 }
13635
13636 return true
13637}
13638
13639function isPubKeyHashInput() {
13640 return this.chunks.length === 2 &&
13641 isCanonicalSignature(this.chunks[0]) &&
13642 isCanonicalPubKey(this.chunks[1])
13643}
13644
13645function isPubKeyHashOutput() {
13646 return this.chunks.length === 5 &&
13647 this.chunks[0] === opcodes.OP_DUP &&
13648 this.chunks[1] === opcodes.OP_HASH160 &&
13649 Buffer.isBuffer(this.chunks[2]) &&
13650 this.chunks[2].length === 20 &&
13651 this.chunks[3] === opcodes.OP_EQUALVERIFY &&
13652 this.chunks[4] === opcodes.OP_CHECKSIG
13653}
13654
13655function isPubKeyInput() {
13656 return this.chunks.length === 1 &&
13657 isCanonicalSignature(this.chunks[0])
13658}
13659
13660function isPubKeyOutput() {
13661 return this.chunks.length === 2 &&
13662 isCanonicalPubKey(this.chunks[0]) &&
13663 this.chunks[1] === opcodes.OP_CHECKSIG
13664}
13665
13666function isScriptHashInput() {
13667 if (this.chunks.length < 2) return false
13668 var lastChunk = this.chunks[this.chunks.length - 1]
13669
13670 if (!Buffer.isBuffer(lastChunk)) return false
13671
13672 var scriptSig = Script.fromChunks(this.chunks.slice(0, -1))
13673 var scriptPubKey = Script.fromBuffer(lastChunk)
13674
13675 return classifyInput(scriptSig) === classifyOutput(scriptPubKey)
13676}
13677
13678function isScriptHashOutput() {
13679 return this.chunks.length === 3 &&
13680 this.chunks[0] === opcodes.OP_HASH160 &&
13681 Buffer.isBuffer(this.chunks[1]) &&
13682 this.chunks[1].length === 20 &&
13683 this.chunks[2] === opcodes.OP_EQUAL
13684}
13685
13686function isMultisigInput() {
13687 return this.chunks[0] === opcodes.OP_0 &&
13688 this.chunks.slice(1).every(isCanonicalSignature)
13689}
13690
13691function isMultisigOutput() {
13692 if (this.chunks < 4) return false
13693 if (this.chunks[this.chunks.length - 1] !== opcodes.OP_CHECKMULTISIG) return false
13694
13695 var mOp = this.chunks[0]
13696 if (mOp === opcodes.OP_0) return false
13697 if (mOp < opcodes.OP_1) return false
13698 if (mOp > opcodes.OP_16) return false
13699
13700 var nOp = this.chunks[this.chunks.length - 2]
13701 if (nOp === opcodes.OP_0) return false
13702 if (nOp < opcodes.OP_1) return false
13703 if (nOp > opcodes.OP_16) return false
13704
13705 var m = mOp - (opcodes.OP_1 - 1)
13706 var n = nOp - (opcodes.OP_1 - 1)
13707 if (n < m) return false
13708
13709 var pubKeys = this.chunks.slice(1, -2)
13710 if (n < pubKeys.length) return false
13711
13712 return pubKeys.every(isCanonicalPubKey)
13713}
13714
13715function isNulldataOutput() {
13716 return this.chunks[0] === opcodes.OP_RETURN
13717}
13718
13719// Standard Script Templates
13720// {pubKey} OP_CHECKSIG
13721function pubKeyOutput(pubKey) {
13722 return Script.fromChunks([
13723 pubKey.toBuffer(),
13724 opcodes.OP_CHECKSIG
13725 ])
13726}
13727
13728// OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
13729function pubKeyHashOutput(hash) {
13730 assert(Buffer.isBuffer(hash), 'Expected Buffer, got ' + hash)
13731
13732 return Script.fromChunks([
13733 opcodes.OP_DUP,
13734 opcodes.OP_HASH160,
13735 hash,
13736 opcodes.OP_EQUALVERIFY,
13737 opcodes.OP_CHECKSIG
13738 ])
13739}
13740
13741// OP_HASH160 {scriptHash} OP_EQUAL
13742function scriptHashOutput(hash) {
13743 assert(Buffer.isBuffer(hash), 'Expected Buffer, got ' + hash)
13744
13745 return Script.fromChunks([
13746 opcodes.OP_HASH160,
13747 hash,
13748 opcodes.OP_EQUAL
13749 ])
13750}
13751
13752// m [pubKeys ...] n OP_CHECKMULTISIG
13753function multisigOutput(m, pubKeys) {
13754 assert(Array.isArray(pubKeys), 'Expected Array, got ' + pubKeys)
13755 assert(pubKeys.length >= m, 'Not enough pubKeys provided')
13756
13757 var pubKeyBuffers = pubKeys.map(function(pubKey) {
13758 return pubKey.toBuffer()
13759 })
13760 var n = pubKeys.length
13761
13762 return Script.fromChunks([].concat(
13763 (opcodes.OP_1 - 1) + m,
13764 pubKeyBuffers,
13765 (opcodes.OP_1 - 1) + n,
13766 opcodes.OP_CHECKMULTISIG
13767 ))
13768}
13769
13770// {signature}
13771function pubKeyInput(signature) {
13772 assert(Buffer.isBuffer(signature), 'Expected Buffer, got ' + signature)
13773
13774 return Script.fromChunks([signature])
13775}
13776
13777// {signature} {pubKey}
13778function pubKeyHashInput(signature, pubKey) {
13779 assert(Buffer.isBuffer(signature), 'Expected Buffer, got ' + signature)
13780
13781 return Script.fromChunks([signature, pubKey.toBuffer()])
13782}
13783
13784// <scriptSig> {serialized scriptPubKey script}
13785function scriptHashInput(scriptSig, scriptPubKey) {
13786 return Script.fromChunks([].concat(
13787 scriptSig.chunks,
13788 scriptPubKey.toBuffer()
13789 ))
13790}
13791
13792// OP_0 [signatures ...]
13793function multisigInput(signatures, scriptPubKey) {
13794 if (scriptPubKey) {
13795 assert(isMultisigOutput.call(scriptPubKey))
13796
13797 var m = scriptPubKey.chunks[0]
13798 var k = m - (opcodes.OP_1 - 1)
13799 assert(k <= signatures.length, 'Not enough signatures provided')
13800 }
13801
13802 return Script.fromChunks([].concat(opcodes.OP_0, signatures))
13803}
13804
13805module.exports = {
13806 classifyInput: classifyInput,
13807 classifyOutput: classifyOutput,
13808 multisigInput: multisigInput,
13809 multisigOutput: multisigOutput,
13810 pubKeyHashInput: pubKeyHashInput,
13811 pubKeyHashOutput: pubKeyHashOutput,
13812 pubKeyInput: pubKeyInput,
13813 pubKeyOutput: pubKeyOutput,
13814 scriptHashInput: scriptHashInput,
13815 scriptHashOutput: scriptHashOutput
13816}
13817
13818}).call(this,_dereq_("buffer").Buffer)
13819},{"./ecsignature":77,"./opcodes":82,"./script":83,"assert":4,"buffer":8,"ecurve":65}],85:[function(_dereq_,module,exports){
13820(function (Buffer){
13821var assert = _dereq_('assert')
13822var bufferutils = _dereq_('./bufferutils')
13823var crypto = _dereq_('./crypto')
13824var opcodes = _dereq_('./opcodes')
13825var scripts = _dereq_('./scripts')
13826
13827var Address = _dereq_('./address')
13828var ECKey = _dereq_('./eckey')
13829var ECSignature = _dereq_('./ecsignature')
13830var Script = _dereq_('./script')
13831
13832Transaction.DEFAULT_SEQUENCE = 0xffffffff
13833Transaction.SIGHASH_ALL = 0x01
13834Transaction.SIGHASH_NONE = 0x02
13835Transaction.SIGHASH_SINGLE = 0x03
13836Transaction.SIGHASH_ANYONECANPAY = 0x80
13837
13838function Transaction() {
13839 this.version = 1
13840 this.locktime = 0
13841 this.ins = []
13842 this.outs = []
13843}
13844
13845/**
13846 * Create a new txin.
13847 *
13848 * Can be called with any of:
13849 *
13850 * - A transaction and an index
13851 * - A transaction hash and an index
13852 *
13853 * Note that this method does not sign the created input.
13854 */
13855Transaction.prototype.addInput = function(tx, index, sequence) {
13856 if (sequence == undefined) sequence = Transaction.DEFAULT_SEQUENCE
13857
13858 var hash
13859
13860 if (typeof tx === 'string') {
13861 hash = new Buffer(tx, 'hex')
13862
13863 // TxId hex is big-endian, we need little-endian
13864 Array.prototype.reverse.call(hash)
13865
13866 } else if (tx instanceof Transaction) {
13867 hash = tx.getHash()
13868
13869 } else {
13870 hash = tx
13871 }
13872
13873 assert(Buffer.isBuffer(hash), 'Expected Transaction, txId or txHash, got ' + tx)
13874 assert.equal(hash.length, 32, 'Expected hash length of 32, got ' + hash.length)
13875 assert.equal(typeof index, 'number', 'Expected number index, got ' + index)
13876
13877 return (this.ins.push({
13878 hash: hash,
13879 index: index,
13880 script: Script.EMPTY,
13881 sequence: sequence
13882 }) - 1)
13883}
13884
13885/**
13886 * Create a new txout.
13887 *
13888 * Can be called with:
13889 *
13890 * - A base58 address string and a value
13891 * - An Address object and a value
13892 * - A scriptPubKey Script and a value
13893 */
13894Transaction.prototype.addOutput = function(scriptPubKey, value) {
13895 // Attempt to get a valid address if it's a base58 address string
13896 if (typeof scriptPubKey === 'string') {
13897 scriptPubKey = Address.fromBase58Check(scriptPubKey)
13898 }
13899
13900 // Attempt to get a valid script if it's an Address object
13901 if (scriptPubKey instanceof Address) {
13902 var address = scriptPubKey
13903
13904 scriptPubKey = address.toOutputScript()
13905 }
13906
13907 return (this.outs.push({
13908 script: scriptPubKey,
13909 value: value,
13910 }) - 1)
13911}
13912
13913Transaction.prototype.toBuffer = function () {
13914 var txInSize = this.ins.reduce(function(a, x) {
13915 return a + (40 + bufferutils.varIntSize(x.script.buffer.length) + x.script.buffer.length)
13916 }, 0)
13917
13918 var txOutSize = this.outs.reduce(function(a, x) {
13919 return a + (8 + bufferutils.varIntSize(x.script.buffer.length) + x.script.buffer.length)
13920 }, 0)
13921
13922 var buffer = new Buffer(
13923 8 +
13924 bufferutils.varIntSize(this.ins.length) +
13925 bufferutils.varIntSize(this.outs.length) +
13926 txInSize +
13927 txOutSize
13928 )
13929
13930 var offset = 0
13931 function writeSlice(slice) {
13932 slice.copy(buffer, offset)
13933 offset += slice.length
13934 }
13935 function writeUInt32(i) {
13936 buffer.writeUInt32LE(i, offset)
13937 offset += 4
13938 }
13939 function writeUInt64(i) {
13940 bufferutils.writeUInt64LE(buffer, i, offset)
13941 offset += 8
13942 }
13943 function writeVarInt(i) {
13944 var n = bufferutils.writeVarInt(buffer, i, offset)
13945 offset += n
13946 }
13947
13948 writeUInt32(this.version)
13949 writeVarInt(this.ins.length)
13950
13951 this.ins.forEach(function(txin) {
13952 writeSlice(txin.hash)
13953 writeUInt32(txin.index)
13954 writeVarInt(txin.script.buffer.length)
13955 writeSlice(txin.script.buffer)
13956 writeUInt32(txin.sequence)
13957 })
13958
13959 writeVarInt(this.outs.length)
13960 this.outs.forEach(function(txout) {
13961 writeUInt64(txout.value)
13962 writeVarInt(txout.script.buffer.length)
13963 writeSlice(txout.script.buffer)
13964 })
13965
13966 writeUInt32(this.locktime)
13967
13968 return buffer
13969}
13970
13971Transaction.prototype.toHex = function() {
13972 return this.toBuffer().toString('hex')
13973}
13974
13975/**
13976 * Hash transaction for signing a specific input.
13977 *
13978 * Bitcoin uses a different hash for each signed transaction input. This
13979 * method copies the transaction, makes the necessary changes based on the
13980 * hashType, serializes and finally hashes the result. This hash can then be
13981 * used to sign the transaction input in question.
13982 */
13983Transaction.prototype.hashForSignature = function(prevOutScript, inIndex, hashType) {
13984 assert(inIndex >= 0, 'Invalid vin index')
13985 assert(inIndex < this.ins.length, 'Invalid vin index')
13986 assert(prevOutScript instanceof Script, 'Invalid Script object')
13987
13988 var txTmp = this.clone()
13989 var hashScript = prevOutScript.without(opcodes.OP_CODESEPARATOR)
13990
13991 // Blank out other inputs' signatures
13992 txTmp.ins.forEach(function(txin) {
13993 txin.script = Script.EMPTY
13994 })
13995 txTmp.ins[inIndex].script = hashScript
13996
13997 var hashTypeModifier = hashType & 0x1f
13998 if (hashTypeModifier === Transaction.SIGHASH_NONE) {
13999 assert(false, 'SIGHASH_NONE not yet supported')
14000
14001 } else if (hashTypeModifier === Transaction.SIGHASH_SINGLE) {
14002 assert(false, 'SIGHASH_SINGLE not yet supported')
14003
14004 }
14005
14006 if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
14007 assert(false, 'SIGHASH_ANYONECANPAY not yet supported')
14008 }
14009
14010 var hashTypeBuffer = new Buffer(4)
14011 hashTypeBuffer.writeInt32LE(hashType, 0)
14012
14013 var buffer = Buffer.concat([txTmp.toBuffer(), hashTypeBuffer])
14014 return crypto.hash256(buffer)
14015}
14016
14017Transaction.prototype.getHash = function () {
14018 return crypto.hash256(this.toBuffer())
14019}
14020
14021Transaction.prototype.getId = function () {
14022 var buffer = this.getHash()
14023
14024 // Big-endian is used for TxHash
14025 Array.prototype.reverse.call(buffer)
14026
14027 return buffer.toString('hex')
14028}
14029
14030Transaction.prototype.clone = function () {
14031 var newTx = new Transaction()
14032 newTx.version = this.version
14033 newTx.locktime = this.locktime
14034
14035 newTx.ins = this.ins.map(function(txin) {
14036 return {
14037 hash: txin.hash,
14038 index: txin.index,
14039 script: txin.script,
14040 sequence: txin.sequence
14041 }
14042 })
14043
14044 newTx.outs = this.outs.map(function(txout) {
14045 return {
14046 script: txout.script,
14047 value: txout.value
14048 }
14049 })
14050
14051 return newTx
14052}
14053
14054Transaction.fromBuffer = function(buffer) {
14055 var offset = 0
14056 function readSlice(n) {
14057 offset += n
14058 return buffer.slice(offset - n, offset)
14059 }
14060 function readUInt32() {
14061 var i = buffer.readUInt32LE(offset)
14062 offset += 4
14063 return i
14064 }
14065 function readUInt64() {
14066 var i = bufferutils.readUInt64LE(buffer, offset)
14067 offset += 8
14068 return i
14069 }
14070 function readVarInt() {
14071 var vi = bufferutils.readVarInt(buffer, offset)
14072 offset += vi.size
14073 return vi.number
14074 }
14075
14076 var tx = new Transaction()
14077 tx.version = readUInt32()
14078
14079 var vinLen = readVarInt()
14080 for (var i = 0; i < vinLen; ++i) {
14081 var hash = readSlice(32)
14082 var vout = readUInt32()
14083 var scriptLen = readVarInt()
14084 var script = readSlice(scriptLen)
14085 var sequence = readUInt32()
14086
14087 tx.ins.push({
14088 hash: hash,
14089 index: vout,
14090 script: Script.fromBuffer(script),
14091 sequence: sequence
14092 })
14093 }
14094
14095 var voutLen = readVarInt()
14096 for (i = 0; i < voutLen; ++i) {
14097 var value = readUInt64()
14098 var scriptLen = readVarInt()
14099 var script = readSlice(scriptLen)
14100
14101 tx.outs.push({
14102 value: value,
14103 script: Script.fromBuffer(script)
14104 })
14105 }
14106
14107 tx.locktime = readUInt32()
14108 assert.equal(offset, buffer.length, 'Transaction has unexpected data')
14109
14110 return tx
14111}
14112
14113Transaction.fromHex = function(hex) {
14114 return Transaction.fromBuffer(new Buffer(hex, 'hex'))
14115}
14116
14117/**
14118 * Signs a pubKeyHash output at some index with the given key
14119 */
14120Transaction.prototype.sign = function(index, privKey, hashType) {
14121 var prevOutScript = privKey.pub.getAddress().toOutputScript()
14122 var signature = this.signInput(index, prevOutScript, privKey, hashType)
14123
14124 // FIXME: Assumed prior TX was pay-to-pubkey-hash
14125 var scriptSig = scripts.pubKeyHashInput(signature, privKey.pub)
14126 this.setInputScript(index, scriptSig)
14127}
14128
14129Transaction.prototype.signInput = function(index, prevOutScript, privKey, hashType) {
14130 hashType = hashType || Transaction.SIGHASH_ALL
14131
14132 var hash = this.hashForSignature(prevOutScript, index, hashType)
14133 var signature = privKey.sign(hash)
14134
14135 return signature.toScriptSignature(hashType)
14136}
14137
14138Transaction.prototype.setInputScript = function(index, script) {
14139 this.ins[index].script = script
14140}
14141
14142// FIXME: could be validateInput(index, prevTxOut, pub)
14143Transaction.prototype.validateInput = function(index, prevOutScript, pubKey, buffer) {
14144 var parsed = ECSignature.parseScriptSignature(buffer)
14145 var hash = this.hashForSignature(prevOutScript, index, parsed.hashType)
14146
14147 return pubKey.verify(hash, parsed.signature)
14148}
14149
14150module.exports = Transaction
14151
14152}).call(this,_dereq_("buffer").Buffer)
14153},{"./address":69,"./bufferutils":71,"./crypto":73,"./eckey":75,"./ecsignature":77,"./opcodes":82,"./script":83,"./scripts":84,"assert":4,"buffer":8}],86:[function(_dereq_,module,exports){
14154(function (Buffer){
14155var assert = _dereq_('assert')
14156var networks = _dereq_('./networks')
14157var rng = _dereq_('secure-random')
14158
14159var Address = _dereq_('./address')
14160var HDNode = _dereq_('./hdnode')
14161var Transaction = _dereq_('./transaction')
14162
14163function Wallet(seed, network) {
14164 network = network || networks.bitcoin
14165
14166 // Stored in a closure to make accidental serialization less likely
14167 var masterkey = null
14168 var me = this
14169 var accountZero = null
14170 var internalAccount = null
14171 var externalAccount = null
14172
14173 // Addresses
14174 this.addresses = []
14175 this.changeAddresses = []
14176
14177 // Transaction output data
14178 this.outputs = {}
14179
14180 // Make a new master key
14181 this.newMasterKey = function(seed) {
14182 seed = seed || new Buffer(rng(32))
14183 masterkey = HDNode.fromSeedBuffer(seed, network)
14184
14185 // HD first-level child derivation method should be hardened
14186 // See https://bitcointalk.org/index.php?topic=405179.msg4415254#msg4415254
14187 accountZero = masterkey.deriveHardened(0)
14188 externalAccount = accountZero.derive(0)
14189 internalAccount = accountZero.derive(1)
14190
14191 me.addresses = []
14192 me.changeAddresses = []
14193
14194 me.outputs = {}
14195 }
14196
14197 this.newMasterKey(seed)
14198
14199 this.generateAddress = function() {
14200 var key = externalAccount.derive(this.addresses.length)
14201 this.addresses.push(key.getAddress().toString())
14202 return this.addresses[this.addresses.length - 1]
14203 }
14204
14205 this.generateChangeAddress = function() {
14206 var key = internalAccount.derive(this.changeAddresses.length)
14207 this.changeAddresses.push(key.getAddress().toString())
14208 return this.changeAddresses[this.changeAddresses.length - 1]
14209 }
14210
14211 this.getBalance = function() {
14212 return this.getUnspentOutputs().reduce(function(memo, output){
14213 return memo + output.value
14214 }, 0)
14215 }
14216
14217 this.getUnspentOutputs = function() {
14218 var utxo = []
14219
14220 for(var key in this.outputs){
14221 var output = this.outputs[key]
14222 if(!output.to) utxo.push(outputToUnspentOutput(output))
14223 }
14224
14225 return utxo
14226 }
14227
14228 this.setUnspentOutputs = function(utxo) {
14229 var outputs = {}
14230
14231 utxo.forEach(function(uo){
14232 validateUnspentOutput(uo)
14233 var o = unspentOutputToOutput(uo)
14234 outputs[o.from] = o
14235 })
14236
14237 this.outputs = outputs
14238 }
14239
14240 function outputToUnspentOutput(output){
14241 var hashAndIndex = output.from.split(":")
14242
14243 return {
14244 hash: hashAndIndex[0],
14245 outputIndex: parseInt(hashAndIndex[1]),
14246 address: output.address,
14247 value: output.value,
14248 pending: output.pending
14249 }
14250 }
14251
14252 function unspentOutputToOutput(o) {
14253 var hash = o.hash
14254 var key = hash + ":" + o.outputIndex
14255 return {
14256 from: key,
14257 address: o.address,
14258 value: o.value,
14259 pending: o.pending
14260 }
14261 }
14262
14263 function validateUnspentOutput(uo) {
14264 var missingField
14265
14266 if (isNullOrUndefined(uo.hash)) {
14267 missingField = "hash"
14268 }
14269
14270 var requiredKeys = ['outputIndex', 'address', 'value']
14271 requiredKeys.forEach(function (key) {
14272 if (isNullOrUndefined(uo[key])){
14273 missingField = key
14274 }
14275 })
14276
14277 if (missingField) {
14278 var message = [
14279 'Invalid unspent output: key', missingField, 'is missing.',
14280 'A valid unspent output must contain'
14281 ]
14282 message.push(requiredKeys.join(', '))
14283 message.push("and hash")
14284 throw new Error(message.join(' '))
14285 }
14286 }
14287
14288 function isNullOrUndefined(value) {
14289 return value == undefined
14290 }
14291
14292 this.processPendingTx = function(tx){
14293 processTx(tx, true)
14294 }
14295
14296 this.processConfirmedTx = function(tx){
14297 processTx(tx, false)
14298 }
14299
14300 function processTx(tx, isPending) {
14301 var txid = tx.getId()
14302
14303 tx.outs.forEach(function(txOut, i) {
14304 var address
14305
14306 try {
14307 address = Address.fromOutputScript(txOut.script, network).toString()
14308 } catch(e) {
14309 if (!(e.message.match(/has no matching Address/))) throw e
14310 }
14311
14312 if (isMyAddress(address)) {
14313 var output = txid + ':' + i
14314
14315 me.outputs[output] = {
14316 from: output,
14317 value: txOut.value,
14318 address: address,
14319 pending: isPending
14320 }
14321 }
14322 })
14323
14324 tx.ins.forEach(function(txIn, i) {
14325 // copy and convert to big-endian hex
14326 var txinId = new Buffer(txIn.hash)
14327 Array.prototype.reverse.call(txinId)
14328 txinId = txinId.toString('hex')
14329
14330 var output = txinId + ':' + txIn.index
14331
14332 if (!(output in me.outputs)) return
14333
14334 if (isPending) {
14335 me.outputs[output].to = txid + ':' + i
14336 me.outputs[output].pending = true
14337 } else {
14338 delete me.outputs[output]
14339 }
14340 })
14341 }
14342
14343 this.createTx = function(to, value, fixedFee, changeAddress) {
14344 assert(value > network.dustThreshold, value + ' must be above dust threshold (' + network.dustThreshold + ' Satoshis)')
14345
14346 var utxos = getCandidateOutputs(value)
14347 var accum = 0
14348 var subTotal = value
14349 var addresses = []
14350
14351 var tx = new Transaction()
14352 tx.addOutput(to, value)
14353
14354 for (var i = 0; i < utxos.length; ++i) {
14355 var utxo = utxos[i]
14356 addresses.push(utxo.address)
14357
14358 var outpoint = utxo.from.split(':')
14359 tx.addInput(outpoint[0], parseInt(outpoint[1]))
14360
14361 var fee = fixedFee == undefined ? estimateFeePadChangeOutput(tx) : fixedFee
14362
14363 accum += utxo.value
14364 subTotal = value + fee
14365 if (accum >= subTotal) {
14366 var change = accum - subTotal
14367
14368 if (change > network.dustThreshold) {
14369 tx.addOutput(changeAddress || getChangeAddress(), change)
14370 }
14371
14372 break
14373 }
14374 }
14375
14376 assert(accum >= subTotal, 'Not enough funds (incl. fee): ' + accum + ' < ' + subTotal)
14377
14378 this.signWith(tx, addresses)
14379 return tx
14380 }
14381
14382 function getCandidateOutputs() {
14383 var unspent = []
14384
14385 for (var key in me.outputs) {
14386 var output = me.outputs[key]
14387 if (!output.pending) unspent.push(output)
14388 }
14389
14390 var sortByValueDesc = unspent.sort(function(o1, o2){
14391 return o2.value - o1.value
14392 })
14393
14394 return sortByValueDesc
14395 }
14396
14397 function estimateFeePadChangeOutput(tx) {
14398 var tmpTx = tx.clone()
14399 tmpTx.addOutput(getChangeAddress(), network.dustSoftThreshold || 0)
14400
14401 return network.estimateFee(tmpTx)
14402 }
14403
14404 function getChangeAddress() {
14405 if(me.changeAddresses.length === 0) me.generateChangeAddress();
14406 return me.changeAddresses[me.changeAddresses.length - 1]
14407 }
14408
14409 this.signWith = function(tx, addresses) {
14410 assert.equal(tx.ins.length, addresses.length, 'Number of addresses must match number of transaction inputs')
14411
14412 addresses.forEach(function(address, i) {
14413 var key = me.getPrivateKeyForAddress(address)
14414
14415 tx.sign(i, key)
14416 })
14417
14418 return tx
14419 }
14420
14421 this.getMasterKey = function() { return masterkey }
14422 this.getAccountZero = function() { return accountZero }
14423 this.getInternalAccount = function() { return internalAccount }
14424 this.getExternalAccount = function() { return externalAccount }
14425
14426 this.getPrivateKey = function(index) {
14427 return externalAccount.derive(index).privKey
14428 }
14429
14430 this.getInternalPrivateKey = function(index) {
14431 return internalAccount.derive(index).privKey
14432 }
14433
14434 this.getPrivateKeyForAddress = function(address) {
14435 var index
14436 if((index = this.addresses.indexOf(address)) > -1) {
14437 return this.getPrivateKey(index)
14438 } else if((index = this.changeAddresses.indexOf(address)) > -1) {
14439 return this.getInternalPrivateKey(index)
14440 } else {
14441 throw new Error('Unknown address. Make sure the address is from the keychain and has been generated.')
14442 }
14443 }
14444
14445 function isReceiveAddress(address){
14446 return me.addresses.indexOf(address) > -1
14447 }
14448
14449 function isChangeAddress(address){
14450 return me.changeAddresses.indexOf(address) > -1
14451 }
14452
14453 function isMyAddress(address) {
14454 return isReceiveAddress(address) || isChangeAddress(address)
14455 }
14456}
14457
14458module.exports = Wallet
14459
14460}).call(this,_dereq_("buffer").Buffer)
14461},{"./address":69,"./hdnode":78,"./networks":81,"./transaction":85,"assert":4,"buffer":8,"secure-random":68}]},{},[79])
14462(79)
14463});
diff --git a/src/js/bitcoinjs-1-5-7.js b/src/js/bitcoinjs-1-5-7.js
new file mode 100644
index 0000000..7b7e8e8
--- /dev/null
+++ b/src/js/bitcoinjs-1-5-7.js
@@ -0,0 +1,12683 @@
1(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.bitcoin = 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<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2// (public) Constructor
3function BigInteger(a, b, c) {
4 if (!(this instanceof BigInteger))
5 return new BigInteger(a, b, c)
6
7 if (a != null) {
8 if ("number" == typeof a) this.fromNumber(a, b, c)
9 else if (b == null && "string" != typeof a) this.fromString(a, 256)
10 else this.fromString(a, b)
11 }
12}
13
14var proto = BigInteger.prototype
15
16// duck-typed isBigInteger
17proto.__bigi = require('../package.json').version
18BigInteger.isBigInteger = function (obj, check_ver) {
19 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
20}
21
22// Bits per digit
23var dbits
24
25// am: Compute w_j += (x*this_i), propagate carries,
26// c is initial carry, returns final carry.
27// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
28// We need to select the fastest one that works in this environment.
29
30// am1: use a single mult and divide to get the high bits,
31// max digit bits should be 26 because
32// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
33function am1(i, x, w, j, c, n) {
34 while (--n >= 0) {
35 var v = x * this[i++] + w[j] + c
36 c = Math.floor(v / 0x4000000)
37 w[j++] = v & 0x3ffffff
38 }
39 return c
40}
41// am2 avoids a big mult-and-extract completely.
42// Max digit bits should be <= 30 because we do bitwise ops
43// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
44function am2(i, x, w, j, c, n) {
45 var xl = x & 0x7fff,
46 xh = x >> 15
47 while (--n >= 0) {
48 var l = this[i] & 0x7fff
49 var h = this[i++] >> 15
50 var m = xh * l + h * xl
51 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
52 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
53 w[j++] = l & 0x3fffffff
54 }
55 return c
56}
57// Alternately, set max digit bits to 28 since some
58// browsers slow down when dealing with 32-bit numbers.
59function am3(i, x, w, j, c, n) {
60 var xl = x & 0x3fff,
61 xh = x >> 14
62 while (--n >= 0) {
63 var l = this[i] & 0x3fff
64 var h = this[i++] >> 14
65 var m = xh * l + h * xl
66 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
67 c = (l >> 28) + (m >> 14) + xh * h
68 w[j++] = l & 0xfffffff
69 }
70 return c
71}
72
73// wtf?
74BigInteger.prototype.am = am1
75dbits = 26
76
77BigInteger.prototype.DB = dbits
78BigInteger.prototype.DM = ((1 << dbits) - 1)
79var DV = BigInteger.prototype.DV = (1 << dbits)
80
81var BI_FP = 52
82BigInteger.prototype.FV = Math.pow(2, BI_FP)
83BigInteger.prototype.F1 = BI_FP - dbits
84BigInteger.prototype.F2 = 2 * dbits - BI_FP
85
86// Digit conversions
87var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
88var BI_RC = new Array()
89var rr, vv
90rr = "0".charCodeAt(0)
91for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
92rr = "a".charCodeAt(0)
93for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
94rr = "A".charCodeAt(0)
95for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
96
97function int2char(n) {
98 return BI_RM.charAt(n)
99}
100
101function intAt(s, i) {
102 var c = BI_RC[s.charCodeAt(i)]
103 return (c == null) ? -1 : c
104}
105
106// (protected) copy this to r
107function bnpCopyTo(r) {
108 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
109 r.t = this.t
110 r.s = this.s
111}
112
113// (protected) set from integer value x, -DV <= x < DV
114function bnpFromInt(x) {
115 this.t = 1
116 this.s = (x < 0) ? -1 : 0
117 if (x > 0) this[0] = x
118 else if (x < -1) this[0] = x + DV
119 else this.t = 0
120}
121
122// return bigint initialized to value
123function nbv(i) {
124 var r = new BigInteger()
125 r.fromInt(i)
126 return r
127}
128
129// (protected) set from string and radix
130function bnpFromString(s, b) {
131 var self = this
132
133 var k
134 if (b == 16) k = 4
135 else if (b == 8) k = 3
136 else if (b == 256) k = 8; // byte array
137 else if (b == 2) k = 1
138 else if (b == 32) k = 5
139 else if (b == 4) k = 2
140 else {
141 self.fromRadix(s, b)
142 return
143 }
144 self.t = 0
145 self.s = 0
146 var i = s.length,
147 mi = false,
148 sh = 0
149 while (--i >= 0) {
150 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
151 if (x < 0) {
152 if (s.charAt(i) == "-") mi = true
153 continue
154 }
155 mi = false
156 if (sh == 0)
157 self[self.t++] = x
158 else if (sh + k > self.DB) {
159 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
160 self[self.t++] = (x >> (self.DB - sh))
161 } else
162 self[self.t - 1] |= x << sh
163 sh += k
164 if (sh >= self.DB) sh -= self.DB
165 }
166 if (k == 8 && (s[0] & 0x80) != 0) {
167 self.s = -1
168 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
169 }
170 self.clamp()
171 if (mi) BigInteger.ZERO.subTo(self, self)
172}
173
174// (protected) clamp off excess high words
175function bnpClamp() {
176 var c = this.s & this.DM
177 while (this.t > 0 && this[this.t - 1] == c)--this.t
178}
179
180// (public) return string representation in given radix
181function bnToString(b) {
182 var self = this
183 if (self.s < 0) return "-" + self.negate()
184 .toString(b)
185 var k
186 if (b == 16) k = 4
187 else if (b == 8) k = 3
188 else if (b == 2) k = 1
189 else if (b == 32) k = 5
190 else if (b == 4) k = 2
191 else return self.toRadix(b)
192 var km = (1 << k) - 1,
193 d, m = false,
194 r = "",
195 i = self.t
196 var p = self.DB - (i * self.DB) % k
197 if (i-- > 0) {
198 if (p < self.DB && (d = self[i] >> p) > 0) {
199 m = true
200 r = int2char(d)
201 }
202 while (i >= 0) {
203 if (p < k) {
204 d = (self[i] & ((1 << p) - 1)) << (k - p)
205 d |= self[--i] >> (p += self.DB - k)
206 } else {
207 d = (self[i] >> (p -= k)) & km
208 if (p <= 0) {
209 p += self.DB
210 --i
211 }
212 }
213 if (d > 0) m = true
214 if (m) r += int2char(d)
215 }
216 }
217 return m ? r : "0"
218}
219
220// (public) -this
221function bnNegate() {
222 var r = new BigInteger()
223 BigInteger.ZERO.subTo(this, r)
224 return r
225}
226
227// (public) |this|
228function bnAbs() {
229 return (this.s < 0) ? this.negate() : this
230}
231
232// (public) return + if this > a, - if this < a, 0 if equal
233function bnCompareTo(a) {
234 var r = this.s - a.s
235 if (r != 0) return r
236 var i = this.t
237 r = i - a.t
238 if (r != 0) return (this.s < 0) ? -r : r
239 while (--i >= 0)
240 if ((r = this[i] - a[i]) != 0) return r
241 return 0
242}
243
244// returns bit length of the integer x
245function nbits(x) {
246 var r = 1,
247 t
248 if ((t = x >>> 16) != 0) {
249 x = t
250 r += 16
251 }
252 if ((t = x >> 8) != 0) {
253 x = t
254 r += 8
255 }
256 if ((t = x >> 4) != 0) {
257 x = t
258 r += 4
259 }
260 if ((t = x >> 2) != 0) {
261 x = t
262 r += 2
263 }
264 if ((t = x >> 1) != 0) {
265 x = t
266 r += 1
267 }
268 return r
269}
270
271// (public) return the number of bits in "this"
272function bnBitLength() {
273 if (this.t <= 0) return 0
274 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
275}
276
277// (public) return the number of bytes in "this"
278function bnByteLength() {
279 return this.bitLength() >> 3
280}
281
282// (protected) r = this << n*DB
283function bnpDLShiftTo(n, r) {
284 var i
285 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
286 for (i = n - 1; i >= 0; --i) r[i] = 0
287 r.t = this.t + n
288 r.s = this.s
289}
290
291// (protected) r = this >> n*DB
292function bnpDRShiftTo(n, r) {
293 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
294 r.t = Math.max(this.t - n, 0)
295 r.s = this.s
296}
297
298// (protected) r = this << n
299function bnpLShiftTo(n, r) {
300 var self = this
301 var bs = n % self.DB
302 var cbs = self.DB - bs
303 var bm = (1 << cbs) - 1
304 var ds = Math.floor(n / self.DB),
305 c = (self.s << bs) & self.DM,
306 i
307 for (i = self.t - 1; i >= 0; --i) {
308 r[i + ds + 1] = (self[i] >> cbs) | c
309 c = (self[i] & bm) << bs
310 }
311 for (i = ds - 1; i >= 0; --i) r[i] = 0
312 r[ds] = c
313 r.t = self.t + ds + 1
314 r.s = self.s
315 r.clamp()
316}
317
318// (protected) r = this >> n
319function bnpRShiftTo(n, r) {
320 var self = this
321 r.s = self.s
322 var ds = Math.floor(n / self.DB)
323 if (ds >= self.t) {
324 r.t = 0
325 return
326 }
327 var bs = n % self.DB
328 var cbs = self.DB - bs
329 var bm = (1 << bs) - 1
330 r[0] = self[ds] >> bs
331 for (var i = ds + 1; i < self.t; ++i) {
332 r[i - ds - 1] |= (self[i] & bm) << cbs
333 r[i - ds] = self[i] >> bs
334 }
335 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
336 r.t = self.t - ds
337 r.clamp()
338}
339
340// (protected) r = this - a
341function bnpSubTo(a, r) {
342 var self = this
343 var i = 0,
344 c = 0,
345 m = Math.min(a.t, self.t)
346 while (i < m) {
347 c += self[i] - a[i]
348 r[i++] = c & self.DM
349 c >>= self.DB
350 }
351 if (a.t < self.t) {
352 c -= a.s
353 while (i < self.t) {
354 c += self[i]
355 r[i++] = c & self.DM
356 c >>= self.DB
357 }
358 c += self.s
359 } else {
360 c += self.s
361 while (i < a.t) {
362 c -= a[i]
363 r[i++] = c & self.DM
364 c >>= self.DB
365 }
366 c -= a.s
367 }
368 r.s = (c < 0) ? -1 : 0
369 if (c < -1) r[i++] = self.DV + c
370 else if (c > 0) r[i++] = c
371 r.t = i
372 r.clamp()
373}
374
375// (protected) r = this * a, r != this,a (HAC 14.12)
376// "this" should be the larger one if appropriate.
377function bnpMultiplyTo(a, r) {
378 var x = this.abs(),
379 y = a.abs()
380 var i = x.t
381 r.t = i + y.t
382 while (--i >= 0) r[i] = 0
383 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
384 r.s = 0
385 r.clamp()
386 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
387}
388
389// (protected) r = this^2, r != this (HAC 14.16)
390function bnpSquareTo(r) {
391 var x = this.abs()
392 var i = r.t = 2 * x.t
393 while (--i >= 0) r[i] = 0
394 for (i = 0; i < x.t - 1; ++i) {
395 var c = x.am(i, x[i], r, 2 * i, 0, 1)
396 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
397 r[i + x.t] -= x.DV
398 r[i + x.t + 1] = 1
399 }
400 }
401 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
402 r.s = 0
403 r.clamp()
404}
405
406// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
407// r != q, this != m. q or r may be null.
408function bnpDivRemTo(m, q, r) {
409 var self = this
410 var pm = m.abs()
411 if (pm.t <= 0) return
412 var pt = self.abs()
413 if (pt.t < pm.t) {
414 if (q != null) q.fromInt(0)
415 if (r != null) self.copyTo(r)
416 return
417 }
418 if (r == null) r = new BigInteger()
419 var y = new BigInteger(),
420 ts = self.s,
421 ms = m.s
422 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
423 if (nsh > 0) {
424 pm.lShiftTo(nsh, y)
425 pt.lShiftTo(nsh, r)
426 } else {
427 pm.copyTo(y)
428 pt.copyTo(r)
429 }
430 var ys = y.t
431 var y0 = y[ys - 1]
432 if (y0 == 0) return
433 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
434 var d1 = self.FV / yt,
435 d2 = (1 << self.F1) / yt,
436 e = 1 << self.F2
437 var i = r.t,
438 j = i - ys,
439 t = (q == null) ? new BigInteger() : q
440 y.dlShiftTo(j, t)
441 if (r.compareTo(t) >= 0) {
442 r[r.t++] = 1
443 r.subTo(t, r)
444 }
445 BigInteger.ONE.dlShiftTo(ys, t)
446 t.subTo(y, y); // "negative" y so we can replace sub with am later
447 while (y.t < ys) y[y.t++] = 0
448 while (--j >= 0) {
449 // Estimate quotient digit
450 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
451 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
452 y.dlShiftTo(j, t)
453 r.subTo(t, r)
454 while (r[i] < --qd) r.subTo(t, r)
455 }
456 }
457 if (q != null) {
458 r.drShiftTo(ys, q)
459 if (ts != ms) BigInteger.ZERO.subTo(q, q)
460 }
461 r.t = ys
462 r.clamp()
463 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
464 if (ts < 0) BigInteger.ZERO.subTo(r, r)
465}
466
467// (public) this mod a
468function bnMod(a) {
469 var r = new BigInteger()
470 this.abs()
471 .divRemTo(a, null, r)
472 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
473 return r
474}
475
476// Modular reduction using "classic" algorithm
477function Classic(m) {
478 this.m = m
479}
480
481function cConvert(x) {
482 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
483 else return x
484}
485
486function cRevert(x) {
487 return x
488}
489
490function cReduce(x) {
491 x.divRemTo(this.m, null, x)
492}
493
494function cMulTo(x, y, r) {
495 x.multiplyTo(y, r)
496 this.reduce(r)
497}
498
499function cSqrTo(x, r) {
500 x.squareTo(r)
501 this.reduce(r)
502}
503
504Classic.prototype.convert = cConvert
505Classic.prototype.revert = cRevert
506Classic.prototype.reduce = cReduce
507Classic.prototype.mulTo = cMulTo
508Classic.prototype.sqrTo = cSqrTo
509
510// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
511// justification:
512// xy == 1 (mod m)
513// xy = 1+km
514// xy(2-xy) = (1+km)(1-km)
515// x[y(2-xy)] = 1-k^2m^2
516// x[y(2-xy)] == 1 (mod m^2)
517// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
518// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
519// JS multiply "overflows" differently from C/C++, so care is needed here.
520function bnpInvDigit() {
521 if (this.t < 1) return 0
522 var x = this[0]
523 if ((x & 1) == 0) return 0
524 var y = x & 3; // y == 1/x mod 2^2
525 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
526 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
527 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
528 // last step - calculate inverse mod DV directly
529 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
530 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
531 // we really want the negative inverse, and -DV < y < DV
532 return (y > 0) ? this.DV - y : -y
533}
534
535// Montgomery reduction
536function Montgomery(m) {
537 this.m = m
538 this.mp = m.invDigit()
539 this.mpl = this.mp & 0x7fff
540 this.mph = this.mp >> 15
541 this.um = (1 << (m.DB - 15)) - 1
542 this.mt2 = 2 * m.t
543}
544
545// xR mod m
546function montConvert(x) {
547 var r = new BigInteger()
548 x.abs()
549 .dlShiftTo(this.m.t, r)
550 r.divRemTo(this.m, null, r)
551 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
552 return r
553}
554
555// x/R mod m
556function montRevert(x) {
557 var r = new BigInteger()
558 x.copyTo(r)
559 this.reduce(r)
560 return r
561}
562
563// x = x/R mod m (HAC 14.32)
564function montReduce(x) {
565 while (x.t <= this.mt2) // pad x so am has enough room later
566 x[x.t++] = 0
567 for (var i = 0; i < this.m.t; ++i) {
568 // faster way of calculating u0 = x[i]*mp mod DV
569 var j = x[i] & 0x7fff
570 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
571 // use am to combine the multiply-shift-add into one call
572 j = i + this.m.t
573 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
574 // propagate carry
575 while (x[j] >= x.DV) {
576 x[j] -= x.DV
577 x[++j]++
578 }
579 }
580 x.clamp()
581 x.drShiftTo(this.m.t, x)
582 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
583}
584
585// r = "x^2/R mod m"; x != r
586function montSqrTo(x, r) {
587 x.squareTo(r)
588 this.reduce(r)
589}
590
591// r = "xy/R mod m"; x,y != r
592function montMulTo(x, y, r) {
593 x.multiplyTo(y, r)
594 this.reduce(r)
595}
596
597Montgomery.prototype.convert = montConvert
598Montgomery.prototype.revert = montRevert
599Montgomery.prototype.reduce = montReduce
600Montgomery.prototype.mulTo = montMulTo
601Montgomery.prototype.sqrTo = montSqrTo
602
603// (protected) true iff this is even
604function bnpIsEven() {
605 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
606}
607
608// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
609function bnpExp(e, z) {
610 if (e > 0xffffffff || e < 1) return BigInteger.ONE
611 var r = new BigInteger(),
612 r2 = new BigInteger(),
613 g = z.convert(this),
614 i = nbits(e) - 1
615 g.copyTo(r)
616 while (--i >= 0) {
617 z.sqrTo(r, r2)
618 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
619 else {
620 var t = r
621 r = r2
622 r2 = t
623 }
624 }
625 return z.revert(r)
626}
627
628// (public) this^e % m, 0 <= e < 2^32
629function bnModPowInt(e, m) {
630 var z
631 if (e < 256 || m.isEven()) z = new Classic(m)
632 else z = new Montgomery(m)
633 return this.exp(e, z)
634}
635
636// protected
637proto.copyTo = bnpCopyTo
638proto.fromInt = bnpFromInt
639proto.fromString = bnpFromString
640proto.clamp = bnpClamp
641proto.dlShiftTo = bnpDLShiftTo
642proto.drShiftTo = bnpDRShiftTo
643proto.lShiftTo = bnpLShiftTo
644proto.rShiftTo = bnpRShiftTo
645proto.subTo = bnpSubTo
646proto.multiplyTo = bnpMultiplyTo
647proto.squareTo = bnpSquareTo
648proto.divRemTo = bnpDivRemTo
649proto.invDigit = bnpInvDigit
650proto.isEven = bnpIsEven
651proto.exp = bnpExp
652
653// public
654proto.toString = bnToString
655proto.negate = bnNegate
656proto.abs = bnAbs
657proto.compareTo = bnCompareTo
658proto.bitLength = bnBitLength
659proto.byteLength = bnByteLength
660proto.mod = bnMod
661proto.modPowInt = bnModPowInt
662
663// (public)
664function bnClone() {
665 var r = new BigInteger()
666 this.copyTo(r)
667 return r
668}
669
670// (public) return value as integer
671function bnIntValue() {
672 if (this.s < 0) {
673 if (this.t == 1) return this[0] - this.DV
674 else if (this.t == 0) return -1
675 } else if (this.t == 1) return this[0]
676 else if (this.t == 0) return 0
677 // assumes 16 < DB < 32
678 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
679}
680
681// (public) return value as byte
682function bnByteValue() {
683 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
684}
685
686// (public) return value as short (assumes DB>=16)
687function bnShortValue() {
688 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
689}
690
691// (protected) return x s.t. r^x < DV
692function bnpChunkSize(r) {
693 return Math.floor(Math.LN2 * this.DB / Math.log(r))
694}
695
696// (public) 0 if this == 0, 1 if this > 0
697function bnSigNum() {
698 if (this.s < 0) return -1
699 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
700 else return 1
701}
702
703// (protected) convert to radix string
704function bnpToRadix(b) {
705 if (b == null) b = 10
706 if (this.signum() == 0 || b < 2 || b > 36) return "0"
707 var cs = this.chunkSize(b)
708 var a = Math.pow(b, cs)
709 var d = nbv(a),
710 y = new BigInteger(),
711 z = new BigInteger(),
712 r = ""
713 this.divRemTo(d, y, z)
714 while (y.signum() > 0) {
715 r = (a + z.intValue())
716 .toString(b)
717 .substr(1) + r
718 y.divRemTo(d, y, z)
719 }
720 return z.intValue()
721 .toString(b) + r
722}
723
724// (protected) convert from radix string
725function bnpFromRadix(s, b) {
726 var self = this
727 self.fromInt(0)
728 if (b == null) b = 10
729 var cs = self.chunkSize(b)
730 var d = Math.pow(b, cs),
731 mi = false,
732 j = 0,
733 w = 0
734 for (var i = 0; i < s.length; ++i) {
735 var x = intAt(s, i)
736 if (x < 0) {
737 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
738 continue
739 }
740 w = b * w + x
741 if (++j >= cs) {
742 self.dMultiply(d)
743 self.dAddOffset(w, 0)
744 j = 0
745 w = 0
746 }
747 }
748 if (j > 0) {
749 self.dMultiply(Math.pow(b, j))
750 self.dAddOffset(w, 0)
751 }
752 if (mi) BigInteger.ZERO.subTo(self, self)
753}
754
755// (protected) alternate constructor
756function bnpFromNumber(a, b, c) {
757 var self = this
758 if ("number" == typeof b) {
759 // new BigInteger(int,int,RNG)
760 if (a < 2) self.fromInt(1)
761 else {
762 self.fromNumber(a, c)
763 if (!self.testBit(a - 1)) // force MSB set
764 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
765 if (self.isEven()) self.dAddOffset(1, 0); // force odd
766 while (!self.isProbablePrime(b)) {
767 self.dAddOffset(2, 0)
768 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
769 }
770 }
771 } else {
772 // new BigInteger(int,RNG)
773 var x = new Array(),
774 t = a & 7
775 x.length = (a >> 3) + 1
776 b.nextBytes(x)
777 if (t > 0) x[0] &= ((1 << t) - 1)
778 else x[0] = 0
779 self.fromString(x, 256)
780 }
781}
782
783// (public) convert to bigendian byte array
784function bnToByteArray() {
785 var self = this
786 var i = self.t,
787 r = new Array()
788 r[0] = self.s
789 var p = self.DB - (i * self.DB) % 8,
790 d, k = 0
791 if (i-- > 0) {
792 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
793 r[k++] = d | (self.s << (self.DB - p))
794 while (i >= 0) {
795 if (p < 8) {
796 d = (self[i] & ((1 << p) - 1)) << (8 - p)
797 d |= self[--i] >> (p += self.DB - 8)
798 } else {
799 d = (self[i] >> (p -= 8)) & 0xff
800 if (p <= 0) {
801 p += self.DB
802 --i
803 }
804 }
805 if ((d & 0x80) != 0) d |= -256
806 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
807 if (k > 0 || d != self.s) r[k++] = d
808 }
809 }
810 return r
811}
812
813function bnEquals(a) {
814 return (this.compareTo(a) == 0)
815}
816
817function bnMin(a) {
818 return (this.compareTo(a) < 0) ? this : a
819}
820
821function bnMax(a) {
822 return (this.compareTo(a) > 0) ? this : a
823}
824
825// (protected) r = this op a (bitwise)
826function bnpBitwiseTo(a, op, r) {
827 var self = this
828 var i, f, m = Math.min(a.t, self.t)
829 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
830 if (a.t < self.t) {
831 f = a.s & self.DM
832 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
833 r.t = self.t
834 } else {
835 f = self.s & self.DM
836 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
837 r.t = a.t
838 }
839 r.s = op(self.s, a.s)
840 r.clamp()
841}
842
843// (public) this & a
844function op_and(x, y) {
845 return x & y
846}
847
848function bnAnd(a) {
849 var r = new BigInteger()
850 this.bitwiseTo(a, op_and, r)
851 return r
852}
853
854// (public) this | a
855function op_or(x, y) {
856 return x | y
857}
858
859function bnOr(a) {
860 var r = new BigInteger()
861 this.bitwiseTo(a, op_or, r)
862 return r
863}
864
865// (public) this ^ a
866function op_xor(x, y) {
867 return x ^ y
868}
869
870function bnXor(a) {
871 var r = new BigInteger()
872 this.bitwiseTo(a, op_xor, r)
873 return r
874}
875
876// (public) this & ~a
877function op_andnot(x, y) {
878 return x & ~y
879}
880
881function bnAndNot(a) {
882 var r = new BigInteger()
883 this.bitwiseTo(a, op_andnot, r)
884 return r
885}
886
887// (public) ~this
888function bnNot() {
889 var r = new BigInteger()
890 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
891 r.t = this.t
892 r.s = ~this.s
893 return r
894}
895
896// (public) this << n
897function bnShiftLeft(n) {
898 var r = new BigInteger()
899 if (n < 0) this.rShiftTo(-n, r)
900 else this.lShiftTo(n, r)
901 return r
902}
903
904// (public) this >> n
905function bnShiftRight(n) {
906 var r = new BigInteger()
907 if (n < 0) this.lShiftTo(-n, r)
908 else this.rShiftTo(n, r)
909 return r
910}
911
912// return index of lowest 1-bit in x, x < 2^31
913function lbit(x) {
914 if (x == 0) return -1
915 var r = 0
916 if ((x & 0xffff) == 0) {
917 x >>= 16
918 r += 16
919 }
920 if ((x & 0xff) == 0) {
921 x >>= 8
922 r += 8
923 }
924 if ((x & 0xf) == 0) {
925 x >>= 4
926 r += 4
927 }
928 if ((x & 3) == 0) {
929 x >>= 2
930 r += 2
931 }
932 if ((x & 1) == 0)++r
933 return r
934}
935
936// (public) returns index of lowest 1-bit (or -1 if none)
937function bnGetLowestSetBit() {
938 for (var i = 0; i < this.t; ++i)
939 if (this[i] != 0) return i * this.DB + lbit(this[i])
940 if (this.s < 0) return this.t * this.DB
941 return -1
942}
943
944// return number of 1 bits in x
945function cbit(x) {
946 var r = 0
947 while (x != 0) {
948 x &= x - 1
949 ++r
950 }
951 return r
952}
953
954// (public) return number of set bits
955function bnBitCount() {
956 var r = 0,
957 x = this.s & this.DM
958 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
959 return r
960}
961
962// (public) true iff nth bit is set
963function bnTestBit(n) {
964 var j = Math.floor(n / this.DB)
965 if (j >= this.t) return (this.s != 0)
966 return ((this[j] & (1 << (n % this.DB))) != 0)
967}
968
969// (protected) this op (1<<n)
970function bnpChangeBit(n, op) {
971 var r = BigInteger.ONE.shiftLeft(n)
972 this.bitwiseTo(r, op, r)
973 return r
974}
975
976// (public) this | (1<<n)
977function bnSetBit(n) {
978 return this.changeBit(n, op_or)
979}
980
981// (public) this & ~(1<<n)
982function bnClearBit(n) {
983 return this.changeBit(n, op_andnot)
984}
985
986// (public) this ^ (1<<n)
987function bnFlipBit(n) {
988 return this.changeBit(n, op_xor)
989}
990
991// (protected) r = this + a
992function bnpAddTo(a, r) {
993 var self = this
994
995 var i = 0,
996 c = 0,
997 m = Math.min(a.t, self.t)
998 while (i < m) {
999 c += self[i] + a[i]
1000 r[i++] = c & self.DM
1001 c >>= self.DB
1002 }
1003 if (a.t < self.t) {
1004 c += a.s
1005 while (i < self.t) {
1006 c += self[i]
1007 r[i++] = c & self.DM
1008 c >>= self.DB
1009 }
1010 c += self.s
1011 } else {
1012 c += self.s
1013 while (i < a.t) {
1014 c += a[i]
1015 r[i++] = c & self.DM
1016 c >>= self.DB
1017 }
1018 c += a.s
1019 }
1020 r.s = (c < 0) ? -1 : 0
1021 if (c > 0) r[i++] = c
1022 else if (c < -1) r[i++] = self.DV + c
1023 r.t = i
1024 r.clamp()
1025}
1026
1027// (public) this + a
1028function bnAdd(a) {
1029 var r = new BigInteger()
1030 this.addTo(a, r)
1031 return r
1032}
1033
1034// (public) this - a
1035function bnSubtract(a) {
1036 var r = new BigInteger()
1037 this.subTo(a, r)
1038 return r
1039}
1040
1041// (public) this * a
1042function bnMultiply(a) {
1043 var r = new BigInteger()
1044 this.multiplyTo(a, r)
1045 return r
1046}
1047
1048// (public) this^2
1049function bnSquare() {
1050 var r = new BigInteger()
1051 this.squareTo(r)
1052 return r
1053}
1054
1055// (public) this / a
1056function bnDivide(a) {
1057 var r = new BigInteger()
1058 this.divRemTo(a, r, null)
1059 return r
1060}
1061
1062// (public) this % a
1063function bnRemainder(a) {
1064 var r = new BigInteger()
1065 this.divRemTo(a, null, r)
1066 return r
1067}
1068
1069// (public) [this/a,this%a]
1070function bnDivideAndRemainder(a) {
1071 var q = new BigInteger(),
1072 r = new BigInteger()
1073 this.divRemTo(a, q, r)
1074 return new Array(q, r)
1075}
1076
1077// (protected) this *= n, this >= 0, 1 < n < DV
1078function bnpDMultiply(n) {
1079 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
1080 ++this.t
1081 this.clamp()
1082}
1083
1084// (protected) this += n << w words, this >= 0
1085function bnpDAddOffset(n, w) {
1086 if (n == 0) return
1087 while (this.t <= w) this[this.t++] = 0
1088 this[w] += n
1089 while (this[w] >= this.DV) {
1090 this[w] -= this.DV
1091 if (++w >= this.t) this[this.t++] = 0
1092 ++this[w]
1093 }
1094}
1095
1096// A "null" reducer
1097function NullExp() {}
1098
1099function nNop(x) {
1100 return x
1101}
1102
1103function nMulTo(x, y, r) {
1104 x.multiplyTo(y, r)
1105}
1106
1107function nSqrTo(x, r) {
1108 x.squareTo(r)
1109}
1110
1111NullExp.prototype.convert = nNop
1112NullExp.prototype.revert = nNop
1113NullExp.prototype.mulTo = nMulTo
1114NullExp.prototype.sqrTo = nSqrTo
1115
1116// (public) this^e
1117function bnPow(e) {
1118 return this.exp(e, new NullExp())
1119}
1120
1121// (protected) r = lower n words of "this * a", a.t <= n
1122// "this" should be the larger one if appropriate.
1123function bnpMultiplyLowerTo(a, n, r) {
1124 var i = Math.min(this.t + a.t, n)
1125 r.s = 0; // assumes a,this >= 0
1126 r.t = i
1127 while (i > 0) r[--i] = 0
1128 var j
1129 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
1130 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
1131 r.clamp()
1132}
1133
1134// (protected) r = "this * a" without lower n words, n > 0
1135// "this" should be the larger one if appropriate.
1136function bnpMultiplyUpperTo(a, n, r) {
1137 --n
1138 var i = r.t = this.t + a.t - n
1139 r.s = 0; // assumes a,this >= 0
1140 while (--i >= 0) r[i] = 0
1141 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
1142 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
1143 r.clamp()
1144 r.drShiftTo(1, r)
1145}
1146
1147// Barrett modular reduction
1148function Barrett(m) {
1149 // setup Barrett
1150 this.r2 = new BigInteger()
1151 this.q3 = new BigInteger()
1152 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
1153 this.mu = this.r2.divide(m)
1154 this.m = m
1155}
1156
1157function barrettConvert(x) {
1158 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
1159 else if (x.compareTo(this.m) < 0) return x
1160 else {
1161 var r = new BigInteger()
1162 x.copyTo(r)
1163 this.reduce(r)
1164 return r
1165 }
1166}
1167
1168function barrettRevert(x) {
1169 return x
1170}
1171
1172// x = x mod m (HAC 14.42)
1173function barrettReduce(x) {
1174 var self = this
1175 x.drShiftTo(self.m.t - 1, self.r2)
1176 if (x.t > self.m.t + 1) {
1177 x.t = self.m.t + 1
1178 x.clamp()
1179 }
1180 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
1181 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
1182 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
1183 x.subTo(self.r2, x)
1184 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
1185}
1186
1187// r = x^2 mod m; x != r
1188function barrettSqrTo(x, r) {
1189 x.squareTo(r)
1190 this.reduce(r)
1191}
1192
1193// r = x*y mod m; x,y != r
1194function barrettMulTo(x, y, r) {
1195 x.multiplyTo(y, r)
1196 this.reduce(r)
1197}
1198
1199Barrett.prototype.convert = barrettConvert
1200Barrett.prototype.revert = barrettRevert
1201Barrett.prototype.reduce = barrettReduce
1202Barrett.prototype.mulTo = barrettMulTo
1203Barrett.prototype.sqrTo = barrettSqrTo
1204
1205// (public) this^e % m (HAC 14.85)
1206function bnModPow(e, m) {
1207 var i = e.bitLength(),
1208 k, r = nbv(1),
1209 z
1210 if (i <= 0) return r
1211 else if (i < 18) k = 1
1212 else if (i < 48) k = 3
1213 else if (i < 144) k = 4
1214 else if (i < 768) k = 5
1215 else k = 6
1216 if (i < 8)
1217 z = new Classic(m)
1218 else if (m.isEven())
1219 z = new Barrett(m)
1220 else
1221 z = new Montgomery(m)
1222
1223 // precomputation
1224 var g = new Array(),
1225 n = 3,
1226 k1 = k - 1,
1227 km = (1 << k) - 1
1228 g[1] = z.convert(this)
1229 if (k > 1) {
1230 var g2 = new BigInteger()
1231 z.sqrTo(g[1], g2)
1232 while (n <= km) {
1233 g[n] = new BigInteger()
1234 z.mulTo(g2, g[n - 2], g[n])
1235 n += 2
1236 }
1237 }
1238
1239 var j = e.t - 1,
1240 w, is1 = true,
1241 r2 = new BigInteger(),
1242 t
1243 i = nbits(e[j]) - 1
1244 while (j >= 0) {
1245 if (i >= k1) w = (e[j] >> (i - k1)) & km
1246 else {
1247 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
1248 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
1249 }
1250
1251 n = k
1252 while ((w & 1) == 0) {
1253 w >>= 1
1254 --n
1255 }
1256 if ((i -= n) < 0) {
1257 i += this.DB
1258 --j
1259 }
1260 if (is1) { // ret == 1, don't bother squaring or multiplying it
1261 g[w].copyTo(r)
1262 is1 = false
1263 } else {
1264 while (n > 1) {
1265 z.sqrTo(r, r2)
1266 z.sqrTo(r2, r)
1267 n -= 2
1268 }
1269 if (n > 0) z.sqrTo(r, r2)
1270 else {
1271 t = r
1272 r = r2
1273 r2 = t
1274 }
1275 z.mulTo(r2, g[w], r)
1276 }
1277
1278 while (j >= 0 && (e[j] & (1 << i)) == 0) {
1279 z.sqrTo(r, r2)
1280 t = r
1281 r = r2
1282 r2 = t
1283 if (--i < 0) {
1284 i = this.DB - 1
1285 --j
1286 }
1287 }
1288 }
1289 return z.revert(r)
1290}
1291
1292// (public) gcd(this,a) (HAC 14.54)
1293function bnGCD(a) {
1294 var x = (this.s < 0) ? this.negate() : this.clone()
1295 var y = (a.s < 0) ? a.negate() : a.clone()
1296 if (x.compareTo(y) < 0) {
1297 var t = x
1298 x = y
1299 y = t
1300 }
1301 var i = x.getLowestSetBit(),
1302 g = y.getLowestSetBit()
1303 if (g < 0) return x
1304 if (i < g) g = i
1305 if (g > 0) {
1306 x.rShiftTo(g, x)
1307 y.rShiftTo(g, y)
1308 }
1309 while (x.signum() > 0) {
1310 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
1311 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
1312 if (x.compareTo(y) >= 0) {
1313 x.subTo(y, x)
1314 x.rShiftTo(1, x)
1315 } else {
1316 y.subTo(x, y)
1317 y.rShiftTo(1, y)
1318 }
1319 }
1320 if (g > 0) y.lShiftTo(g, y)
1321 return y
1322}
1323
1324// (protected) this % n, n < 2^26
1325function bnpModInt(n) {
1326 if (n <= 0) return 0
1327 var d = this.DV % n,
1328 r = (this.s < 0) ? n - 1 : 0
1329 if (this.t > 0)
1330 if (d == 0) r = this[0] % n
1331 else
1332 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
1333 return r
1334}
1335
1336// (public) 1/this % m (HAC 14.61)
1337function bnModInverse(m) {
1338 var ac = m.isEven()
1339 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO
1340 var u = m.clone(),
1341 v = this.clone()
1342 var a = nbv(1),
1343 b = nbv(0),
1344 c = nbv(0),
1345 d = nbv(1)
1346 while (u.signum() != 0) {
1347 while (u.isEven()) {
1348 u.rShiftTo(1, u)
1349 if (ac) {
1350 if (!a.isEven() || !b.isEven()) {
1351 a.addTo(this, a)
1352 b.subTo(m, b)
1353 }
1354 a.rShiftTo(1, a)
1355 } else if (!b.isEven()) b.subTo(m, b)
1356 b.rShiftTo(1, b)
1357 }
1358 while (v.isEven()) {
1359 v.rShiftTo(1, v)
1360 if (ac) {
1361 if (!c.isEven() || !d.isEven()) {
1362 c.addTo(this, c)
1363 d.subTo(m, d)
1364 }
1365 c.rShiftTo(1, c)
1366 } else if (!d.isEven()) d.subTo(m, d)
1367 d.rShiftTo(1, d)
1368 }
1369 if (u.compareTo(v) >= 0) {
1370 u.subTo(v, u)
1371 if (ac) a.subTo(c, a)
1372 b.subTo(d, b)
1373 } else {
1374 v.subTo(u, v)
1375 if (ac) c.subTo(a, c)
1376 d.subTo(b, d)
1377 }
1378 }
1379 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
1380 if (d.compareTo(m) >= 0) return d.subtract(m)
1381 if (d.signum() < 0) d.addTo(m, d)
1382 else return d
1383 if (d.signum() < 0) return d.add(m)
1384 else return d
1385}
1386
1387var lowprimes = [
1388 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
1389 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
1390 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
1391 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
1392 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
1393 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
1394 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
1395 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
1396 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
1397 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
1398 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
1399]
1400
1401var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
1402
1403// (public) test primality with certainty >= 1-.5^t
1404function bnIsProbablePrime(t) {
1405 var i, x = this.abs()
1406 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
1407 for (i = 0; i < lowprimes.length; ++i)
1408 if (x[0] == lowprimes[i]) return true
1409 return false
1410 }
1411 if (x.isEven()) return false
1412 i = 1
1413 while (i < lowprimes.length) {
1414 var m = lowprimes[i],
1415 j = i + 1
1416 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
1417 m = x.modInt(m)
1418 while (i < j) if (m % lowprimes[i++] == 0) return false
1419 }
1420 return x.millerRabin(t)
1421}
1422
1423// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
1424function bnpMillerRabin(t) {
1425 var n1 = this.subtract(BigInteger.ONE)
1426 var k = n1.getLowestSetBit()
1427 if (k <= 0) return false
1428 var r = n1.shiftRight(k)
1429 t = (t + 1) >> 1
1430 if (t > lowprimes.length) t = lowprimes.length
1431 var a = new BigInteger(null)
1432 var j, bases = []
1433 for (var i = 0; i < t; ++i) {
1434 for (;;) {
1435 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
1436 if (bases.indexOf(j) == -1) break
1437 }
1438 bases.push(j)
1439 a.fromInt(j)
1440 var y = a.modPow(r, this)
1441 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
1442 var j = 1
1443 while (j++ < k && y.compareTo(n1) != 0) {
1444 y = y.modPowInt(2, this)
1445 if (y.compareTo(BigInteger.ONE) == 0) return false
1446 }
1447 if (y.compareTo(n1) != 0) return false
1448 }
1449 }
1450 return true
1451}
1452
1453// protected
1454proto.chunkSize = bnpChunkSize
1455proto.toRadix = bnpToRadix
1456proto.fromRadix = bnpFromRadix
1457proto.fromNumber = bnpFromNumber
1458proto.bitwiseTo = bnpBitwiseTo
1459proto.changeBit = bnpChangeBit
1460proto.addTo = bnpAddTo
1461proto.dMultiply = bnpDMultiply
1462proto.dAddOffset = bnpDAddOffset
1463proto.multiplyLowerTo = bnpMultiplyLowerTo
1464proto.multiplyUpperTo = bnpMultiplyUpperTo
1465proto.modInt = bnpModInt
1466proto.millerRabin = bnpMillerRabin
1467
1468// public
1469proto.clone = bnClone
1470proto.intValue = bnIntValue
1471proto.byteValue = bnByteValue
1472proto.shortValue = bnShortValue
1473proto.signum = bnSigNum
1474proto.toByteArray = bnToByteArray
1475proto.equals = bnEquals
1476proto.min = bnMin
1477proto.max = bnMax
1478proto.and = bnAnd
1479proto.or = bnOr
1480proto.xor = bnXor
1481proto.andNot = bnAndNot
1482proto.not = bnNot
1483proto.shiftLeft = bnShiftLeft
1484proto.shiftRight = bnShiftRight
1485proto.getLowestSetBit = bnGetLowestSetBit
1486proto.bitCount = bnBitCount
1487proto.testBit = bnTestBit
1488proto.setBit = bnSetBit
1489proto.clearBit = bnClearBit
1490proto.flipBit = bnFlipBit
1491proto.add = bnAdd
1492proto.subtract = bnSubtract
1493proto.multiply = bnMultiply
1494proto.divide = bnDivide
1495proto.remainder = bnRemainder
1496proto.divideAndRemainder = bnDivideAndRemainder
1497proto.modPow = bnModPow
1498proto.modInverse = bnModInverse
1499proto.pow = bnPow
1500proto.gcd = bnGCD
1501proto.isProbablePrime = bnIsProbablePrime
1502
1503// JSBN-specific extension
1504proto.square = bnSquare
1505
1506// constants
1507BigInteger.ZERO = nbv(0)
1508BigInteger.ONE = nbv(1)
1509BigInteger.valueOf = nbv
1510
1511module.exports = BigInteger
1512
1513},{"../package.json":4}],2:[function(require,module,exports){
1514(function (Buffer){
1515// FIXME: Kind of a weird way to throw exceptions, consider removing
1516var assert = require('assert')
1517var BigInteger = require('./bigi')
1518
1519/**
1520 * Turns a byte array into a big integer.
1521 *
1522 * This function will interpret a byte array as a big integer in big
1523 * endian notation.
1524 */
1525BigInteger.fromByteArrayUnsigned = function(byteArray) {
1526 // BigInteger expects a DER integer conformant byte array
1527 if (byteArray[0] & 0x80) {
1528 return new BigInteger([0].concat(byteArray))
1529 }
1530
1531 return new BigInteger(byteArray)
1532}
1533
1534/**
1535 * Returns a byte array representation of the big integer.
1536 *
1537 * This returns the absolute of the contained value in big endian
1538 * form. A value of zero results in an empty array.
1539 */
1540BigInteger.prototype.toByteArrayUnsigned = function() {
1541 var byteArray = this.toByteArray()
1542 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
1543}
1544
1545BigInteger.fromDERInteger = function(byteArray) {
1546 return new BigInteger(byteArray)
1547}
1548
1549/*
1550 * Converts BigInteger to a DER integer representation.
1551 *
1552 * The format for this value uses the most significant bit as a sign
1553 * bit. If the most significant bit is already set and the integer is
1554 * positive, a 0x00 is prepended.
1555 *
1556 * Examples:
1557 *
1558 * 0 => 0x00
1559 * 1 => 0x01
1560 * -1 => 0xff
1561 * 127 => 0x7f
1562 * -127 => 0x81
1563 * 128 => 0x0080
1564 * -128 => 0x80
1565 * 255 => 0x00ff
1566 * -255 => 0xff01
1567 * 16300 => 0x3fac
1568 * -16300 => 0xc054
1569 * 62300 => 0x00f35c
1570 * -62300 => 0xff0ca4
1571*/
1572BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
1573
1574BigInteger.fromBuffer = function(buffer) {
1575 // BigInteger expects a DER integer conformant byte array
1576 if (buffer[0] & 0x80) {
1577 var byteArray = Array.prototype.slice.call(buffer)
1578
1579 return new BigInteger([0].concat(byteArray))
1580 }
1581
1582 return new BigInteger(buffer)
1583}
1584
1585BigInteger.fromHex = function(hex) {
1586 if (hex === '') return BigInteger.ZERO
1587
1588 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
1589 assert.equal(hex.length % 2, 0, 'Incomplete hex')
1590 return new BigInteger(hex, 16)
1591}
1592
1593BigInteger.prototype.toBuffer = function(size) {
1594 var byteArray = this.toByteArrayUnsigned()
1595 var zeros = []
1596
1597 var padding = size - byteArray.length
1598 while (zeros.length < padding) zeros.push(0)
1599
1600 return new Buffer(zeros.concat(byteArray))
1601}
1602
1603BigInteger.prototype.toHex = function(size) {
1604 return this.toBuffer(size).toString('hex')
1605}
1606
1607}).call(this,require("buffer").Buffer)
1608},{"./bigi":1,"assert":5,"buffer":7}],3:[function(require,module,exports){
1609var BigInteger = require('./bigi')
1610
1611//addons
1612require('./convert')
1613
1614module.exports = BigInteger
1615},{"./bigi":1,"./convert":2}],4:[function(require,module,exports){
1616module.exports={
1617 "name": "bigi",
1618 "version": "1.4.0",
1619 "description": "Big integers.",
1620 "keywords": [
1621 "cryptography",
1622 "math",
1623 "bitcoin",
1624 "arbitrary",
1625 "precision",
1626 "arithmetic",
1627 "big",
1628 "integer",
1629 "int",
1630 "number",
1631 "biginteger",
1632 "bigint",
1633 "bignumber",
1634 "decimal",
1635 "float"
1636 ],
1637 "devDependencies": {
1638 "mocha": "^1.20.1",
1639 "jshint": "^2.5.1",
1640 "coveralls": "^2.10.0",
1641 "istanbul": "^0.2.11"
1642 },
1643 "repository": {
1644 "url": "https://github.com/cryptocoinjs/bigi",
1645 "type": "git"
1646 },
1647 "main": "./lib/index.js",
1648 "scripts": {
1649 "test": "_mocha -- test/*.js",
1650 "jshint": "jshint --config jshint.json lib/*.js ; true",
1651 "unit": "mocha",
1652 "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
1653 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info"
1654 },
1655 "dependencies": {},
1656 "testling": {
1657 "files": "test/*.js",
1658 "harness": "mocha",
1659 "browsers": [
1660 "ie/9..latest",
1661 "firefox/latest",
1662 "chrome/latest",
1663 "safari/6.0..latest",
1664 "iphone/6.0..latest",
1665 "android-browser/4.2..latest"
1666 ]
1667 },
1668 "bugs": {
1669 "url": "https://github.com/cryptocoinjs/bigi/issues"
1670 },
1671 "homepage": "https://github.com/cryptocoinjs/bigi",
1672 "_id": "bigi@1.4.0",
1673 "dist": {
1674 "shasum": "90ac1aeac0a531216463bdb58f42c1e05c8407ac",
1675 "tarball": "http://registry.npmjs.org/bigi/-/bigi-1.4.0.tgz"
1676 },
1677 "_from": "bigi@^1.4.0",
1678 "_npmVersion": "1.4.3",
1679 "_npmUser": {
1680 "name": "jp",
1681 "email": "jprichardson@gmail.com"
1682 },
1683 "maintainers": [
1684 {
1685 "name": "jp",
1686 "email": "jprichardson@gmail.com"
1687 },
1688 {
1689 "name": "midnightlightning",
1690 "email": "boydb@midnightdesign.ws"
1691 },
1692 {
1693 "name": "sidazhang",
1694 "email": "sidazhang89@gmail.com"
1695 },
1696 {
1697 "name": "nadav",
1698 "email": "npm@shesek.info"
1699 }
1700 ],
1701 "directories": {},
1702 "_shasum": "90ac1aeac0a531216463bdb58f42c1e05c8407ac",
1703 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.0.tgz"
1704}
1705
1706},{}],5:[function(require,module,exports){
1707// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
1708//
1709// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
1710//
1711// Originally from narwhal.js (http://narwhaljs.org)
1712// Copyright (c) 2009 Thomas Robinson <280north.com>
1713//
1714// Permission is hereby granted, free of charge, to any person obtaining a copy
1715// of this software and associated documentation files (the 'Software'), to
1716// deal in the Software without restriction, including without limitation the
1717// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
1718// sell copies of the Software, and to permit persons to whom the Software is
1719// furnished to do so, subject to the following conditions:
1720//
1721// The above copyright notice and this permission notice shall be included in
1722// all copies or substantial portions of the Software.
1723//
1724// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1725// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1726// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1727// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1728// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
1729// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1730
1731// when used in node, this will actually load the util module we depend on
1732// versus loading the builtin util module as happens otherwise
1733// this is a bug in node module loading as far as I am concerned
1734var util = require('util/');
1735
1736var pSlice = Array.prototype.slice;
1737var hasOwn = Object.prototype.hasOwnProperty;
1738
1739// 1. The assert module provides functions that throw
1740// AssertionError's when particular conditions are not met. The
1741// assert module must conform to the following interface.
1742
1743var assert = module.exports = ok;
1744
1745// 2. The AssertionError is defined in assert.
1746// new assert.AssertionError({ message: message,
1747// actual: actual,
1748// expected: expected })
1749
1750assert.AssertionError = function AssertionError(options) {
1751 this.name = 'AssertionError';
1752 this.actual = options.actual;
1753 this.expected = options.expected;
1754 this.operator = options.operator;
1755 if (options.message) {
1756 this.message = options.message;
1757 this.generatedMessage = false;
1758 } else {
1759 this.message = getMessage(this);
1760 this.generatedMessage = true;
1761 }
1762 var stackStartFunction = options.stackStartFunction || fail;
1763
1764 if (Error.captureStackTrace) {
1765 Error.captureStackTrace(this, stackStartFunction);
1766 }
1767 else {
1768 // non v8 browsers so we can have a stacktrace
1769 var err = new Error();
1770 if (err.stack) {
1771 var out = err.stack;
1772
1773 // try to strip useless frames
1774 var fn_name = stackStartFunction.name;
1775 var idx = out.indexOf('\n' + fn_name);
1776 if (idx >= 0) {
1777 // once we have located the function frame
1778 // we need to strip out everything before it (and its line)
1779 var next_line = out.indexOf('\n', idx + 1);
1780 out = out.substring(next_line + 1);
1781 }
1782
1783 this.stack = out;
1784 }
1785 }
1786};
1787
1788// assert.AssertionError instanceof Error
1789util.inherits(assert.AssertionError, Error);
1790
1791function replacer(key, value) {
1792 if (util.isUndefined(value)) {
1793 return '' + value;
1794 }
1795 if (util.isNumber(value) && !isFinite(value)) {
1796 return value.toString();
1797 }
1798 if (util.isFunction(value) || util.isRegExp(value)) {
1799 return value.toString();
1800 }
1801 return value;
1802}
1803
1804function truncate(s, n) {
1805 if (util.isString(s)) {
1806 return s.length < n ? s : s.slice(0, n);
1807 } else {
1808 return s;
1809 }
1810}
1811
1812function getMessage(self) {
1813 return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
1814 self.operator + ' ' +
1815 truncate(JSON.stringify(self.expected, replacer), 128);
1816}
1817
1818// At present only the three keys mentioned above are used and
1819// understood by the spec. Implementations or sub modules can pass
1820// other keys to the AssertionError's constructor - they will be
1821// ignored.
1822
1823// 3. All of the following functions must throw an AssertionError
1824// when a corresponding condition is not met, with a message that
1825// may be undefined if not provided. All assertion methods provide
1826// both the actual and expected values to the assertion error for
1827// display purposes.
1828
1829function fail(actual, expected, message, operator, stackStartFunction) {
1830 throw new assert.AssertionError({
1831 message: message,
1832 actual: actual,
1833 expected: expected,
1834 operator: operator,
1835 stackStartFunction: stackStartFunction
1836 });
1837}
1838
1839// EXTENSION! allows for well behaved errors defined elsewhere.
1840assert.fail = fail;
1841
1842// 4. Pure assertion tests whether a value is truthy, as determined
1843// by !!guard.
1844// assert.ok(guard, message_opt);
1845// This statement is equivalent to assert.equal(true, !!guard,
1846// message_opt);. To test strictly for the value true, use
1847// assert.strictEqual(true, guard, message_opt);.
1848
1849function ok(value, message) {
1850 if (!value) fail(value, true, message, '==', assert.ok);
1851}
1852assert.ok = ok;
1853
1854// 5. The equality assertion tests shallow, coercive equality with
1855// ==.
1856// assert.equal(actual, expected, message_opt);
1857
1858assert.equal = function equal(actual, expected, message) {
1859 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
1860};
1861
1862// 6. The non-equality assertion tests for whether two objects are not equal
1863// with != assert.notEqual(actual, expected, message_opt);
1864
1865assert.notEqual = function notEqual(actual, expected, message) {
1866 if (actual == expected) {
1867 fail(actual, expected, message, '!=', assert.notEqual);
1868 }
1869};
1870
1871// 7. The equivalence assertion tests a deep equality relation.
1872// assert.deepEqual(actual, expected, message_opt);
1873
1874assert.deepEqual = function deepEqual(actual, expected, message) {
1875 if (!_deepEqual(actual, expected)) {
1876 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
1877 }
1878};
1879
1880function _deepEqual(actual, expected) {
1881 // 7.1. All identical values are equivalent, as determined by ===.
1882 if (actual === expected) {
1883 return true;
1884
1885 } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
1886 if (actual.length != expected.length) return false;
1887
1888 for (var i = 0; i < actual.length; i++) {
1889 if (actual[i] !== expected[i]) return false;
1890 }
1891
1892 return true;
1893
1894 // 7.2. If the expected value is a Date object, the actual value is
1895 // equivalent if it is also a Date object that refers to the same time.
1896 } else if (util.isDate(actual) && util.isDate(expected)) {
1897 return actual.getTime() === expected.getTime();
1898
1899 // 7.3 If the expected value is a RegExp object, the actual value is
1900 // equivalent if it is also a RegExp object with the same source and
1901 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
1902 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
1903 return actual.source === expected.source &&
1904 actual.global === expected.global &&
1905 actual.multiline === expected.multiline &&
1906 actual.lastIndex === expected.lastIndex &&
1907 actual.ignoreCase === expected.ignoreCase;
1908
1909 // 7.4. Other pairs that do not both pass typeof value == 'object',
1910 // equivalence is determined by ==.
1911 } else if (!util.isObject(actual) && !util.isObject(expected)) {
1912 return actual == expected;
1913
1914 // 7.5 For all other Object pairs, including Array objects, equivalence is
1915 // determined by having the same number of owned properties (as verified
1916 // with Object.prototype.hasOwnProperty.call), the same set of keys
1917 // (although not necessarily the same order), equivalent values for every
1918 // corresponding key, and an identical 'prototype' property. Note: this
1919 // accounts for both named and indexed properties on Arrays.
1920 } else {
1921 return objEquiv(actual, expected);
1922 }
1923}
1924
1925function isArguments(object) {
1926 return Object.prototype.toString.call(object) == '[object Arguments]';
1927}
1928
1929function objEquiv(a, b) {
1930 if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
1931 return false;
1932 // an identical 'prototype' property.
1933 if (a.prototype !== b.prototype) return false;
1934 // if one is a primitive, the other must be same
1935 if (util.isPrimitive(a) || util.isPrimitive(b)) {
1936 return a === b;
1937 }
1938 var aIsArgs = isArguments(a),
1939 bIsArgs = isArguments(b);
1940 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
1941 return false;
1942 if (aIsArgs) {
1943 a = pSlice.call(a);
1944 b = pSlice.call(b);
1945 return _deepEqual(a, b);
1946 }
1947 var ka = objectKeys(a),
1948 kb = objectKeys(b),
1949 key, i;
1950 // having the same number of owned properties (keys incorporates
1951 // hasOwnProperty)
1952 if (ka.length != kb.length)
1953 return false;
1954 //the same set of keys (although not necessarily the same order),
1955 ka.sort();
1956 kb.sort();
1957 //~~~cheap key test
1958 for (i = ka.length - 1; i >= 0; i--) {
1959 if (ka[i] != kb[i])
1960 return false;
1961 }
1962 //equivalent values for every corresponding key, and
1963 //~~~possibly expensive deep test
1964 for (i = ka.length - 1; i >= 0; i--) {
1965 key = ka[i];
1966 if (!_deepEqual(a[key], b[key])) return false;
1967 }
1968 return true;
1969}
1970
1971// 8. The non-equivalence assertion tests for any deep inequality.
1972// assert.notDeepEqual(actual, expected, message_opt);
1973
1974assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
1975 if (_deepEqual(actual, expected)) {
1976 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
1977 }
1978};
1979
1980// 9. The strict equality assertion tests strict equality, as determined by ===.
1981// assert.strictEqual(actual, expected, message_opt);
1982
1983assert.strictEqual = function strictEqual(actual, expected, message) {
1984 if (actual !== expected) {
1985 fail(actual, expected, message, '===', assert.strictEqual);
1986 }
1987};
1988
1989// 10. The strict non-equality assertion tests for strict inequality, as
1990// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
1991
1992assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
1993 if (actual === expected) {
1994 fail(actual, expected, message, '!==', assert.notStrictEqual);
1995 }
1996};
1997
1998function expectedException(actual, expected) {
1999 if (!actual || !expected) {
2000 return false;
2001 }
2002
2003 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
2004 return expected.test(actual);
2005 } else if (actual instanceof expected) {
2006 return true;
2007 } else if (expected.call({}, actual) === true) {
2008 return true;
2009 }
2010
2011 return false;
2012}
2013
2014function _throws(shouldThrow, block, expected, message) {
2015 var actual;
2016
2017 if (util.isString(expected)) {
2018 message = expected;
2019 expected = null;
2020 }
2021
2022 try {
2023 block();
2024 } catch (e) {
2025 actual = e;
2026 }
2027
2028 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
2029 (message ? ' ' + message : '.');
2030
2031 if (shouldThrow && !actual) {
2032 fail(actual, expected, 'Missing expected exception' + message);
2033 }
2034
2035 if (!shouldThrow && expectedException(actual, expected)) {
2036 fail(actual, expected, 'Got unwanted exception' + message);
2037 }
2038
2039 if ((shouldThrow && actual && expected &&
2040 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
2041 throw actual;
2042 }
2043}
2044
2045// 11. Expected to throw an error:
2046// assert.throws(block, Error_opt, message_opt);
2047
2048assert.throws = function(block, /*optional*/error, /*optional*/message) {
2049 _throws.apply(this, [true].concat(pSlice.call(arguments)));
2050};
2051
2052// EXTENSION! This is annoying to write outside this module.
2053assert.doesNotThrow = function(block, /*optional*/message) {
2054 _throws.apply(this, [false].concat(pSlice.call(arguments)));
2055};
2056
2057assert.ifError = function(err) { if (err) {throw err;}};
2058
2059var objectKeys = Object.keys || function (obj) {
2060 var keys = [];
2061 for (var key in obj) {
2062 if (hasOwn.call(obj, key)) keys.push(key);
2063 }
2064 return keys;
2065};
2066
2067},{"util/":29}],6:[function(require,module,exports){
2068
2069},{}],7:[function(require,module,exports){
2070/*!
2071 * The buffer module from node.js, for the browser.
2072 *
2073 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2074 * @license MIT
2075 */
2076
2077var base64 = require('base64-js')
2078var ieee754 = require('ieee754')
2079var isArray = require('is-array')
2080
2081exports.Buffer = Buffer
2082exports.SlowBuffer = SlowBuffer
2083exports.INSPECT_MAX_BYTES = 50
2084Buffer.poolSize = 8192 // not used by this implementation
2085
2086var rootParent = {}
2087
2088/**
2089 * If `Buffer.TYPED_ARRAY_SUPPORT`:
2090 * === true Use Uint8Array implementation (fastest)
2091 * === false Use Object implementation (most compatible, even IE6)
2092 *
2093 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
2094 * Opera 11.6+, iOS 4.2+.
2095 *
2096 * Due to various browser bugs, sometimes the Object implementation will be used even
2097 * when the browser supports typed arrays.
2098 *
2099 * Note:
2100 *
2101 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
2102 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
2103 *
2104 * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
2105 * on objects.
2106 *
2107 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
2108 *
2109 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
2110 * incorrect length in some situations.
2111
2112 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
2113 * get the Object implementation, which is slower but behaves correctly.
2114 */
2115Buffer.TYPED_ARRAY_SUPPORT = (function () {
2116 function Bar () {}
2117 try {
2118 var arr = new Uint8Array(1)
2119 arr.foo = function () { return 42 }
2120 arr.constructor = Bar
2121 return arr.foo() === 42 && // typed array instances can be augmented
2122 arr.constructor === Bar && // constructor can be set
2123 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
2124 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
2125 } catch (e) {
2126 return false
2127 }
2128})()
2129
2130function kMaxLength () {
2131 return Buffer.TYPED_ARRAY_SUPPORT
2132 ? 0x7fffffff
2133 : 0x3fffffff
2134}
2135
2136/**
2137 * Class: Buffer
2138 * =============
2139 *
2140 * The Buffer constructor returns instances of `Uint8Array` that are augmented
2141 * with function properties for all the node `Buffer` API functions. We use
2142 * `Uint8Array` so that square bracket notation works as expected -- it returns
2143 * a single octet.
2144 *
2145 * By augmenting the instances, we can avoid modifying the `Uint8Array`
2146 * prototype.
2147 */
2148function Buffer (arg) {
2149 if (!(this instanceof Buffer)) {
2150 // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
2151 if (arguments.length > 1) return new Buffer(arg, arguments[1])
2152 return new Buffer(arg)
2153 }
2154
2155 this.length = 0
2156 this.parent = undefined
2157
2158 // Common case.
2159 if (typeof arg === 'number') {
2160 return fromNumber(this, arg)
2161 }
2162
2163 // Slightly less common case.
2164 if (typeof arg === 'string') {
2165 return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
2166 }
2167
2168 // Unusual.
2169 return fromObject(this, arg)
2170}
2171
2172function fromNumber (that, length) {
2173 that = allocate(that, length < 0 ? 0 : checked(length) | 0)
2174 if (!Buffer.TYPED_ARRAY_SUPPORT) {
2175 for (var i = 0; i < length; i++) {
2176 that[i] = 0
2177 }
2178 }
2179 return that
2180}
2181
2182function fromString (that, string, encoding) {
2183 if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
2184
2185 // Assumption: byteLength() return value is always < kMaxLength.
2186 var length = byteLength(string, encoding) | 0
2187 that = allocate(that, length)
2188
2189 that.write(string, encoding)
2190 return that
2191}
2192
2193function fromObject (that, object) {
2194 if (Buffer.isBuffer(object)) return fromBuffer(that, object)
2195
2196 if (isArray(object)) return fromArray(that, object)
2197
2198 if (object == null) {
2199 throw new TypeError('must start with number, buffer, array or string')
2200 }
2201
2202 if (typeof ArrayBuffer !== 'undefined') {
2203 if (object.buffer instanceof ArrayBuffer) {
2204 return fromTypedArray(that, object)
2205 }
2206 if (object instanceof ArrayBuffer) {
2207 return fromArrayBuffer(that, object)
2208 }
2209 }
2210
2211 if (object.length) return fromArrayLike(that, object)
2212
2213 return fromJsonObject(that, object)
2214}
2215
2216function fromBuffer (that, buffer) {
2217 var length = checked(buffer.length) | 0
2218 that = allocate(that, length)
2219 buffer.copy(that, 0, 0, length)
2220 return that
2221}
2222
2223function fromArray (that, array) {
2224 var length = checked(array.length) | 0
2225 that = allocate(that, length)
2226 for (var i = 0; i < length; i += 1) {
2227 that[i] = array[i] & 255
2228 }
2229 return that
2230}
2231
2232// Duplicate of fromArray() to keep fromArray() monomorphic.
2233function fromTypedArray (that, array) {
2234 var length = checked(array.length) | 0
2235 that = allocate(that, length)
2236 // Truncating the elements is probably not what people expect from typed
2237 // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
2238 // of the old Buffer constructor.
2239 for (var i = 0; i < length; i += 1) {
2240 that[i] = array[i] & 255
2241 }
2242 return that
2243}
2244
2245function fromArrayBuffer (that, array) {
2246 if (Buffer.TYPED_ARRAY_SUPPORT) {
2247 // Return an augmented `Uint8Array` instance, for best performance
2248 array.byteLength
2249 that = Buffer._augment(new Uint8Array(array))
2250 } else {
2251 // Fallback: Return an object instance of the Buffer class
2252 that = fromTypedArray(that, new Uint8Array(array))
2253 }
2254 return that
2255}
2256
2257function fromArrayLike (that, array) {
2258 var length = checked(array.length) | 0
2259 that = allocate(that, length)
2260 for (var i = 0; i < length; i += 1) {
2261 that[i] = array[i] & 255
2262 }
2263 return that
2264}
2265
2266// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
2267// Returns a zero-length buffer for inputs that don't conform to the spec.
2268function fromJsonObject (that, object) {
2269 var array
2270 var length = 0
2271
2272 if (object.type === 'Buffer' && isArray(object.data)) {
2273 array = object.data
2274 length = checked(array.length) | 0
2275 }
2276 that = allocate(that, length)
2277
2278 for (var i = 0; i < length; i += 1) {
2279 that[i] = array[i] & 255
2280 }
2281 return that
2282}
2283
2284function allocate (that, length) {
2285 if (Buffer.TYPED_ARRAY_SUPPORT) {
2286 // Return an augmented `Uint8Array` instance, for best performance
2287 that = Buffer._augment(new Uint8Array(length))
2288 } else {
2289 // Fallback: Return an object instance of the Buffer class
2290 that.length = length
2291 that._isBuffer = true
2292 }
2293
2294 var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
2295 if (fromPool) that.parent = rootParent
2296
2297 return that
2298}
2299
2300function checked (length) {
2301 // Note: cannot use `length < kMaxLength` here because that fails when
2302 // length is NaN (which is otherwise coerced to zero.)
2303 if (length >= kMaxLength()) {
2304 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
2305 'size: 0x' + kMaxLength().toString(16) + ' bytes')
2306 }
2307 return length | 0
2308}
2309
2310function SlowBuffer (subject, encoding) {
2311 if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
2312
2313 var buf = new Buffer(subject, encoding)
2314 delete buf.parent
2315 return buf
2316}
2317
2318Buffer.isBuffer = function isBuffer (b) {
2319 return !!(b != null && b._isBuffer)
2320}
2321
2322Buffer.compare = function compare (a, b) {
2323 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
2324 throw new TypeError('Arguments must be Buffers')
2325 }
2326
2327 if (a === b) return 0
2328
2329 var x = a.length
2330 var y = b.length
2331
2332 var i = 0
2333 var len = Math.min(x, y)
2334 while (i < len) {
2335 if (a[i] !== b[i]) break
2336
2337 ++i
2338 }
2339
2340 if (i !== len) {
2341 x = a[i]
2342 y = b[i]
2343 }
2344
2345 if (x < y) return -1
2346 if (y < x) return 1
2347 return 0
2348}
2349
2350Buffer.isEncoding = function isEncoding (encoding) {
2351 switch (String(encoding).toLowerCase()) {
2352 case 'hex':
2353 case 'utf8':
2354 case 'utf-8':
2355 case 'ascii':
2356 case 'binary':
2357 case 'base64':
2358 case 'raw':
2359 case 'ucs2':
2360 case 'ucs-2':
2361 case 'utf16le':
2362 case 'utf-16le':
2363 return true
2364 default:
2365 return false
2366 }
2367}
2368
2369Buffer.concat = function concat (list, length) {
2370 if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
2371
2372 if (list.length === 0) {
2373 return new Buffer(0)
2374 }
2375
2376 var i
2377 if (length === undefined) {
2378 length = 0
2379 for (i = 0; i < list.length; i++) {
2380 length += list[i].length
2381 }
2382 }
2383
2384 var buf = new Buffer(length)
2385 var pos = 0
2386 for (i = 0; i < list.length; i++) {
2387 var item = list[i]
2388 item.copy(buf, pos)
2389 pos += item.length
2390 }
2391 return buf
2392}
2393
2394function byteLength (string, encoding) {
2395 if (typeof string !== 'string') string = '' + string
2396
2397 var len = string.length
2398 if (len === 0) return 0
2399
2400 // Use a for loop to avoid recursion
2401 var loweredCase = false
2402 for (;;) {
2403 switch (encoding) {
2404 case 'ascii':
2405 case 'binary':
2406 // Deprecated
2407 case 'raw':
2408 case 'raws':
2409 return len
2410 case 'utf8':
2411 case 'utf-8':
2412 return utf8ToBytes(string).length
2413 case 'ucs2':
2414 case 'ucs-2':
2415 case 'utf16le':
2416 case 'utf-16le':
2417 return len * 2
2418 case 'hex':
2419 return len >>> 1
2420 case 'base64':
2421 return base64ToBytes(string).length
2422 default:
2423 if (loweredCase) return utf8ToBytes(string).length // assume utf8
2424 encoding = ('' + encoding).toLowerCase()
2425 loweredCase = true
2426 }
2427 }
2428}
2429Buffer.byteLength = byteLength
2430
2431// pre-set for values that may exist in the future
2432Buffer.prototype.length = undefined
2433Buffer.prototype.parent = undefined
2434
2435function slowToString (encoding, start, end) {
2436 var loweredCase = false
2437
2438 start = start | 0
2439 end = end === undefined || end === Infinity ? this.length : end | 0
2440
2441 if (!encoding) encoding = 'utf8'
2442 if (start < 0) start = 0
2443 if (end > this.length) end = this.length
2444 if (end <= start) return ''
2445
2446 while (true) {
2447 switch (encoding) {
2448 case 'hex':
2449 return hexSlice(this, start, end)
2450
2451 case 'utf8':
2452 case 'utf-8':
2453 return utf8Slice(this, start, end)
2454
2455 case 'ascii':
2456 return asciiSlice(this, start, end)
2457
2458 case 'binary':
2459 return binarySlice(this, start, end)
2460
2461 case 'base64':
2462 return base64Slice(this, start, end)
2463
2464 case 'ucs2':
2465 case 'ucs-2':
2466 case 'utf16le':
2467 case 'utf-16le':
2468 return utf16leSlice(this, start, end)
2469
2470 default:
2471 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2472 encoding = (encoding + '').toLowerCase()
2473 loweredCase = true
2474 }
2475 }
2476}
2477
2478Buffer.prototype.toString = function toString () {
2479 var length = this.length | 0
2480 if (length === 0) return ''
2481 if (arguments.length === 0) return utf8Slice(this, 0, length)
2482 return slowToString.apply(this, arguments)
2483}
2484
2485Buffer.prototype.equals = function equals (b) {
2486 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2487 if (this === b) return true
2488 return Buffer.compare(this, b) === 0
2489}
2490
2491Buffer.prototype.inspect = function inspect () {
2492 var str = ''
2493 var max = exports.INSPECT_MAX_BYTES
2494 if (this.length > 0) {
2495 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
2496 if (this.length > max) str += ' ... '
2497 }
2498 return '<Buffer ' + str + '>'
2499}
2500
2501Buffer.prototype.compare = function compare (b) {
2502 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2503 if (this === b) return 0
2504 return Buffer.compare(this, b)
2505}
2506
2507Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
2508 if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
2509 else if (byteOffset < -0x80000000) byteOffset = -0x80000000
2510 byteOffset >>= 0
2511
2512 if (this.length === 0) return -1
2513 if (byteOffset >= this.length) return -1
2514
2515 // Negative offsets start from the end of the buffer
2516 if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
2517
2518 if (typeof val === 'string') {
2519 if (val.length === 0) return -1 // special case: looking for empty string always fails
2520 return String.prototype.indexOf.call(this, val, byteOffset)
2521 }
2522 if (Buffer.isBuffer(val)) {
2523 return arrayIndexOf(this, val, byteOffset)
2524 }
2525 if (typeof val === 'number') {
2526 if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
2527 return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
2528 }
2529 return arrayIndexOf(this, [ val ], byteOffset)
2530 }
2531
2532 function arrayIndexOf (arr, val, byteOffset) {
2533 var foundIndex = -1
2534 for (var i = 0; byteOffset + i < arr.length; i++) {
2535 if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
2536 if (foundIndex === -1) foundIndex = i
2537 if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
2538 } else {
2539 foundIndex = -1
2540 }
2541 }
2542 return -1
2543 }
2544
2545 throw new TypeError('val must be string, number or Buffer')
2546}
2547
2548// `get` is deprecated
2549Buffer.prototype.get = function get (offset) {
2550 console.log('.get() is deprecated. Access using array indexes instead.')
2551 return this.readUInt8(offset)
2552}
2553
2554// `set` is deprecated
2555Buffer.prototype.set = function set (v, offset) {
2556 console.log('.set() is deprecated. Access using array indexes instead.')
2557 return this.writeUInt8(v, offset)
2558}
2559
2560function hexWrite (buf, string, offset, length) {
2561 offset = Number(offset) || 0
2562 var remaining = buf.length - offset
2563 if (!length) {
2564 length = remaining
2565 } else {
2566 length = Number(length)
2567 if (length > remaining) {
2568 length = remaining
2569 }
2570 }
2571
2572 // must be an even number of digits
2573 var strLen = string.length
2574 if (strLen % 2 !== 0) throw new Error('Invalid hex string')
2575
2576 if (length > strLen / 2) {
2577 length = strLen / 2
2578 }
2579 for (var i = 0; i < length; i++) {
2580 var parsed = parseInt(string.substr(i * 2, 2), 16)
2581 if (isNaN(parsed)) throw new Error('Invalid hex string')
2582 buf[offset + i] = parsed
2583 }
2584 return i
2585}
2586
2587function utf8Write (buf, string, offset, length) {
2588 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2589}
2590
2591function asciiWrite (buf, string, offset, length) {
2592 return blitBuffer(asciiToBytes(string), buf, offset, length)
2593}
2594
2595function binaryWrite (buf, string, offset, length) {
2596 return asciiWrite(buf, string, offset, length)
2597}
2598
2599function base64Write (buf, string, offset, length) {
2600 return blitBuffer(base64ToBytes(string), buf, offset, length)
2601}
2602
2603function ucs2Write (buf, string, offset, length) {
2604 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2605}
2606
2607Buffer.prototype.write = function write (string, offset, length, encoding) {
2608 // Buffer#write(string)
2609 if (offset === undefined) {
2610 encoding = 'utf8'
2611 length = this.length
2612 offset = 0
2613 // Buffer#write(string, encoding)
2614 } else if (length === undefined && typeof offset === 'string') {
2615 encoding = offset
2616 length = this.length
2617 offset = 0
2618 // Buffer#write(string, offset[, length][, encoding])
2619 } else if (isFinite(offset)) {
2620 offset = offset | 0
2621 if (isFinite(length)) {
2622 length = length | 0
2623 if (encoding === undefined) encoding = 'utf8'
2624 } else {
2625 encoding = length
2626 length = undefined
2627 }
2628 // legacy write(string, encoding, offset, length) - remove in v0.13
2629 } else {
2630 var swap = encoding
2631 encoding = offset
2632 offset = length | 0
2633 length = swap
2634 }
2635
2636 var remaining = this.length - offset
2637 if (length === undefined || length > remaining) length = remaining
2638
2639 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2640 throw new RangeError('attempt to write outside buffer bounds')
2641 }
2642
2643 if (!encoding) encoding = 'utf8'
2644
2645 var loweredCase = false
2646 for (;;) {
2647 switch (encoding) {
2648 case 'hex':
2649 return hexWrite(this, string, offset, length)
2650
2651 case 'utf8':
2652 case 'utf-8':
2653 return utf8Write(this, string, offset, length)
2654
2655 case 'ascii':
2656 return asciiWrite(this, string, offset, length)
2657
2658 case 'binary':
2659 return binaryWrite(this, string, offset, length)
2660
2661 case 'base64':
2662 // Warning: maxLength not taken into account in base64Write
2663 return base64Write(this, string, offset, length)
2664
2665 case 'ucs2':
2666 case 'ucs-2':
2667 case 'utf16le':
2668 case 'utf-16le':
2669 return ucs2Write(this, string, offset, length)
2670
2671 default:
2672 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2673 encoding = ('' + encoding).toLowerCase()
2674 loweredCase = true
2675 }
2676 }
2677}
2678
2679Buffer.prototype.toJSON = function toJSON () {
2680 return {
2681 type: 'Buffer',
2682 data: Array.prototype.slice.call(this._arr || this, 0)
2683 }
2684}
2685
2686function base64Slice (buf, start, end) {
2687 if (start === 0 && end === buf.length) {
2688 return base64.fromByteArray(buf)
2689 } else {
2690 return base64.fromByteArray(buf.slice(start, end))
2691 }
2692}
2693
2694function utf8Slice (buf, start, end) {
2695 end = Math.min(buf.length, end)
2696 var firstByte
2697 var secondByte
2698 var thirdByte
2699 var fourthByte
2700 var bytesPerSequence
2701 var tempCodePoint
2702 var codePoint
2703 var res = []
2704 var i = start
2705
2706 for (; i < end; i += bytesPerSequence) {
2707 firstByte = buf[i]
2708 codePoint = 0xFFFD
2709
2710 if (firstByte > 0xEF) {
2711 bytesPerSequence = 4
2712 } else if (firstByte > 0xDF) {
2713 bytesPerSequence = 3
2714 } else if (firstByte > 0xBF) {
2715 bytesPerSequence = 2
2716 } else {
2717 bytesPerSequence = 1
2718 }
2719
2720 if (i + bytesPerSequence <= end) {
2721 switch (bytesPerSequence) {
2722 case 1:
2723 if (firstByte < 0x80) {
2724 codePoint = firstByte
2725 }
2726 break
2727 case 2:
2728 secondByte = buf[i + 1]
2729 if ((secondByte & 0xC0) === 0x80) {
2730 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2731 if (tempCodePoint > 0x7F) {
2732 codePoint = tempCodePoint
2733 }
2734 }
2735 break
2736 case 3:
2737 secondByte = buf[i + 1]
2738 thirdByte = buf[i + 2]
2739 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2740 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2741 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2742 codePoint = tempCodePoint
2743 }
2744 }
2745 break
2746 case 4:
2747 secondByte = buf[i + 1]
2748 thirdByte = buf[i + 2]
2749 fourthByte = buf[i + 3]
2750 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2751 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2752 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2753 codePoint = tempCodePoint
2754 }
2755 }
2756 }
2757 }
2758
2759 if (codePoint === 0xFFFD) {
2760 // we generated an invalid codePoint so make sure to only advance by 1 byte
2761 bytesPerSequence = 1
2762 } else if (codePoint > 0xFFFF) {
2763 // encode to utf16 (surrogate pair dance)
2764 codePoint -= 0x10000
2765 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2766 codePoint = 0xDC00 | codePoint & 0x3FF
2767 }
2768
2769 res.push(codePoint)
2770 }
2771
2772 return String.fromCharCode.apply(String, res)
2773}
2774
2775function asciiSlice (buf, start, end) {
2776 var ret = ''
2777 end = Math.min(buf.length, end)
2778
2779 for (var i = start; i < end; i++) {
2780 ret += String.fromCharCode(buf[i] & 0x7F)
2781 }
2782 return ret
2783}
2784
2785function binarySlice (buf, start, end) {
2786 var ret = ''
2787 end = Math.min(buf.length, end)
2788
2789 for (var i = start; i < end; i++) {
2790 ret += String.fromCharCode(buf[i])
2791 }
2792 return ret
2793}
2794
2795function hexSlice (buf, start, end) {
2796 var len = buf.length
2797
2798 if (!start || start < 0) start = 0
2799 if (!end || end < 0 || end > len) end = len
2800
2801 var out = ''
2802 for (var i = start; i < end; i++) {
2803 out += toHex(buf[i])
2804 }
2805 return out
2806}
2807
2808function utf16leSlice (buf, start, end) {
2809 var bytes = buf.slice(start, end)
2810 var res = ''
2811 for (var i = 0; i < bytes.length; i += 2) {
2812 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
2813 }
2814 return res
2815}
2816
2817Buffer.prototype.slice = function slice (start, end) {
2818 var len = this.length
2819 start = ~~start
2820 end = end === undefined ? len : ~~end
2821
2822 if (start < 0) {
2823 start += len
2824 if (start < 0) start = 0
2825 } else if (start > len) {
2826 start = len
2827 }
2828
2829 if (end < 0) {
2830 end += len
2831 if (end < 0) end = 0
2832 } else if (end > len) {
2833 end = len
2834 }
2835
2836 if (end < start) end = start
2837
2838 var newBuf
2839 if (Buffer.TYPED_ARRAY_SUPPORT) {
2840 newBuf = Buffer._augment(this.subarray(start, end))
2841 } else {
2842 var sliceLen = end - start
2843 newBuf = new Buffer(sliceLen, undefined)
2844 for (var i = 0; i < sliceLen; i++) {
2845 newBuf[i] = this[i + start]
2846 }
2847 }
2848
2849 if (newBuf.length) newBuf.parent = this.parent || this
2850
2851 return newBuf
2852}
2853
2854/*
2855 * Need to make sure that buffer isn't trying to write out of bounds.
2856 */
2857function checkOffset (offset, ext, length) {
2858 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2859 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2860}
2861
2862Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2863 offset = offset | 0
2864 byteLength = byteLength | 0
2865 if (!noAssert) checkOffset(offset, byteLength, this.length)
2866
2867 var val = this[offset]
2868 var mul = 1
2869 var i = 0
2870 while (++i < byteLength && (mul *= 0x100)) {
2871 val += this[offset + i] * mul
2872 }
2873
2874 return val
2875}
2876
2877Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2878 offset = offset | 0
2879 byteLength = byteLength | 0
2880 if (!noAssert) {
2881 checkOffset(offset, byteLength, this.length)
2882 }
2883
2884 var val = this[offset + --byteLength]
2885 var mul = 1
2886 while (byteLength > 0 && (mul *= 0x100)) {
2887 val += this[offset + --byteLength] * mul
2888 }
2889
2890 return val
2891}
2892
2893Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2894 if (!noAssert) checkOffset(offset, 1, this.length)
2895 return this[offset]
2896}
2897
2898Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2899 if (!noAssert) checkOffset(offset, 2, this.length)
2900 return this[offset] | (this[offset + 1] << 8)
2901}
2902
2903Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2904 if (!noAssert) checkOffset(offset, 2, this.length)
2905 return (this[offset] << 8) | this[offset + 1]
2906}
2907
2908Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2909 if (!noAssert) checkOffset(offset, 4, this.length)
2910
2911 return ((this[offset]) |
2912 (this[offset + 1] << 8) |
2913 (this[offset + 2] << 16)) +
2914 (this[offset + 3] * 0x1000000)
2915}
2916
2917Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2918 if (!noAssert) checkOffset(offset, 4, this.length)
2919
2920 return (this[offset] * 0x1000000) +
2921 ((this[offset + 1] << 16) |
2922 (this[offset + 2] << 8) |
2923 this[offset + 3])
2924}
2925
2926Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2927 offset = offset | 0
2928 byteLength = byteLength | 0
2929 if (!noAssert) checkOffset(offset, byteLength, this.length)
2930
2931 var val = this[offset]
2932 var mul = 1
2933 var i = 0
2934 while (++i < byteLength && (mul *= 0x100)) {
2935 val += this[offset + i] * mul
2936 }
2937 mul *= 0x80
2938
2939 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2940
2941 return val
2942}
2943
2944Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2945 offset = offset | 0
2946 byteLength = byteLength | 0
2947 if (!noAssert) checkOffset(offset, byteLength, this.length)
2948
2949 var i = byteLength
2950 var mul = 1
2951 var val = this[offset + --i]
2952 while (i > 0 && (mul *= 0x100)) {
2953 val += this[offset + --i] * mul
2954 }
2955 mul *= 0x80
2956
2957 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2958
2959 return val
2960}
2961
2962Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2963 if (!noAssert) checkOffset(offset, 1, this.length)
2964 if (!(this[offset] & 0x80)) return (this[offset])
2965 return ((0xff - this[offset] + 1) * -1)
2966}
2967
2968Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2969 if (!noAssert) checkOffset(offset, 2, this.length)
2970 var val = this[offset] | (this[offset + 1] << 8)
2971 return (val & 0x8000) ? val | 0xFFFF0000 : val
2972}
2973
2974Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2975 if (!noAssert) checkOffset(offset, 2, this.length)
2976 var val = this[offset + 1] | (this[offset] << 8)
2977 return (val & 0x8000) ? val | 0xFFFF0000 : val
2978}
2979
2980Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2981 if (!noAssert) checkOffset(offset, 4, this.length)
2982
2983 return (this[offset]) |
2984 (this[offset + 1] << 8) |
2985 (this[offset + 2] << 16) |
2986 (this[offset + 3] << 24)
2987}
2988
2989Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2990 if (!noAssert) checkOffset(offset, 4, this.length)
2991
2992 return (this[offset] << 24) |
2993 (this[offset + 1] << 16) |
2994 (this[offset + 2] << 8) |
2995 (this[offset + 3])
2996}
2997
2998Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2999 if (!noAssert) checkOffset(offset, 4, this.length)
3000 return ieee754.read(this, offset, true, 23, 4)
3001}
3002
3003Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
3004 if (!noAssert) checkOffset(offset, 4, this.length)
3005 return ieee754.read(this, offset, false, 23, 4)
3006}
3007
3008Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
3009 if (!noAssert) checkOffset(offset, 8, this.length)
3010 return ieee754.read(this, offset, true, 52, 8)
3011}
3012
3013Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
3014 if (!noAssert) checkOffset(offset, 8, this.length)
3015 return ieee754.read(this, offset, false, 52, 8)
3016}
3017
3018function checkInt (buf, value, offset, ext, max, min) {
3019 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
3020 if (value > max || value < min) throw new RangeError('value is out of bounds')
3021 if (offset + ext > buf.length) throw new RangeError('index out of range')
3022}
3023
3024Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
3025 value = +value
3026 offset = offset | 0
3027 byteLength = byteLength | 0
3028 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
3029
3030 var mul = 1
3031 var i = 0
3032 this[offset] = value & 0xFF
3033 while (++i < byteLength && (mul *= 0x100)) {
3034 this[offset + i] = (value / mul) & 0xFF
3035 }
3036
3037 return offset + byteLength
3038}
3039
3040Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
3041 value = +value
3042 offset = offset | 0
3043 byteLength = byteLength | 0
3044 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
3045
3046 var i = byteLength - 1
3047 var mul = 1
3048 this[offset + i] = value & 0xFF
3049 while (--i >= 0 && (mul *= 0x100)) {
3050 this[offset + i] = (value / mul) & 0xFF
3051 }
3052
3053 return offset + byteLength
3054}
3055
3056Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
3057 value = +value
3058 offset = offset | 0
3059 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
3060 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
3061 this[offset] = value
3062 return offset + 1
3063}
3064
3065function objectWriteUInt16 (buf, value, offset, littleEndian) {
3066 if (value < 0) value = 0xffff + value + 1
3067 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
3068 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
3069 (littleEndian ? i : 1 - i) * 8
3070 }
3071}
3072
3073Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
3074 value = +value
3075 offset = offset | 0
3076 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3077 if (Buffer.TYPED_ARRAY_SUPPORT) {
3078 this[offset] = value
3079 this[offset + 1] = (value >>> 8)
3080 } else {
3081 objectWriteUInt16(this, value, offset, true)
3082 }
3083 return offset + 2
3084}
3085
3086Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
3087 value = +value
3088 offset = offset | 0
3089 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3090 if (Buffer.TYPED_ARRAY_SUPPORT) {
3091 this[offset] = (value >>> 8)
3092 this[offset + 1] = value
3093 } else {
3094 objectWriteUInt16(this, value, offset, false)
3095 }
3096 return offset + 2
3097}
3098
3099function objectWriteUInt32 (buf, value, offset, littleEndian) {
3100 if (value < 0) value = 0xffffffff + value + 1
3101 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
3102 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
3103 }
3104}
3105
3106Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
3107 value = +value
3108 offset = offset | 0
3109 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3110 if (Buffer.TYPED_ARRAY_SUPPORT) {
3111 this[offset + 3] = (value >>> 24)
3112 this[offset + 2] = (value >>> 16)
3113 this[offset + 1] = (value >>> 8)
3114 this[offset] = value
3115 } else {
3116 objectWriteUInt32(this, value, offset, true)
3117 }
3118 return offset + 4
3119}
3120
3121Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
3122 value = +value
3123 offset = offset | 0
3124 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3125 if (Buffer.TYPED_ARRAY_SUPPORT) {
3126 this[offset] = (value >>> 24)
3127 this[offset + 1] = (value >>> 16)
3128 this[offset + 2] = (value >>> 8)
3129 this[offset + 3] = value
3130 } else {
3131 objectWriteUInt32(this, value, offset, false)
3132 }
3133 return offset + 4
3134}
3135
3136Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
3137 value = +value
3138 offset = offset | 0
3139 if (!noAssert) {
3140 var limit = Math.pow(2, 8 * byteLength - 1)
3141
3142 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3143 }
3144
3145 var i = 0
3146 var mul = 1
3147 var sub = value < 0 ? 1 : 0
3148 this[offset] = value & 0xFF
3149 while (++i < byteLength && (mul *= 0x100)) {
3150 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3151 }
3152
3153 return offset + byteLength
3154}
3155
3156Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
3157 value = +value
3158 offset = offset | 0
3159 if (!noAssert) {
3160 var limit = Math.pow(2, 8 * byteLength - 1)
3161
3162 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3163 }
3164
3165 var i = byteLength - 1
3166 var mul = 1
3167 var sub = value < 0 ? 1 : 0
3168 this[offset + i] = value & 0xFF
3169 while (--i >= 0 && (mul *= 0x100)) {
3170 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3171 }
3172
3173 return offset + byteLength
3174}
3175
3176Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
3177 value = +value
3178 offset = offset | 0
3179 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
3180 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
3181 if (value < 0) value = 0xff + value + 1
3182 this[offset] = value
3183 return offset + 1
3184}
3185
3186Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
3187 value = +value
3188 offset = offset | 0
3189 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3190 if (Buffer.TYPED_ARRAY_SUPPORT) {
3191 this[offset] = value
3192 this[offset + 1] = (value >>> 8)
3193 } else {
3194 objectWriteUInt16(this, value, offset, true)
3195 }
3196 return offset + 2
3197}
3198
3199Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
3200 value = +value
3201 offset = offset | 0
3202 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3203 if (Buffer.TYPED_ARRAY_SUPPORT) {
3204 this[offset] = (value >>> 8)
3205 this[offset + 1] = value
3206 } else {
3207 objectWriteUInt16(this, value, offset, false)
3208 }
3209 return offset + 2
3210}
3211
3212Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
3213 value = +value
3214 offset = offset | 0
3215 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3216 if (Buffer.TYPED_ARRAY_SUPPORT) {
3217 this[offset] = value
3218 this[offset + 1] = (value >>> 8)
3219 this[offset + 2] = (value >>> 16)
3220 this[offset + 3] = (value >>> 24)
3221 } else {
3222 objectWriteUInt32(this, value, offset, true)
3223 }
3224 return offset + 4
3225}
3226
3227Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
3228 value = +value
3229 offset = offset | 0
3230 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3231 if (value < 0) value = 0xffffffff + value + 1
3232 if (Buffer.TYPED_ARRAY_SUPPORT) {
3233 this[offset] = (value >>> 24)
3234 this[offset + 1] = (value >>> 16)
3235 this[offset + 2] = (value >>> 8)
3236 this[offset + 3] = value
3237 } else {
3238 objectWriteUInt32(this, value, offset, false)
3239 }
3240 return offset + 4
3241}
3242
3243function checkIEEE754 (buf, value, offset, ext, max, min) {
3244 if (value > max || value < min) throw new RangeError('value is out of bounds')
3245 if (offset + ext > buf.length) throw new RangeError('index out of range')
3246 if (offset < 0) throw new RangeError('index out of range')
3247}
3248
3249function writeFloat (buf, value, offset, littleEndian, noAssert) {
3250 if (!noAssert) {
3251 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3252 }
3253 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3254 return offset + 4
3255}
3256
3257Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
3258 return writeFloat(this, value, offset, true, noAssert)
3259}
3260
3261Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
3262 return writeFloat(this, value, offset, false, noAssert)
3263}
3264
3265function writeDouble (buf, value, offset, littleEndian, noAssert) {
3266 if (!noAssert) {
3267 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3268 }
3269 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3270 return offset + 8
3271}
3272
3273Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
3274 return writeDouble(this, value, offset, true, noAssert)
3275}
3276
3277Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
3278 return writeDouble(this, value, offset, false, noAssert)
3279}
3280
3281// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3282Buffer.prototype.copy = function copy (target, targetStart, start, end) {
3283 if (!start) start = 0
3284 if (!end && end !== 0) end = this.length
3285 if (targetStart >= target.length) targetStart = target.length
3286 if (!targetStart) targetStart = 0
3287 if (end > 0 && end < start) end = start
3288
3289 // Copy 0 bytes; we're done
3290 if (end === start) return 0
3291 if (target.length === 0 || this.length === 0) return 0
3292
3293 // Fatal error conditions
3294 if (targetStart < 0) {
3295 throw new RangeError('targetStart out of bounds')
3296 }
3297 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
3298 if (end < 0) throw new RangeError('sourceEnd out of bounds')
3299
3300 // Are we oob?
3301 if (end > this.length) end = this.length
3302 if (target.length - targetStart < end - start) {
3303 end = target.length - targetStart + start
3304 }
3305
3306 var len = end - start
3307 var i
3308
3309 if (this === target && start < targetStart && targetStart < end) {
3310 // descending copy from end
3311 for (i = len - 1; i >= 0; i--) {
3312 target[i + targetStart] = this[i + start]
3313 }
3314 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
3315 // ascending copy from start
3316 for (i = 0; i < len; i++) {
3317 target[i + targetStart] = this[i + start]
3318 }
3319 } else {
3320 target._set(this.subarray(start, start + len), targetStart)
3321 }
3322
3323 return len
3324}
3325
3326// fill(value, start=0, end=buffer.length)
3327Buffer.prototype.fill = function fill (value, start, end) {
3328 if (!value) value = 0
3329 if (!start) start = 0
3330 if (!end) end = this.length
3331
3332 if (end < start) throw new RangeError('end < start')
3333
3334 // Fill 0 bytes; we're done
3335 if (end === start) return
3336 if (this.length === 0) return
3337
3338 if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
3339 if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
3340
3341 var i
3342 if (typeof value === 'number') {
3343 for (i = start; i < end; i++) {
3344 this[i] = value
3345 }
3346 } else {
3347 var bytes = utf8ToBytes(value.toString())
3348 var len = bytes.length
3349 for (i = start; i < end; i++) {
3350 this[i] = bytes[i % len]
3351 }
3352 }
3353
3354 return this
3355}
3356
3357/**
3358 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
3359 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
3360 */
3361Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
3362 if (typeof Uint8Array !== 'undefined') {
3363 if (Buffer.TYPED_ARRAY_SUPPORT) {
3364 return (new Buffer(this)).buffer
3365 } else {
3366 var buf = new Uint8Array(this.length)
3367 for (var i = 0, len = buf.length; i < len; i += 1) {
3368 buf[i] = this[i]
3369 }
3370 return buf.buffer
3371 }
3372 } else {
3373 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
3374 }
3375}
3376
3377// HELPER FUNCTIONS
3378// ================
3379
3380var BP = Buffer.prototype
3381
3382/**
3383 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
3384 */
3385Buffer._augment = function _augment (arr) {
3386 arr.constructor = Buffer
3387 arr._isBuffer = true
3388
3389 // save reference to original Uint8Array set method before overwriting
3390 arr._set = arr.set
3391
3392 // deprecated
3393 arr.get = BP.get
3394 arr.set = BP.set
3395
3396 arr.write = BP.write
3397 arr.toString = BP.toString
3398 arr.toLocaleString = BP.toString
3399 arr.toJSON = BP.toJSON
3400 arr.equals = BP.equals
3401 arr.compare = BP.compare
3402 arr.indexOf = BP.indexOf
3403 arr.copy = BP.copy
3404 arr.slice = BP.slice
3405 arr.readUIntLE = BP.readUIntLE
3406 arr.readUIntBE = BP.readUIntBE
3407 arr.readUInt8 = BP.readUInt8
3408 arr.readUInt16LE = BP.readUInt16LE
3409 arr.readUInt16BE = BP.readUInt16BE
3410 arr.readUInt32LE = BP.readUInt32LE
3411 arr.readUInt32BE = BP.readUInt32BE
3412 arr.readIntLE = BP.readIntLE
3413 arr.readIntBE = BP.readIntBE
3414 arr.readInt8 = BP.readInt8
3415 arr.readInt16LE = BP.readInt16LE
3416 arr.readInt16BE = BP.readInt16BE
3417 arr.readInt32LE = BP.readInt32LE
3418 arr.readInt32BE = BP.readInt32BE
3419 arr.readFloatLE = BP.readFloatLE
3420 arr.readFloatBE = BP.readFloatBE
3421 arr.readDoubleLE = BP.readDoubleLE
3422 arr.readDoubleBE = BP.readDoubleBE
3423 arr.writeUInt8 = BP.writeUInt8
3424 arr.writeUIntLE = BP.writeUIntLE
3425 arr.writeUIntBE = BP.writeUIntBE
3426 arr.writeUInt16LE = BP.writeUInt16LE
3427 arr.writeUInt16BE = BP.writeUInt16BE
3428 arr.writeUInt32LE = BP.writeUInt32LE
3429 arr.writeUInt32BE = BP.writeUInt32BE
3430 arr.writeIntLE = BP.writeIntLE
3431 arr.writeIntBE = BP.writeIntBE
3432 arr.writeInt8 = BP.writeInt8
3433 arr.writeInt16LE = BP.writeInt16LE
3434 arr.writeInt16BE = BP.writeInt16BE
3435 arr.writeInt32LE = BP.writeInt32LE
3436 arr.writeInt32BE = BP.writeInt32BE
3437 arr.writeFloatLE = BP.writeFloatLE
3438 arr.writeFloatBE = BP.writeFloatBE
3439 arr.writeDoubleLE = BP.writeDoubleLE
3440 arr.writeDoubleBE = BP.writeDoubleBE
3441 arr.fill = BP.fill
3442 arr.inspect = BP.inspect
3443 arr.toArrayBuffer = BP.toArrayBuffer
3444
3445 return arr
3446}
3447
3448var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
3449
3450function base64clean (str) {
3451 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3452 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
3453 // Node converts strings with length < 2 to ''
3454 if (str.length < 2) return ''
3455 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3456 while (str.length % 4 !== 0) {
3457 str = str + '='
3458 }
3459 return str
3460}
3461
3462function stringtrim (str) {
3463 if (str.trim) return str.trim()
3464 return str.replace(/^\s+|\s+$/g, '')
3465}
3466
3467function toHex (n) {
3468 if (n < 16) return '0' + n.toString(16)
3469 return n.toString(16)
3470}
3471
3472function utf8ToBytes (string, units) {
3473 units = units || Infinity
3474 var codePoint
3475 var length = string.length
3476 var leadSurrogate = null
3477 var bytes = []
3478
3479 for (var i = 0; i < length; i++) {
3480 codePoint = string.charCodeAt(i)
3481
3482 // is surrogate component
3483 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3484 // last char was a lead
3485 if (!leadSurrogate) {
3486 // no lead yet
3487 if (codePoint > 0xDBFF) {
3488 // unexpected trail
3489 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3490 continue
3491
3492 } else if (i + 1 === length) {
3493 // unpaired lead
3494 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3495 continue
3496 }
3497
3498 // valid lead
3499 leadSurrogate = codePoint
3500
3501 continue
3502 }
3503
3504 // 2 leads in a row
3505 if (codePoint < 0xDC00) {
3506 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3507 leadSurrogate = codePoint
3508 continue
3509 }
3510
3511 // valid surrogate pair
3512 codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
3513
3514 } else if (leadSurrogate) {
3515 // valid bmp char, but last char was a lead
3516 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3517 }
3518
3519 leadSurrogate = null
3520
3521 // encode utf8
3522 if (codePoint < 0x80) {
3523 if ((units -= 1) < 0) break
3524 bytes.push(codePoint)
3525 } else if (codePoint < 0x800) {
3526 if ((units -= 2) < 0) break
3527 bytes.push(
3528 codePoint >> 0x6 | 0xC0,
3529 codePoint & 0x3F | 0x80
3530 )
3531 } else if (codePoint < 0x10000) {
3532 if ((units -= 3) < 0) break
3533 bytes.push(
3534 codePoint >> 0xC | 0xE0,
3535 codePoint >> 0x6 & 0x3F | 0x80,
3536 codePoint & 0x3F | 0x80
3537 )
3538 } else if (codePoint < 0x110000) {
3539 if ((units -= 4) < 0) break
3540 bytes.push(
3541 codePoint >> 0x12 | 0xF0,
3542 codePoint >> 0xC & 0x3F | 0x80,
3543 codePoint >> 0x6 & 0x3F | 0x80,
3544 codePoint & 0x3F | 0x80
3545 )
3546 } else {
3547 throw new Error('Invalid code point')
3548 }
3549 }
3550
3551 return bytes
3552}
3553
3554function asciiToBytes (str) {
3555 var byteArray = []
3556 for (var i = 0; i < str.length; i++) {
3557 // Node's code seems to be doing this and not & 0x7F..
3558 byteArray.push(str.charCodeAt(i) & 0xFF)
3559 }
3560 return byteArray
3561}
3562
3563function utf16leToBytes (str, units) {
3564 var c, hi, lo
3565 var byteArray = []
3566 for (var i = 0; i < str.length; i++) {
3567 if ((units -= 2) < 0) break
3568
3569 c = str.charCodeAt(i)
3570 hi = c >> 8
3571 lo = c % 256
3572 byteArray.push(lo)
3573 byteArray.push(hi)
3574 }
3575
3576 return byteArray
3577}
3578
3579function base64ToBytes (str) {
3580 return base64.toByteArray(base64clean(str))
3581}
3582
3583function blitBuffer (src, dst, offset, length) {
3584 for (var i = 0; i < length; i++) {
3585 if ((i + offset >= dst.length) || (i >= src.length)) break
3586 dst[i + offset] = src[i]
3587 }
3588 return i
3589}
3590
3591},{"base64-js":8,"ieee754":9,"is-array":10}],8:[function(require,module,exports){
3592var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3593
3594;(function (exports) {
3595 'use strict';
3596
3597 var Arr = (typeof Uint8Array !== 'undefined')
3598 ? Uint8Array
3599 : Array
3600
3601 var PLUS = '+'.charCodeAt(0)
3602 var SLASH = '/'.charCodeAt(0)
3603 var NUMBER = '0'.charCodeAt(0)
3604 var LOWER = 'a'.charCodeAt(0)
3605 var UPPER = 'A'.charCodeAt(0)
3606 var PLUS_URL_SAFE = '-'.charCodeAt(0)
3607 var SLASH_URL_SAFE = '_'.charCodeAt(0)
3608
3609 function decode (elt) {
3610 var code = elt.charCodeAt(0)
3611 if (code === PLUS ||
3612 code === PLUS_URL_SAFE)
3613 return 62 // '+'
3614 if (code === SLASH ||
3615 code === SLASH_URL_SAFE)
3616 return 63 // '/'
3617 if (code < NUMBER)
3618 return -1 //no match
3619 if (code < NUMBER + 10)
3620 return code - NUMBER + 26 + 26
3621 if (code < UPPER + 26)
3622 return code - UPPER
3623 if (code < LOWER + 26)
3624 return code - LOWER + 26
3625 }
3626
3627 function b64ToByteArray (b64) {
3628 var i, j, l, tmp, placeHolders, arr
3629
3630 if (b64.length % 4 > 0) {
3631 throw new Error('Invalid string. Length must be a multiple of 4')
3632 }
3633
3634 // the number of equal signs (place holders)
3635 // if there are two placeholders, than the two characters before it
3636 // represent one byte
3637 // if there is only one, then the three characters before it represent 2 bytes
3638 // this is just a cheap hack to not do indexOf twice
3639 var len = b64.length
3640 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
3641
3642 // base64 is 4/3 + up to two characters of the original data
3643 arr = new Arr(b64.length * 3 / 4 - placeHolders)
3644
3645 // if there are placeholders, only get up to the last complete 4 chars
3646 l = placeHolders > 0 ? b64.length - 4 : b64.length
3647
3648 var L = 0
3649
3650 function push (v) {
3651 arr[L++] = v
3652 }
3653
3654 for (i = 0, j = 0; i < l; i += 4, j += 3) {
3655 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
3656 push((tmp & 0xFF0000) >> 16)
3657 push((tmp & 0xFF00) >> 8)
3658 push(tmp & 0xFF)
3659 }
3660
3661 if (placeHolders === 2) {
3662 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
3663 push(tmp & 0xFF)
3664 } else if (placeHolders === 1) {
3665 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
3666 push((tmp >> 8) & 0xFF)
3667 push(tmp & 0xFF)
3668 }
3669
3670 return arr
3671 }
3672
3673 function uint8ToBase64 (uint8) {
3674 var i,
3675 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
3676 output = "",
3677 temp, length
3678
3679 function encode (num) {
3680 return lookup.charAt(num)
3681 }
3682
3683 function tripletToBase64 (num) {
3684 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
3685 }
3686
3687 // go through the array every three bytes, we'll deal with trailing stuff later
3688 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
3689 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
3690 output += tripletToBase64(temp)
3691 }
3692
3693 // pad the end with zeros, but make sure to not forget the extra bytes
3694 switch (extraBytes) {
3695 case 1:
3696 temp = uint8[uint8.length - 1]
3697 output += encode(temp >> 2)
3698 output += encode((temp << 4) & 0x3F)
3699 output += '=='
3700 break
3701 case 2:
3702 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
3703 output += encode(temp >> 10)
3704 output += encode((temp >> 4) & 0x3F)
3705 output += encode((temp << 2) & 0x3F)
3706 output += '='
3707 break
3708 }
3709
3710 return output
3711 }
3712
3713 exports.toByteArray = b64ToByteArray
3714 exports.fromByteArray = uint8ToBase64
3715}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
3716
3717},{}],9:[function(require,module,exports){
3718exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3719 var e, m
3720 var eLen = nBytes * 8 - mLen - 1
3721 var eMax = (1 << eLen) - 1
3722 var eBias = eMax >> 1
3723 var nBits = -7
3724 var i = isLE ? (nBytes - 1) : 0
3725 var d = isLE ? -1 : 1
3726 var s = buffer[offset + i]
3727
3728 i += d
3729
3730 e = s & ((1 << (-nBits)) - 1)
3731 s >>= (-nBits)
3732 nBits += eLen
3733 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3734
3735 m = e & ((1 << (-nBits)) - 1)
3736 e >>= (-nBits)
3737 nBits += mLen
3738 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3739
3740 if (e === 0) {
3741 e = 1 - eBias
3742 } else if (e === eMax) {
3743 return m ? NaN : ((s ? -1 : 1) * Infinity)
3744 } else {
3745 m = m + Math.pow(2, mLen)
3746 e = e - eBias
3747 }
3748 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3749}
3750
3751exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3752 var e, m, c
3753 var eLen = nBytes * 8 - mLen - 1
3754 var eMax = (1 << eLen) - 1
3755 var eBias = eMax >> 1
3756 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3757 var i = isLE ? 0 : (nBytes - 1)
3758 var d = isLE ? 1 : -1
3759 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3760
3761 value = Math.abs(value)
3762
3763 if (isNaN(value) || value === Infinity) {
3764 m = isNaN(value) ? 1 : 0
3765 e = eMax
3766 } else {
3767 e = Math.floor(Math.log(value) / Math.LN2)
3768 if (value * (c = Math.pow(2, -e)) < 1) {
3769 e--
3770 c *= 2
3771 }
3772 if (e + eBias >= 1) {
3773 value += rt / c
3774 } else {
3775 value += rt * Math.pow(2, 1 - eBias)
3776 }
3777 if (value * c >= 2) {
3778 e++
3779 c /= 2
3780 }
3781
3782 if (e + eBias >= eMax) {
3783 m = 0
3784 e = eMax
3785 } else if (e + eBias >= 1) {
3786 m = (value * c - 1) * Math.pow(2, mLen)
3787 e = e + eBias
3788 } else {
3789 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3790 e = 0
3791 }
3792 }
3793
3794 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3795
3796 e = (e << mLen) | m
3797 eLen += mLen
3798 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3799
3800 buffer[offset + i - d] |= s * 128
3801}
3802
3803},{}],10:[function(require,module,exports){
3804
3805/**
3806 * isArray
3807 */
3808
3809var isArray = Array.isArray;
3810
3811/**
3812 * toString
3813 */
3814
3815var str = Object.prototype.toString;
3816
3817/**
3818 * Whether or not the given `val`
3819 * is an array.
3820 *
3821 * example:
3822 *
3823 * isArray([]);
3824 * // > true
3825 * isArray(arguments);
3826 * // > false
3827 * isArray('');
3828 * // > false
3829 *
3830 * @param {mixed} val
3831 * @return {bool}
3832 */
3833
3834module.exports = isArray || function (val) {
3835 return !! val && '[object Array]' == str.call(val);
3836};
3837
3838},{}],11:[function(require,module,exports){
3839// Copyright Joyent, Inc. and other Node contributors.
3840//
3841// Permission is hereby granted, free of charge, to any person obtaining a
3842// copy of this software and associated documentation files (the
3843// "Software"), to deal in the Software without restriction, including
3844// without limitation the rights to use, copy, modify, merge, publish,
3845// distribute, sublicense, and/or sell copies of the Software, and to permit
3846// persons to whom the Software is furnished to do so, subject to the
3847// following conditions:
3848//
3849// The above copyright notice and this permission notice shall be included
3850// in all copies or substantial portions of the Software.
3851//
3852// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3853// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3854// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3855// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3856// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3857// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3858// USE OR OTHER DEALINGS IN THE SOFTWARE.
3859
3860function EventEmitter() {
3861 this._events = this._events || {};
3862 this._maxListeners = this._maxListeners || undefined;
3863}
3864module.exports = EventEmitter;
3865
3866// Backwards-compat with node 0.10.x
3867EventEmitter.EventEmitter = EventEmitter;
3868
3869EventEmitter.prototype._events = undefined;
3870EventEmitter.prototype._maxListeners = undefined;
3871
3872// By default EventEmitters will print a warning if more than 10 listeners are
3873// added to it. This is a useful default which helps finding memory leaks.
3874EventEmitter.defaultMaxListeners = 10;
3875
3876// Obviously not all Emitters should be limited to 10. This function allows
3877// that to be increased. Set to zero for unlimited.
3878EventEmitter.prototype.setMaxListeners = function(n) {
3879 if (!isNumber(n) || n < 0 || isNaN(n))
3880 throw TypeError('n must be a positive number');
3881 this._maxListeners = n;
3882 return this;
3883};
3884
3885EventEmitter.prototype.emit = function(type) {
3886 var er, handler, len, args, i, listeners;
3887
3888 if (!this._events)
3889 this._events = {};
3890
3891 // If there is no 'error' event listener then throw.
3892 if (type === 'error') {
3893 if (!this._events.error ||
3894 (isObject(this._events.error) && !this._events.error.length)) {
3895 er = arguments[1];
3896 if (er instanceof Error) {
3897 throw er; // Unhandled 'error' event
3898 }
3899 throw TypeError('Uncaught, unspecified "error" event.');
3900 }
3901 }
3902
3903 handler = this._events[type];
3904
3905 if (isUndefined(handler))
3906 return false;
3907
3908 if (isFunction(handler)) {
3909 switch (arguments.length) {
3910 // fast cases
3911 case 1:
3912 handler.call(this);
3913 break;
3914 case 2:
3915 handler.call(this, arguments[1]);
3916 break;
3917 case 3:
3918 handler.call(this, arguments[1], arguments[2]);
3919 break;
3920 // slower
3921 default:
3922 len = arguments.length;
3923 args = new Array(len - 1);
3924 for (i = 1; i < len; i++)
3925 args[i - 1] = arguments[i];
3926 handler.apply(this, args);
3927 }
3928 } else if (isObject(handler)) {
3929 len = arguments.length;
3930 args = new Array(len - 1);
3931 for (i = 1; i < len; i++)
3932 args[i - 1] = arguments[i];
3933
3934 listeners = handler.slice();
3935 len = listeners.length;
3936 for (i = 0; i < len; i++)
3937 listeners[i].apply(this, args);
3938 }
3939
3940 return true;
3941};
3942
3943EventEmitter.prototype.addListener = function(type, listener) {
3944 var m;
3945
3946 if (!isFunction(listener))
3947 throw TypeError('listener must be a function');
3948
3949 if (!this._events)
3950 this._events = {};
3951
3952 // To avoid recursion in the case that type === "newListener"! Before
3953 // adding it to the listeners, first emit "newListener".
3954 if (this._events.newListener)
3955 this.emit('newListener', type,
3956 isFunction(listener.listener) ?
3957 listener.listener : listener);
3958
3959 if (!this._events[type])
3960 // Optimize the case of one listener. Don't need the extra array object.
3961 this._events[type] = listener;
3962 else if (isObject(this._events[type]))
3963 // If we've already got an array, just append.
3964 this._events[type].push(listener);
3965 else
3966 // Adding the second element, need to change to array.
3967 this._events[type] = [this._events[type], listener];
3968
3969 // Check for listener leak
3970 if (isObject(this._events[type]) && !this._events[type].warned) {
3971 var m;
3972 if (!isUndefined(this._maxListeners)) {
3973 m = this._maxListeners;
3974 } else {
3975 m = EventEmitter.defaultMaxListeners;
3976 }
3977
3978 if (m && m > 0 && this._events[type].length > m) {
3979 this._events[type].warned = true;
3980 console.error('(node) warning: possible EventEmitter memory ' +
3981 'leak detected. %d listeners added. ' +
3982 'Use emitter.setMaxListeners() to increase limit.',
3983 this._events[type].length);
3984 if (typeof console.trace === 'function') {
3985 // not supported in IE 10
3986 console.trace();
3987 }
3988 }
3989 }
3990
3991 return this;
3992};
3993
3994EventEmitter.prototype.on = EventEmitter.prototype.addListener;
3995
3996EventEmitter.prototype.once = function(type, listener) {
3997 if (!isFunction(listener))
3998 throw TypeError('listener must be a function');
3999
4000 var fired = false;
4001
4002 function g() {
4003 this.removeListener(type, g);
4004
4005 if (!fired) {
4006 fired = true;
4007 listener.apply(this, arguments);
4008 }
4009 }
4010
4011 g.listener = listener;
4012 this.on(type, g);
4013
4014 return this;
4015};
4016
4017// emits a 'removeListener' event iff the listener was removed
4018EventEmitter.prototype.removeListener = function(type, listener) {
4019 var list, position, length, i;
4020
4021 if (!isFunction(listener))
4022 throw TypeError('listener must be a function');
4023
4024 if (!this._events || !this._events[type])
4025 return this;
4026
4027 list = this._events[type];
4028 length = list.length;
4029 position = -1;
4030
4031 if (list === listener ||
4032 (isFunction(list.listener) && list.listener === listener)) {
4033 delete this._events[type];
4034 if (this._events.removeListener)
4035 this.emit('removeListener', type, listener);
4036
4037 } else if (isObject(list)) {
4038 for (i = length; i-- > 0;) {
4039 if (list[i] === listener ||
4040 (list[i].listener && list[i].listener === listener)) {
4041 position = i;
4042 break;
4043 }
4044 }
4045
4046 if (position < 0)
4047 return this;
4048
4049 if (list.length === 1) {
4050 list.length = 0;
4051 delete this._events[type];
4052 } else {
4053 list.splice(position, 1);
4054 }
4055
4056 if (this._events.removeListener)
4057 this.emit('removeListener', type, listener);
4058 }
4059
4060 return this;
4061};
4062
4063EventEmitter.prototype.removeAllListeners = function(type) {
4064 var key, listeners;
4065
4066 if (!this._events)
4067 return this;
4068
4069 // not listening for removeListener, no need to emit
4070 if (!this._events.removeListener) {
4071 if (arguments.length === 0)
4072 this._events = {};
4073 else if (this._events[type])
4074 delete this._events[type];
4075 return this;
4076 }
4077
4078 // emit removeListener for all listeners on all events
4079 if (arguments.length === 0) {
4080 for (key in this._events) {
4081 if (key === 'removeListener') continue;
4082 this.removeAllListeners(key);
4083 }
4084 this.removeAllListeners('removeListener');
4085 this._events = {};
4086 return this;
4087 }
4088
4089 listeners = this._events[type];
4090
4091 if (isFunction(listeners)) {
4092 this.removeListener(type, listeners);
4093 } else {
4094 // LIFO order
4095 while (listeners.length)
4096 this.removeListener(type, listeners[listeners.length - 1]);
4097 }
4098 delete this._events[type];
4099
4100 return this;
4101};
4102
4103EventEmitter.prototype.listeners = function(type) {
4104 var ret;
4105 if (!this._events || !this._events[type])
4106 ret = [];
4107 else if (isFunction(this._events[type]))
4108 ret = [this._events[type]];
4109 else
4110 ret = this._events[type].slice();
4111 return ret;
4112};
4113
4114EventEmitter.listenerCount = function(emitter, type) {
4115 var ret;
4116 if (!emitter._events || !emitter._events[type])
4117 ret = 0;
4118 else if (isFunction(emitter._events[type]))
4119 ret = 1;
4120 else
4121 ret = emitter._events[type].length;
4122 return ret;
4123};
4124
4125function isFunction(arg) {
4126 return typeof arg === 'function';
4127}
4128
4129function isNumber(arg) {
4130 return typeof arg === 'number';
4131}
4132
4133function isObject(arg) {
4134 return typeof arg === 'object' && arg !== null;
4135}
4136
4137function isUndefined(arg) {
4138 return arg === void 0;
4139}
4140
4141},{}],12:[function(require,module,exports){
4142if (typeof Object.create === 'function') {
4143 // implementation from standard node.js 'util' module
4144 module.exports = function inherits(ctor, superCtor) {
4145 ctor.super_ = superCtor
4146 ctor.prototype = Object.create(superCtor.prototype, {
4147 constructor: {
4148 value: ctor,
4149 enumerable: false,
4150 writable: true,
4151 configurable: true
4152 }
4153 });
4154 };
4155} else {
4156 // old school shim for old browsers
4157 module.exports = function inherits(ctor, superCtor) {
4158 ctor.super_ = superCtor
4159 var TempCtor = function () {}
4160 TempCtor.prototype = superCtor.prototype
4161 ctor.prototype = new TempCtor()
4162 ctor.prototype.constructor = ctor
4163 }
4164}
4165
4166},{}],13:[function(require,module,exports){
4167module.exports = Array.isArray || function (arr) {
4168 return Object.prototype.toString.call(arr) == '[object Array]';
4169};
4170
4171},{}],14:[function(require,module,exports){
4172// shim for using process in browser
4173
4174var process = module.exports = {};
4175var queue = [];
4176var draining = false;
4177var currentQueue;
4178var queueIndex = -1;
4179
4180function cleanUpNextTick() {
4181 draining = false;
4182 if (currentQueue.length) {
4183 queue = currentQueue.concat(queue);
4184 } else {
4185 queueIndex = -1;
4186 }
4187 if (queue.length) {
4188 drainQueue();
4189 }
4190}
4191
4192function drainQueue() {
4193 if (draining) {
4194 return;
4195 }
4196 var timeout = setTimeout(cleanUpNextTick);
4197 draining = true;
4198
4199 var len = queue.length;
4200 while(len) {
4201 currentQueue = queue;
4202 queue = [];
4203 while (++queueIndex < len) {
4204 currentQueue[queueIndex].run();
4205 }
4206 queueIndex = -1;
4207 len = queue.length;
4208 }
4209 currentQueue = null;
4210 draining = false;
4211 clearTimeout(timeout);
4212}
4213
4214process.nextTick = function (fun) {
4215 var args = new Array(arguments.length - 1);
4216 if (arguments.length > 1) {
4217 for (var i = 1; i < arguments.length; i++) {
4218 args[i - 1] = arguments[i];
4219 }
4220 }
4221 queue.push(new Item(fun, args));
4222 if (queue.length === 1 && !draining) {
4223 setTimeout(drainQueue, 0);
4224 }
4225};
4226
4227// v8 likes predictible objects
4228function Item(fun, array) {
4229 this.fun = fun;
4230 this.array = array;
4231}
4232Item.prototype.run = function () {
4233 this.fun.apply(null, this.array);
4234};
4235process.title = 'browser';
4236process.browser = true;
4237process.env = {};
4238process.argv = [];
4239process.version = ''; // empty string to avoid regexp issues
4240process.versions = {};
4241
4242function noop() {}
4243
4244process.on = noop;
4245process.addListener = noop;
4246process.once = noop;
4247process.off = noop;
4248process.removeListener = noop;
4249process.removeAllListeners = noop;
4250process.emit = noop;
4251
4252process.binding = function (name) {
4253 throw new Error('process.binding is not supported');
4254};
4255
4256// TODO(shtylman)
4257process.cwd = function () { return '/' };
4258process.chdir = function (dir) {
4259 throw new Error('process.chdir is not supported');
4260};
4261process.umask = function() { return 0; };
4262
4263},{}],15:[function(require,module,exports){
4264module.exports = require("./lib/_stream_duplex.js")
4265
4266},{"./lib/_stream_duplex.js":16}],16:[function(require,module,exports){
4267(function (process){
4268// Copyright Joyent, Inc. and other Node contributors.
4269//
4270// Permission is hereby granted, free of charge, to any person obtaining a
4271// copy of this software and associated documentation files (the
4272// "Software"), to deal in the Software without restriction, including
4273// without limitation the rights to use, copy, modify, merge, publish,
4274// distribute, sublicense, and/or sell copies of the Software, and to permit
4275// persons to whom the Software is furnished to do so, subject to the
4276// following conditions:
4277//
4278// The above copyright notice and this permission notice shall be included
4279// in all copies or substantial portions of the Software.
4280//
4281// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4282// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4283// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4284// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4285// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4286// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4287// USE OR OTHER DEALINGS IN THE SOFTWARE.
4288
4289// a duplex stream is just a stream that is both readable and writable.
4290// Since JS doesn't have multiple prototypal inheritance, this class
4291// prototypally inherits from Readable, and then parasitically from
4292// Writable.
4293
4294module.exports = Duplex;
4295
4296/*<replacement>*/
4297var objectKeys = Object.keys || function (obj) {
4298 var keys = [];
4299 for (var key in obj) keys.push(key);
4300 return keys;
4301}
4302/*</replacement>*/
4303
4304
4305/*<replacement>*/
4306var util = require('core-util-is');
4307util.inherits = require('inherits');
4308/*</replacement>*/
4309
4310var Readable = require('./_stream_readable');
4311var Writable = require('./_stream_writable');
4312
4313util.inherits(Duplex, Readable);
4314
4315forEach(objectKeys(Writable.prototype), function(method) {
4316 if (!Duplex.prototype[method])
4317 Duplex.prototype[method] = Writable.prototype[method];
4318});
4319
4320function Duplex(options) {
4321 if (!(this instanceof Duplex))
4322 return new Duplex(options);
4323
4324 Readable.call(this, options);
4325 Writable.call(this, options);
4326
4327 if (options && options.readable === false)
4328 this.readable = false;
4329
4330 if (options && options.writable === false)
4331 this.writable = false;
4332
4333 this.allowHalfOpen = true;
4334 if (options && options.allowHalfOpen === false)
4335 this.allowHalfOpen = false;
4336
4337 this.once('end', onend);
4338}
4339
4340// the no-half-open enforcer
4341function onend() {
4342 // if we allow half-open state, or if the writable side ended,
4343 // then we're ok.
4344 if (this.allowHalfOpen || this._writableState.ended)
4345 return;
4346
4347 // no more data can be written.
4348 // But allow more writes to happen in this tick.
4349 process.nextTick(this.end.bind(this));
4350}
4351
4352function forEach (xs, f) {
4353 for (var i = 0, l = xs.length; i < l; i++) {
4354 f(xs[i], i);
4355 }
4356}
4357
4358}).call(this,require('_process'))
4359},{"./_stream_readable":18,"./_stream_writable":20,"_process":14,"core-util-is":21,"inherits":12}],17:[function(require,module,exports){
4360// Copyright Joyent, Inc. and other Node contributors.
4361//
4362// Permission is hereby granted, free of charge, to any person obtaining a
4363// copy of this software and associated documentation files (the
4364// "Software"), to deal in the Software without restriction, including
4365// without limitation the rights to use, copy, modify, merge, publish,
4366// distribute, sublicense, and/or sell copies of the Software, and to permit
4367// persons to whom the Software is furnished to do so, subject to the
4368// following conditions:
4369//
4370// The above copyright notice and this permission notice shall be included
4371// in all copies or substantial portions of the Software.
4372//
4373// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4374// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4375// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4376// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4377// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4378// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4379// USE OR OTHER DEALINGS IN THE SOFTWARE.
4380
4381// a passthrough stream.
4382// basically just the most minimal sort of Transform stream.
4383// Every written chunk gets output as-is.
4384
4385module.exports = PassThrough;
4386
4387var Transform = require('./_stream_transform');
4388
4389/*<replacement>*/
4390var util = require('core-util-is');
4391util.inherits = require('inherits');
4392/*</replacement>*/
4393
4394util.inherits(PassThrough, Transform);
4395
4396function PassThrough(options) {
4397 if (!(this instanceof PassThrough))
4398 return new PassThrough(options);
4399
4400 Transform.call(this, options);
4401}
4402
4403PassThrough.prototype._transform = function(chunk, encoding, cb) {
4404 cb(null, chunk);
4405};
4406
4407},{"./_stream_transform":19,"core-util-is":21,"inherits":12}],18:[function(require,module,exports){
4408(function (process){
4409// Copyright Joyent, Inc. and other Node contributors.
4410//
4411// Permission is hereby granted, free of charge, to any person obtaining a
4412// copy of this software and associated documentation files (the
4413// "Software"), to deal in the Software without restriction, including
4414// without limitation the rights to use, copy, modify, merge, publish,
4415// distribute, sublicense, and/or sell copies of the Software, and to permit
4416// persons to whom the Software is furnished to do so, subject to the
4417// following conditions:
4418//
4419// The above copyright notice and this permission notice shall be included
4420// in all copies or substantial portions of the Software.
4421//
4422// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4423// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4424// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4425// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4426// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4427// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4428// USE OR OTHER DEALINGS IN THE SOFTWARE.
4429
4430module.exports = Readable;
4431
4432/*<replacement>*/
4433var isArray = require('isarray');
4434/*</replacement>*/
4435
4436
4437/*<replacement>*/
4438var Buffer = require('buffer').Buffer;
4439/*</replacement>*/
4440
4441Readable.ReadableState = ReadableState;
4442
4443var EE = require('events').EventEmitter;
4444
4445/*<replacement>*/
4446if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
4447 return emitter.listeners(type).length;
4448};
4449/*</replacement>*/
4450
4451var Stream = require('stream');
4452
4453/*<replacement>*/
4454var util = require('core-util-is');
4455util.inherits = require('inherits');
4456/*</replacement>*/
4457
4458var StringDecoder;
4459
4460
4461/*<replacement>*/
4462var debug = require('util');
4463if (debug && debug.debuglog) {
4464 debug = debug.debuglog('stream');
4465} else {
4466 debug = function () {};
4467}
4468/*</replacement>*/
4469
4470
4471util.inherits(Readable, Stream);
4472
4473function ReadableState(options, stream) {
4474 var Duplex = require('./_stream_duplex');
4475
4476 options = options || {};
4477
4478 // the point at which it stops calling _read() to fill the buffer
4479 // Note: 0 is a valid value, means "don't call _read preemptively ever"
4480 var hwm = options.highWaterMark;
4481 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
4482 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
4483
4484 // cast to ints.
4485 this.highWaterMark = ~~this.highWaterMark;
4486
4487 this.buffer = [];
4488 this.length = 0;
4489 this.pipes = null;
4490 this.pipesCount = 0;
4491 this.flowing = null;
4492 this.ended = false;
4493 this.endEmitted = false;
4494 this.reading = false;
4495
4496 // a flag to be able to tell if the onwrite cb is called immediately,
4497 // or on a later tick. We set this to true at first, because any
4498 // actions that shouldn't happen until "later" should generally also
4499 // not happen before the first write call.
4500 this.sync = true;
4501
4502 // whenever we return null, then we set a flag to say
4503 // that we're awaiting a 'readable' event emission.
4504 this.needReadable = false;
4505 this.emittedReadable = false;
4506 this.readableListening = false;
4507
4508
4509 // object stream flag. Used to make read(n) ignore n and to
4510 // make all the buffer merging and length checks go away
4511 this.objectMode = !!options.objectMode;
4512
4513 if (stream instanceof Duplex)
4514 this.objectMode = this.objectMode || !!options.readableObjectMode;
4515
4516 // Crypto is kind of old and crusty. Historically, its default string
4517 // encoding is 'binary' so we have to make this configurable.
4518 // Everything else in the universe uses 'utf8', though.
4519 this.defaultEncoding = options.defaultEncoding || 'utf8';
4520
4521 // when piping, we only care about 'readable' events that happen
4522 // after read()ing all the bytes and not getting any pushback.
4523 this.ranOut = false;
4524
4525 // the number of writers that are awaiting a drain event in .pipe()s
4526 this.awaitDrain = 0;
4527
4528 // if true, a maybeReadMore has been scheduled
4529 this.readingMore = false;
4530
4531 this.decoder = null;
4532 this.encoding = null;
4533 if (options.encoding) {
4534 if (!StringDecoder)
4535 StringDecoder = require('string_decoder/').StringDecoder;
4536 this.decoder = new StringDecoder(options.encoding);
4537 this.encoding = options.encoding;
4538 }
4539}
4540
4541function Readable(options) {
4542 var Duplex = require('./_stream_duplex');
4543
4544 if (!(this instanceof Readable))
4545 return new Readable(options);
4546
4547 this._readableState = new ReadableState(options, this);
4548
4549 // legacy
4550 this.readable = true;
4551
4552 Stream.call(this);
4553}
4554
4555// Manually shove something into the read() buffer.
4556// This returns true if the highWaterMark has not been hit yet,
4557// similar to how Writable.write() returns true if you should
4558// write() some more.
4559Readable.prototype.push = function(chunk, encoding) {
4560 var state = this._readableState;
4561
4562 if (util.isString(chunk) && !state.objectMode) {
4563 encoding = encoding || state.defaultEncoding;
4564 if (encoding !== state.encoding) {
4565 chunk = new Buffer(chunk, encoding);
4566 encoding = '';
4567 }
4568 }
4569
4570 return readableAddChunk(this, state, chunk, encoding, false);
4571};
4572
4573// Unshift should *always* be something directly out of read()
4574Readable.prototype.unshift = function(chunk) {
4575 var state = this._readableState;
4576 return readableAddChunk(this, state, chunk, '', true);
4577};
4578
4579function readableAddChunk(stream, state, chunk, encoding, addToFront) {
4580 var er = chunkInvalid(state, chunk);
4581 if (er) {
4582 stream.emit('error', er);
4583 } else if (util.isNullOrUndefined(chunk)) {
4584 state.reading = false;
4585 if (!state.ended)
4586 onEofChunk(stream, state);
4587 } else if (state.objectMode || chunk && chunk.length > 0) {
4588 if (state.ended && !addToFront) {
4589 var e = new Error('stream.push() after EOF');
4590 stream.emit('error', e);
4591 } else if (state.endEmitted && addToFront) {
4592 var e = new Error('stream.unshift() after end event');
4593 stream.emit('error', e);
4594 } else {
4595 if (state.decoder && !addToFront && !encoding)
4596 chunk = state.decoder.write(chunk);
4597
4598 if (!addToFront)
4599 state.reading = false;
4600
4601 // if we want the data now, just emit it.
4602 if (state.flowing && state.length === 0 && !state.sync) {
4603 stream.emit('data', chunk);
4604 stream.read(0);
4605 } else {
4606 // update the buffer info.
4607 state.length += state.objectMode ? 1 : chunk.length;
4608 if (addToFront)
4609 state.buffer.unshift(chunk);
4610 else
4611 state.buffer.push(chunk);
4612
4613 if (state.needReadable)
4614 emitReadable(stream);
4615 }
4616
4617 maybeReadMore(stream, state);
4618 }
4619 } else if (!addToFront) {
4620 state.reading = false;
4621 }
4622
4623 return needMoreData(state);
4624}
4625
4626
4627
4628// if it's past the high water mark, we can push in some more.
4629// Also, if we have no data yet, we can stand some
4630// more bytes. This is to work around cases where hwm=0,
4631// such as the repl. Also, if the push() triggered a
4632// readable event, and the user called read(largeNumber) such that
4633// needReadable was set, then we ought to push more, so that another
4634// 'readable' event will be triggered.
4635function needMoreData(state) {
4636 return !state.ended &&
4637 (state.needReadable ||
4638 state.length < state.highWaterMark ||
4639 state.length === 0);
4640}
4641
4642// backwards compatibility.
4643Readable.prototype.setEncoding = function(enc) {
4644 if (!StringDecoder)
4645 StringDecoder = require('string_decoder/').StringDecoder;
4646 this._readableState.decoder = new StringDecoder(enc);
4647 this._readableState.encoding = enc;
4648 return this;
4649};
4650
4651// Don't raise the hwm > 128MB
4652var MAX_HWM = 0x800000;
4653function roundUpToNextPowerOf2(n) {
4654 if (n >= MAX_HWM) {
4655 n = MAX_HWM;
4656 } else {
4657 // Get the next highest power of 2
4658 n--;
4659 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
4660 n++;
4661 }
4662 return n;
4663}
4664
4665function howMuchToRead(n, state) {
4666 if (state.length === 0 && state.ended)
4667 return 0;
4668
4669 if (state.objectMode)
4670 return n === 0 ? 0 : 1;
4671
4672 if (isNaN(n) || util.isNull(n)) {
4673 // only flow one buffer at a time
4674 if (state.flowing && state.buffer.length)
4675 return state.buffer[0].length;
4676 else
4677 return state.length;
4678 }
4679
4680 if (n <= 0)
4681 return 0;
4682
4683 // If we're asking for more than the target buffer level,
4684 // then raise the water mark. Bump up to the next highest
4685 // power of 2, to prevent increasing it excessively in tiny
4686 // amounts.
4687 if (n > state.highWaterMark)
4688 state.highWaterMark = roundUpToNextPowerOf2(n);
4689
4690 // don't have that much. return null, unless we've ended.
4691 if (n > state.length) {
4692 if (!state.ended) {
4693 state.needReadable = true;
4694 return 0;
4695 } else
4696 return state.length;
4697 }
4698
4699 return n;
4700}
4701
4702// you can override either this method, or the async _read(n) below.
4703Readable.prototype.read = function(n) {
4704 debug('read', n);
4705 var state = this._readableState;
4706 var nOrig = n;
4707
4708 if (!util.isNumber(n) || n > 0)
4709 state.emittedReadable = false;
4710
4711 // if we're doing read(0) to trigger a readable event, but we
4712 // already have a bunch of data in the buffer, then just trigger
4713 // the 'readable' event and move on.
4714 if (n === 0 &&
4715 state.needReadable &&
4716 (state.length >= state.highWaterMark || state.ended)) {
4717 debug('read: emitReadable', state.length, state.ended);
4718 if (state.length === 0 && state.ended)
4719 endReadable(this);
4720 else
4721 emitReadable(this);
4722 return null;
4723 }
4724
4725 n = howMuchToRead(n, state);
4726
4727 // if we've ended, and we're now clear, then finish it up.
4728 if (n === 0 && state.ended) {
4729 if (state.length === 0)
4730 endReadable(this);
4731 return null;
4732 }
4733
4734 // All the actual chunk generation logic needs to be
4735 // *below* the call to _read. The reason is that in certain
4736 // synthetic stream cases, such as passthrough streams, _read
4737 // may be a completely synchronous operation which may change
4738 // the state of the read buffer, providing enough data when
4739 // before there was *not* enough.
4740 //
4741 // So, the steps are:
4742 // 1. Figure out what the state of things will be after we do
4743 // a read from the buffer.
4744 //
4745 // 2. If that resulting state will trigger a _read, then call _read.
4746 // Note that this may be asynchronous, or synchronous. Yes, it is
4747 // deeply ugly to write APIs this way, but that still doesn't mean
4748 // that the Readable class should behave improperly, as streams are
4749 // designed to be sync/async agnostic.
4750 // Take note if the _read call is sync or async (ie, if the read call
4751 // has returned yet), so that we know whether or not it's safe to emit
4752 // 'readable' etc.
4753 //
4754 // 3. Actually pull the requested chunks out of the buffer and return.
4755
4756 // if we need a readable event, then we need to do some reading.
4757 var doRead = state.needReadable;
4758 debug('need readable', doRead);
4759
4760 // if we currently have less than the highWaterMark, then also read some
4761 if (state.length === 0 || state.length - n < state.highWaterMark) {
4762 doRead = true;
4763 debug('length less than watermark', doRead);
4764 }
4765
4766 // however, if we've ended, then there's no point, and if we're already
4767 // reading, then it's unnecessary.
4768 if (state.ended || state.reading) {
4769 doRead = false;
4770 debug('reading or ended', doRead);
4771 }
4772
4773 if (doRead) {
4774 debug('do read');
4775 state.reading = true;
4776 state.sync = true;
4777 // if the length is currently zero, then we *need* a readable event.
4778 if (state.length === 0)
4779 state.needReadable = true;
4780 // call internal read method
4781 this._read(state.highWaterMark);
4782 state.sync = false;
4783 }
4784
4785 // If _read pushed data synchronously, then `reading` will be false,
4786 // and we need to re-evaluate how much data we can return to the user.
4787 if (doRead && !state.reading)
4788 n = howMuchToRead(nOrig, state);
4789
4790 var ret;
4791 if (n > 0)
4792 ret = fromList(n, state);
4793 else
4794 ret = null;
4795
4796 if (util.isNull(ret)) {
4797 state.needReadable = true;
4798 n = 0;
4799 }
4800
4801 state.length -= n;
4802
4803 // If we have nothing in the buffer, then we want to know
4804 // as soon as we *do* get something into the buffer.
4805 if (state.length === 0 && !state.ended)
4806 state.needReadable = true;
4807
4808 // If we tried to read() past the EOF, then emit end on the next tick.
4809 if (nOrig !== n && state.ended && state.length === 0)
4810 endReadable(this);
4811
4812 if (!util.isNull(ret))
4813 this.emit('data', ret);
4814
4815 return ret;
4816};
4817
4818function chunkInvalid(state, chunk) {
4819 var er = null;
4820 if (!util.isBuffer(chunk) &&
4821 !util.isString(chunk) &&
4822 !util.isNullOrUndefined(chunk) &&
4823 !state.objectMode) {
4824 er = new TypeError('Invalid non-string/buffer chunk');
4825 }
4826 return er;
4827}
4828
4829
4830function onEofChunk(stream, state) {
4831 if (state.decoder && !state.ended) {
4832 var chunk = state.decoder.end();
4833 if (chunk && chunk.length) {
4834 state.buffer.push(chunk);
4835 state.length += state.objectMode ? 1 : chunk.length;
4836 }
4837 }
4838 state.ended = true;
4839
4840 // emit 'readable' now to make sure it gets picked up.
4841 emitReadable(stream);
4842}
4843
4844// Don't emit readable right away in sync mode, because this can trigger
4845// another read() call => stack overflow. This way, it might trigger
4846// a nextTick recursion warning, but that's not so bad.
4847function emitReadable(stream) {
4848 var state = stream._readableState;
4849 state.needReadable = false;
4850 if (!state.emittedReadable) {
4851 debug('emitReadable', state.flowing);
4852 state.emittedReadable = true;
4853 if (state.sync)
4854 process.nextTick(function() {
4855 emitReadable_(stream);
4856 });
4857 else
4858 emitReadable_(stream);
4859 }
4860}
4861
4862function emitReadable_(stream) {
4863 debug('emit readable');
4864 stream.emit('readable');
4865 flow(stream);
4866}
4867
4868
4869// at this point, the user has presumably seen the 'readable' event,
4870// and called read() to consume some data. that may have triggered
4871// in turn another _read(n) call, in which case reading = true if
4872// it's in progress.
4873// However, if we're not ended, or reading, and the length < hwm,
4874// then go ahead and try to read some more preemptively.
4875function maybeReadMore(stream, state) {
4876 if (!state.readingMore) {
4877 state.readingMore = true;
4878 process.nextTick(function() {
4879 maybeReadMore_(stream, state);
4880 });
4881 }
4882}
4883
4884function maybeReadMore_(stream, state) {
4885 var len = state.length;
4886 while (!state.reading && !state.flowing && !state.ended &&
4887 state.length < state.highWaterMark) {
4888 debug('maybeReadMore read 0');
4889 stream.read(0);
4890 if (len === state.length)
4891 // didn't get any data, stop spinning.
4892 break;
4893 else
4894 len = state.length;
4895 }
4896 state.readingMore = false;
4897}
4898
4899// abstract method. to be overridden in specific implementation classes.
4900// call cb(er, data) where data is <= n in length.
4901// for virtual (non-string, non-buffer) streams, "length" is somewhat
4902// arbitrary, and perhaps not very meaningful.
4903Readable.prototype._read = function(n) {
4904 this.emit('error', new Error('not implemented'));
4905};
4906
4907Readable.prototype.pipe = function(dest, pipeOpts) {
4908 var src = this;
4909 var state = this._readableState;
4910
4911 switch (state.pipesCount) {
4912 case 0:
4913 state.pipes = dest;
4914 break;
4915 case 1:
4916 state.pipes = [state.pipes, dest];
4917 break;
4918 default:
4919 state.pipes.push(dest);
4920 break;
4921 }
4922 state.pipesCount += 1;
4923 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
4924
4925 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
4926 dest !== process.stdout &&
4927 dest !== process.stderr;
4928
4929 var endFn = doEnd ? onend : cleanup;
4930 if (state.endEmitted)
4931 process.nextTick(endFn);
4932 else
4933 src.once('end', endFn);
4934
4935 dest.on('unpipe', onunpipe);
4936 function onunpipe(readable) {
4937 debug('onunpipe');
4938 if (readable === src) {
4939 cleanup();
4940 }
4941 }
4942
4943 function onend() {
4944 debug('onend');
4945 dest.end();
4946 }
4947
4948 // when the dest drains, it reduces the awaitDrain counter
4949 // on the source. This would be more elegant with a .once()
4950 // handler in flow(), but adding and removing repeatedly is
4951 // too slow.
4952 var ondrain = pipeOnDrain(src);
4953 dest.on('drain', ondrain);
4954
4955 function cleanup() {
4956 debug('cleanup');
4957 // cleanup event handlers once the pipe is broken
4958 dest.removeListener('close', onclose);
4959 dest.removeListener('finish', onfinish);
4960 dest.removeListener('drain', ondrain);
4961 dest.removeListener('error', onerror);
4962 dest.removeListener('unpipe', onunpipe);
4963 src.removeListener('end', onend);
4964 src.removeListener('end', cleanup);
4965 src.removeListener('data', ondata);
4966
4967 // if the reader is waiting for a drain event from this
4968 // specific writer, then it would cause it to never start
4969 // flowing again.
4970 // So, if this is awaiting a drain, then we just call it now.
4971 // If we don't know, then assume that we are waiting for one.
4972 if (state.awaitDrain &&
4973 (!dest._writableState || dest._writableState.needDrain))
4974 ondrain();
4975 }
4976
4977 src.on('data', ondata);
4978 function ondata(chunk) {
4979 debug('ondata');
4980 var ret = dest.write(chunk);
4981 if (false === ret) {
4982 debug('false write response, pause',
4983 src._readableState.awaitDrain);
4984 src._readableState.awaitDrain++;
4985 src.pause();
4986 }
4987 }
4988
4989 // if the dest has an error, then stop piping into it.
4990 // however, don't suppress the throwing behavior for this.
4991 function onerror(er) {
4992 debug('onerror', er);
4993 unpipe();
4994 dest.removeListener('error', onerror);
4995 if (EE.listenerCount(dest, 'error') === 0)
4996 dest.emit('error', er);
4997 }
4998 // This is a brutally ugly hack to make sure that our error handler
4999 // is attached before any userland ones. NEVER DO THIS.
5000 if (!dest._events || !dest._events.error)
5001 dest.on('error', onerror);
5002 else if (isArray(dest._events.error))
5003 dest._events.error.unshift(onerror);
5004 else
5005 dest._events.error = [onerror, dest._events.error];
5006
5007
5008
5009 // Both close and finish should trigger unpipe, but only once.
5010 function onclose() {
5011 dest.removeListener('finish', onfinish);
5012 unpipe();
5013 }
5014 dest.once('close', onclose);
5015 function onfinish() {
5016 debug('onfinish');
5017 dest.removeListener('close', onclose);
5018 unpipe();
5019 }
5020 dest.once('finish', onfinish);
5021
5022 function unpipe() {
5023 debug('unpipe');
5024 src.unpipe(dest);
5025 }
5026
5027 // tell the dest that it's being piped to
5028 dest.emit('pipe', src);
5029
5030 // start the flow if it hasn't been started already.
5031 if (!state.flowing) {
5032 debug('pipe resume');
5033 src.resume();
5034 }
5035
5036 return dest;
5037};
5038
5039function pipeOnDrain(src) {
5040 return function() {
5041 var state = src._readableState;
5042 debug('pipeOnDrain', state.awaitDrain);
5043 if (state.awaitDrain)
5044 state.awaitDrain--;
5045 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
5046 state.flowing = true;
5047 flow(src);
5048 }
5049 };
5050}
5051
5052
5053Readable.prototype.unpipe = function(dest) {
5054 var state = this._readableState;
5055
5056 // if we're not piping anywhere, then do nothing.
5057 if (state.pipesCount === 0)
5058 return this;
5059
5060 // just one destination. most common case.
5061 if (state.pipesCount === 1) {
5062 // passed in one, but it's not the right one.
5063 if (dest && dest !== state.pipes)
5064 return this;
5065
5066 if (!dest)
5067 dest = state.pipes;
5068
5069 // got a match.
5070 state.pipes = null;
5071 state.pipesCount = 0;
5072 state.flowing = false;
5073 if (dest)
5074 dest.emit('unpipe', this);
5075 return this;
5076 }
5077
5078 // slow case. multiple pipe destinations.
5079
5080 if (!dest) {
5081 // remove all.
5082 var dests = state.pipes;
5083 var len = state.pipesCount;
5084 state.pipes = null;
5085 state.pipesCount = 0;
5086 state.flowing = false;
5087
5088 for (var i = 0; i < len; i++)
5089 dests[i].emit('unpipe', this);
5090 return this;
5091 }
5092
5093 // try to find the right one.
5094 var i = indexOf(state.pipes, dest);
5095 if (i === -1)
5096 return this;
5097
5098 state.pipes.splice(i, 1);
5099 state.pipesCount -= 1;
5100 if (state.pipesCount === 1)
5101 state.pipes = state.pipes[0];
5102
5103 dest.emit('unpipe', this);
5104
5105 return this;
5106};
5107
5108// set up data events if they are asked for
5109// Ensure readable listeners eventually get something
5110Readable.prototype.on = function(ev, fn) {
5111 var res = Stream.prototype.on.call(this, ev, fn);
5112
5113 // If listening to data, and it has not explicitly been paused,
5114 // then call resume to start the flow of data on the next tick.
5115 if (ev === 'data' && false !== this._readableState.flowing) {
5116 this.resume();
5117 }
5118
5119 if (ev === 'readable' && this.readable) {
5120 var state = this._readableState;
5121 if (!state.readableListening) {
5122 state.readableListening = true;
5123 state.emittedReadable = false;
5124 state.needReadable = true;
5125 if (!state.reading) {
5126 var self = this;
5127 process.nextTick(function() {
5128 debug('readable nexttick read 0');
5129 self.read(0);
5130 });
5131 } else if (state.length) {
5132 emitReadable(this, state);
5133 }
5134 }
5135 }
5136
5137 return res;
5138};
5139Readable.prototype.addListener = Readable.prototype.on;
5140
5141// pause() and resume() are remnants of the legacy readable stream API
5142// If the user uses them, then switch into old mode.
5143Readable.prototype.resume = function() {
5144 var state = this._readableState;
5145 if (!state.flowing) {
5146 debug('resume');
5147 state.flowing = true;
5148 if (!state.reading) {
5149 debug('resume read 0');
5150 this.read(0);
5151 }
5152 resume(this, state);
5153 }
5154 return this;
5155};
5156
5157function resume(stream, state) {
5158 if (!state.resumeScheduled) {
5159 state.resumeScheduled = true;
5160 process.nextTick(function() {
5161 resume_(stream, state);
5162 });
5163 }
5164}
5165
5166function resume_(stream, state) {
5167 state.resumeScheduled = false;
5168 stream.emit('resume');
5169 flow(stream);
5170 if (state.flowing && !state.reading)
5171 stream.read(0);
5172}
5173
5174Readable.prototype.pause = function() {
5175 debug('call pause flowing=%j', this._readableState.flowing);
5176 if (false !== this._readableState.flowing) {
5177 debug('pause');
5178 this._readableState.flowing = false;
5179 this.emit('pause');
5180 }
5181 return this;
5182};
5183
5184function flow(stream) {
5185 var state = stream._readableState;
5186 debug('flow', state.flowing);
5187 if (state.flowing) {
5188 do {
5189 var chunk = stream.read();
5190 } while (null !== chunk && state.flowing);
5191 }
5192}
5193
5194// wrap an old-style stream as the async data source.
5195// This is *not* part of the readable stream interface.
5196// It is an ugly unfortunate mess of history.
5197Readable.prototype.wrap = function(stream) {
5198 var state = this._readableState;
5199 var paused = false;
5200
5201 var self = this;
5202 stream.on('end', function() {
5203 debug('wrapped end');
5204 if (state.decoder && !state.ended) {
5205 var chunk = state.decoder.end();
5206 if (chunk && chunk.length)
5207 self.push(chunk);
5208 }
5209
5210 self.push(null);
5211 });
5212
5213 stream.on('data', function(chunk) {
5214 debug('wrapped data');
5215 if (state.decoder)
5216 chunk = state.decoder.write(chunk);
5217 if (!chunk || !state.objectMode && !chunk.length)
5218 return;
5219
5220 var ret = self.push(chunk);
5221 if (!ret) {
5222 paused = true;
5223 stream.pause();
5224 }
5225 });
5226
5227 // proxy all the other methods.
5228 // important when wrapping filters and duplexes.
5229 for (var i in stream) {
5230 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
5231 this[i] = function(method) { return function() {
5232 return stream[method].apply(stream, arguments);
5233 }}(i);
5234 }
5235 }
5236
5237 // proxy certain important events.
5238 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
5239 forEach(events, function(ev) {
5240 stream.on(ev, self.emit.bind(self, ev));
5241 });
5242
5243 // when we try to consume some more bytes, simply unpause the
5244 // underlying stream.
5245 self._read = function(n) {
5246 debug('wrapped _read', n);
5247 if (paused) {
5248 paused = false;
5249 stream.resume();
5250 }
5251 };
5252
5253 return self;
5254};
5255
5256
5257
5258// exposed for testing purposes only.
5259Readable._fromList = fromList;
5260
5261// Pluck off n bytes from an array of buffers.
5262// Length is the combined lengths of all the buffers in the list.
5263function fromList(n, state) {
5264 var list = state.buffer;
5265 var length = state.length;
5266 var stringMode = !!state.decoder;
5267 var objectMode = !!state.objectMode;
5268 var ret;
5269
5270 // nothing in the list, definitely empty.
5271 if (list.length === 0)
5272 return null;
5273
5274 if (length === 0)
5275 ret = null;
5276 else if (objectMode)
5277 ret = list.shift();
5278 else if (!n || n >= length) {
5279 // read it all, truncate the array.
5280 if (stringMode)
5281 ret = list.join('');
5282 else
5283 ret = Buffer.concat(list, length);
5284 list.length = 0;
5285 } else {
5286 // read just some of it.
5287 if (n < list[0].length) {
5288 // just take a part of the first list item.
5289 // slice is the same for buffers and strings.
5290 var buf = list[0];
5291 ret = buf.slice(0, n);
5292 list[0] = buf.slice(n);
5293 } else if (n === list[0].length) {
5294 // first list is a perfect match
5295 ret = list.shift();
5296 } else {
5297 // complex case.
5298 // we have enough to cover it, but it spans past the first buffer.
5299 if (stringMode)
5300 ret = '';
5301 else
5302 ret = new Buffer(n);
5303
5304 var c = 0;
5305 for (var i = 0, l = list.length; i < l && c < n; i++) {
5306 var buf = list[0];
5307 var cpy = Math.min(n - c, buf.length);
5308
5309 if (stringMode)
5310 ret += buf.slice(0, cpy);
5311 else
5312 buf.copy(ret, c, 0, cpy);
5313
5314 if (cpy < buf.length)
5315 list[0] = buf.slice(cpy);
5316 else
5317 list.shift();
5318
5319 c += cpy;
5320 }
5321 }
5322 }
5323
5324 return ret;
5325}
5326
5327function endReadable(stream) {
5328 var state = stream._readableState;
5329
5330 // If we get here before consuming all the bytes, then that is a
5331 // bug in node. Should never happen.
5332 if (state.length > 0)
5333 throw new Error('endReadable called on non-empty stream');
5334
5335 if (!state.endEmitted) {
5336 state.ended = true;
5337 process.nextTick(function() {
5338 // Check that we didn't get one last unshift.
5339 if (!state.endEmitted && state.length === 0) {
5340 state.endEmitted = true;
5341 stream.readable = false;
5342 stream.emit('end');
5343 }
5344 });
5345 }
5346}
5347
5348function forEach (xs, f) {
5349 for (var i = 0, l = xs.length; i < l; i++) {
5350 f(xs[i], i);
5351 }
5352}
5353
5354function indexOf (xs, x) {
5355 for (var i = 0, l = xs.length; i < l; i++) {
5356 if (xs[i] === x) return i;
5357 }
5358 return -1;
5359}
5360
5361}).call(this,require('_process'))
5362},{"./_stream_duplex":16,"_process":14,"buffer":7,"core-util-is":21,"events":11,"inherits":12,"isarray":13,"stream":26,"string_decoder/":27,"util":6}],19:[function(require,module,exports){
5363// Copyright Joyent, Inc. and other Node contributors.
5364//
5365// Permission is hereby granted, free of charge, to any person obtaining a
5366// copy of this software and associated documentation files (the
5367// "Software"), to deal in the Software without restriction, including
5368// without limitation the rights to use, copy, modify, merge, publish,
5369// distribute, sublicense, and/or sell copies of the Software, and to permit
5370// persons to whom the Software is furnished to do so, subject to the
5371// following conditions:
5372//
5373// The above copyright notice and this permission notice shall be included
5374// in all copies or substantial portions of the Software.
5375//
5376// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5377// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5378// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5379// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5380// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5381// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5382// USE OR OTHER DEALINGS IN THE SOFTWARE.
5383
5384
5385// a transform stream is a readable/writable stream where you do
5386// something with the data. Sometimes it's called a "filter",
5387// but that's not a great name for it, since that implies a thing where
5388// some bits pass through, and others are simply ignored. (That would
5389// be a valid example of a transform, of course.)
5390//
5391// While the output is causally related to the input, it's not a
5392// necessarily symmetric or synchronous transformation. For example,
5393// a zlib stream might take multiple plain-text writes(), and then
5394// emit a single compressed chunk some time in the future.
5395//
5396// Here's how this works:
5397//
5398// The Transform stream has all the aspects of the readable and writable
5399// stream classes. When you write(chunk), that calls _write(chunk,cb)
5400// internally, and returns false if there's a lot of pending writes
5401// buffered up. When you call read(), that calls _read(n) until
5402// there's enough pending readable data buffered up.
5403//
5404// In a transform stream, the written data is placed in a buffer. When
5405// _read(n) is called, it transforms the queued up data, calling the
5406// buffered _write cb's as it consumes chunks. If consuming a single
5407// written chunk would result in multiple output chunks, then the first
5408// outputted bit calls the readcb, and subsequent chunks just go into
5409// the read buffer, and will cause it to emit 'readable' if necessary.
5410//
5411// This way, back-pressure is actually determined by the reading side,
5412// since _read has to be called to start processing a new chunk. However,
5413// a pathological inflate type of transform can cause excessive buffering
5414// here. For example, imagine a stream where every byte of input is
5415// interpreted as an integer from 0-255, and then results in that many
5416// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
5417// 1kb of data being output. In this case, you could write a very small
5418// amount of input, and end up with a very large amount of output. In
5419// such a pathological inflating mechanism, there'd be no way to tell
5420// the system to stop doing the transform. A single 4MB write could
5421// cause the system to run out of memory.
5422//
5423// However, even in such a pathological case, only a single written chunk
5424// would be consumed, and then the rest would wait (un-transformed) until
5425// the results of the previous transformed chunk were consumed.
5426
5427module.exports = Transform;
5428
5429var Duplex = require('./_stream_duplex');
5430
5431/*<replacement>*/
5432var util = require('core-util-is');
5433util.inherits = require('inherits');
5434/*</replacement>*/
5435
5436util.inherits(Transform, Duplex);
5437
5438
5439function TransformState(options, stream) {
5440 this.afterTransform = function(er, data) {
5441 return afterTransform(stream, er, data);
5442 };
5443
5444 this.needTransform = false;
5445 this.transforming = false;
5446 this.writecb = null;
5447 this.writechunk = null;
5448}
5449
5450function afterTransform(stream, er, data) {
5451 var ts = stream._transformState;
5452 ts.transforming = false;
5453
5454 var cb = ts.writecb;
5455
5456 if (!cb)
5457 return stream.emit('error', new Error('no writecb in Transform class'));
5458
5459 ts.writechunk = null;
5460 ts.writecb = null;
5461
5462 if (!util.isNullOrUndefined(data))
5463 stream.push(data);
5464
5465 if (cb)
5466 cb(er);
5467
5468 var rs = stream._readableState;
5469 rs.reading = false;
5470 if (rs.needReadable || rs.length < rs.highWaterMark) {
5471 stream._read(rs.highWaterMark);
5472 }
5473}
5474
5475
5476function Transform(options) {
5477 if (!(this instanceof Transform))
5478 return new Transform(options);
5479
5480 Duplex.call(this, options);
5481
5482 this._transformState = new TransformState(options, this);
5483
5484 // when the writable side finishes, then flush out anything remaining.
5485 var stream = this;
5486
5487 // start out asking for a readable event once data is transformed.
5488 this._readableState.needReadable = true;
5489
5490 // we have implemented the _read method, and done the other things
5491 // that Readable wants before the first _read call, so unset the
5492 // sync guard flag.
5493 this._readableState.sync = false;
5494
5495 this.once('prefinish', function() {
5496 if (util.isFunction(this._flush))
5497 this._flush(function(er) {
5498 done(stream, er);
5499 });
5500 else
5501 done(stream);
5502 });
5503}
5504
5505Transform.prototype.push = function(chunk, encoding) {
5506 this._transformState.needTransform = false;
5507 return Duplex.prototype.push.call(this, chunk, encoding);
5508};
5509
5510// This is the part where you do stuff!
5511// override this function in implementation classes.
5512// 'chunk' is an input chunk.
5513//
5514// Call `push(newChunk)` to pass along transformed output
5515// to the readable side. You may call 'push' zero or more times.
5516//
5517// Call `cb(err)` when you are done with this chunk. If you pass
5518// an error, then that'll put the hurt on the whole operation. If you
5519// never call cb(), then you'll never get another chunk.
5520Transform.prototype._transform = function(chunk, encoding, cb) {
5521 throw new Error('not implemented');
5522};
5523
5524Transform.prototype._write = function(chunk, encoding, cb) {
5525 var ts = this._transformState;
5526 ts.writecb = cb;
5527 ts.writechunk = chunk;
5528 ts.writeencoding = encoding;
5529 if (!ts.transforming) {
5530 var rs = this._readableState;
5531 if (ts.needTransform ||
5532 rs.needReadable ||
5533 rs.length < rs.highWaterMark)
5534 this._read(rs.highWaterMark);
5535 }
5536};
5537
5538// Doesn't matter what the args are here.
5539// _transform does all the work.
5540// That we got here means that the readable side wants more data.
5541Transform.prototype._read = function(n) {
5542 var ts = this._transformState;
5543
5544 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
5545 ts.transforming = true;
5546 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
5547 } else {
5548 // mark that we need a transform, so that any data that comes in
5549 // will get processed, now that we've asked for it.
5550 ts.needTransform = true;
5551 }
5552};
5553
5554
5555function done(stream, er) {
5556 if (er)
5557 return stream.emit('error', er);
5558
5559 // if there's nothing in the write buffer, then that means
5560 // that nothing more will ever be provided
5561 var ws = stream._writableState;
5562 var ts = stream._transformState;
5563
5564 if (ws.length)
5565 throw new Error('calling transform done when ws.length != 0');
5566
5567 if (ts.transforming)
5568 throw new Error('calling transform done when still transforming');
5569
5570 return stream.push(null);
5571}
5572
5573},{"./_stream_duplex":16,"core-util-is":21,"inherits":12}],20:[function(require,module,exports){
5574(function (process){
5575// Copyright Joyent, Inc. and other Node contributors.
5576//
5577// Permission is hereby granted, free of charge, to any person obtaining a
5578// copy of this software and associated documentation files (the
5579// "Software"), to deal in the Software without restriction, including
5580// without limitation the rights to use, copy, modify, merge, publish,
5581// distribute, sublicense, and/or sell copies of the Software, and to permit
5582// persons to whom the Software is furnished to do so, subject to the
5583// following conditions:
5584//
5585// The above copyright notice and this permission notice shall be included
5586// in all copies or substantial portions of the Software.
5587//
5588// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5589// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5590// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5591// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5592// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5593// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5594// USE OR OTHER DEALINGS IN THE SOFTWARE.
5595
5596// A bit simpler than readable streams.
5597// Implement an async ._write(chunk, cb), and it'll handle all
5598// the drain event emission and buffering.
5599
5600module.exports = Writable;
5601
5602/*<replacement>*/
5603var Buffer = require('buffer').Buffer;
5604/*</replacement>*/
5605
5606Writable.WritableState = WritableState;
5607
5608
5609/*<replacement>*/
5610var util = require('core-util-is');
5611util.inherits = require('inherits');
5612/*</replacement>*/
5613
5614var Stream = require('stream');
5615
5616util.inherits(Writable, Stream);
5617
5618function WriteReq(chunk, encoding, cb) {
5619 this.chunk = chunk;
5620 this.encoding = encoding;
5621 this.callback = cb;
5622}
5623
5624function WritableState(options, stream) {
5625 var Duplex = require('./_stream_duplex');
5626
5627 options = options || {};
5628
5629 // the point at which write() starts returning false
5630 // Note: 0 is a valid value, means that we always return false if
5631 // the entire buffer is not flushed immediately on write()
5632 var hwm = options.highWaterMark;
5633 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
5634 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
5635
5636 // object stream flag to indicate whether or not this stream
5637 // contains buffers or objects.
5638 this.objectMode = !!options.objectMode;
5639
5640 if (stream instanceof Duplex)
5641 this.objectMode = this.objectMode || !!options.writableObjectMode;
5642
5643 // cast to ints.
5644 this.highWaterMark = ~~this.highWaterMark;
5645
5646 this.needDrain = false;
5647 // at the start of calling end()
5648 this.ending = false;
5649 // when end() has been called, and returned
5650 this.ended = false;
5651 // when 'finish' is emitted
5652 this.finished = false;
5653
5654 // should we decode strings into buffers before passing to _write?
5655 // this is here so that some node-core streams can optimize string
5656 // handling at a lower level.
5657 var noDecode = options.decodeStrings === false;
5658 this.decodeStrings = !noDecode;
5659
5660 // Crypto is kind of old and crusty. Historically, its default string
5661 // encoding is 'binary' so we have to make this configurable.
5662 // Everything else in the universe uses 'utf8', though.
5663 this.defaultEncoding = options.defaultEncoding || 'utf8';
5664
5665 // not an actual buffer we keep track of, but a measurement
5666 // of how much we're waiting to get pushed to some underlying
5667 // socket or file.
5668 this.length = 0;
5669
5670 // a flag to see when we're in the middle of a write.
5671 this.writing = false;
5672
5673 // when true all writes will be buffered until .uncork() call
5674 this.corked = 0;
5675
5676 // a flag to be able to tell if the onwrite cb is called immediately,
5677 // or on a later tick. We set this to true at first, because any
5678 // actions that shouldn't happen until "later" should generally also
5679 // not happen before the first write call.
5680 this.sync = true;
5681
5682 // a flag to know if we're processing previously buffered items, which
5683 // may call the _write() callback in the same tick, so that we don't
5684 // end up in an overlapped onwrite situation.
5685 this.bufferProcessing = false;
5686
5687 // the callback that's passed to _write(chunk,cb)
5688 this.onwrite = function(er) {
5689 onwrite(stream, er);
5690 };
5691
5692 // the callback that the user supplies to write(chunk,encoding,cb)
5693 this.writecb = null;
5694
5695 // the amount that is being written when _write is called.
5696 this.writelen = 0;
5697
5698 this.buffer = [];
5699
5700 // number of pending user-supplied write callbacks
5701 // this must be 0 before 'finish' can be emitted
5702 this.pendingcb = 0;
5703
5704 // emit prefinish if the only thing we're waiting for is _write cbs
5705 // This is relevant for synchronous Transform streams
5706 this.prefinished = false;
5707
5708 // True if the error was already emitted and should not be thrown again
5709 this.errorEmitted = false;
5710}
5711
5712function Writable(options) {
5713 var Duplex = require('./_stream_duplex');
5714
5715 // Writable ctor is applied to Duplexes, though they're not
5716 // instanceof Writable, they're instanceof Readable.
5717 if (!(this instanceof Writable) && !(this instanceof Duplex))
5718 return new Writable(options);
5719
5720 this._writableState = new WritableState(options, this);
5721
5722 // legacy.
5723 this.writable = true;
5724
5725 Stream.call(this);
5726}
5727
5728// Otherwise people can pipe Writable streams, which is just wrong.
5729Writable.prototype.pipe = function() {
5730 this.emit('error', new Error('Cannot pipe. Not readable.'));
5731};
5732
5733
5734function writeAfterEnd(stream, state, cb) {
5735 var er = new Error('write after end');
5736 // TODO: defer error events consistently everywhere, not just the cb
5737 stream.emit('error', er);
5738 process.nextTick(function() {
5739 cb(er);
5740 });
5741}
5742
5743// If we get something that is not a buffer, string, null, or undefined,
5744// and we're not in objectMode, then that's an error.
5745// Otherwise stream chunks are all considered to be of length=1, and the
5746// watermarks determine how many objects to keep in the buffer, rather than
5747// how many bytes or characters.
5748function validChunk(stream, state, chunk, cb) {
5749 var valid = true;
5750 if (!util.isBuffer(chunk) &&
5751 !util.isString(chunk) &&
5752 !util.isNullOrUndefined(chunk) &&
5753 !state.objectMode) {
5754 var er = new TypeError('Invalid non-string/buffer chunk');
5755 stream.emit('error', er);
5756 process.nextTick(function() {
5757 cb(er);
5758 });
5759 valid = false;
5760 }
5761 return valid;
5762}
5763
5764Writable.prototype.write = function(chunk, encoding, cb) {
5765 var state = this._writableState;
5766 var ret = false;
5767
5768 if (util.isFunction(encoding)) {
5769 cb = encoding;
5770 encoding = null;
5771 }
5772
5773 if (util.isBuffer(chunk))
5774 encoding = 'buffer';
5775 else if (!encoding)
5776 encoding = state.defaultEncoding;
5777
5778 if (!util.isFunction(cb))
5779 cb = function() {};
5780
5781 if (state.ended)
5782 writeAfterEnd(this, state, cb);
5783 else if (validChunk(this, state, chunk, cb)) {
5784 state.pendingcb++;
5785 ret = writeOrBuffer(this, state, chunk, encoding, cb);
5786 }
5787
5788 return ret;
5789};
5790
5791Writable.prototype.cork = function() {
5792 var state = this._writableState;
5793
5794 state.corked++;
5795};
5796
5797Writable.prototype.uncork = function() {
5798 var state = this._writableState;
5799
5800 if (state.corked) {
5801 state.corked--;
5802
5803 if (!state.writing &&
5804 !state.corked &&
5805 !state.finished &&
5806 !state.bufferProcessing &&
5807 state.buffer.length)
5808 clearBuffer(this, state);
5809 }
5810};
5811
5812function decodeChunk(state, chunk, encoding) {
5813 if (!state.objectMode &&
5814 state.decodeStrings !== false &&
5815 util.isString(chunk)) {
5816 chunk = new Buffer(chunk, encoding);
5817 }
5818 return chunk;
5819}
5820
5821// if we're already writing something, then just put this
5822// in the queue, and wait our turn. Otherwise, call _write
5823// If we return false, then we need a drain event, so set that flag.
5824function writeOrBuffer(stream, state, chunk, encoding, cb) {
5825 chunk = decodeChunk(state, chunk, encoding);
5826 if (util.isBuffer(chunk))
5827 encoding = 'buffer';
5828 var len = state.objectMode ? 1 : chunk.length;
5829
5830 state.length += len;
5831
5832 var ret = state.length < state.highWaterMark;
5833 // we must ensure that previous needDrain will not be reset to false.
5834 if (!ret)
5835 state.needDrain = true;
5836
5837 if (state.writing || state.corked)
5838 state.buffer.push(new WriteReq(chunk, encoding, cb));
5839 else
5840 doWrite(stream, state, false, len, chunk, encoding, cb);
5841
5842 return ret;
5843}
5844
5845function doWrite(stream, state, writev, len, chunk, encoding, cb) {
5846 state.writelen = len;
5847 state.writecb = cb;
5848 state.writing = true;
5849 state.sync = true;
5850 if (writev)
5851 stream._writev(chunk, state.onwrite);
5852 else
5853 stream._write(chunk, encoding, state.onwrite);
5854 state.sync = false;
5855}
5856
5857function onwriteError(stream, state, sync, er, cb) {
5858 if (sync)
5859 process.nextTick(function() {
5860 state.pendingcb--;
5861 cb(er);
5862 });
5863 else {
5864 state.pendingcb--;
5865 cb(er);
5866 }
5867
5868 stream._writableState.errorEmitted = true;
5869 stream.emit('error', er);
5870}
5871
5872function onwriteStateUpdate(state) {
5873 state.writing = false;
5874 state.writecb = null;
5875 state.length -= state.writelen;
5876 state.writelen = 0;
5877}
5878
5879function onwrite(stream, er) {
5880 var state = stream._writableState;
5881 var sync = state.sync;
5882 var cb = state.writecb;
5883
5884 onwriteStateUpdate(state);
5885
5886 if (er)
5887 onwriteError(stream, state, sync, er, cb);
5888 else {
5889 // Check if we're actually ready to finish, but don't emit yet
5890 var finished = needFinish(stream, state);
5891
5892 if (!finished &&
5893 !state.corked &&
5894 !state.bufferProcessing &&
5895 state.buffer.length) {
5896 clearBuffer(stream, state);
5897 }
5898
5899 if (sync) {
5900 process.nextTick(function() {
5901 afterWrite(stream, state, finished, cb);
5902 });
5903 } else {
5904 afterWrite(stream, state, finished, cb);
5905 }
5906 }
5907}
5908
5909function afterWrite(stream, state, finished, cb) {
5910 if (!finished)
5911 onwriteDrain(stream, state);
5912 state.pendingcb--;
5913 cb();
5914 finishMaybe(stream, state);
5915}
5916
5917// Must force callback to be called on nextTick, so that we don't
5918// emit 'drain' before the write() consumer gets the 'false' return
5919// value, and has a chance to attach a 'drain' listener.
5920function onwriteDrain(stream, state) {
5921 if (state.length === 0 && state.needDrain) {
5922 state.needDrain = false;
5923 stream.emit('drain');
5924 }
5925}
5926
5927
5928// if there's something in the buffer waiting, then process it
5929function clearBuffer(stream, state) {
5930 state.bufferProcessing = true;
5931
5932 if (stream._writev && state.buffer.length > 1) {
5933 // Fast case, write everything using _writev()
5934 var cbs = [];
5935 for (var c = 0; c < state.buffer.length; c++)
5936 cbs.push(state.buffer[c].callback);
5937
5938 // count the one we are adding, as well.
5939 // TODO(isaacs) clean this up
5940 state.pendingcb++;
5941 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
5942 for (var i = 0; i < cbs.length; i++) {
5943 state.pendingcb--;
5944 cbs[i](err);
5945 }
5946 });
5947
5948 // Clear buffer
5949 state.buffer = [];
5950 } else {
5951 // Slow case, write chunks one-by-one
5952 for (var c = 0; c < state.buffer.length; c++) {
5953 var entry = state.buffer[c];
5954 var chunk = entry.chunk;
5955 var encoding = entry.encoding;
5956 var cb = entry.callback;
5957 var len = state.objectMode ? 1 : chunk.length;
5958
5959 doWrite(stream, state, false, len, chunk, encoding, cb);
5960
5961 // if we didn't call the onwrite immediately, then
5962 // it means that we need to wait until it does.
5963 // also, that means that the chunk and cb are currently
5964 // being processed, so move the buffer counter past them.
5965 if (state.writing) {
5966 c++;
5967 break;
5968 }
5969 }
5970
5971 if (c < state.buffer.length)
5972 state.buffer = state.buffer.slice(c);
5973 else
5974 state.buffer.length = 0;
5975 }
5976
5977 state.bufferProcessing = false;
5978}
5979
5980Writable.prototype._write = function(chunk, encoding, cb) {
5981 cb(new Error('not implemented'));
5982
5983};
5984
5985Writable.prototype._writev = null;
5986
5987Writable.prototype.end = function(chunk, encoding, cb) {
5988 var state = this._writableState;
5989
5990 if (util.isFunction(chunk)) {
5991 cb = chunk;
5992 chunk = null;
5993 encoding = null;
5994 } else if (util.isFunction(encoding)) {
5995 cb = encoding;
5996 encoding = null;
5997 }
5998
5999 if (!util.isNullOrUndefined(chunk))
6000 this.write(chunk, encoding);
6001
6002 // .end() fully uncorks
6003 if (state.corked) {
6004 state.corked = 1;
6005 this.uncork();
6006 }
6007
6008 // ignore unnecessary end() calls.
6009 if (!state.ending && !state.finished)
6010 endWritable(this, state, cb);
6011};
6012
6013
6014function needFinish(stream, state) {
6015 return (state.ending &&
6016 state.length === 0 &&
6017 !state.finished &&
6018 !state.writing);
6019}
6020
6021function prefinish(stream, state) {
6022 if (!state.prefinished) {
6023 state.prefinished = true;
6024 stream.emit('prefinish');
6025 }
6026}
6027
6028function finishMaybe(stream, state) {
6029 var need = needFinish(stream, state);
6030 if (need) {
6031 if (state.pendingcb === 0) {
6032 prefinish(stream, state);
6033 state.finished = true;
6034 stream.emit('finish');
6035 } else
6036 prefinish(stream, state);
6037 }
6038 return need;
6039}
6040
6041function endWritable(stream, state, cb) {
6042 state.ending = true;
6043 finishMaybe(stream, state);
6044 if (cb) {
6045 if (state.finished)
6046 process.nextTick(cb);
6047 else
6048 stream.once('finish', cb);
6049 }
6050 state.ended = true;
6051}
6052
6053}).call(this,require('_process'))
6054},{"./_stream_duplex":16,"_process":14,"buffer":7,"core-util-is":21,"inherits":12,"stream":26}],21:[function(require,module,exports){
6055(function (Buffer){
6056// Copyright Joyent, Inc. and other Node contributors.
6057//
6058// Permission is hereby granted, free of charge, to any person obtaining a
6059// copy of this software and associated documentation files (the
6060// "Software"), to deal in the Software without restriction, including
6061// without limitation the rights to use, copy, modify, merge, publish,
6062// distribute, sublicense, and/or sell copies of the Software, and to permit
6063// persons to whom the Software is furnished to do so, subject to the
6064// following conditions:
6065//
6066// The above copyright notice and this permission notice shall be included
6067// in all copies or substantial portions of the Software.
6068//
6069// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6070// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6071// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6072// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6073// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6074// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6075// USE OR OTHER DEALINGS IN THE SOFTWARE.
6076
6077// NOTE: These type checking functions intentionally don't use `instanceof`
6078// because it is fragile and can be easily faked with `Object.create()`.
6079function isArray(ar) {
6080 return Array.isArray(ar);
6081}
6082exports.isArray = isArray;
6083
6084function isBoolean(arg) {
6085 return typeof arg === 'boolean';
6086}
6087exports.isBoolean = isBoolean;
6088
6089function isNull(arg) {
6090 return arg === null;
6091}
6092exports.isNull = isNull;
6093
6094function isNullOrUndefined(arg) {
6095 return arg == null;
6096}
6097exports.isNullOrUndefined = isNullOrUndefined;
6098
6099function isNumber(arg) {
6100 return typeof arg === 'number';
6101}
6102exports.isNumber = isNumber;
6103
6104function isString(arg) {
6105 return typeof arg === 'string';
6106}
6107exports.isString = isString;
6108
6109function isSymbol(arg) {
6110 return typeof arg === 'symbol';
6111}
6112exports.isSymbol = isSymbol;
6113
6114function isUndefined(arg) {
6115 return arg === void 0;
6116}
6117exports.isUndefined = isUndefined;
6118
6119function isRegExp(re) {
6120 return isObject(re) && objectToString(re) === '[object RegExp]';
6121}
6122exports.isRegExp = isRegExp;
6123
6124function isObject(arg) {
6125 return typeof arg === 'object' && arg !== null;
6126}
6127exports.isObject = isObject;
6128
6129function isDate(d) {
6130 return isObject(d) && objectToString(d) === '[object Date]';
6131}
6132exports.isDate = isDate;
6133
6134function isError(e) {
6135 return isObject(e) &&
6136 (objectToString(e) === '[object Error]' || e instanceof Error);
6137}
6138exports.isError = isError;
6139
6140function isFunction(arg) {
6141 return typeof arg === 'function';
6142}
6143exports.isFunction = isFunction;
6144
6145function isPrimitive(arg) {
6146 return arg === null ||
6147 typeof arg === 'boolean' ||
6148 typeof arg === 'number' ||
6149 typeof arg === 'string' ||
6150 typeof arg === 'symbol' || // ES6 symbol
6151 typeof arg === 'undefined';
6152}
6153exports.isPrimitive = isPrimitive;
6154
6155function isBuffer(arg) {
6156 return Buffer.isBuffer(arg);
6157}
6158exports.isBuffer = isBuffer;
6159
6160function objectToString(o) {
6161 return Object.prototype.toString.call(o);
6162}
6163}).call(this,require("buffer").Buffer)
6164},{"buffer":7}],22:[function(require,module,exports){
6165module.exports = require("./lib/_stream_passthrough.js")
6166
6167},{"./lib/_stream_passthrough.js":17}],23:[function(require,module,exports){
6168exports = module.exports = require('./lib/_stream_readable.js');
6169exports.Stream = require('stream');
6170exports.Readable = exports;
6171exports.Writable = require('./lib/_stream_writable.js');
6172exports.Duplex = require('./lib/_stream_duplex.js');
6173exports.Transform = require('./lib/_stream_transform.js');
6174exports.PassThrough = require('./lib/_stream_passthrough.js');
6175
6176},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"stream":26}],24:[function(require,module,exports){
6177module.exports = require("./lib/_stream_transform.js")
6178
6179},{"./lib/_stream_transform.js":19}],25:[function(require,module,exports){
6180module.exports = require("./lib/_stream_writable.js")
6181
6182},{"./lib/_stream_writable.js":20}],26:[function(require,module,exports){
6183// Copyright Joyent, Inc. and other Node contributors.
6184//
6185// Permission is hereby granted, free of charge, to any person obtaining a
6186// copy of this software and associated documentation files (the
6187// "Software"), to deal in the Software without restriction, including
6188// without limitation the rights to use, copy, modify, merge, publish,
6189// distribute, sublicense, and/or sell copies of the Software, and to permit
6190// persons to whom the Software is furnished to do so, subject to the
6191// following conditions:
6192//
6193// The above copyright notice and this permission notice shall be included
6194// in all copies or substantial portions of the Software.
6195//
6196// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6197// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6198// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6199// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6200// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6201// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6202// USE OR OTHER DEALINGS IN THE SOFTWARE.
6203
6204module.exports = Stream;
6205
6206var EE = require('events').EventEmitter;
6207var inherits = require('inherits');
6208
6209inherits(Stream, EE);
6210Stream.Readable = require('readable-stream/readable.js');
6211Stream.Writable = require('readable-stream/writable.js');
6212Stream.Duplex = require('readable-stream/duplex.js');
6213Stream.Transform = require('readable-stream/transform.js');
6214Stream.PassThrough = require('readable-stream/passthrough.js');
6215
6216// Backwards-compat with node 0.4.x
6217Stream.Stream = Stream;
6218
6219
6220
6221// old-style streams. Note that the pipe method (the only relevant
6222// part of this class) is overridden in the Readable class.
6223
6224function Stream() {
6225 EE.call(this);
6226}
6227
6228Stream.prototype.pipe = function(dest, options) {
6229 var source = this;
6230
6231 function ondata(chunk) {
6232 if (dest.writable) {
6233 if (false === dest.write(chunk) && source.pause) {
6234 source.pause();
6235 }
6236 }
6237 }
6238
6239 source.on('data', ondata);
6240
6241 function ondrain() {
6242 if (source.readable && source.resume) {
6243 source.resume();
6244 }
6245 }
6246
6247 dest.on('drain', ondrain);
6248
6249 // If the 'end' option is not supplied, dest.end() will be called when
6250 // source gets the 'end' or 'close' events. Only dest.end() once.
6251 if (!dest._isStdio && (!options || options.end !== false)) {
6252 source.on('end', onend);
6253 source.on('close', onclose);
6254 }
6255
6256 var didOnEnd = false;
6257 function onend() {
6258 if (didOnEnd) return;
6259 didOnEnd = true;
6260
6261 dest.end();
6262 }
6263
6264
6265 function onclose() {
6266 if (didOnEnd) return;
6267 didOnEnd = true;
6268
6269 if (typeof dest.destroy === 'function') dest.destroy();
6270 }
6271
6272 // don't leave dangling pipes when there are errors.
6273 function onerror(er) {
6274 cleanup();
6275 if (EE.listenerCount(this, 'error') === 0) {
6276 throw er; // Unhandled stream error in pipe.
6277 }
6278 }
6279
6280 source.on('error', onerror);
6281 dest.on('error', onerror);
6282
6283 // remove all the event listeners that were added.
6284 function cleanup() {
6285 source.removeListener('data', ondata);
6286 dest.removeListener('drain', ondrain);
6287
6288 source.removeListener('end', onend);
6289 source.removeListener('close', onclose);
6290
6291 source.removeListener('error', onerror);
6292 dest.removeListener('error', onerror);
6293
6294 source.removeListener('end', cleanup);
6295 source.removeListener('close', cleanup);
6296
6297 dest.removeListener('close', cleanup);
6298 }
6299
6300 source.on('end', cleanup);
6301 source.on('close', cleanup);
6302
6303 dest.on('close', cleanup);
6304
6305 dest.emit('pipe', source);
6306
6307 // Allow for unix-like usage: A.pipe(B).pipe(C)
6308 return dest;
6309};
6310
6311},{"events":11,"inherits":12,"readable-stream/duplex.js":15,"readable-stream/passthrough.js":22,"readable-stream/readable.js":23,"readable-stream/transform.js":24,"readable-stream/writable.js":25}],27:[function(require,module,exports){
6312// Copyright Joyent, Inc. and other Node contributors.
6313//
6314// Permission is hereby granted, free of charge, to any person obtaining a
6315// copy of this software and associated documentation files (the
6316// "Software"), to deal in the Software without restriction, including
6317// without limitation the rights to use, copy, modify, merge, publish,
6318// distribute, sublicense, and/or sell copies of the Software, and to permit
6319// persons to whom the Software is furnished to do so, subject to the
6320// following conditions:
6321//
6322// The above copyright notice and this permission notice shall be included
6323// in all copies or substantial portions of the Software.
6324//
6325// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6326// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6327// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6328// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6329// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6330// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6331// USE OR OTHER DEALINGS IN THE SOFTWARE.
6332
6333var Buffer = require('buffer').Buffer;
6334
6335var isBufferEncoding = Buffer.isEncoding
6336 || function(encoding) {
6337 switch (encoding && encoding.toLowerCase()) {
6338 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
6339 default: return false;
6340 }
6341 }
6342
6343
6344function assertEncoding(encoding) {
6345 if (encoding && !isBufferEncoding(encoding)) {
6346 throw new Error('Unknown encoding: ' + encoding);
6347 }
6348}
6349
6350// StringDecoder provides an interface for efficiently splitting a series of
6351// buffers into a series of JS strings without breaking apart multi-byte
6352// characters. CESU-8 is handled as part of the UTF-8 encoding.
6353//
6354// @TODO Handling all encodings inside a single object makes it very difficult
6355// to reason about this code, so it should be split up in the future.
6356// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
6357// points as used by CESU-8.
6358var StringDecoder = exports.StringDecoder = function(encoding) {
6359 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
6360 assertEncoding(encoding);
6361 switch (this.encoding) {
6362 case 'utf8':
6363 // CESU-8 represents each of Surrogate Pair by 3-bytes
6364 this.surrogateSize = 3;
6365 break;
6366 case 'ucs2':
6367 case 'utf16le':
6368 // UTF-16 represents each of Surrogate Pair by 2-bytes
6369 this.surrogateSize = 2;
6370 this.detectIncompleteChar = utf16DetectIncompleteChar;
6371 break;
6372 case 'base64':
6373 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
6374 this.surrogateSize = 3;
6375 this.detectIncompleteChar = base64DetectIncompleteChar;
6376 break;
6377 default:
6378 this.write = passThroughWrite;
6379 return;
6380 }
6381
6382 // Enough space to store all bytes of a single character. UTF-8 needs 4
6383 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
6384 this.charBuffer = new Buffer(6);
6385 // Number of bytes received for the current incomplete multi-byte character.
6386 this.charReceived = 0;
6387 // Number of bytes expected for the current incomplete multi-byte character.
6388 this.charLength = 0;
6389};
6390
6391
6392// write decodes the given buffer and returns it as JS string that is
6393// guaranteed to not contain any partial multi-byte characters. Any partial
6394// character found at the end of the buffer is buffered up, and will be
6395// returned when calling write again with the remaining bytes.
6396//
6397// Note: Converting a Buffer containing an orphan surrogate to a String
6398// currently works, but converting a String to a Buffer (via `new Buffer`, or
6399// Buffer#write) will replace incomplete surrogates with the unicode
6400// replacement character. See https://codereview.chromium.org/121173009/ .
6401StringDecoder.prototype.write = function(buffer) {
6402 var charStr = '';
6403 // if our last write ended with an incomplete multibyte character
6404 while (this.charLength) {
6405 // determine how many remaining bytes this buffer has to offer for this char
6406 var available = (buffer.length >= this.charLength - this.charReceived) ?
6407 this.charLength - this.charReceived :
6408 buffer.length;
6409
6410 // add the new bytes to the char buffer
6411 buffer.copy(this.charBuffer, this.charReceived, 0, available);
6412 this.charReceived += available;
6413
6414 if (this.charReceived < this.charLength) {
6415 // still not enough chars in this buffer? wait for more ...
6416 return '';
6417 }
6418
6419 // remove bytes belonging to the current character from the buffer
6420 buffer = buffer.slice(available, buffer.length);
6421
6422 // get the character that was split
6423 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
6424
6425 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
6426 var charCode = charStr.charCodeAt(charStr.length - 1);
6427 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
6428 this.charLength += this.surrogateSize;
6429 charStr = '';
6430 continue;
6431 }
6432 this.charReceived = this.charLength = 0;
6433
6434 // if there are no more bytes in this buffer, just emit our char
6435 if (buffer.length === 0) {
6436 return charStr;
6437 }
6438 break;
6439 }
6440
6441 // determine and set charLength / charReceived
6442 this.detectIncompleteChar(buffer);
6443
6444 var end = buffer.length;
6445 if (this.charLength) {
6446 // buffer the incomplete character bytes we got
6447 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
6448 end -= this.charReceived;
6449 }
6450
6451 charStr += buffer.toString(this.encoding, 0, end);
6452
6453 var end = charStr.length - 1;
6454 var charCode = charStr.charCodeAt(end);
6455 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
6456 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
6457 var size = this.surrogateSize;
6458 this.charLength += size;
6459 this.charReceived += size;
6460 this.charBuffer.copy(this.charBuffer, size, 0, size);
6461 buffer.copy(this.charBuffer, 0, 0, size);
6462 return charStr.substring(0, end);
6463 }
6464
6465 // or just emit the charStr
6466 return charStr;
6467};
6468
6469// detectIncompleteChar determines if there is an incomplete UTF-8 character at
6470// the end of the given buffer. If so, it sets this.charLength to the byte
6471// length that character, and sets this.charReceived to the number of bytes
6472// that are available for this character.
6473StringDecoder.prototype.detectIncompleteChar = function(buffer) {
6474 // determine how many bytes we have to check at the end of this buffer
6475 var i = (buffer.length >= 3) ? 3 : buffer.length;
6476
6477 // Figure out if one of the last i bytes of our buffer announces an
6478 // incomplete char.
6479 for (; i > 0; i--) {
6480 var c = buffer[buffer.length - i];
6481
6482 // See http://en.wikipedia.org/wiki/UTF-8#Description
6483
6484 // 110XXXXX
6485 if (i == 1 && c >> 5 == 0x06) {
6486 this.charLength = 2;
6487 break;
6488 }
6489
6490 // 1110XXXX
6491 if (i <= 2 && c >> 4 == 0x0E) {
6492 this.charLength = 3;
6493 break;
6494 }
6495
6496 // 11110XXX
6497 if (i <= 3 && c >> 3 == 0x1E) {
6498 this.charLength = 4;
6499 break;
6500 }
6501 }
6502 this.charReceived = i;
6503};
6504
6505StringDecoder.prototype.end = function(buffer) {
6506 var res = '';
6507 if (buffer && buffer.length)
6508 res = this.write(buffer);
6509
6510 if (this.charReceived) {
6511 var cr = this.charReceived;
6512 var buf = this.charBuffer;
6513 var enc = this.encoding;
6514 res += buf.slice(0, cr).toString(enc);
6515 }
6516
6517 return res;
6518};
6519
6520function passThroughWrite(buffer) {
6521 return buffer.toString(this.encoding);
6522}
6523
6524function utf16DetectIncompleteChar(buffer) {
6525 this.charReceived = buffer.length % 2;
6526 this.charLength = this.charReceived ? 2 : 0;
6527}
6528
6529function base64DetectIncompleteChar(buffer) {
6530 this.charReceived = buffer.length % 3;
6531 this.charLength = this.charReceived ? 3 : 0;
6532}
6533
6534},{"buffer":7}],28:[function(require,module,exports){
6535module.exports = function isBuffer(arg) {
6536 return arg && typeof arg === 'object'
6537 && typeof arg.copy === 'function'
6538 && typeof arg.fill === 'function'
6539 && typeof arg.readUInt8 === 'function';
6540}
6541},{}],29:[function(require,module,exports){
6542(function (process,global){
6543// Copyright Joyent, Inc. and other Node contributors.
6544//
6545// Permission is hereby granted, free of charge, to any person obtaining a
6546// copy of this software and associated documentation files (the
6547// "Software"), to deal in the Software without restriction, including
6548// without limitation the rights to use, copy, modify, merge, publish,
6549// distribute, sublicense, and/or sell copies of the Software, and to permit
6550// persons to whom the Software is furnished to do so, subject to the
6551// following conditions:
6552//
6553// The above copyright notice and this permission notice shall be included
6554// in all copies or substantial portions of the Software.
6555//
6556// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6557// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6558// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6559// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6560// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6561// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6562// USE OR OTHER DEALINGS IN THE SOFTWARE.
6563
6564var formatRegExp = /%[sdj%]/g;
6565exports.format = function(f) {
6566 if (!isString(f)) {
6567 var objects = [];
6568 for (var i = 0; i < arguments.length; i++) {
6569 objects.push(inspect(arguments[i]));
6570 }
6571 return objects.join(' ');
6572 }
6573
6574 var i = 1;
6575 var args = arguments;
6576 var len = args.length;
6577 var str = String(f).replace(formatRegExp, function(x) {
6578 if (x === '%%') return '%';
6579 if (i >= len) return x;
6580 switch (x) {
6581 case '%s': return String(args[i++]);
6582 case '%d': return Number(args[i++]);
6583 case '%j':
6584 try {
6585 return JSON.stringify(args[i++]);
6586 } catch (_) {
6587 return '[Circular]';
6588 }
6589 default:
6590 return x;
6591 }
6592 });
6593 for (var x = args[i]; i < len; x = args[++i]) {
6594 if (isNull(x) || !isObject(x)) {
6595 str += ' ' + x;
6596 } else {
6597 str += ' ' + inspect(x);
6598 }
6599 }
6600 return str;
6601};
6602
6603
6604// Mark that a method should not be used.
6605// Returns a modified function which warns once by default.
6606// If --no-deprecation is set, then it is a no-op.
6607exports.deprecate = function(fn, msg) {
6608 // Allow for deprecating things in the process of starting up.
6609 if (isUndefined(global.process)) {
6610 return function() {
6611 return exports.deprecate(fn, msg).apply(this, arguments);
6612 };
6613 }
6614
6615 if (process.noDeprecation === true) {
6616 return fn;
6617 }
6618
6619 var warned = false;
6620 function deprecated() {
6621 if (!warned) {
6622 if (process.throwDeprecation) {
6623 throw new Error(msg);
6624 } else if (process.traceDeprecation) {
6625 console.trace(msg);
6626 } else {
6627 console.error(msg);
6628 }
6629 warned = true;
6630 }
6631 return fn.apply(this, arguments);
6632 }
6633
6634 return deprecated;
6635};
6636
6637
6638var debugs = {};
6639var debugEnviron;
6640exports.debuglog = function(set) {
6641 if (isUndefined(debugEnviron))
6642 debugEnviron = process.env.NODE_DEBUG || '';
6643 set = set.toUpperCase();
6644 if (!debugs[set]) {
6645 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
6646 var pid = process.pid;
6647 debugs[set] = function() {
6648 var msg = exports.format.apply(exports, arguments);
6649 console.error('%s %d: %s', set, pid, msg);
6650 };
6651 } else {
6652 debugs[set] = function() {};
6653 }
6654 }
6655 return debugs[set];
6656};
6657
6658
6659/**
6660 * Echos the value of a value. Trys to print the value out
6661 * in the best way possible given the different types.
6662 *
6663 * @param {Object} obj The object to print out.
6664 * @param {Object} opts Optional options object that alters the output.
6665 */
6666/* legacy: obj, showHidden, depth, colors*/
6667function inspect(obj, opts) {
6668 // default options
6669 var ctx = {
6670 seen: [],
6671 stylize: stylizeNoColor
6672 };
6673 // legacy...
6674 if (arguments.length >= 3) ctx.depth = arguments[2];
6675 if (arguments.length >= 4) ctx.colors = arguments[3];
6676 if (isBoolean(opts)) {
6677 // legacy...
6678 ctx.showHidden = opts;
6679 } else if (opts) {
6680 // got an "options" object
6681 exports._extend(ctx, opts);
6682 }
6683 // set default options
6684 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
6685 if (isUndefined(ctx.depth)) ctx.depth = 2;
6686 if (isUndefined(ctx.colors)) ctx.colors = false;
6687 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
6688 if (ctx.colors) ctx.stylize = stylizeWithColor;
6689 return formatValue(ctx, obj, ctx.depth);
6690}
6691exports.inspect = inspect;
6692
6693
6694// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
6695inspect.colors = {
6696 'bold' : [1, 22],
6697 'italic' : [3, 23],
6698 'underline' : [4, 24],
6699 'inverse' : [7, 27],
6700 'white' : [37, 39],
6701 'grey' : [90, 39],
6702 'black' : [30, 39],
6703 'blue' : [34, 39],
6704 'cyan' : [36, 39],
6705 'green' : [32, 39],
6706 'magenta' : [35, 39],
6707 'red' : [31, 39],
6708 'yellow' : [33, 39]
6709};
6710
6711// Don't use 'blue' not visible on cmd.exe
6712inspect.styles = {
6713 'special': 'cyan',
6714 'number': 'yellow',
6715 'boolean': 'yellow',
6716 'undefined': 'grey',
6717 'null': 'bold',
6718 'string': 'green',
6719 'date': 'magenta',
6720 // "name": intentionally not styling
6721 'regexp': 'red'
6722};
6723
6724
6725function stylizeWithColor(str, styleType) {
6726 var style = inspect.styles[styleType];
6727
6728 if (style) {
6729 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
6730 '\u001b[' + inspect.colors[style][1] + 'm';
6731 } else {
6732 return str;
6733 }
6734}
6735
6736
6737function stylizeNoColor(str, styleType) {
6738 return str;
6739}
6740
6741
6742function arrayToHash(array) {
6743 var hash = {};
6744
6745 array.forEach(function(val, idx) {
6746 hash[val] = true;
6747 });
6748
6749 return hash;
6750}
6751
6752
6753function formatValue(ctx, value, recurseTimes) {
6754 // Provide a hook for user-specified inspect functions.
6755 // Check that value is an object with an inspect function on it
6756 if (ctx.customInspect &&
6757 value &&
6758 isFunction(value.inspect) &&
6759 // Filter out the util module, it's inspect function is special
6760 value.inspect !== exports.inspect &&
6761 // Also filter out any prototype objects using the circular check.
6762 !(value.constructor && value.constructor.prototype === value)) {
6763 var ret = value.inspect(recurseTimes, ctx);
6764 if (!isString(ret)) {
6765 ret = formatValue(ctx, ret, recurseTimes);
6766 }
6767 return ret;
6768 }
6769
6770 // Primitive types cannot have properties
6771 var primitive = formatPrimitive(ctx, value);
6772 if (primitive) {
6773 return primitive;
6774 }
6775
6776 // Look up the keys of the object.
6777 var keys = Object.keys(value);
6778 var visibleKeys = arrayToHash(keys);
6779
6780 if (ctx.showHidden) {
6781 keys = Object.getOwnPropertyNames(value);
6782 }
6783
6784 // IE doesn't make error fields non-enumerable
6785 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
6786 if (isError(value)
6787 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
6788 return formatError(value);
6789 }
6790
6791 // Some type of object without properties can be shortcutted.
6792 if (keys.length === 0) {
6793 if (isFunction(value)) {
6794 var name = value.name ? ': ' + value.name : '';
6795 return ctx.stylize('[Function' + name + ']', 'special');
6796 }
6797 if (isRegExp(value)) {
6798 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6799 }
6800 if (isDate(value)) {
6801 return ctx.stylize(Date.prototype.toString.call(value), 'date');
6802 }
6803 if (isError(value)) {
6804 return formatError(value);
6805 }
6806 }
6807
6808 var base = '', array = false, braces = ['{', '}'];
6809
6810 // Make Array say that they are Array
6811 if (isArray(value)) {
6812 array = true;
6813 braces = ['[', ']'];
6814 }
6815
6816 // Make functions say that they are functions
6817 if (isFunction(value)) {
6818 var n = value.name ? ': ' + value.name : '';
6819 base = ' [Function' + n + ']';
6820 }
6821
6822 // Make RegExps say that they are RegExps
6823 if (isRegExp(value)) {
6824 base = ' ' + RegExp.prototype.toString.call(value);
6825 }
6826
6827 // Make dates with properties first say the date
6828 if (isDate(value)) {
6829 base = ' ' + Date.prototype.toUTCString.call(value);
6830 }
6831
6832 // Make error with message first say the error
6833 if (isError(value)) {
6834 base = ' ' + formatError(value);
6835 }
6836
6837 if (keys.length === 0 && (!array || value.length == 0)) {
6838 return braces[0] + base + braces[1];
6839 }
6840
6841 if (recurseTimes < 0) {
6842 if (isRegExp(value)) {
6843 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6844 } else {
6845 return ctx.stylize('[Object]', 'special');
6846 }
6847 }
6848
6849 ctx.seen.push(value);
6850
6851 var output;
6852 if (array) {
6853 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
6854 } else {
6855 output = keys.map(function(key) {
6856 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
6857 });
6858 }
6859
6860 ctx.seen.pop();
6861
6862 return reduceToSingleString(output, base, braces);
6863}
6864
6865
6866function formatPrimitive(ctx, value) {
6867 if (isUndefined(value))
6868 return ctx.stylize('undefined', 'undefined');
6869 if (isString(value)) {
6870 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
6871 .replace(/'/g, "\\'")
6872 .replace(/\\"/g, '"') + '\'';
6873 return ctx.stylize(simple, 'string');
6874 }
6875 if (isNumber(value))
6876 return ctx.stylize('' + value, 'number');
6877 if (isBoolean(value))
6878 return ctx.stylize('' + value, 'boolean');
6879 // For some reason typeof null is "object", so special case here.
6880 if (isNull(value))
6881 return ctx.stylize('null', 'null');
6882}
6883
6884
6885function formatError(value) {
6886 return '[' + Error.prototype.toString.call(value) + ']';
6887}
6888
6889
6890function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
6891 var output = [];
6892 for (var i = 0, l = value.length; i < l; ++i) {
6893 if (hasOwnProperty(value, String(i))) {
6894 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
6895 String(i), true));
6896 } else {
6897 output.push('');
6898 }
6899 }
6900 keys.forEach(function(key) {
6901 if (!key.match(/^\d+$/)) {
6902 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
6903 key, true));
6904 }
6905 });
6906 return output;
6907}
6908
6909
6910function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
6911 var name, str, desc;
6912 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
6913 if (desc.get) {
6914 if (desc.set) {
6915 str = ctx.stylize('[Getter/Setter]', 'special');
6916 } else {
6917 str = ctx.stylize('[Getter]', 'special');
6918 }
6919 } else {
6920 if (desc.set) {
6921 str = ctx.stylize('[Setter]', 'special');
6922 }
6923 }
6924 if (!hasOwnProperty(visibleKeys, key)) {
6925 name = '[' + key + ']';
6926 }
6927 if (!str) {
6928 if (ctx.seen.indexOf(desc.value) < 0) {
6929 if (isNull(recurseTimes)) {
6930 str = formatValue(ctx, desc.value, null);
6931 } else {
6932 str = formatValue(ctx, desc.value, recurseTimes - 1);
6933 }
6934 if (str.indexOf('\n') > -1) {
6935 if (array) {
6936 str = str.split('\n').map(function(line) {
6937 return ' ' + line;
6938 }).join('\n').substr(2);
6939 } else {
6940 str = '\n' + str.split('\n').map(function(line) {
6941 return ' ' + line;
6942 }).join('\n');
6943 }
6944 }
6945 } else {
6946 str = ctx.stylize('[Circular]', 'special');
6947 }
6948 }
6949 if (isUndefined(name)) {
6950 if (array && key.match(/^\d+$/)) {
6951 return str;
6952 }
6953 name = JSON.stringify('' + key);
6954 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
6955 name = name.substr(1, name.length - 2);
6956 name = ctx.stylize(name, 'name');
6957 } else {
6958 name = name.replace(/'/g, "\\'")
6959 .replace(/\\"/g, '"')
6960 .replace(/(^"|"$)/g, "'");
6961 name = ctx.stylize(name, 'string');
6962 }
6963 }
6964
6965 return name + ': ' + str;
6966}
6967
6968
6969function reduceToSingleString(output, base, braces) {
6970 var numLinesEst = 0;
6971 var length = output.reduce(function(prev, cur) {
6972 numLinesEst++;
6973 if (cur.indexOf('\n') >= 0) numLinesEst++;
6974 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
6975 }, 0);
6976
6977 if (length > 60) {
6978 return braces[0] +
6979 (base === '' ? '' : base + '\n ') +
6980 ' ' +
6981 output.join(',\n ') +
6982 ' ' +
6983 braces[1];
6984 }
6985
6986 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
6987}
6988
6989
6990// NOTE: These type checking functions intentionally don't use `instanceof`
6991// because it is fragile and can be easily faked with `Object.create()`.
6992function isArray(ar) {
6993 return Array.isArray(ar);
6994}
6995exports.isArray = isArray;
6996
6997function isBoolean(arg) {
6998 return typeof arg === 'boolean';
6999}
7000exports.isBoolean = isBoolean;
7001
7002function isNull(arg) {
7003 return arg === null;
7004}
7005exports.isNull = isNull;
7006
7007function isNullOrUndefined(arg) {
7008 return arg == null;
7009}
7010exports.isNullOrUndefined = isNullOrUndefined;
7011
7012function isNumber(arg) {
7013 return typeof arg === 'number';
7014}
7015exports.isNumber = isNumber;
7016
7017function isString(arg) {
7018 return typeof arg === 'string';
7019}
7020exports.isString = isString;
7021
7022function isSymbol(arg) {
7023 return typeof arg === 'symbol';
7024}
7025exports.isSymbol = isSymbol;
7026
7027function isUndefined(arg) {
7028 return arg === void 0;
7029}
7030exports.isUndefined = isUndefined;
7031
7032function isRegExp(re) {
7033 return isObject(re) && objectToString(re) === '[object RegExp]';
7034}
7035exports.isRegExp = isRegExp;
7036
7037function isObject(arg) {
7038 return typeof arg === 'object' && arg !== null;
7039}
7040exports.isObject = isObject;
7041
7042function isDate(d) {
7043 return isObject(d) && objectToString(d) === '[object Date]';
7044}
7045exports.isDate = isDate;
7046
7047function isError(e) {
7048 return isObject(e) &&
7049 (objectToString(e) === '[object Error]' || e instanceof Error);
7050}
7051exports.isError = isError;
7052
7053function isFunction(arg) {
7054 return typeof arg === 'function';
7055}
7056exports.isFunction = isFunction;
7057
7058function isPrimitive(arg) {
7059 return arg === null ||
7060 typeof arg === 'boolean' ||
7061 typeof arg === 'number' ||
7062 typeof arg === 'string' ||
7063 typeof arg === 'symbol' || // ES6 symbol
7064 typeof arg === 'undefined';
7065}
7066exports.isPrimitive = isPrimitive;
7067
7068exports.isBuffer = require('./support/isBuffer');
7069
7070function objectToString(o) {
7071 return Object.prototype.toString.call(o);
7072}
7073
7074
7075function pad(n) {
7076 return n < 10 ? '0' + n.toString(10) : n.toString(10);
7077}
7078
7079
7080var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
7081 'Oct', 'Nov', 'Dec'];
7082
7083// 26 Feb 16:19:34
7084function timestamp() {
7085 var d = new Date();
7086 var time = [pad(d.getHours()),
7087 pad(d.getMinutes()),
7088 pad(d.getSeconds())].join(':');
7089 return [d.getDate(), months[d.getMonth()], time].join(' ');
7090}
7091
7092
7093// log is just a thin wrapper to console.log that prepends a timestamp
7094exports.log = function() {
7095 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
7096};
7097
7098
7099/**
7100 * Inherit the prototype methods from one constructor into another.
7101 *
7102 * The Function.prototype.inherits from lang.js rewritten as a standalone
7103 * function (not on Function.prototype). NOTE: If this file is to be loaded
7104 * during bootstrapping this function needs to be rewritten using some native
7105 * functions as prototype setup using normal JavaScript does not work as
7106 * expected during bootstrapping (see mirror.js in r114903).
7107 *
7108 * @param {function} ctor Constructor function which needs to inherit the
7109 * prototype.
7110 * @param {function} superCtor Constructor function to inherit prototype from.
7111 */
7112exports.inherits = require('inherits');
7113
7114exports._extend = function(origin, add) {
7115 // Don't do anything if add isn't an object
7116 if (!add || !isObject(add)) return origin;
7117
7118 var keys = Object.keys(add);
7119 var i = keys.length;
7120 while (i--) {
7121 origin[keys[i]] = add[keys[i]];
7122 }
7123 return origin;
7124};
7125
7126function hasOwnProperty(obj, prop) {
7127 return Object.prototype.hasOwnProperty.call(obj, prop);
7128}
7129
7130}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7131},{"./support/isBuffer":28,"_process":14,"inherits":12}],30:[function(require,module,exports){
7132// Base58 encoding/decoding
7133// Originally written by Mike Hearn for BitcoinJ
7134// Copyright (c) 2011 Google Inc
7135// Ported to JavaScript by Stefan Thomas
7136// Merged Buffer refactorings from base58-native by Stephen Pair
7137// Copyright (c) 2013 BitPay Inc
7138
7139var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
7140var ALPHABET_MAP = {}
7141for(var i = 0; i < ALPHABET.length; i++) {
7142 ALPHABET_MAP[ALPHABET.charAt(i)] = i
7143}
7144var BASE = 58
7145
7146function encode(buffer) {
7147 if (buffer.length === 0) return ''
7148
7149 var i, j, digits = [0]
7150 for (i = 0; i < buffer.length; i++) {
7151 for (j = 0; j < digits.length; j++) digits[j] <<= 8
7152
7153 digits[0] += buffer[i]
7154
7155 var carry = 0
7156 for (j = 0; j < digits.length; ++j) {
7157 digits[j] += carry
7158
7159 carry = (digits[j] / BASE) | 0
7160 digits[j] %= BASE
7161 }
7162
7163 while (carry) {
7164 digits.push(carry % BASE)
7165
7166 carry = (carry / BASE) | 0
7167 }
7168 }
7169
7170 // deal with leading zeros
7171 for (i = 0; buffer[i] === 0 && i < buffer.length - 1; i++) digits.push(0)
7172
7173 // convert digits to a string
7174 var stringOutput = ""
7175 for (var i = digits.length - 1; i >= 0; i--) {
7176 stringOutput = stringOutput + ALPHABET[digits[i]]
7177 }
7178 return stringOutput
7179}
7180
7181function decode(string) {
7182 if (string.length === 0) return []
7183
7184 var i, j, bytes = [0]
7185 for (i = 0; i < string.length; i++) {
7186 var c = string[i]
7187 if (!(c in ALPHABET_MAP)) throw new Error('Non-base58 character')
7188
7189 for (j = 0; j < bytes.length; j++) bytes[j] *= BASE
7190 bytes[0] += ALPHABET_MAP[c]
7191
7192 var carry = 0
7193 for (j = 0; j < bytes.length; ++j) {
7194 bytes[j] += carry
7195
7196 carry = bytes[j] >> 8
7197 bytes[j] &= 0xff
7198 }
7199
7200 while (carry) {
7201 bytes.push(carry & 0xff)
7202
7203 carry >>= 8
7204 }
7205 }
7206
7207 // deal with leading zeros
7208 for (i = 0; string[i] === '1' && i < string.length - 1; i++) bytes.push(0)
7209
7210 return bytes.reverse()
7211}
7212
7213module.exports = {
7214 encode: encode,
7215 decode: decode
7216}
7217
7218},{}],31:[function(require,module,exports){
7219(function (Buffer){
7220'use strict'
7221
7222var base58 = require('bs58')
7223var createHash = require('create-hash')
7224
7225// SHA256(SHA256(buffer))
7226function sha256x2 (buffer) {
7227 buffer = createHash('sha256').update(buffer).digest()
7228 return createHash('sha256').update(buffer).digest()
7229}
7230
7231// Encode a buffer as a base58-check encoded string
7232function encode (payload) {
7233 var checksum = sha256x2(payload).slice(0, 4)
7234
7235 return base58.encode(Buffer.concat([
7236 payload,
7237 checksum
7238 ]))
7239}
7240
7241// Decode a base58-check encoded string to a buffer
7242function decode (string) {
7243 var buffer = new Buffer(base58.decode(string))
7244
7245 var payload = buffer.slice(0, -4)
7246 var checksum = buffer.slice(-4)
7247 var newChecksum = sha256x2(payload).slice(0, 4)
7248
7249 for (var i = 0; i < newChecksum.length; ++i) {
7250 if (newChecksum[i] === checksum[i]) continue
7251
7252 throw new Error('Invalid checksum')
7253 }
7254
7255 return payload
7256}
7257
7258module.exports = {
7259 encode: encode,
7260 decode: decode
7261}
7262
7263}).call(this,require("buffer").Buffer)
7264},{"bs58":30,"buffer":7,"create-hash":32}],32:[function(require,module,exports){
7265(function (Buffer){
7266'use strict';
7267var inherits = require('inherits')
7268var md5 = require('./md5')
7269var rmd160 = require('ripemd160')
7270var sha = require('sha.js')
7271
7272var Transform = require('stream').Transform
7273
7274function HashNoConstructor(hash) {
7275 Transform.call(this)
7276
7277 this._hash = hash
7278 this.buffers = []
7279}
7280
7281inherits(HashNoConstructor, Transform)
7282
7283HashNoConstructor.prototype._transform = function (data, _, next) {
7284 this.buffers.push(data)
7285
7286 next()
7287}
7288
7289HashNoConstructor.prototype._flush = function (next) {
7290 this.push(this.digest())
7291 next()
7292}
7293
7294HashNoConstructor.prototype.update = function (data, enc) {
7295 if (typeof data === 'string') {
7296 data = new Buffer(data, enc)
7297 }
7298
7299 this.buffers.push(data)
7300 return this
7301}
7302
7303HashNoConstructor.prototype.digest = function (enc) {
7304 var buf = Buffer.concat(this.buffers)
7305 var r = this._hash(buf)
7306 this.buffers = null
7307
7308 return enc ? r.toString(enc) : r
7309}
7310
7311function Hash(hash) {
7312 Transform.call(this)
7313
7314 this._hash = hash
7315}
7316
7317inherits(Hash, Transform)
7318
7319Hash.prototype._transform = function (data, enc, next) {
7320 if (enc) data = new Buffer(data, enc)
7321
7322 this._hash.update(data)
7323
7324 next()
7325}
7326
7327Hash.prototype._flush = function (next) {
7328 this.push(this._hash.digest())
7329 this._hash = null
7330
7331 next()
7332}
7333
7334Hash.prototype.update = function (data, enc) {
7335 if (typeof data === 'string') {
7336 data = new Buffer(data, enc)
7337 }
7338
7339 this._hash.update(data)
7340 return this
7341}
7342
7343Hash.prototype.digest = function (enc) {
7344 var outData = this._hash.digest()
7345
7346 return enc ? outData.toString(enc) : outData
7347}
7348
7349module.exports = function createHash (alg) {
7350 if ('md5' === alg) return new HashNoConstructor(md5)
7351 if ('rmd160' === alg) return new HashNoConstructor(rmd160)
7352
7353 return new Hash(sha(alg))
7354}
7355
7356}).call(this,require("buffer").Buffer)
7357},{"./md5":34,"buffer":7,"inherits":35,"ripemd160":36,"sha.js":38,"stream":26}],33:[function(require,module,exports){
7358(function (Buffer){
7359'use strict';
7360var intSize = 4;
7361var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
7362var chrsz = 8;
7363
7364function toArray(buf, bigEndian) {
7365 if ((buf.length % intSize) !== 0) {
7366 var len = buf.length + (intSize - (buf.length % intSize));
7367 buf = Buffer.concat([buf, zeroBuffer], len);
7368 }
7369
7370 var arr = [];
7371 var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
7372 for (var i = 0; i < buf.length; i += intSize) {
7373 arr.push(fn.call(buf, i));
7374 }
7375 return arr;
7376}
7377
7378function toBuffer(arr, size, bigEndian) {
7379 var buf = new Buffer(size);
7380 var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
7381 for (var i = 0; i < arr.length; i++) {
7382 fn.call(buf, arr[i], i * 4, true);
7383 }
7384 return buf;
7385}
7386
7387function hash(buf, fn, hashSize, bigEndian) {
7388 if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
7389 var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
7390 return toBuffer(arr, hashSize, bigEndian);
7391}
7392exports.hash = hash;
7393}).call(this,require("buffer").Buffer)
7394},{"buffer":7}],34:[function(require,module,exports){
7395'use strict';
7396/*
7397 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
7398 * Digest Algorithm, as defined in RFC 1321.
7399 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
7400 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
7401 * Distributed under the BSD License
7402 * See http://pajhome.org.uk/crypt/md5 for more info.
7403 */
7404
7405var helpers = require('./helpers');
7406
7407/*
7408 * Calculate the MD5 of an array of little-endian words, and a bit length
7409 */
7410function core_md5(x, len)
7411{
7412 /* append padding */
7413 x[len >> 5] |= 0x80 << ((len) % 32);
7414 x[(((len + 64) >>> 9) << 4) + 14] = len;
7415
7416 var a = 1732584193;
7417 var b = -271733879;
7418 var c = -1732584194;
7419 var d = 271733878;
7420
7421 for(var i = 0; i < x.length; i += 16)
7422 {
7423 var olda = a;
7424 var oldb = b;
7425 var oldc = c;
7426 var oldd = d;
7427
7428 a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
7429 d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
7430 c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
7431 b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
7432 a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
7433 d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
7434 c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
7435 b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
7436 a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
7437 d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
7438 c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
7439 b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
7440 a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
7441 d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
7442 c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
7443 b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
7444
7445 a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
7446 d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
7447 c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
7448 b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
7449 a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
7450 d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
7451 c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
7452 b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
7453 a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
7454 d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
7455 c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
7456 b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
7457 a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
7458 d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
7459 c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
7460 b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
7461
7462 a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
7463 d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
7464 c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
7465 b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
7466 a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
7467 d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
7468 c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
7469 b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
7470 a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
7471 d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
7472 c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
7473 b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
7474 a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
7475 d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
7476 c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
7477 b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
7478
7479 a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
7480 d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
7481 c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
7482 b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
7483 a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
7484 d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
7485 c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
7486 b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
7487 a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
7488 d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
7489 c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
7490 b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
7491 a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
7492 d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
7493 c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
7494 b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
7495
7496 a = safe_add(a, olda);
7497 b = safe_add(b, oldb);
7498 c = safe_add(c, oldc);
7499 d = safe_add(d, oldd);
7500 }
7501 return Array(a, b, c, d);
7502
7503}
7504
7505/*
7506 * These functions implement the four basic operations the algorithm uses.
7507 */
7508function md5_cmn(q, a, b, x, s, t)
7509{
7510 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
7511}
7512function md5_ff(a, b, c, d, x, s, t)
7513{
7514 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
7515}
7516function md5_gg(a, b, c, d, x, s, t)
7517{
7518 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
7519}
7520function md5_hh(a, b, c, d, x, s, t)
7521{
7522 return md5_cmn(b ^ c ^ d, a, b, x, s, t);
7523}
7524function md5_ii(a, b, c, d, x, s, t)
7525{
7526 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
7527}
7528
7529/*
7530 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
7531 * to work around bugs in some JS interpreters.
7532 */
7533function safe_add(x, y)
7534{
7535 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
7536 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
7537 return (msw << 16) | (lsw & 0xFFFF);
7538}
7539
7540/*
7541 * Bitwise rotate a 32-bit number to the left.
7542 */
7543function bit_rol(num, cnt)
7544{
7545 return (num << cnt) | (num >>> (32 - cnt));
7546}
7547
7548module.exports = function md5(buf) {
7549 return helpers.hash(buf, core_md5, 16);
7550};
7551},{"./helpers":33}],35:[function(require,module,exports){
7552arguments[4][12][0].apply(exports,arguments)
7553},{"dup":12}],36:[function(require,module,exports){
7554(function (Buffer){
7555/*
7556CryptoJS v3.1.2
7557code.google.com/p/crypto-js
7558(c) 2009-2013 by Jeff Mott. All rights reserved.
7559code.google.com/p/crypto-js/wiki/License
7560*/
7561/** @preserve
7562(c) 2012 by Cédric Mesnil. All rights reserved.
7563
7564Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
7565
7566 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7567 - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
7568
7569THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7570*/
7571
7572// constants table
7573var zl = [
7574 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7575 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
7576 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
7577 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
7578 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
7579]
7580
7581var zr = [
7582 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
7583 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
7584 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
7585 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
7586 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
7587]
7588
7589var sl = [
7590 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7591 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
7592 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
7593 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
7594 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
7595]
7596
7597var sr = [
7598 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
7599 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
7600 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
7601 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
7602 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
7603]
7604
7605var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
7606var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
7607
7608function bytesToWords (bytes) {
7609 var words = []
7610 for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
7611 words[b >>> 5] |= bytes[i] << (24 - b % 32)
7612 }
7613 return words
7614}
7615
7616function wordsToBytes (words) {
7617 var bytes = []
7618 for (var b = 0; b < words.length * 32; b += 8) {
7619 bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF)
7620 }
7621 return bytes
7622}
7623
7624function processBlock (H, M, offset) {
7625 // swap endian
7626 for (var i = 0; i < 16; i++) {
7627 var offset_i = offset + i
7628 var M_offset_i = M[offset_i]
7629
7630 // Swap
7631 M[offset_i] = (
7632 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
7633 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
7634 )
7635 }
7636
7637 // Working variables
7638 var al, bl, cl, dl, el
7639 var ar, br, cr, dr, er
7640
7641 ar = al = H[0]
7642 br = bl = H[1]
7643 cr = cl = H[2]
7644 dr = dl = H[3]
7645 er = el = H[4]
7646
7647 // computation
7648 var t
7649 for (i = 0; i < 80; i += 1) {
7650 t = (al + M[offset + zl[i]]) | 0
7651 if (i < 16) {
7652 t += f1(bl, cl, dl) + hl[0]
7653 } else if (i < 32) {
7654 t += f2(bl, cl, dl) + hl[1]
7655 } else if (i < 48) {
7656 t += f3(bl, cl, dl) + hl[2]
7657 } else if (i < 64) {
7658 t += f4(bl, cl, dl) + hl[3]
7659 } else {// if (i<80) {
7660 t += f5(bl, cl, dl) + hl[4]
7661 }
7662 t = t | 0
7663 t = rotl(t, sl[i])
7664 t = (t + el) | 0
7665 al = el
7666 el = dl
7667 dl = rotl(cl, 10)
7668 cl = bl
7669 bl = t
7670
7671 t = (ar + M[offset + zr[i]]) | 0
7672 if (i < 16) {
7673 t += f5(br, cr, dr) + hr[0]
7674 } else if (i < 32) {
7675 t += f4(br, cr, dr) + hr[1]
7676 } else if (i < 48) {
7677 t += f3(br, cr, dr) + hr[2]
7678 } else if (i < 64) {
7679 t += f2(br, cr, dr) + hr[3]
7680 } else {// if (i<80) {
7681 t += f1(br, cr, dr) + hr[4]
7682 }
7683
7684 t = t | 0
7685 t = rotl(t, sr[i])
7686 t = (t + er) | 0
7687 ar = er
7688 er = dr
7689 dr = rotl(cr, 10)
7690 cr = br
7691 br = t
7692 }
7693
7694 // intermediate hash value
7695 t = (H[1] + cl + dr) | 0
7696 H[1] = (H[2] + dl + er) | 0
7697 H[2] = (H[3] + el + ar) | 0
7698 H[3] = (H[4] + al + br) | 0
7699 H[4] = (H[0] + bl + cr) | 0
7700 H[0] = t
7701}
7702
7703function f1 (x, y, z) {
7704 return ((x) ^ (y) ^ (z))
7705}
7706
7707function f2 (x, y, z) {
7708 return (((x) & (y)) | ((~x) & (z)))
7709}
7710
7711function f3 (x, y, z) {
7712 return (((x) | (~(y))) ^ (z))
7713}
7714
7715function f4 (x, y, z) {
7716 return (((x) & (z)) | ((y) & (~(z))))
7717}
7718
7719function f5 (x, y, z) {
7720 return ((x) ^ ((y) | (~(z))))
7721}
7722
7723function rotl (x, n) {
7724 return (x << n) | (x >>> (32 - n))
7725}
7726
7727function ripemd160 (message) {
7728 var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
7729
7730 if (typeof message === 'string') {
7731 message = new Buffer(message, 'utf8')
7732 }
7733
7734 var m = bytesToWords(message)
7735
7736 var nBitsLeft = message.length * 8
7737 var nBitsTotal = message.length * 8
7738
7739 // Add padding
7740 m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32)
7741 m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
7742 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
7743 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
7744 )
7745
7746 for (var i = 0; i < m.length; i += 16) {
7747 processBlock(H, m, i)
7748 }
7749
7750 // swap endian
7751 for (i = 0; i < 5; i++) {
7752 // shortcut
7753 var H_i = H[i]
7754
7755 // Swap
7756 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
7757 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00)
7758 }
7759
7760 var digestbytes = wordsToBytes(H)
7761 return new Buffer(digestbytes)
7762}
7763
7764module.exports = ripemd160
7765
7766}).call(this,require("buffer").Buffer)
7767},{"buffer":7}],37:[function(require,module,exports){
7768(function (Buffer){
7769// prototype class for hash functions
7770function Hash (blockSize, finalSize) {
7771 this._block = new Buffer(blockSize)
7772 this._finalSize = finalSize
7773 this._blockSize = blockSize
7774 this._len = 0
7775 this._s = 0
7776}
7777
7778Hash.prototype.update = function (data, enc) {
7779 if (typeof data === 'string') {
7780 enc = enc || 'utf8'
7781 data = new Buffer(data, enc)
7782 }
7783
7784 var l = this._len += data.length
7785 var s = this._s || 0
7786 var f = 0
7787 var buffer = this._block
7788
7789 while (s < l) {
7790 var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
7791 var ch = (t - f)
7792
7793 for (var i = 0; i < ch; i++) {
7794 buffer[(s % this._blockSize) + i] = data[i + f]
7795 }
7796
7797 s += ch
7798 f += ch
7799
7800 if ((s % this._blockSize) === 0) {
7801 this._update(buffer)
7802 }
7803 }
7804 this._s = s
7805
7806 return this
7807}
7808
7809Hash.prototype.digest = function (enc) {
7810 // Suppose the length of the message M, in bits, is l
7811 var l = this._len * 8
7812
7813 // Append the bit 1 to the end of the message
7814 this._block[this._len % this._blockSize] = 0x80
7815
7816 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
7817 this._block.fill(0, this._len % this._blockSize + 1)
7818
7819 if (l % (this._blockSize * 8) >= this._finalSize * 8) {
7820 this._update(this._block)
7821 this._block.fill(0)
7822 }
7823
7824 // to this append the block which is equal to the number l written in binary
7825 // TODO: handle case where l is > Math.pow(2, 29)
7826 this._block.writeInt32BE(l, this._blockSize - 4)
7827
7828 var hash = this._update(this._block) || this._hash()
7829
7830 return enc ? hash.toString(enc) : hash
7831}
7832
7833Hash.prototype._update = function () {
7834 throw new Error('_update must be implemented by subclass')
7835}
7836
7837module.exports = Hash
7838
7839}).call(this,require("buffer").Buffer)
7840},{"buffer":7}],38:[function(require,module,exports){
7841var exports = module.exports = function SHA (algorithm) {
7842 algorithm = algorithm.toLowerCase()
7843
7844 var Algorithm = exports[algorithm]
7845 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
7846
7847 return new Algorithm()
7848}
7849
7850exports.sha = require('./sha')
7851exports.sha1 = require('./sha1')
7852exports.sha224 = require('./sha224')
7853exports.sha256 = require('./sha256')
7854exports.sha384 = require('./sha384')
7855exports.sha512 = require('./sha512')
7856
7857},{"./sha":39,"./sha1":40,"./sha224":41,"./sha256":42,"./sha384":43,"./sha512":44}],39:[function(require,module,exports){
7858(function (Buffer){
7859/*
7860 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
7861 * in FIPS PUB 180-1
7862 * This source code is derived from sha1.js of the same repository.
7863 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
7864 * operation was added.
7865 */
7866
7867var inherits = require('inherits')
7868var Hash = require('./hash')
7869
7870var W = new Array(80)
7871
7872function Sha () {
7873 this.init()
7874 this._w = W
7875
7876 Hash.call(this, 64, 56)
7877}
7878
7879inherits(Sha, Hash)
7880
7881Sha.prototype.init = function () {
7882 this._a = 0x67452301 | 0
7883 this._b = 0xefcdab89 | 0
7884 this._c = 0x98badcfe | 0
7885 this._d = 0x10325476 | 0
7886 this._e = 0xc3d2e1f0 | 0
7887
7888 return this
7889}
7890
7891/*
7892 * Bitwise rotate a 32-bit number to the left.
7893 */
7894function rol (num, cnt) {
7895 return (num << cnt) | (num >>> (32 - cnt))
7896}
7897
7898Sha.prototype._update = function (M) {
7899 var W = this._w
7900
7901 var a = this._a
7902 var b = this._b
7903 var c = this._c
7904 var d = this._d
7905 var e = this._e
7906
7907 var j = 0, k
7908
7909 /*
7910 * SHA-1 has a bitwise rotate left operation. But, SHA is not
7911 * function calcW() { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) }
7912 */
7913 function calcW () { return W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16] }
7914 function loop (w, f) {
7915 W[j] = w
7916
7917 var t = rol(a, 5) + f + e + w + k
7918
7919 e = d
7920 d = c
7921 c = rol(b, 30)
7922 b = a
7923 a = t
7924 j++
7925 }
7926
7927 k = 1518500249
7928 while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d))
7929 while (j < 20) loop(calcW(), (b & c) | ((~b) & d))
7930 k = 1859775393
7931 while (j < 40) loop(calcW(), b ^ c ^ d)
7932 k = -1894007588
7933 while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d))
7934 k = -899497514
7935 while (j < 80) loop(calcW(), b ^ c ^ d)
7936
7937 this._a = (a + this._a) | 0
7938 this._b = (b + this._b) | 0
7939 this._c = (c + this._c) | 0
7940 this._d = (d + this._d) | 0
7941 this._e = (e + this._e) | 0
7942}
7943
7944Sha.prototype._hash = function () {
7945 var H = new Buffer(20)
7946
7947 H.writeInt32BE(this._a | 0, 0)
7948 H.writeInt32BE(this._b | 0, 4)
7949 H.writeInt32BE(this._c | 0, 8)
7950 H.writeInt32BE(this._d | 0, 12)
7951 H.writeInt32BE(this._e | 0, 16)
7952
7953 return H
7954}
7955
7956module.exports = Sha
7957
7958
7959}).call(this,require("buffer").Buffer)
7960},{"./hash":37,"buffer":7,"inherits":35}],40:[function(require,module,exports){
7961(function (Buffer){
7962/*
7963 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
7964 * in FIPS PUB 180-1
7965 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
7966 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
7967 * Distributed under the BSD License
7968 * See http://pajhome.org.uk/crypt/md5 for details.
7969 */
7970
7971var inherits = require('inherits')
7972var Hash = require('./hash')
7973
7974var W = new Array(80)
7975
7976function Sha1 () {
7977 this.init()
7978 this._w = W
7979
7980 Hash.call(this, 64, 56)
7981}
7982
7983inherits(Sha1, Hash)
7984
7985Sha1.prototype.init = function () {
7986 this._a = 0x67452301 | 0
7987 this._b = 0xefcdab89 | 0
7988 this._c = 0x98badcfe | 0
7989 this._d = 0x10325476 | 0
7990 this._e = 0xc3d2e1f0 | 0
7991
7992 return this
7993}
7994
7995/*
7996 * Bitwise rotate a 32-bit number to the left.
7997 */
7998function rol (num, cnt) {
7999 return (num << cnt) | (num >>> (32 - cnt))
8000}
8001
8002Sha1.prototype._update = function (M) {
8003 var W = this._w
8004
8005 var a = this._a
8006 var b = this._b
8007 var c = this._c
8008 var d = this._d
8009 var e = this._e
8010
8011 var j = 0, k
8012
8013 function calcW () { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) }
8014 function loop (w, f) {
8015 W[j] = w
8016
8017 var t = rol(a, 5) + f + e + w + k
8018
8019 e = d
8020 d = c
8021 c = rol(b, 30)
8022 b = a
8023 a = t
8024 j++
8025 }
8026
8027 k = 1518500249
8028 while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d))
8029 while (j < 20) loop(calcW(), (b & c) | ((~b) & d))
8030 k = 1859775393
8031 while (j < 40) loop(calcW(), b ^ c ^ d)
8032 k = -1894007588
8033 while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d))
8034 k = -899497514
8035 while (j < 80) loop(calcW(), b ^ c ^ d)
8036
8037 this._a = (a + this._a) | 0
8038 this._b = (b + this._b) | 0
8039 this._c = (c + this._c) | 0
8040 this._d = (d + this._d) | 0
8041 this._e = (e + this._e) | 0
8042}
8043
8044Sha1.prototype._hash = function () {
8045 var H = new Buffer(20)
8046
8047 H.writeInt32BE(this._a | 0, 0)
8048 H.writeInt32BE(this._b | 0, 4)
8049 H.writeInt32BE(this._c | 0, 8)
8050 H.writeInt32BE(this._d | 0, 12)
8051 H.writeInt32BE(this._e | 0, 16)
8052
8053 return H
8054}
8055
8056module.exports = Sha1
8057
8058}).call(this,require("buffer").Buffer)
8059},{"./hash":37,"buffer":7,"inherits":35}],41:[function(require,module,exports){
8060(function (Buffer){
8061/**
8062 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
8063 * in FIPS 180-2
8064 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
8065 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
8066 *
8067 */
8068
8069var inherits = require('inherits')
8070var Sha256 = require('./sha256')
8071var Hash = require('./hash')
8072
8073var W = new Array(64)
8074
8075function Sha224 () {
8076 this.init()
8077
8078 this._w = W // new Array(64)
8079
8080 Hash.call(this, 64, 56)
8081}
8082
8083inherits(Sha224, Sha256)
8084
8085Sha224.prototype.init = function () {
8086 this._a = 0xc1059ed8 | 0
8087 this._b = 0x367cd507 | 0
8088 this._c = 0x3070dd17 | 0
8089 this._d = 0xf70e5939 | 0
8090 this._e = 0xffc00b31 | 0
8091 this._f = 0x68581511 | 0
8092 this._g = 0x64f98fa7 | 0
8093 this._h = 0xbefa4fa4 | 0
8094
8095 return this
8096}
8097
8098Sha224.prototype._hash = function () {
8099 var H = new Buffer(28)
8100
8101 H.writeInt32BE(this._a, 0)
8102 H.writeInt32BE(this._b, 4)
8103 H.writeInt32BE(this._c, 8)
8104 H.writeInt32BE(this._d, 12)
8105 H.writeInt32BE(this._e, 16)
8106 H.writeInt32BE(this._f, 20)
8107 H.writeInt32BE(this._g, 24)
8108
8109 return H
8110}
8111
8112module.exports = Sha224
8113
8114}).call(this,require("buffer").Buffer)
8115},{"./hash":37,"./sha256":42,"buffer":7,"inherits":35}],42:[function(require,module,exports){
8116(function (Buffer){
8117/**
8118 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
8119 * in FIPS 180-2
8120 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
8121 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
8122 *
8123 */
8124
8125var inherits = require('inherits')
8126var Hash = require('./hash')
8127
8128var K = [
8129 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
8130 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
8131 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
8132 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
8133 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
8134 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
8135 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
8136 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
8137 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
8138 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
8139 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
8140 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
8141 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
8142 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
8143 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
8144 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
8145]
8146
8147var W = new Array(64)
8148
8149function Sha256 () {
8150 this.init()
8151
8152 this._w = W // new Array(64)
8153
8154 Hash.call(this, 64, 56)
8155}
8156
8157inherits(Sha256, Hash)
8158
8159Sha256.prototype.init = function () {
8160 this._a = 0x6a09e667 | 0
8161 this._b = 0xbb67ae85 | 0
8162 this._c = 0x3c6ef372 | 0
8163 this._d = 0xa54ff53a | 0
8164 this._e = 0x510e527f | 0
8165 this._f = 0x9b05688c | 0
8166 this._g = 0x1f83d9ab | 0
8167 this._h = 0x5be0cd19 | 0
8168
8169 return this
8170}
8171
8172function S (X, n) {
8173 return (X >>> n) | (X << (32 - n))
8174}
8175
8176function R (X, n) {
8177 return (X >>> n)
8178}
8179
8180function Ch (x, y, z) {
8181 return ((x & y) ^ ((~x) & z))
8182}
8183
8184function Maj (x, y, z) {
8185 return ((x & y) ^ (x & z) ^ (y & z))
8186}
8187
8188function Sigma0256 (x) {
8189 return (S(x, 2) ^ S(x, 13) ^ S(x, 22))
8190}
8191
8192function Sigma1256 (x) {
8193 return (S(x, 6) ^ S(x, 11) ^ S(x, 25))
8194}
8195
8196function Gamma0256 (x) {
8197 return (S(x, 7) ^ S(x, 18) ^ R(x, 3))
8198}
8199
8200function Gamma1256 (x) {
8201 return (S(x, 17) ^ S(x, 19) ^ R(x, 10))
8202}
8203
8204Sha256.prototype._update = function (M) {
8205 var W = this._w
8206
8207 var a = this._a | 0
8208 var b = this._b | 0
8209 var c = this._c | 0
8210 var d = this._d | 0
8211 var e = this._e | 0
8212 var f = this._f | 0
8213 var g = this._g | 0
8214 var h = this._h | 0
8215
8216 var j = 0
8217
8218 function calcW () { return Gamma1256(W[j - 2]) + W[j - 7] + Gamma0256(W[j - 15]) + W[j - 16] }
8219 function loop (w) {
8220 W[j] = w
8221
8222 var T1 = h + Sigma1256(e) + Ch(e, f, g) + K[j] + w
8223 var T2 = Sigma0256(a) + Maj(a, b, c)
8224
8225 h = g
8226 g = f
8227 f = e
8228 e = d + T1
8229 d = c
8230 c = b
8231 b = a
8232 a = T1 + T2
8233
8234 j++
8235 }
8236
8237 while (j < 16) loop(M.readInt32BE(j * 4))
8238 while (j < 64) loop(calcW())
8239
8240 this._a = (a + this._a) | 0
8241 this._b = (b + this._b) | 0
8242 this._c = (c + this._c) | 0
8243 this._d = (d + this._d) | 0
8244 this._e = (e + this._e) | 0
8245 this._f = (f + this._f) | 0
8246 this._g = (g + this._g) | 0
8247 this._h = (h + this._h) | 0
8248}
8249
8250Sha256.prototype._hash = function () {
8251 var H = new Buffer(32)
8252
8253 H.writeInt32BE(this._a, 0)
8254 H.writeInt32BE(this._b, 4)
8255 H.writeInt32BE(this._c, 8)
8256 H.writeInt32BE(this._d, 12)
8257 H.writeInt32BE(this._e, 16)
8258 H.writeInt32BE(this._f, 20)
8259 H.writeInt32BE(this._g, 24)
8260 H.writeInt32BE(this._h, 28)
8261
8262 return H
8263}
8264
8265module.exports = Sha256
8266
8267}).call(this,require("buffer").Buffer)
8268},{"./hash":37,"buffer":7,"inherits":35}],43:[function(require,module,exports){
8269(function (Buffer){
8270var inherits = require('inherits')
8271var SHA512 = require('./sha512')
8272var Hash = require('./hash')
8273
8274var W = new Array(160)
8275
8276function Sha384 () {
8277 this.init()
8278 this._w = W
8279
8280 Hash.call(this, 128, 112)
8281}
8282
8283inherits(Sha384, SHA512)
8284
8285Sha384.prototype.init = function () {
8286 this._a = 0xcbbb9d5d | 0
8287 this._b = 0x629a292a | 0
8288 this._c = 0x9159015a | 0
8289 this._d = 0x152fecd8 | 0
8290 this._e = 0x67332667 | 0
8291 this._f = 0x8eb44a87 | 0
8292 this._g = 0xdb0c2e0d | 0
8293 this._h = 0x47b5481d | 0
8294
8295 this._al = 0xc1059ed8 | 0
8296 this._bl = 0x367cd507 | 0
8297 this._cl = 0x3070dd17 | 0
8298 this._dl = 0xf70e5939 | 0
8299 this._el = 0xffc00b31 | 0
8300 this._fl = 0x68581511 | 0
8301 this._gl = 0x64f98fa7 | 0
8302 this._hl = 0xbefa4fa4 | 0
8303
8304 return this
8305}
8306
8307Sha384.prototype._hash = function () {
8308 var H = new Buffer(48)
8309
8310 function writeInt64BE (h, l, offset) {
8311 H.writeInt32BE(h, offset)
8312 H.writeInt32BE(l, offset + 4)
8313 }
8314
8315 writeInt64BE(this._a, this._al, 0)
8316 writeInt64BE(this._b, this._bl, 8)
8317 writeInt64BE(this._c, this._cl, 16)
8318 writeInt64BE(this._d, this._dl, 24)
8319 writeInt64BE(this._e, this._el, 32)
8320 writeInt64BE(this._f, this._fl, 40)
8321
8322 return H
8323}
8324
8325module.exports = Sha384
8326
8327}).call(this,require("buffer").Buffer)
8328},{"./hash":37,"./sha512":44,"buffer":7,"inherits":35}],44:[function(require,module,exports){
8329(function (Buffer){
8330var inherits = require('inherits')
8331var Hash = require('./hash')
8332
8333var K = [
8334 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
8335 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
8336 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
8337 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
8338 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
8339 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
8340 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
8341 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
8342 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
8343 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
8344 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
8345 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
8346 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
8347 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
8348 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
8349 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
8350 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
8351 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
8352 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
8353 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
8354 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
8355 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
8356 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
8357 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
8358 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
8359 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
8360 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
8361 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
8362 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
8363 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
8364 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
8365 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
8366 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
8367 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
8368 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
8369 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
8370 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
8371 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
8372 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
8373 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
8374]
8375
8376var W = new Array(160)
8377
8378function Sha512 () {
8379 this.init()
8380 this._w = W
8381
8382 Hash.call(this, 128, 112)
8383}
8384
8385inherits(Sha512, Hash)
8386
8387Sha512.prototype.init = function () {
8388 this._a = 0x6a09e667 | 0
8389 this._b = 0xbb67ae85 | 0
8390 this._c = 0x3c6ef372 | 0
8391 this._d = 0xa54ff53a | 0
8392 this._e = 0x510e527f | 0
8393 this._f = 0x9b05688c | 0
8394 this._g = 0x1f83d9ab | 0
8395 this._h = 0x5be0cd19 | 0
8396
8397 this._al = 0xf3bcc908 | 0
8398 this._bl = 0x84caa73b | 0
8399 this._cl = 0xfe94f82b | 0
8400 this._dl = 0x5f1d36f1 | 0
8401 this._el = 0xade682d1 | 0
8402 this._fl = 0x2b3e6c1f | 0
8403 this._gl = 0xfb41bd6b | 0
8404 this._hl = 0x137e2179 | 0
8405
8406 return this
8407}
8408
8409function S (X, Xl, n) {
8410 return (X >>> n) | (Xl << (32 - n))
8411}
8412
8413function Ch (x, y, z) {
8414 return ((x & y) ^ ((~x) & z))
8415}
8416
8417function Maj (x, y, z) {
8418 return ((x & y) ^ (x & z) ^ (y & z))
8419}
8420
8421Sha512.prototype._update = function (M) {
8422 var W = this._w
8423
8424 var a = this._a | 0
8425 var b = this._b | 0
8426 var c = this._c | 0
8427 var d = this._d | 0
8428 var e = this._e | 0
8429 var f = this._f | 0
8430 var g = this._g | 0
8431 var h = this._h | 0
8432
8433 var al = this._al | 0
8434 var bl = this._bl | 0
8435 var cl = this._cl | 0
8436 var dl = this._dl | 0
8437 var el = this._el | 0
8438 var fl = this._fl | 0
8439 var gl = this._gl | 0
8440 var hl = this._hl | 0
8441
8442 var i = 0, j = 0
8443 var Wi, Wil
8444 function calcW () {
8445 var x = W[j - 15 * 2]
8446 var xl = W[j - 15 * 2 + 1]
8447 var gamma0 = S(x, xl, 1) ^ S(x, xl, 8) ^ (x >>> 7)
8448 var gamma0l = S(xl, x, 1) ^ S(xl, x, 8) ^ S(xl, x, 7)
8449
8450 x = W[j - 2 * 2]
8451 xl = W[j - 2 * 2 + 1]
8452 var gamma1 = S(x, xl, 19) ^ S(xl, x, 29) ^ (x >>> 6)
8453 var gamma1l = S(xl, x, 19) ^ S(x, xl, 29) ^ S(xl, x, 6)
8454
8455 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
8456 var Wi7 = W[j - 7 * 2]
8457 var Wi7l = W[j - 7 * 2 + 1]
8458
8459 var Wi16 = W[j - 16 * 2]
8460 var Wi16l = W[j - 16 * 2 + 1]
8461
8462 Wil = gamma0l + Wi7l
8463 Wi = gamma0 + Wi7 + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0)
8464 Wil = Wil + gamma1l
8465 Wi = Wi + gamma1 + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0)
8466 Wil = Wil + Wi16l
8467 Wi = Wi + Wi16 + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0)
8468 }
8469
8470 function loop () {
8471 W[j] = Wi
8472 W[j + 1] = Wil
8473
8474 var maj = Maj(a, b, c)
8475 var majl = Maj(al, bl, cl)
8476
8477 var sigma0h = S(a, al, 28) ^ S(al, a, 2) ^ S(al, a, 7)
8478 var sigma0l = S(al, a, 28) ^ S(a, al, 2) ^ S(a, al, 7)
8479 var sigma1h = S(e, el, 14) ^ S(e, el, 18) ^ S(el, e, 9)
8480 var sigma1l = S(el, e, 14) ^ S(el, e, 18) ^ S(e, el, 9)
8481
8482 // t1 = h + sigma1 + ch + K[i] + W[i]
8483 var Ki = K[j]
8484 var Kil = K[j + 1]
8485
8486 var ch = Ch(e, f, g)
8487 var chl = Ch(el, fl, gl)
8488
8489 var t1l = hl + sigma1l
8490 var t1 = h + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0)
8491 t1l = t1l + chl
8492 t1 = t1 + ch + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0)
8493 t1l = t1l + Kil
8494 t1 = t1 + Ki + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0)
8495 t1l = t1l + Wil
8496 t1 = t1 + Wi + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0)
8497
8498 // t2 = sigma0 + maj
8499 var t2l = sigma0l + majl
8500 var t2 = sigma0h + maj + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0)
8501
8502 h = g
8503 hl = gl
8504 g = f
8505 gl = fl
8506 f = e
8507 fl = el
8508 el = (dl + t1l) | 0
8509 e = (d + t1 + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
8510 d = c
8511 dl = cl
8512 c = b
8513 cl = bl
8514 b = a
8515 bl = al
8516 al = (t1l + t2l) | 0
8517 a = (t1 + t2 + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0
8518
8519 i++
8520 j += 2
8521 }
8522
8523 while (i < 16) {
8524 Wi = M.readInt32BE(j * 4)
8525 Wil = M.readInt32BE(j * 4 + 4)
8526
8527 loop()
8528 }
8529
8530 while (i < 80) {
8531 calcW()
8532 loop()
8533 }
8534
8535 this._al = (this._al + al) | 0
8536 this._bl = (this._bl + bl) | 0
8537 this._cl = (this._cl + cl) | 0
8538 this._dl = (this._dl + dl) | 0
8539 this._el = (this._el + el) | 0
8540 this._fl = (this._fl + fl) | 0
8541 this._gl = (this._gl + gl) | 0
8542 this._hl = (this._hl + hl) | 0
8543
8544 this._a = (this._a + a + ((this._al >>> 0) < (al >>> 0) ? 1 : 0)) | 0
8545 this._b = (this._b + b + ((this._bl >>> 0) < (bl >>> 0) ? 1 : 0)) | 0
8546 this._c = (this._c + c + ((this._cl >>> 0) < (cl >>> 0) ? 1 : 0)) | 0
8547 this._d = (this._d + d + ((this._dl >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
8548 this._e = (this._e + e + ((this._el >>> 0) < (el >>> 0) ? 1 : 0)) | 0
8549 this._f = (this._f + f + ((this._fl >>> 0) < (fl >>> 0) ? 1 : 0)) | 0
8550 this._g = (this._g + g + ((this._gl >>> 0) < (gl >>> 0) ? 1 : 0)) | 0
8551 this._h = (this._h + h + ((this._hl >>> 0) < (hl >>> 0) ? 1 : 0)) | 0
8552}
8553
8554Sha512.prototype._hash = function () {
8555 var H = new Buffer(64)
8556
8557 function writeInt64BE (h, l, offset) {
8558 H.writeInt32BE(h, offset)
8559 H.writeInt32BE(l, offset + 4)
8560 }
8561
8562 writeInt64BE(this._a, this._al, 0)
8563 writeInt64BE(this._b, this._bl, 8)
8564 writeInt64BE(this._c, this._cl, 16)
8565 writeInt64BE(this._d, this._dl, 24)
8566 writeInt64BE(this._e, this._el, 32)
8567 writeInt64BE(this._f, this._fl, 40)
8568 writeInt64BE(this._g, this._gl, 48)
8569 writeInt64BE(this._h, this._hl, 56)
8570
8571 return H
8572}
8573
8574module.exports = Sha512
8575
8576}).call(this,require("buffer").Buffer)
8577},{"./hash":37,"buffer":7,"inherits":35}],45:[function(require,module,exports){
8578(function (Buffer){
8579'use strict';
8580var createHash = require('create-hash/browser');
8581var inherits = require('inherits')
8582
8583var Transform = require('stream').Transform
8584
8585var ZEROS = new Buffer(128)
8586ZEROS.fill(0)
8587
8588function Hmac(alg, key) {
8589 Transform.call(this)
8590
8591 if (typeof key === 'string') {
8592 key = new Buffer(key)
8593 }
8594
8595 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
8596
8597 this._alg = alg
8598 this._key = key
8599
8600 if (key.length > blocksize) {
8601 key = createHash(alg).update(key).digest()
8602
8603 } else if (key.length < blocksize) {
8604 key = Buffer.concat([key, ZEROS], blocksize)
8605 }
8606
8607 var ipad = this._ipad = new Buffer(blocksize)
8608 var opad = this._opad = new Buffer(blocksize)
8609
8610 for (var i = 0; i < blocksize; i++) {
8611 ipad[i] = key[i] ^ 0x36
8612 opad[i] = key[i] ^ 0x5C
8613 }
8614
8615 this._hash = createHash(alg).update(ipad)
8616}
8617
8618inherits(Hmac, Transform)
8619
8620Hmac.prototype.update = function (data, enc) {
8621 this._hash.update(data, enc)
8622
8623 return this
8624}
8625
8626Hmac.prototype._transform = function (data, _, next) {
8627 this._hash.update(data)
8628
8629 next()
8630}
8631
8632Hmac.prototype._flush = function (next) {
8633 this.push(this.digest())
8634
8635 next()
8636}
8637
8638Hmac.prototype.digest = function (enc) {
8639 var h = this._hash.digest()
8640
8641 return createHash(this._alg).update(this._opad).update(h).digest(enc)
8642}
8643
8644module.exports = function createHmac(alg, key) {
8645 return new Hmac(alg, key)
8646}
8647
8648}).call(this,require("buffer").Buffer)
8649},{"buffer":7,"create-hash/browser":32,"inherits":46,"stream":26}],46:[function(require,module,exports){
8650arguments[4][12][0].apply(exports,arguments)
8651},{"dup":12}],47:[function(require,module,exports){
8652var assert = require('assert')
8653var BigInteger = require('bigi')
8654
8655var Point = require('./point')
8656
8657function Curve(p, a, b, Gx, Gy, n, h) {
8658 this.p = p
8659 this.a = a
8660 this.b = b
8661 this.G = Point.fromAffine(this, Gx, Gy)
8662 this.n = n
8663 this.h = h
8664
8665 this.infinity = new Point(this, null, null, BigInteger.ZERO)
8666
8667 // result caching
8668 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
8669}
8670
8671Curve.prototype.pointFromX = function(isOdd, x) {
8672 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
8673 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves
8674
8675 var y = beta
8676 if (beta.isEven() ^ !isOdd) {
8677 y = this.p.subtract(y) // -y % p
8678 }
8679
8680 return Point.fromAffine(this, x, y)
8681}
8682
8683Curve.prototype.isInfinity = function(Q) {
8684 if (Q === this.infinity) return true
8685
8686 return Q.z.signum() === 0 && Q.y.signum() !== 0
8687}
8688
8689Curve.prototype.isOnCurve = function(Q) {
8690 if (this.isInfinity(Q)) return true
8691
8692 var x = Q.affineX
8693 var y = Q.affineY
8694 var a = this.a
8695 var b = this.b
8696 var p = this.p
8697
8698 // Check that xQ and yQ are integers in the interval [0, p - 1]
8699 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
8700 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
8701
8702 // and check that y^2 = x^3 + ax + b (mod p)
8703 var lhs = y.square().mod(p)
8704 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
8705 return lhs.equals(rhs)
8706}
8707
8708/**
8709 * Validate an elliptic curve point.
8710 *
8711 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
8712 */
8713Curve.prototype.validate = function(Q) {
8714 // Check Q != O
8715 assert(!this.isInfinity(Q), 'Point is at infinity')
8716 assert(this.isOnCurve(Q), 'Point is not on the curve')
8717
8718 // Check nQ = O (where Q is a scalar multiple of G)
8719 var nQ = Q.multiply(this.n)
8720 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
8721
8722 return true
8723}
8724
8725module.exports = Curve
8726
8727},{"./point":51,"assert":5,"bigi":3}],48:[function(require,module,exports){
8728module.exports={
8729 "secp128r1": {
8730 "p": "fffffffdffffffffffffffffffffffff",
8731 "a": "fffffffdfffffffffffffffffffffffc",
8732 "b": "e87579c11079f43dd824993c2cee5ed3",
8733 "n": "fffffffe0000000075a30d1b9038a115",
8734 "h": "01",
8735 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
8736 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
8737 },
8738 "secp160k1": {
8739 "p": "fffffffffffffffffffffffffffffffeffffac73",
8740 "a": "00",
8741 "b": "07",
8742 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
8743 "h": "01",
8744 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
8745 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
8746 },
8747 "secp160r1": {
8748 "p": "ffffffffffffffffffffffffffffffff7fffffff",
8749 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
8750 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
8751 "n": "0100000000000000000001f4c8f927aed3ca752257",
8752 "h": "01",
8753 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
8754 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
8755 },
8756 "secp192k1": {
8757 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
8758 "a": "00",
8759 "b": "03",
8760 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
8761 "h": "01",
8762 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
8763 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
8764 },
8765 "secp192r1": {
8766 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
8767 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
8768 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
8769 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
8770 "h": "01",
8771 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
8772 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
8773 },
8774 "secp256k1": {
8775 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
8776 "a": "00",
8777 "b": "07",
8778 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
8779 "h": "01",
8780 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
8781 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
8782 },
8783 "secp256r1": {
8784 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
8785 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
8786 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
8787 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
8788 "h": "01",
8789 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
8790 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
8791 }
8792}
8793
8794},{}],49:[function(require,module,exports){
8795var Point = require('./point')
8796var Curve = require('./curve')
8797
8798var getCurveByName = require('./names')
8799
8800module.exports = {
8801 Curve: Curve,
8802 Point: Point,
8803 getCurveByName: getCurveByName
8804}
8805
8806},{"./curve":47,"./names":50,"./point":51}],50:[function(require,module,exports){
8807var BigInteger = require('bigi')
8808
8809var curves = require('./curves')
8810var Curve = require('./curve')
8811
8812function getCurveByName(name) {
8813 var curve = curves[name]
8814 if (!curve) return null
8815
8816 var p = new BigInteger(curve.p, 16)
8817 var a = new BigInteger(curve.a, 16)
8818 var b = new BigInteger(curve.b, 16)
8819 var n = new BigInteger(curve.n, 16)
8820 var h = new BigInteger(curve.h, 16)
8821 var Gx = new BigInteger(curve.Gx, 16)
8822 var Gy = new BigInteger(curve.Gy, 16)
8823
8824 return new Curve(p, a, b, Gx, Gy, n, h)
8825}
8826
8827module.exports = getCurveByName
8828
8829},{"./curve":47,"./curves":48,"bigi":3}],51:[function(require,module,exports){
8830(function (Buffer){
8831var assert = require('assert')
8832var BigInteger = require('bigi')
8833
8834var THREE = BigInteger.valueOf(3)
8835
8836function Point(curve, x, y, z) {
8837 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
8838
8839 this.curve = curve
8840 this.x = x
8841 this.y = y
8842 this.z = z
8843 this._zInv = null
8844
8845 this.compressed = true
8846}
8847
8848Object.defineProperty(Point.prototype, 'zInv', {
8849 get: function() {
8850 if (this._zInv === null) {
8851 this._zInv = this.z.modInverse(this.curve.p)
8852 }
8853
8854 return this._zInv
8855 }
8856})
8857
8858Object.defineProperty(Point.prototype, 'affineX', {
8859 get: function() {
8860 return this.x.multiply(this.zInv).mod(this.curve.p)
8861 }
8862})
8863
8864Object.defineProperty(Point.prototype, 'affineY', {
8865 get: function() {
8866 return this.y.multiply(this.zInv).mod(this.curve.p)
8867 }
8868})
8869
8870Point.fromAffine = function(curve, x, y) {
8871 return new Point(curve, x, y, BigInteger.ONE)
8872}
8873
8874Point.prototype.equals = function(other) {
8875 if (other === this) return true
8876 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
8877 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
8878
8879 // u = Y2 * Z1 - Y1 * Z2
8880 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
8881
8882 if (u.signum() !== 0) return false
8883
8884 // v = X2 * Z1 - X1 * Z2
8885 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
8886
8887 return v.signum() === 0
8888}
8889
8890Point.prototype.negate = function() {
8891 var y = this.curve.p.subtract(this.y)
8892
8893 return new Point(this.curve, this.x, y, this.z)
8894}
8895
8896Point.prototype.add = function(b) {
8897 if (this.curve.isInfinity(this)) return b
8898 if (this.curve.isInfinity(b)) return this
8899
8900 var x1 = this.x
8901 var y1 = this.y
8902 var x2 = b.x
8903 var y2 = b.y
8904
8905 // u = Y2 * Z1 - Y1 * Z2
8906 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
8907 // v = X2 * Z1 - X1 * Z2
8908 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
8909
8910 if (v.signum() === 0) {
8911 if (u.signum() === 0) {
8912 return this.twice() // this == b, so double
8913 }
8914
8915 return this.curve.infinity // this = -b, so infinity
8916 }
8917
8918 var v2 = v.square()
8919 var v3 = v2.multiply(v)
8920 var x1v2 = x1.multiply(v2)
8921 var zu2 = u.square().multiply(this.z)
8922
8923 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
8924 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
8925 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
8926 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p)
8927 // z3 = v^3 * z1 * z2
8928 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
8929
8930 return new Point(this.curve, x3, y3, z3)
8931}
8932
8933Point.prototype.twice = function() {
8934 if (this.curve.isInfinity(this)) return this
8935 if (this.y.signum() === 0) return this.curve.infinity
8936
8937 var x1 = this.x
8938 var y1 = this.y
8939
8940 var y1z1 = y1.multiply(this.z)
8941 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
8942 var a = this.curve.a
8943
8944 // w = 3 * x1^2 + a * z1^2
8945 var w = x1.square().multiply(THREE)
8946
8947 if (a.signum() !== 0) {
8948 w = w.add(this.z.square().multiply(a))
8949 }
8950
8951 w = w.mod(this.curve.p)
8952 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
8953 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
8954 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
8955 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
8956 // z3 = 8 * (y1 * z1)^3
8957 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
8958
8959 return new Point(this.curve, x3, y3, z3)
8960}
8961
8962// Simple NAF (Non-Adjacent Form) multiplication algorithm
8963// TODO: modularize the multiplication algorithm
8964Point.prototype.multiply = function(k) {
8965 if (this.curve.isInfinity(this)) return this
8966 if (k.signum() === 0) return this.curve.infinity
8967
8968 var e = k
8969 var h = e.multiply(THREE)
8970
8971 var neg = this.negate()
8972 var R = this
8973
8974 for (var i = h.bitLength() - 2; i > 0; --i) {
8975 R = R.twice()
8976
8977 var hBit = h.testBit(i)
8978 var eBit = e.testBit(i)
8979
8980 if (hBit != eBit) {
8981 R = R.add(hBit ? this : neg)
8982 }
8983 }
8984
8985 return R
8986}
8987
8988// Compute this*j + x*k (simultaneous multiplication)
8989Point.prototype.multiplyTwo = function(j, x, k) {
8990 var i
8991
8992 if (j.bitLength() > k.bitLength())
8993 i = j.bitLength() - 1
8994 else
8995 i = k.bitLength() - 1
8996
8997 var R = this.curve.infinity
8998 var both = this.add(x)
8999
9000 while (i >= 0) {
9001 R = R.twice()
9002
9003 var jBit = j.testBit(i)
9004 var kBit = k.testBit(i)
9005
9006 if (jBit) {
9007 if (kBit) {
9008 R = R.add(both)
9009
9010 } else {
9011 R = R.add(this)
9012 }
9013
9014 } else {
9015 if (kBit) {
9016 R = R.add(x)
9017 }
9018 }
9019 --i
9020 }
9021
9022 return R
9023}
9024
9025Point.prototype.getEncoded = function(compressed) {
9026 if (compressed == undefined) compressed = this.compressed
9027 if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00'
9028
9029 var x = this.affineX
9030 var y = this.affineY
9031
9032 var buffer
9033
9034 // Determine size of q in bytes
9035 var byteLength = Math.floor((this.curve.p.bitLength() + 7) / 8)
9036
9037 // 0x02/0x03 | X
9038 if (compressed) {
9039 buffer = new Buffer(1 + byteLength)
9040 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
9041
9042 // 0x04 | X | Y
9043 } else {
9044 buffer = new Buffer(1 + byteLength + byteLength)
9045 buffer.writeUInt8(0x04, 0)
9046
9047 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
9048 }
9049
9050 x.toBuffer(byteLength).copy(buffer, 1)
9051
9052 return buffer
9053}
9054
9055Point.decodeFrom = function(curve, buffer) {
9056 var type = buffer.readUInt8(0)
9057 var compressed = (type !== 4)
9058
9059 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
9060 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength))
9061
9062 var Q
9063 if (compressed) {
9064 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
9065 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
9066
9067 var isOdd = (type === 0x03)
9068 Q = curve.pointFromX(isOdd, x)
9069
9070 } else {
9071 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
9072
9073 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
9074 Q = Point.fromAffine(curve, x, y)
9075 }
9076
9077 Q.compressed = compressed
9078 return Q
9079}
9080
9081Point.prototype.toString = function () {
9082 if (this.curve.isInfinity(this)) return '(INFINITY)'
9083
9084 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
9085}
9086
9087module.exports = Point
9088
9089}).call(this,require("buffer").Buffer)
9090},{"assert":5,"bigi":3,"buffer":7}],52:[function(require,module,exports){
9091(function (process,global,Buffer){
9092'use strict';
9093
9094var crypto = global.crypto || global.msCrypto
9095if(crypto && crypto.getRandomValues) {
9096 module.exports = randomBytes;
9097} else {
9098 module.exports = oldBrowser;
9099}
9100function randomBytes(size, cb) {
9101 var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
9102 /* This will not work in older browsers.
9103 * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
9104 */
9105
9106 crypto.getRandomValues(bytes);
9107 if (typeof cb === 'function') {
9108 return process.nextTick(function () {
9109 cb(null, bytes);
9110 });
9111 }
9112 return bytes;
9113}
9114function oldBrowser() {
9115 throw new Error(
9116 'secure random number generation not supported by this browser\n'+
9117 'use chrome, FireFox or Internet Explorer 11'
9118 )
9119}
9120
9121}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
9122},{"_process":14,"buffer":7}],53:[function(require,module,exports){
9123(function (Buffer){
9124'use strict';
9125
9126function getFunctionName(fn) {
9127 return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1];
9128}
9129
9130function getTypeTypeName(type) {
9131 if (nativeTypes.Function(type)) {
9132 type = type.toJSON ? type.toJSON() : getFunctionName(type);
9133 }
9134 if (nativeTypes.Object(type)) return JSON.stringify(type);
9135
9136 return type;
9137}
9138
9139function getValueTypeName(value) {
9140 if (nativeTypes.Null(value)) return '';
9141
9142 return getFunctionName(value.constructor);
9143}
9144
9145function tfErrorString(type, value) {
9146 var typeTypeName = getTypeTypeName(type);
9147 var valueTypeName = getValueTypeName(value);
9148
9149 return 'Expected ' + typeTypeName + ', got ' + (valueTypeName && valueTypeName + ' ') + JSON.stringify(value);
9150}
9151
9152function tfPropertyErrorString(type, name, value) {
9153 return tfErrorString('property \"' + name + '\" of type ' + getTypeTypeName(type), value);
9154}
9155
9156var nativeTypes = {
9157 Array: (function (_Array) {
9158 function Array(_x) {
9159 return _Array.apply(this, arguments);
9160 }
9161
9162 Array.toString = function () {
9163 return _Array.toString();
9164 };
9165
9166 return Array;
9167 })(function (value) {
9168 return value !== null && value !== undefined && value.constructor === Array;
9169 }),
9170 Boolean: function Boolean(value) {
9171 return typeof value === 'boolean';
9172 },
9173 Buffer: (function (_Buffer) {
9174 function Buffer(_x2) {
9175 return _Buffer.apply(this, arguments);
9176 }
9177
9178 Buffer.toString = function () {
9179 return _Buffer.toString();
9180 };
9181
9182 return Buffer;
9183 })(function (value) {
9184 return Buffer.isBuffer(value);
9185 }),
9186 Function: function Function(value) {
9187 return typeof value === 'function';
9188 },
9189 Null: function Null(value) {
9190 return value === undefined || value === null;
9191 },
9192 Number: function Number(value) {
9193 return typeof value === 'number';
9194 },
9195 Object: function Object(value) {
9196 return typeof value === 'object';
9197 },
9198 String: function String(value) {
9199 return typeof value === 'string';
9200 },
9201 '': function _() {
9202 return true;
9203 }
9204};
9205
9206function tJSON(type) {
9207 return type && type.toJSON ? type.toJSON() : type;
9208}
9209
9210function sJSON(type) {
9211 var json = tJSON(type);
9212 return nativeTypes.Object(json) ? JSON.stringify(json) : json;
9213}
9214
9215var otherTypes = {
9216 arrayOf: function arrayOf(type) {
9217 function arrayOf(value, strict) {
9218 try {
9219 return nativeTypes.Array(value) && value.every(function (x) {
9220 return typeforce(type, x, strict);
9221 });
9222 } catch (e) {
9223 return false;
9224 }
9225 }
9226 arrayOf.toJSON = function () {
9227 return [tJSON(type)];
9228 };
9229
9230 return arrayOf;
9231 },
9232
9233 maybe: function maybe(type) {
9234 function maybe(value, strict) {
9235 return nativeTypes.Null(value) || typeforce(type, value, strict);
9236 }
9237 maybe.toJSON = function () {
9238 return '?' + sJSON(type);
9239 };
9240
9241 return maybe;
9242 },
9243
9244 object: function object(type) {
9245 function object(value, strict) {
9246 typeforce(nativeTypes.Object, value, strict);
9247
9248 var propertyName, propertyType, propertyValue;
9249
9250 try {
9251 for (propertyName in type) {
9252 propertyType = type[propertyName];
9253 propertyValue = value[propertyName];
9254
9255 typeforce(propertyType, propertyValue, strict);
9256 }
9257 } catch (e) {
9258 throw new TypeError(tfPropertyErrorString(propertyType, propertyName, propertyValue));
9259 }
9260
9261 if (strict) {
9262 for (propertyName in value) {
9263 if (type[propertyName]) continue;
9264
9265 throw new TypeError('Unexpected property "' + propertyName + '"');
9266 }
9267 }
9268
9269 return true;
9270 }
9271 object.toJSON = function () {
9272 return type;
9273 };
9274
9275 return object;
9276 },
9277
9278 oneOf: function oneOf() {
9279 for (var _len = arguments.length, types = Array(_len), _key = 0; _key < _len; _key++) {
9280 types[_key] = arguments[_key];
9281 }
9282
9283 function oneOf(value, strict) {
9284 return types.some(function (type) {
9285 try {
9286 return typeforce(type, value, strict);
9287 } catch (e) {
9288 return false;
9289 }
9290 });
9291 }
9292 oneOf.toJSON = function () {
9293 return types.map(sJSON).join('|');
9294 };
9295
9296 return oneOf;
9297 },
9298
9299 quacksLike: function quacksLike(type) {
9300 function quacksLike(value, strict) {
9301 return type === getValueTypeName(value);
9302 }
9303 quacksLike.toJSON = function () {
9304 return type;
9305 };
9306
9307 return quacksLike;
9308 },
9309
9310 tuple: function tuple() {
9311 for (var _len2 = arguments.length, types = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
9312 types[_key2] = arguments[_key2];
9313 }
9314
9315 function tuple(value, strict) {
9316 return types.every(function (type, i) {
9317 return typeforce(type, value[i], strict);
9318 });
9319 }
9320 tuple.toJSON = function () {
9321 return '(' + types.map(sJSON).join(', ') + ')';
9322 };
9323
9324 return tuple;
9325 },
9326
9327 value: function value(expected) {
9328 function value(actual) {
9329 return actual === expected;
9330 }
9331 value.toJSON = function () {
9332 return expected;
9333 };
9334
9335 return value;
9336 }
9337};
9338
9339function compile(type) {
9340 if (nativeTypes.String(type)) {
9341 if (type[0] === '?') return otherTypes.maybe(compile(type.slice(1)));
9342
9343 return nativeTypes[type] || otherTypes.quacksLike(type);
9344 } else if (type && nativeTypes.Object(type)) {
9345 if (nativeTypes.Array(type)) return otherTypes.arrayOf(compile(type[0]));
9346
9347 var compiled = {};
9348
9349 for (var propertyName in type) {
9350 compiled[propertyName] = compile(type[propertyName]);
9351 }
9352
9353 return otherTypes.object(compiled);
9354 } else if (nativeTypes.Function(type)) {
9355 return type;
9356 }
9357
9358 return otherTypes.value(type);
9359}
9360
9361function typeforce(_x3, _x4, _x5) {
9362 var _again = true;
9363
9364 _function: while (_again) {
9365 var type = _x3,
9366 value = _x4,
9367 strict = _x5;
9368 _again = false;
9369
9370 if (nativeTypes.Function(type)) {
9371 if (type(value, strict)) return true;
9372
9373 throw new TypeError(tfErrorString(type, value));
9374 }
9375
9376 // JIT
9377 _x3 = compile(type);
9378 _x4 = value;
9379 _x5 = strict;
9380 _again = true;
9381 continue _function;
9382 }
9383}
9384
9385// assign all types to typeforce function
9386var typeName;
9387Object.keys(nativeTypes).forEach(function (typeName) {
9388 var nativeType = nativeTypes[typeName];
9389 nativeType.toJSON = function () {
9390 return typeName;
9391 };
9392
9393 typeforce[typeName] = nativeType;
9394});
9395
9396for (typeName in otherTypes) {
9397 typeforce[typeName] = otherTypes[typeName];
9398}
9399
9400module.exports = typeforce;
9401module.exports.compile = compile;
9402}).call(this,require("buffer").Buffer)
9403},{"buffer":7}],54:[function(require,module,exports){
9404(function (Buffer){
9405var assert = require('assert')
9406var base58check = require('bs58check')
9407var typeForce = require('typeforce')
9408var networks = require('./networks')
9409var scripts = require('./scripts')
9410
9411function findScriptTypeByVersion (version) {
9412 for (var networkName in networks) {
9413 var network = networks[networkName]
9414
9415 if (version === network.pubKeyHash) return 'pubkeyhash'
9416 if (version === network.scriptHash) return 'scripthash'
9417 }
9418}
9419
9420function Address (hash, version) {
9421 typeForce('Buffer', hash)
9422
9423 assert.strictEqual(hash.length, 20, 'Invalid hash length')
9424 assert.strictEqual(version & 0xff, version, 'Invalid version byte')
9425
9426 this.hash = hash
9427 this.version = version
9428}
9429
9430Address.fromBase58Check = function (string) {
9431 var payload = base58check.decode(string)
9432 var version = payload.readUInt8(0)
9433 var hash = payload.slice(1)
9434
9435 return new Address(hash, version)
9436}
9437
9438Address.fromOutputScript = function (script, network) {
9439 network = network || networks.bitcoin
9440
9441 if (scripts.isPubKeyHashOutput(script)) return new Address(script.chunks[2], network.pubKeyHash)
9442 if (scripts.isScriptHashOutput(script)) return new Address(script.chunks[1], network.scriptHash)
9443
9444 assert(false, script.toASM() + ' has no matching Address')
9445}
9446
9447Address.prototype.toBase58Check = function () {
9448 var payload = new Buffer(21)
9449 payload.writeUInt8(this.version, 0)
9450 this.hash.copy(payload, 1)
9451
9452 return base58check.encode(payload)
9453}
9454
9455Address.prototype.toOutputScript = function () {
9456 var scriptType = findScriptTypeByVersion(this.version)
9457
9458 if (scriptType === 'pubkeyhash') return scripts.pubKeyHashOutput(this.hash)
9459 if (scriptType === 'scripthash') return scripts.scriptHashOutput(this.hash)
9460
9461 assert(false, this.toString() + ' has no matching Script')
9462}
9463
9464Address.prototype.toString = Address.prototype.toBase58Check
9465
9466module.exports = Address
9467
9468}).call(this,require("buffer").Buffer)
9469},{"./networks":66,"./scripts":69,"assert":5,"bs58check":31,"buffer":7,"typeforce":53}],55:[function(require,module,exports){
9470var bs58check = require('bs58check')
9471
9472function decode () {
9473 console.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.')
9474
9475 return bs58check.decode.apply(undefined, arguments)
9476}
9477
9478function encode () {
9479 console.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.')
9480
9481 return bs58check.encode.apply(undefined, arguments)
9482}
9483
9484module.exports = {
9485 decode: decode,
9486 encode: encode
9487}
9488
9489},{"bs58check":31}],56:[function(require,module,exports){
9490(function (Buffer){
9491var assert = require('assert')
9492var bufferutils = require('./bufferutils')
9493var crypto = require('./crypto')
9494
9495var Transaction = require('./transaction')
9496
9497function Block () {
9498 this.version = 1
9499 this.prevHash = null
9500 this.merkleRoot = null
9501 this.timestamp = 0
9502 this.bits = 0
9503 this.nonce = 0
9504}
9505
9506Block.fromBuffer = function (buffer) {
9507 assert(buffer.length >= 80, 'Buffer too small (< 80 bytes)')
9508
9509 var offset = 0
9510 function readSlice (n) {
9511 offset += n
9512 return buffer.slice(offset - n, offset)
9513 }
9514
9515 function readUInt32 () {
9516 var i = buffer.readUInt32LE(offset)
9517 offset += 4
9518 return i
9519 }
9520
9521 var block = new Block()
9522 block.version = readUInt32()
9523 block.prevHash = readSlice(32)
9524 block.merkleRoot = readSlice(32)
9525 block.timestamp = readUInt32()
9526 block.bits = readUInt32()
9527 block.nonce = readUInt32()
9528
9529 if (buffer.length === 80) return block
9530
9531 function readVarInt () {
9532 var vi = bufferutils.readVarInt(buffer, offset)
9533 offset += vi.size
9534 return vi.number
9535 }
9536
9537 // FIXME: poor performance
9538 function readTransaction () {
9539 var tx = Transaction.fromBuffer(buffer.slice(offset), true)
9540
9541 offset += tx.toBuffer().length
9542 return tx
9543 }
9544
9545 var nTransactions = readVarInt()
9546 block.transactions = []
9547
9548 for (var i = 0; i < nTransactions; ++i) {
9549 var tx = readTransaction()
9550 block.transactions.push(tx)
9551 }
9552
9553 return block
9554}
9555
9556Block.fromHex = function (hex) {
9557 return Block.fromBuffer(new Buffer(hex, 'hex'))
9558}
9559
9560Block.prototype.getHash = function () {
9561 return crypto.hash256(this.toBuffer(true))
9562}
9563
9564Block.prototype.getId = function () {
9565 return bufferutils.reverse(this.getHash()).toString('hex')
9566}
9567
9568Block.prototype.getUTCDate = function () {
9569 var date = new Date(0) // epoch
9570 date.setUTCSeconds(this.timestamp)
9571
9572 return date
9573}
9574
9575Block.prototype.toBuffer = function (headersOnly) {
9576 var buffer = new Buffer(80)
9577
9578 var offset = 0
9579 function writeSlice (slice) {
9580 slice.copy(buffer, offset)
9581 offset += slice.length
9582 }
9583
9584 function writeUInt32 (i) {
9585 buffer.writeUInt32LE(i, offset)
9586 offset += 4
9587 }
9588
9589 writeUInt32(this.version)
9590 writeSlice(this.prevHash)
9591 writeSlice(this.merkleRoot)
9592 writeUInt32(this.timestamp)
9593 writeUInt32(this.bits)
9594 writeUInt32(this.nonce)
9595
9596 if (headersOnly || !this.transactions) return buffer
9597
9598 var txLenBuffer = bufferutils.varIntBuffer(this.transactions.length)
9599 var txBuffers = this.transactions.map(function (tx) {
9600 return tx.toBuffer()
9601 })
9602
9603 return Buffer.concat([buffer, txLenBuffer].concat(txBuffers))
9604}
9605
9606Block.prototype.toHex = function (headersOnly) {
9607 return this.toBuffer(headersOnly).toString('hex')
9608}
9609
9610module.exports = Block
9611
9612}).call(this,require("buffer").Buffer)
9613},{"./bufferutils":57,"./crypto":58,"./transaction":70,"assert":5,"buffer":7}],57:[function(require,module,exports){
9614(function (Buffer){
9615var assert = require('assert')
9616var opcodes = require('./opcodes')
9617
9618// https://github.com/feross/buffer/blob/master/index.js#L1127
9619function verifuint (value, max) {
9620 assert(typeof value === 'number', 'cannot write a non-number as a number')
9621 assert(value >= 0, 'specified a negative value for writing an unsigned value')
9622 assert(value <= max, 'value is larger than maximum value for type')
9623 assert(Math.floor(value) === value, 'value has a fractional component')
9624}
9625
9626function pushDataSize (i) {
9627 return i < opcodes.OP_PUSHDATA1 ? 1
9628 : i < 0xff ? 2
9629 : i < 0xffff ? 3
9630 : 5
9631}
9632
9633function readPushDataInt (buffer, offset) {
9634 var opcode = buffer.readUInt8(offset)
9635 var number, size
9636
9637 // ~6 bit
9638 if (opcode < opcodes.OP_PUSHDATA1) {
9639 number = opcode
9640 size = 1
9641
9642 // 8 bit
9643 } else if (opcode === opcodes.OP_PUSHDATA1) {
9644 if (offset + 2 > buffer.length) return null
9645 number = buffer.readUInt8(offset + 1)
9646 size = 2
9647
9648 // 16 bit
9649 } else if (opcode === opcodes.OP_PUSHDATA2) {
9650 if (offset + 3 > buffer.length) return null
9651 number = buffer.readUInt16LE(offset + 1)
9652 size = 3
9653
9654 // 32 bit
9655 } else {
9656 if (offset + 5 > buffer.length) return null
9657 assert.equal(opcode, opcodes.OP_PUSHDATA4, 'Unexpected opcode')
9658
9659 number = buffer.readUInt32LE(offset + 1)
9660 size = 5
9661 }
9662
9663 return {
9664 opcode: opcode,
9665 number: number,
9666 size: size
9667 }
9668}
9669
9670function readUInt64LE (buffer, offset) {
9671 var a = buffer.readUInt32LE(offset)
9672 var b = buffer.readUInt32LE(offset + 4)
9673 b *= 0x100000000
9674
9675 verifuint(b + a, 0x001fffffffffffff)
9676
9677 return b + a
9678}
9679
9680function readVarInt (buffer, offset) {
9681 var t = buffer.readUInt8(offset)
9682 var number, size
9683
9684 // 8 bit
9685 if (t < 253) {
9686 number = t
9687 size = 1
9688
9689 // 16 bit
9690 } else if (t < 254) {
9691 number = buffer.readUInt16LE(offset + 1)
9692 size = 3
9693
9694 // 32 bit
9695 } else if (t < 255) {
9696 number = buffer.readUInt32LE(offset + 1)
9697 size = 5
9698
9699 // 64 bit
9700 } else {
9701 number = readUInt64LE(buffer, offset + 1)
9702 size = 9
9703 }
9704
9705 return {
9706 number: number,
9707 size: size
9708 }
9709}
9710
9711function writePushDataInt (buffer, number, offset) {
9712 var size = pushDataSize(number)
9713
9714 // ~6 bit
9715 if (size === 1) {
9716 buffer.writeUInt8(number, offset)
9717
9718 // 8 bit
9719 } else if (size === 2) {
9720 buffer.writeUInt8(opcodes.OP_PUSHDATA1, offset)
9721 buffer.writeUInt8(number, offset + 1)
9722
9723 // 16 bit
9724 } else if (size === 3) {
9725 buffer.writeUInt8(opcodes.OP_PUSHDATA2, offset)
9726 buffer.writeUInt16LE(number, offset + 1)
9727
9728 // 32 bit
9729 } else {
9730 buffer.writeUInt8(opcodes.OP_PUSHDATA4, offset)
9731 buffer.writeUInt32LE(number, offset + 1)
9732 }
9733
9734 return size
9735}
9736
9737function writeUInt64LE (buffer, value, offset) {
9738 verifuint(value, 0x001fffffffffffff)
9739
9740 buffer.writeInt32LE(value & -1, offset)
9741 buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4)
9742}
9743
9744function varIntSize (i) {
9745 return i < 253 ? 1
9746 : i < 0x10000 ? 3
9747 : i < 0x100000000 ? 5
9748 : 9
9749}
9750
9751function writeVarInt (buffer, number, offset) {
9752 var size = varIntSize(number)
9753
9754 // 8 bit
9755 if (size === 1) {
9756 buffer.writeUInt8(number, offset)
9757
9758 // 16 bit
9759 } else if (size === 3) {
9760 buffer.writeUInt8(253, offset)
9761 buffer.writeUInt16LE(number, offset + 1)
9762
9763 // 32 bit
9764 } else if (size === 5) {
9765 buffer.writeUInt8(254, offset)
9766 buffer.writeUInt32LE(number, offset + 1)
9767
9768 // 64 bit
9769 } else {
9770 buffer.writeUInt8(255, offset)
9771 writeUInt64LE(buffer, number, offset + 1)
9772 }
9773
9774 return size
9775}
9776
9777function varIntBuffer (i) {
9778 var size = varIntSize(i)
9779 var buffer = new Buffer(size)
9780 writeVarInt(buffer, i, 0)
9781
9782 return buffer
9783}
9784
9785function reverse (buffer) {
9786 var buffer2 = new Buffer(buffer)
9787 Array.prototype.reverse.call(buffer2)
9788 return buffer2
9789}
9790
9791module.exports = {
9792 pushDataSize: pushDataSize,
9793 readPushDataInt: readPushDataInt,
9794 readUInt64LE: readUInt64LE,
9795 readVarInt: readVarInt,
9796 reverse: reverse,
9797 varIntBuffer: varIntBuffer,
9798 varIntSize: varIntSize,
9799 writePushDataInt: writePushDataInt,
9800 writeUInt64LE: writeUInt64LE,
9801 writeVarInt: writeVarInt
9802}
9803
9804}).call(this,require("buffer").Buffer)
9805},{"./opcodes":67,"assert":5,"buffer":7}],58:[function(require,module,exports){
9806var createHash = require('create-hash')
9807
9808function hash160 (buffer) {
9809 return ripemd160(sha256(buffer))
9810}
9811
9812function hash256 (buffer) {
9813 return sha256(sha256(buffer))
9814}
9815
9816function ripemd160 (buffer) {
9817 return createHash('rmd160').update(buffer).digest()
9818}
9819
9820function sha1 (buffer) {
9821 return createHash('sha1').update(buffer).digest()
9822}
9823
9824function sha256 (buffer) {
9825 return createHash('sha256').update(buffer).digest()
9826}
9827
9828// FIXME: Name not consistent with others
9829var createHmac = require('create-hmac')
9830
9831function HmacSHA256 (buffer, secret) {
9832 console.warn('Hmac* functions are deprecated for removal in 2.0.0, use node crypto instead')
9833 return createHmac('sha256', secret).update(buffer).digest()
9834}
9835
9836function HmacSHA512 (buffer, secret) {
9837 console.warn('Hmac* functions are deprecated for removal in 2.0.0, use node crypto instead')
9838 return createHmac('sha512', secret).update(buffer).digest()
9839}
9840
9841module.exports = {
9842 ripemd160: ripemd160,
9843 sha1: sha1,
9844 sha256: sha256,
9845 hash160: hash160,
9846 hash256: hash256,
9847 HmacSHA256: HmacSHA256,
9848 HmacSHA512: HmacSHA512
9849}
9850
9851},{"create-hash":32,"create-hmac":45}],59:[function(require,module,exports){
9852(function (Buffer){
9853var assert = require('assert')
9854var createHmac = require('create-hmac')
9855var typeForce = require('typeforce')
9856
9857var BigInteger = require('bigi')
9858var ECSignature = require('./ecsignature')
9859
9860var ZERO = new Buffer([0])
9861var ONE = new Buffer([1])
9862
9863// https://tools.ietf.org/html/rfc6979#section-3.2
9864function deterministicGenerateK (curve, hash, d, checkSig) {
9865 typeForce('Buffer', hash)
9866 typeForce('BigInteger', d)
9867
9868 // FIXME: remove/uncomment for 2.0.0
9869 // typeForce('Function', checkSig)
9870
9871 if (typeof checkSig !== 'function') {
9872 console.warn('deterministicGenerateK requires a checkSig callback in 2.0.0, see #337 for more information')
9873
9874 checkSig = function (k) {
9875 var G = curve.G
9876 var n = curve.n
9877 var e = BigInteger.fromBuffer(hash)
9878
9879 var Q = G.multiply(k)
9880
9881 if (curve.isInfinity(Q))
9882 return false
9883
9884 var r = Q.affineX.mod(n)
9885 if (r.signum() === 0)
9886 return false
9887
9888 var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
9889 if (s.signum() === 0)
9890 return false
9891
9892 return true
9893 }
9894 }
9895
9896 // sanity check
9897 assert.equal(hash.length, 32, 'Hash must be 256 bit')
9898
9899 var x = d.toBuffer(32)
9900 var k = new Buffer(32)
9901 var v = new Buffer(32)
9902
9903 // Step A, ignored as hash already provided
9904 // Step B
9905 v.fill(1)
9906
9907 // Step C
9908 k.fill(0)
9909
9910 // Step D
9911 k = createHmac('sha256', k)
9912 .update(v)
9913 .update(ZERO)
9914 .update(x)
9915 .update(hash)
9916 .digest()
9917
9918 // Step E
9919 v = createHmac('sha256', k).update(v).digest()
9920
9921 // Step F
9922 k = createHmac('sha256', k)
9923 .update(v)
9924 .update(ONE)
9925 .update(x)
9926 .update(hash)
9927 .digest()
9928
9929 // Step G
9930 v = createHmac('sha256', k).update(v).digest()
9931
9932 // Step H1/H2a, ignored as tlen === qlen (256 bit)
9933 // Step H2b
9934 v = createHmac('sha256', k).update(v).digest()
9935
9936 var T = BigInteger.fromBuffer(v)
9937
9938 // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA
9939 while ((T.signum() <= 0) || (T.compareTo(curve.n) >= 0) || !checkSig(T)) {
9940 k = createHmac('sha256', k)
9941 .update(v)
9942 .update(ZERO)
9943 .digest()
9944
9945 v = createHmac('sha256', k).update(v).digest()
9946
9947 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
9948 // Step H2b again
9949 v = createHmac('sha256', k).update(v).digest()
9950 T = BigInteger.fromBuffer(v)
9951 }
9952
9953 return T
9954}
9955
9956function sign (curve, hash, d) {
9957 var r, s
9958
9959 var e = BigInteger.fromBuffer(hash)
9960 var n = curve.n
9961 var G = curve.G
9962
9963 deterministicGenerateK(curve, hash, d, function (k) {
9964 var Q = G.multiply(k)
9965
9966 if (curve.isInfinity(Q))
9967 return false
9968
9969 r = Q.affineX.mod(n)
9970 if (r.signum() === 0)
9971 return false
9972
9973 s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
9974 if (s.signum() === 0)
9975 return false
9976
9977 return true
9978 })
9979
9980 var N_OVER_TWO = n.shiftRight(1)
9981
9982 // enforce low S values, see bip62: 'low s values in signatures'
9983 if (s.compareTo(N_OVER_TWO) > 0) {
9984 s = n.subtract(s)
9985 }
9986
9987 return new ECSignature(r, s)
9988}
9989
9990function verifyRaw (curve, e, signature, Q) {
9991 var n = curve.n
9992 var G = curve.G
9993
9994 var r = signature.r
9995 var s = signature.s
9996
9997 // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1]
9998 if (r.signum() <= 0 || r.compareTo(n) >= 0) return false
9999 if (s.signum() <= 0 || s.compareTo(n) >= 0) return false
10000
10001 // c = s^-1 mod n
10002 var c = s.modInverse(n)
10003
10004 // 1.4.4 Compute u1 = es^−1 mod n
10005 // u2 = rs^−1 mod n
10006 var u1 = e.multiply(c).mod(n)
10007 var u2 = r.multiply(c).mod(n)
10008
10009 // 1.4.5 Compute R = (xR, yR) = u1G + u2Q
10010 var R = G.multiplyTwo(u1, Q, u2)
10011 var v = R.affineX.mod(n)
10012
10013 // 1.4.5 (cont.) Enforce R is not at infinity
10014 if (curve.isInfinity(R)) return false
10015
10016 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
10017 return v.equals(r)
10018}
10019
10020function verify (curve, hash, signature, Q) {
10021 // 1.4.2 H = Hash(M), already done by the user
10022 // 1.4.3 e = H
10023 var e = BigInteger.fromBuffer(hash)
10024
10025 return verifyRaw(curve, e, signature, Q)
10026}
10027
10028/**
10029 * Recover a public key from a signature.
10030 *
10031 * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
10032 * Key Recovery Operation".
10033 *
10034 * http://www.secg.org/download/aid-780/sec1-v2.pdf
10035 */
10036function recoverPubKey (curve, e, signature, i) {
10037 assert.strictEqual(i & 3, i, 'Recovery param is more than two bits')
10038
10039 var n = curve.n
10040 var G = curve.G
10041
10042 var r = signature.r
10043 var s = signature.s
10044
10045 assert(r.signum() > 0 && r.compareTo(n) < 0, 'Invalid r value')
10046 assert(s.signum() > 0 && s.compareTo(n) < 0, 'Invalid s value')
10047
10048 // A set LSB signifies that the y-coordinate is odd
10049 var isYOdd = i & 1
10050
10051 // The more significant bit specifies whether we should use the
10052 // first or second candidate key.
10053 var isSecondKey = i >> 1
10054
10055 // 1.1 Let x = r + jn
10056 var x = isSecondKey ? r.add(n) : r
10057 var R = curve.pointFromX(isYOdd, x)
10058
10059 // 1.4 Check that nR is at infinity
10060 var nR = R.multiply(n)
10061 assert(curve.isInfinity(nR), 'nR is not a valid curve point')
10062
10063 // Compute -e from e
10064 var eNeg = e.negate().mod(n)
10065
10066 // 1.6.1 Compute Q = r^-1 (sR - eG)
10067 // Q = r^-1 (sR + -eG)
10068 var rInv = r.modInverse(n)
10069
10070 var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv)
10071 curve.validate(Q)
10072
10073 return Q
10074}
10075
10076/**
10077 * Calculate pubkey extraction parameter.
10078 *
10079 * When extracting a pubkey from a signature, we have to
10080 * distinguish four different cases. Rather than putting this
10081 * burden on the verifier, Bitcoin includes a 2-bit value with the
10082 * signature.
10083 *
10084 * This function simply tries all four cases and returns the value
10085 * that resulted in a successful pubkey recovery.
10086 */
10087function calcPubKeyRecoveryParam (curve, e, signature, Q) {
10088 for (var i = 0; i < 4; i++) {
10089 var Qprime = recoverPubKey(curve, e, signature, i)
10090
10091 // 1.6.2 Verify Q
10092 if (Qprime.equals(Q)) {
10093 return i
10094 }
10095 }
10096
10097 throw new Error('Unable to find valid recovery factor')
10098}
10099
10100module.exports = {
10101 calcPubKeyRecoveryParam: calcPubKeyRecoveryParam,
10102 deterministicGenerateK: deterministicGenerateK,
10103 recoverPubKey: recoverPubKey,
10104 sign: sign,
10105 verify: verify,
10106 verifyRaw: verifyRaw
10107}
10108
10109}).call(this,require("buffer").Buffer)
10110},{"./ecsignature":62,"assert":5,"bigi":3,"buffer":7,"create-hmac":45,"typeforce":53}],60:[function(require,module,exports){
10111(function (Buffer){
10112var assert = require('assert')
10113var base58check = require('bs58check')
10114var ecdsa = require('./ecdsa')
10115var networks = require('./networks')
10116var randomBytes = require('randombytes')
10117var typeForce = require('typeforce')
10118
10119var BigInteger = require('bigi')
10120var ECPubKey = require('./ecpubkey')
10121
10122var ecurve = require('ecurve')
10123var secp256k1 = ecurve.getCurveByName('secp256k1')
10124
10125function ECKey (d, compressed) {
10126 assert(d.signum() > 0, 'Private key must be greater than 0')
10127 assert(d.compareTo(ECKey.curve.n) < 0, 'Private key must be less than the curve order')
10128
10129 var Q = ECKey.curve.G.multiply(d)
10130
10131 this.d = d
10132 this.pub = new ECPubKey(Q, compressed)
10133}
10134
10135// Constants
10136ECKey.curve = secp256k1
10137
10138// Static constructors
10139ECKey.fromWIF = function (string) {
10140 var payload = base58check.decode(string)
10141 var compressed = false
10142
10143 // Ignore the version byte
10144 payload = payload.slice(1)
10145
10146 if (payload.length === 33) {
10147 assert.strictEqual(payload[32], 0x01, 'Invalid compression flag')
10148
10149 // Truncate the compression flag
10150 payload = payload.slice(0, -1)
10151 compressed = true
10152 }
10153
10154 assert.equal(payload.length, 32, 'Invalid WIF payload length')
10155
10156 var d = BigInteger.fromBuffer(payload)
10157 return new ECKey(d, compressed)
10158}
10159
10160ECKey.makeRandom = function (compressed, rng) {
10161 rng = rng || randomBytes
10162
10163 var buffer = rng(32)
10164 typeForce('Buffer', buffer)
10165 assert.equal(buffer.length, 32, 'Expected 256-bit Buffer from RNG')
10166
10167 var d = BigInteger.fromBuffer(buffer)
10168 d = d.mod(ECKey.curve.n)
10169
10170 return new ECKey(d, compressed)
10171}
10172
10173// Export functions
10174ECKey.prototype.toWIF = function (network) {
10175 network = network || networks.bitcoin
10176
10177 var bufferLen = this.pub.compressed ? 34 : 33
10178 var buffer = new Buffer(bufferLen)
10179
10180 buffer.writeUInt8(network.wif, 0)
10181 this.d.toBuffer(32).copy(buffer, 1)
10182
10183 if (this.pub.compressed) {
10184 buffer.writeUInt8(0x01, 33)
10185 }
10186
10187 return base58check.encode(buffer)
10188}
10189
10190// Operations
10191ECKey.prototype.sign = function (hash) {
10192 return ecdsa.sign(ECKey.curve, hash, this.d)
10193}
10194
10195module.exports = ECKey
10196
10197}).call(this,require("buffer").Buffer)
10198},{"./ecdsa":59,"./ecpubkey":61,"./networks":66,"assert":5,"bigi":3,"bs58check":31,"buffer":7,"ecurve":49,"randombytes":52,"typeforce":53}],61:[function(require,module,exports){
10199(function (Buffer){
10200var crypto = require('./crypto')
10201var ecdsa = require('./ecdsa')
10202var typeForce = require('typeforce')
10203var networks = require('./networks')
10204
10205var Address = require('./address')
10206
10207var ecurve = require('ecurve')
10208var secp256k1 = ecurve.getCurveByName('secp256k1')
10209
10210function ECPubKey (Q, compressed) {
10211 if (compressed === undefined) {
10212 compressed = true
10213 }
10214
10215 typeForce('Point', Q)
10216 typeForce('Boolean', compressed)
10217
10218 this.compressed = compressed
10219 this.Q = Q
10220}
10221
10222// Constants
10223ECPubKey.curve = secp256k1
10224
10225// Static constructors
10226ECPubKey.fromBuffer = function (buffer) {
10227 var Q = ecurve.Point.decodeFrom(ECPubKey.curve, buffer)
10228 return new ECPubKey(Q, Q.compressed)
10229}
10230
10231ECPubKey.fromHex = function (hex) {
10232 return ECPubKey.fromBuffer(new Buffer(hex, 'hex'))
10233}
10234
10235// Operations
10236ECPubKey.prototype.getAddress = function (network) {
10237 network = network || networks.bitcoin
10238
10239 return new Address(crypto.hash160(this.toBuffer()), network.pubKeyHash)
10240}
10241
10242ECPubKey.prototype.verify = function (hash, signature) {
10243 return ecdsa.verify(ECPubKey.curve, hash, signature, this.Q)
10244}
10245
10246// Export functions
10247ECPubKey.prototype.toBuffer = function () {
10248 return this.Q.getEncoded(this.compressed)
10249}
10250
10251ECPubKey.prototype.toHex = function () {
10252 return this.toBuffer().toString('hex')
10253}
10254
10255module.exports = ECPubKey
10256
10257}).call(this,require("buffer").Buffer)
10258},{"./address":54,"./crypto":58,"./ecdsa":59,"./networks":66,"buffer":7,"ecurve":49,"typeforce":53}],62:[function(require,module,exports){
10259(function (Buffer){
10260var assert = require('assert')
10261var typeForce = require('typeforce')
10262
10263var BigInteger = require('bigi')
10264
10265function ECSignature (r, s) {
10266 typeForce('BigInteger', r)
10267 typeForce('BigInteger', s)
10268
10269 this.r = r
10270 this.s = s
10271}
10272
10273ECSignature.parseCompact = function (buffer) {
10274 assert.equal(buffer.length, 65, 'Invalid signature length')
10275 var i = buffer.readUInt8(0) - 27
10276
10277 // At most 3 bits
10278 assert.equal(i, i & 7, 'Invalid signature parameter')
10279 var compressed = !!(i & 4)
10280
10281 // Recovery param only
10282 i = i & 3
10283
10284 var r = BigInteger.fromBuffer(buffer.slice(1, 33))
10285 var s = BigInteger.fromBuffer(buffer.slice(33))
10286
10287 return {
10288 compressed: compressed,
10289 i: i,
10290 signature: new ECSignature(r, s)
10291 }
10292}
10293
10294ECSignature.fromDER = function (buffer) {
10295 assert.equal(buffer.readUInt8(0), 0x30, 'Not a DER sequence')
10296 assert.equal(buffer.readUInt8(1), buffer.length - 2, 'Invalid sequence length')
10297 assert.equal(buffer.readUInt8(2), 0x02, 'Expected a DER integer')
10298
10299 var rLen = buffer.readUInt8(3)
10300 assert(rLen > 0, 'R length is zero')
10301
10302 var offset = 4 + rLen
10303 assert.equal(buffer.readUInt8(offset), 0x02, 'Expected a DER integer (2)')
10304
10305 var sLen = buffer.readUInt8(offset + 1)
10306 assert(sLen > 0, 'S length is zero')
10307
10308 var rB = buffer.slice(4, offset)
10309 var sB = buffer.slice(offset + 2)
10310 offset += 2 + sLen
10311
10312 if (rLen > 1 && rB.readUInt8(0) === 0x00) {
10313 assert(rB.readUInt8(1) & 0x80, 'R value excessively padded')
10314 }
10315
10316 if (sLen > 1 && sB.readUInt8(0) === 0x00) {
10317 assert(sB.readUInt8(1) & 0x80, 'S value excessively padded')
10318 }
10319
10320 assert.equal(offset, buffer.length, 'Invalid DER encoding')
10321 var r = BigInteger.fromDERInteger(rB)
10322 var s = BigInteger.fromDERInteger(sB)
10323
10324 assert(r.signum() >= 0, 'R value is negative')
10325 assert(s.signum() >= 0, 'S value is negative')
10326
10327 return new ECSignature(r, s)
10328}
10329
10330// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
10331ECSignature.parseScriptSignature = function (buffer) {
10332 var hashType = buffer.readUInt8(buffer.length - 1)
10333 var hashTypeMod = hashType & ~0x80
10334
10335 assert(hashTypeMod > 0x00 && hashTypeMod < 0x04, 'Invalid hashType ' + hashType)
10336
10337 return {
10338 signature: ECSignature.fromDER(buffer.slice(0, -1)),
10339 hashType: hashType
10340 }
10341}
10342
10343ECSignature.prototype.toCompact = function (i, compressed) {
10344 if (compressed) {
10345 i += 4
10346 }
10347
10348 i += 27
10349
10350 var buffer = new Buffer(65)
10351 buffer.writeUInt8(i, 0)
10352
10353 this.r.toBuffer(32).copy(buffer, 1)
10354 this.s.toBuffer(32).copy(buffer, 33)
10355
10356 return buffer
10357}
10358
10359ECSignature.prototype.toDER = function () {
10360 var rBa = this.r.toDERInteger()
10361 var sBa = this.s.toDERInteger()
10362
10363 var sequence = []
10364
10365 // INTEGER
10366 sequence.push(0x02, rBa.length)
10367 sequence = sequence.concat(rBa)
10368
10369 // INTEGER
10370 sequence.push(0x02, sBa.length)
10371 sequence = sequence.concat(sBa)
10372
10373 // SEQUENCE
10374 sequence.unshift(0x30, sequence.length)
10375
10376 return new Buffer(sequence)
10377}
10378
10379ECSignature.prototype.toScriptSignature = function (hashType) {
10380 var hashTypeMod = hashType & ~0x80
10381 assert(hashTypeMod > 0x00 && hashTypeMod < 0x04, 'Invalid hashType ' + hashType)
10382
10383 var hashTypeBuffer = new Buffer(1)
10384 hashTypeBuffer.writeUInt8(hashType, 0)
10385
10386 return Buffer.concat([this.toDER(), hashTypeBuffer])
10387}
10388
10389module.exports = ECSignature
10390
10391}).call(this,require("buffer").Buffer)
10392},{"assert":5,"bigi":3,"buffer":7,"typeforce":53}],63:[function(require,module,exports){
10393(function (Buffer){
10394var assert = require('assert')
10395var base58check = require('bs58check')
10396var bcrypto = require('./crypto')
10397var createHmac = require('create-hmac')
10398var typeForce = require('typeforce')
10399var networks = require('./networks')
10400
10401var BigInteger = require('bigi')
10402var ECKey = require('./eckey')
10403var ECPubKey = require('./ecpubkey')
10404
10405var ecurve = require('ecurve')
10406var curve = ecurve.getCurveByName('secp256k1')
10407
10408function findBIP32NetworkByVersion (version) {
10409 for (var name in networks) {
10410 var network = networks[name]
10411
10412 if (version === network.bip32.private || version === network.bip32.public) {
10413 return network
10414 }
10415 }
10416
10417 assert(false, 'Could not find network for ' + version.toString(16))
10418}
10419
10420function HDNode (K, chainCode, network) {
10421 network = network || networks.bitcoin
10422
10423 typeForce('Buffer', chainCode)
10424
10425 assert.equal(chainCode.length, 32, 'Expected chainCode length of 32, got ' + chainCode.length)
10426 assert(network.bip32, 'Unknown BIP32 constants for network')
10427
10428 this.chainCode = chainCode
10429 this.depth = 0
10430 this.index = 0
10431 this.parentFingerprint = 0x00000000
10432 this.network = network
10433
10434 if (K instanceof BigInteger) {
10435 this.privKey = new ECKey(K, true)
10436 this.pubKey = this.privKey.pub
10437 } else if (K instanceof ECKey) {
10438 assert(K.pub.compressed, 'ECKey must be compressed')
10439 this.privKey = K
10440 this.pubKey = K.pub
10441 } else if (K instanceof ECPubKey) {
10442 assert(K.compressed, 'ECPubKey must be compressed')
10443 this.pubKey = K
10444 } else {
10445 this.pubKey = new ECPubKey(K, true)
10446 }
10447}
10448
10449HDNode.MASTER_SECRET = new Buffer('Bitcoin seed')
10450HDNode.HIGHEST_BIT = 0x80000000
10451HDNode.LENGTH = 78
10452
10453HDNode.fromSeedBuffer = function (seed, network) {
10454 typeForce('Buffer', seed)
10455
10456 assert(seed.length >= 16, 'Seed should be at least 128 bits')
10457 assert(seed.length <= 64, 'Seed should be at most 512 bits')
10458
10459 var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest()
10460 var IL = I.slice(0, 32)
10461 var IR = I.slice(32)
10462
10463 // In case IL is 0 or >= n, the master key is invalid
10464 // This is handled by `new ECKey` in the HDNode constructor
10465 var pIL = BigInteger.fromBuffer(IL)
10466
10467 return new HDNode(pIL, IR, network)
10468}
10469
10470HDNode.fromSeedHex = function (hex, network) {
10471 return HDNode.fromSeedBuffer(new Buffer(hex, 'hex'), network)
10472}
10473
10474HDNode.fromBase58 = function (string, network) {
10475 return HDNode.fromBuffer(base58check.decode(string), network, true)
10476}
10477
10478// FIXME: remove in 2.x.y
10479HDNode.fromBuffer = function (buffer, network, __ignoreDeprecation) {
10480 if (!__ignoreDeprecation) {
10481 console.warn('HDNode.fromBuffer() is deprecated for removal in 2.x.y, use fromBase58 instead')
10482 }
10483
10484 assert.strictEqual(buffer.length, HDNode.LENGTH, 'Invalid buffer length')
10485
10486 // 4 byte: version bytes
10487 var version = buffer.readUInt32BE(0)
10488
10489 if (network) {
10490 assert(version === network.bip32.private || version === network.bip32.public, "Network doesn't match")
10491
10492 // auto-detect
10493 } else {
10494 network = findBIP32NetworkByVersion(version)
10495 }
10496
10497 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
10498 var depth = buffer.readUInt8(4)
10499
10500 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
10501 var parentFingerprint = buffer.readUInt32BE(5)
10502 if (depth === 0) {
10503 assert.strictEqual(parentFingerprint, 0x00000000, 'Invalid parent fingerprint')
10504 }
10505
10506 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
10507 // This is encoded in MSB order. (0x00000000 if master key)
10508 var index = buffer.readUInt32BE(9)
10509 assert(depth > 0 || index === 0, 'Invalid index')
10510
10511 // 32 bytes: the chain code
10512 var chainCode = buffer.slice(13, 45)
10513 var data, hd
10514
10515 // 33 bytes: private key data (0x00 + k)
10516 if (version === network.bip32.private) {
10517 assert.strictEqual(buffer.readUInt8(45), 0x00, 'Invalid private key')
10518 data = buffer.slice(46, 78)
10519 var d = BigInteger.fromBuffer(data)
10520 hd = new HDNode(d, chainCode, network)
10521
10522 // 33 bytes: public key data (0x02 + X or 0x03 + X)
10523 } else {
10524 data = buffer.slice(45, 78)
10525 var Q = ecurve.Point.decodeFrom(curve, data)
10526 assert.equal(Q.compressed, true, 'Invalid public key')
10527
10528 // Verify that the X coordinate in the public point corresponds to a point on the curve.
10529 // If not, the extended public key is invalid.
10530 curve.validate(Q)
10531
10532 hd = new HDNode(Q, chainCode, network)
10533 }
10534
10535 hd.depth = depth
10536 hd.index = index
10537 hd.parentFingerprint = parentFingerprint
10538
10539 return hd
10540}
10541
10542// FIXME: remove in 2.x.y
10543HDNode.fromHex = function (hex, network) {
10544 return HDNode.fromBuffer(new Buffer(hex, 'hex'), network)
10545}
10546
10547HDNode.prototype.getIdentifier = function () {
10548 return bcrypto.hash160(this.pubKey.toBuffer())
10549}
10550
10551HDNode.prototype.getFingerprint = function () {
10552 return this.getIdentifier().slice(0, 4)
10553}
10554
10555HDNode.prototype.getAddress = function () {
10556 return this.pubKey.getAddress(this.network)
10557}
10558
10559HDNode.prototype.neutered = function () {
10560 var neutered = new HDNode(this.pubKey.Q, this.chainCode, this.network)
10561 neutered.depth = this.depth
10562 neutered.index = this.index
10563 neutered.parentFingerprint = this.parentFingerprint
10564
10565 return neutered
10566}
10567
10568HDNode.prototype.toBase58 = function (isPrivate) {
10569 return base58check.encode(this.toBuffer(isPrivate, true))
10570}
10571
10572// FIXME: remove in 2.x.y
10573HDNode.prototype.toBuffer = function (isPrivate, __ignoreDeprecation) {
10574 if (isPrivate === undefined) {
10575 isPrivate = !!this.privKey
10576
10577 // FIXME: remove in 2.x.y
10578 } else {
10579 console.warn('isPrivate flag is deprecated, please use the .neutered() method instead')
10580 }
10581
10582 if (!__ignoreDeprecation) {
10583 console.warn('HDNode.toBuffer() is deprecated for removal in 2.x.y, use toBase58 instead')
10584 }
10585
10586 // Version
10587 var version = isPrivate ? this.network.bip32.private : this.network.bip32.public
10588 var buffer = new Buffer(HDNode.LENGTH)
10589
10590 // 4 bytes: version bytes
10591 buffer.writeUInt32BE(version, 0)
10592
10593 // Depth
10594 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
10595 buffer.writeUInt8(this.depth, 4)
10596
10597 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
10598 buffer.writeUInt32BE(this.parentFingerprint, 5)
10599
10600 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
10601 // This is encoded in Big endian. (0x00000000 if master key)
10602 buffer.writeUInt32BE(this.index, 9)
10603
10604 // 32 bytes: the chain code
10605 this.chainCode.copy(buffer, 13)
10606
10607 // 33 bytes: the public key or private key data
10608 if (isPrivate) {
10609 // FIXME: remove in 2.x.y
10610 assert(this.privKey, 'Missing private key')
10611
10612 // 0x00 + k for private keys
10613 buffer.writeUInt8(0, 45)
10614 this.privKey.d.toBuffer(32).copy(buffer, 46)
10615 } else {
10616 // X9.62 encoding for public keys
10617 this.pubKey.toBuffer().copy(buffer, 45)
10618 }
10619
10620 return buffer
10621}
10622
10623// FIXME: remove in 2.x.y
10624HDNode.prototype.toHex = function (isPrivate) {
10625 return this.toBuffer(isPrivate).toString('hex')
10626}
10627
10628// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
10629HDNode.prototype.derive = function (index) {
10630 var isHardened = index >= HDNode.HIGHEST_BIT
10631 var indexBuffer = new Buffer(4)
10632 indexBuffer.writeUInt32BE(index, 0)
10633
10634 var data
10635
10636 // Hardened child
10637 if (isHardened) {
10638 assert(this.privKey, 'Could not derive hardened child key')
10639
10640 // data = 0x00 || ser256(kpar) || ser32(index)
10641 data = Buffer.concat([
10642 this.privKey.d.toBuffer(33),
10643 indexBuffer
10644 ])
10645
10646 // Normal child
10647 } else {
10648 // data = serP(point(kpar)) || ser32(index)
10649 // = serP(Kpar) || ser32(index)
10650 data = Buffer.concat([
10651 this.pubKey.toBuffer(),
10652 indexBuffer
10653 ])
10654 }
10655
10656 var I = createHmac('sha512', this.chainCode).update(data).digest()
10657 var IL = I.slice(0, 32)
10658 var IR = I.slice(32)
10659
10660 var pIL = BigInteger.fromBuffer(IL)
10661
10662 // In case parse256(IL) >= n, proceed with the next value for i
10663 if (pIL.compareTo(curve.n) >= 0) {
10664 return this.derive(index + 1)
10665 }
10666
10667 // Private parent key -> private child key
10668 var hd
10669 if (this.privKey) {
10670 // ki = parse256(IL) + kpar (mod n)
10671 var ki = pIL.add(this.privKey.d).mod(curve.n)
10672
10673 // In case ki == 0, proceed with the next value for i
10674 if (ki.signum() === 0) {
10675 return this.derive(index + 1)
10676 }
10677
10678 hd = new HDNode(ki, IR, this.network)
10679
10680 // Public parent key -> public child key
10681 } else {
10682 // Ki = point(parse256(IL)) + Kpar
10683 // = G*IL + Kpar
10684 var Ki = curve.G.multiply(pIL).add(this.pubKey.Q)
10685
10686 // In case Ki is the point at infinity, proceed with the next value for i
10687 if (curve.isInfinity(Ki)) {
10688 return this.derive(index + 1)
10689 }
10690
10691 hd = new HDNode(Ki, IR, this.network)
10692 }
10693
10694 hd.depth = this.depth + 1
10695 hd.index = index
10696 hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)
10697
10698 return hd
10699}
10700
10701HDNode.prototype.deriveHardened = function (index) {
10702 // Only derives hardened private keys by default
10703 return this.derive(index + HDNode.HIGHEST_BIT)
10704}
10705
10706HDNode.prototype.toString = HDNode.prototype.toBase58
10707
10708module.exports = HDNode
10709
10710}).call(this,require("buffer").Buffer)
10711},{"./crypto":58,"./eckey":60,"./ecpubkey":61,"./networks":66,"assert":5,"bigi":3,"bs58check":31,"buffer":7,"create-hmac":45,"ecurve":49,"typeforce":53}],64:[function(require,module,exports){
10712module.exports = {
10713 Address: require('./address'),
10714 base58check: require('./base58check'),
10715 Block: require('./block'),
10716 bufferutils: require('./bufferutils'),
10717 crypto: require('./crypto'),
10718 ecdsa: require('./ecdsa'),
10719 ECKey: require('./eckey'),
10720 ECPubKey: require('./ecpubkey'),
10721 ECSignature: require('./ecsignature'),
10722 Message: require('./message'),
10723 opcodes: require('./opcodes'),
10724 HDNode: require('./hdnode'),
10725 Script: require('./script'),
10726 scripts: require('./scripts'),
10727 Transaction: require('./transaction'),
10728 TransactionBuilder: require('./transaction_builder'),
10729 networks: require('./networks'),
10730 Wallet: require('./wallet')
10731}
10732
10733},{"./address":54,"./base58check":55,"./block":56,"./bufferutils":57,"./crypto":58,"./ecdsa":59,"./eckey":60,"./ecpubkey":61,"./ecsignature":62,"./hdnode":63,"./message":65,"./networks":66,"./opcodes":67,"./script":68,"./scripts":69,"./transaction":70,"./transaction_builder":71,"./wallet":72}],65:[function(require,module,exports){
10734(function (Buffer){
10735var bufferutils = require('./bufferutils')
10736var crypto = require('./crypto')
10737var ecdsa = require('./ecdsa')
10738var networks = require('./networks')
10739
10740var BigInteger = require('bigi')
10741var ECPubKey = require('./ecpubkey')
10742var ECSignature = require('./ecsignature')
10743
10744var ecurve = require('ecurve')
10745var ecparams = ecurve.getCurveByName('secp256k1')
10746
10747function magicHash (message, network) {
10748 var magicPrefix = new Buffer(network.magicPrefix)
10749 var messageBuffer = new Buffer(message)
10750 var lengthBuffer = bufferutils.varIntBuffer(messageBuffer.length)
10751
10752 var buffer = Buffer.concat([magicPrefix, lengthBuffer, messageBuffer])
10753 return crypto.hash256(buffer)
10754}
10755
10756function sign (privKey, message, network) {
10757 network = network || networks.bitcoin
10758
10759 var hash = magicHash(message, network)
10760 var signature = privKey.sign(hash)
10761 var e = BigInteger.fromBuffer(hash)
10762 var i = ecdsa.calcPubKeyRecoveryParam(ecparams, e, signature, privKey.pub.Q)
10763
10764 return signature.toCompact(i, privKey.pub.compressed)
10765}
10766
10767// TODO: network could be implied from address
10768function verify (address, signature, message, network) {
10769 if (!Buffer.isBuffer(signature)) {
10770 signature = new Buffer(signature, 'base64')
10771 }
10772
10773 network = network || networks.bitcoin
10774
10775 var hash = magicHash(message, network)
10776 var parsed = ECSignature.parseCompact(signature)
10777 var e = BigInteger.fromBuffer(hash)
10778 var Q = ecdsa.recoverPubKey(ecparams, e, parsed.signature, parsed.i)
10779
10780 var pubKey = new ECPubKey(Q, parsed.compressed)
10781 return pubKey.getAddress(network).toString() === address.toString()
10782}
10783
10784module.exports = {
10785 magicHash: magicHash,
10786 sign: sign,
10787 verify: verify
10788}
10789
10790}).call(this,require("buffer").Buffer)
10791},{"./bufferutils":57,"./crypto":58,"./ecdsa":59,"./ecpubkey":61,"./ecsignature":62,"./networks":66,"bigi":3,"buffer":7,"ecurve":49}],66:[function(require,module,exports){
10792// https://en.bitcoin.it/wiki/List_of_address_prefixes
10793// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
10794
10795var networks = {
10796 bitcoin: {
10797 magicPrefix: '\x18Bitcoin Signed Message:\n',
10798 bip32: {
10799 public: 0x0488b21e,
10800 private: 0x0488ade4
10801 },
10802 pubKeyHash: 0x00,
10803 scriptHash: 0x05,
10804 wif: 0x80,
10805 dustThreshold: 546, // https://github.com/bitcoin/bitcoin/blob/v0.9.2/src/core.h#L151-L162
10806 feePerKb: 10000, // https://github.com/bitcoin/bitcoin/blob/v0.9.2/src/main.cpp#L53
10807 estimateFee: estimateFee('bitcoin')
10808 },
10809 testnet: {
10810 magicPrefix: '\x18Bitcoin Signed Message:\n',
10811 bip32: {
10812 public: 0x043587cf,
10813 private: 0x04358394
10814 },
10815 pubKeyHash: 0x6f,
10816 scriptHash: 0xc4,
10817 wif: 0xef,
10818 dustThreshold: 546,
10819 feePerKb: 10000,
10820 estimateFee: estimateFee('testnet')
10821 },
10822 litecoin: {
10823 magicPrefix: '\x19Litecoin Signed Message:\n',
10824 bip32: {
10825 public: 0x019da462,
10826 private: 0x019d9cfe
10827 },
10828 pubKeyHash: 0x30,
10829 scriptHash: 0x05,
10830 wif: 0xb0,
10831 dustThreshold: 0, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.cpp#L360-L365
10832 dustSoftThreshold: 100000, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.h#L53
10833 feePerKb: 100000, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.cpp#L56
10834 estimateFee: estimateFee('litecoin')
10835 },
10836 dogecoin: {
10837 magicPrefix: '\x19Dogecoin Signed Message:\n',
10838 bip32: {
10839 public: 0x02facafd,
10840 private: 0x02fac398
10841 },
10842 pubKeyHash: 0x1e,
10843 scriptHash: 0x16,
10844 wif: 0x9e,
10845 dustThreshold: 0, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/core.h#L155-L160
10846 dustSoftThreshold: 100000000, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/main.h#L62
10847 feePerKb: 100000000, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/main.cpp#L58
10848 estimateFee: estimateFee('dogecoin')
10849 },
10850 viacoin: {
10851 magicPrefix: '\x18Viacoin Signed Message:\n',
10852 bip32: {
10853 public: 0x0488b21e,
10854 private: 0x0488ade4
10855 },
10856 pubKeyHash: 0x47,
10857 scriptHash: 0x21,
10858 wif: 0xc7,
10859 dustThreshold: 560,
10860 dustSoftThreshold: 100000,
10861 feePerKb: 100000, //
10862 estimateFee: estimateFee('viacoin')
10863 },
10864 viacointestnet: {
10865 magicPrefix: '\x18Viacoin Signed Message:\n',
10866 bip32: {
10867 public: 0x043587cf,
10868 private: 0x04358394
10869 },
10870 pubKeyHash: 0x7f,
10871 scriptHash: 0xc4,
10872 wif: 0xff,
10873 dustThreshold: 560,
10874 dustSoftThreshold: 100000,
10875 feePerKb: 100000,
10876 estimateFee: estimateFee('viacointestnet')
10877 },
10878 gamerscoin: {
10879 magicPrefix: '\x19Gamerscoin Signed Message:\n',
10880 bip32: {
10881 public: 0x019da462,
10882 private: 0x019d9cfe
10883 },
10884 pubKeyHash: 0x26,
10885 scriptHash: 0x05,
10886 wif: 0xA6,
10887 dustThreshold: 0, // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L358-L363
10888 dustSoftThreshold: 100000, // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L51
10889 feePerKb: 100000, // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L54
10890 estimateFee: estimateFee('gamerscoin')
10891 },
10892 jumbucks: {
10893 magicPrefix: '\x19Jumbucks Signed Message:\n',
10894 bip32: {
10895 public: 0x037a689a,
10896 private: 0x037a6460
10897 },
10898 pubKeyHash: 0x2b,
10899 scriptHash: 0x05,
10900 wif: 0xab,
10901 dustThreshold: 0,
10902 dustSoftThreshold: 10000,
10903 feePerKb: 10000,
10904 estimateFee: estimateFee('jumbucks')
10905 },
10906 zetacoin: {
10907 magicPrefix: '\x18Zetacoin Signed Message:\n',
10908 bip32: {
10909 public: 0x0488b21e,
10910 private: 0x0488ade4
10911 },
10912 pubKeyHash: 0x50,
10913 scriptHash: 0x09,
10914 wif: 0xe0,
10915 dustThreshold: 546, // https://github.com/zetacoin/zetacoin/blob/master/src/core.h#L159
10916 feePerKb: 10000, // https://github.com/zetacoin/zetacoin/blob/master/src/main.cpp#L54
10917 estimateFee: estimateFee('zetacoin')
10918 }
10919}
10920
10921function estimateFee (type) {
10922 return function (tx) {
10923 var network = networks[type]
10924 var baseFee = network.feePerKb
10925 var byteSize = tx.toBuffer().length
10926
10927 var fee = baseFee * Math.ceil(byteSize / 1000)
10928 if (network.dustSoftThreshold === undefined) return fee
10929
10930 tx.outs.forEach(function (e) {
10931 if (e.value < network.dustSoftThreshold) {
10932 fee += baseFee
10933 }
10934 })
10935
10936 return fee
10937 }
10938}
10939
10940module.exports = networks
10941
10942},{}],67:[function(require,module,exports){
10943module.exports = {
10944 // push value
10945 OP_FALSE: 0,
10946 OP_0: 0,
10947 OP_PUSHDATA1: 76,
10948 OP_PUSHDATA2: 77,
10949 OP_PUSHDATA4: 78,
10950 OP_1NEGATE: 79,
10951 OP_RESERVED: 80,
10952 OP_1: 81,
10953 OP_TRUE: 81,
10954 OP_2: 82,
10955 OP_3: 83,
10956 OP_4: 84,
10957 OP_5: 85,
10958 OP_6: 86,
10959 OP_7: 87,
10960 OP_8: 88,
10961 OP_9: 89,
10962 OP_10: 90,
10963 OP_11: 91,
10964 OP_12: 92,
10965 OP_13: 93,
10966 OP_14: 94,
10967 OP_15: 95,
10968 OP_16: 96,
10969
10970 // control
10971 OP_NOP: 97,
10972 OP_VER: 98,
10973 OP_IF: 99,
10974 OP_NOTIF: 100,
10975 OP_VERIF: 101,
10976 OP_VERNOTIF: 102,
10977 OP_ELSE: 103,
10978 OP_ENDIF: 104,
10979 OP_VERIFY: 105,
10980 OP_RETURN: 106,
10981
10982 // stack ops
10983 OP_TOALTSTACK: 107,
10984 OP_FROMALTSTACK: 108,
10985 OP_2DROP: 109,
10986 OP_2DUP: 110,
10987 OP_3DUP: 111,
10988 OP_2OVER: 112,
10989 OP_2ROT: 113,
10990 OP_2SWAP: 114,
10991 OP_IFDUP: 115,
10992 OP_DEPTH: 116,
10993 OP_DROP: 117,
10994 OP_DUP: 118,
10995 OP_NIP: 119,
10996 OP_OVER: 120,
10997 OP_PICK: 121,
10998 OP_ROLL: 122,
10999 OP_ROT: 123,
11000 OP_SWAP: 124,
11001 OP_TUCK: 125,
11002
11003 // splice ops
11004 OP_CAT: 126,
11005 OP_SUBSTR: 127,
11006 OP_LEFT: 128,
11007 OP_RIGHT: 129,
11008 OP_SIZE: 130,
11009
11010 // bit logic
11011 OP_INVERT: 131,
11012 OP_AND: 132,
11013 OP_OR: 133,
11014 OP_XOR: 134,
11015 OP_EQUAL: 135,
11016 OP_EQUALVERIFY: 136,
11017 OP_RESERVED1: 137,
11018 OP_RESERVED2: 138,
11019
11020 // numeric
11021 OP_1ADD: 139,
11022 OP_1SUB: 140,
11023 OP_2MUL: 141,
11024 OP_2DIV: 142,
11025 OP_NEGATE: 143,
11026 OP_ABS: 144,
11027 OP_NOT: 145,
11028 OP_0NOTEQUAL: 146,
11029
11030 OP_ADD: 147,
11031 OP_SUB: 148,
11032 OP_MUL: 149,
11033 OP_DIV: 150,
11034 OP_MOD: 151,
11035 OP_LSHIFT: 152,
11036 OP_RSHIFT: 153,
11037
11038 OP_BOOLAND: 154,
11039 OP_BOOLOR: 155,
11040 OP_NUMEQUAL: 156,
11041 OP_NUMEQUALVERIFY: 157,
11042 OP_NUMNOTEQUAL: 158,
11043 OP_LESSTHAN: 159,
11044 OP_GREATERTHAN: 160,
11045 OP_LESSTHANOREQUAL: 161,
11046 OP_GREATERTHANOREQUAL: 162,
11047 OP_MIN: 163,
11048 OP_MAX: 164,
11049
11050 OP_WITHIN: 165,
11051
11052 // crypto
11053 OP_RIPEMD160: 166,
11054 OP_SHA1: 167,
11055 OP_SHA256: 168,
11056 OP_HASH160: 169,
11057 OP_HASH256: 170,
11058 OP_CODESEPARATOR: 171,
11059 OP_CHECKSIG: 172,
11060 OP_CHECKSIGVERIFY: 173,
11061 OP_CHECKMULTISIG: 174,
11062 OP_CHECKMULTISIGVERIFY: 175,
11063
11064 // expansion
11065 OP_NOP1: 176,
11066 OP_NOP2: 177,
11067 OP_NOP3: 178,
11068 OP_NOP4: 179,
11069 OP_NOP5: 180,
11070 OP_NOP6: 181,
11071 OP_NOP7: 182,
11072 OP_NOP8: 183,
11073 OP_NOP9: 184,
11074 OP_NOP10: 185,
11075
11076 // template matching params
11077 OP_PUBKEYHASH: 253,
11078 OP_PUBKEY: 254,
11079 OP_INVALIDOPCODE: 255
11080}
11081
11082},{}],68:[function(require,module,exports){
11083(function (Buffer){
11084var assert = require('assert')
11085var bufferutils = require('./bufferutils')
11086var crypto = require('./crypto')
11087var typeForce = require('typeforce')
11088var opcodes = require('./opcodes')
11089
11090function Script (buffer, chunks) {
11091 typeForce('Buffer', buffer)
11092 typeForce('Array', chunks)
11093
11094 this.buffer = buffer
11095 this.chunks = chunks
11096}
11097
11098Script.fromASM = function (asm) {
11099 var strChunks = asm.split(' ')
11100 var chunks = strChunks.map(function (strChunk) {
11101 // opcode
11102 if (strChunk in opcodes) {
11103 return opcodes[strChunk]
11104
11105 // data chunk
11106 } else {
11107 return new Buffer(strChunk, 'hex')
11108 }
11109 })
11110
11111 return Script.fromChunks(chunks)
11112}
11113
11114Script.fromBuffer = function (buffer) {
11115 var chunks = []
11116 var i = 0
11117
11118 while (i < buffer.length) {
11119 var opcode = buffer.readUInt8(i)
11120
11121 // data chunk
11122 if ((opcode > opcodes.OP_0) && (opcode <= opcodes.OP_PUSHDATA4)) {
11123 var d = bufferutils.readPushDataInt(buffer, i)
11124
11125 // did reading a pushDataInt fail? return non-chunked script
11126 if (d === null) return new Script(buffer, [])
11127 i += d.size
11128
11129 // attempt to read too much data?
11130 if (i + d.number > buffer.length) return new Script(buffer, [])
11131
11132 var data = buffer.slice(i, i + d.number)
11133 i += d.number
11134
11135 chunks.push(data)
11136
11137 // opcode
11138 } else {
11139 chunks.push(opcode)
11140
11141 i += 1
11142 }
11143 }
11144
11145 return new Script(buffer, chunks)
11146}
11147
11148Script.fromChunks = function (chunks) {
11149 typeForce('Array', chunks)
11150
11151 var bufferSize = chunks.reduce(function (accum, chunk) {
11152 // data chunk
11153 if (Buffer.isBuffer(chunk)) {
11154 return accum + bufferutils.pushDataSize(chunk.length) + chunk.length
11155 }
11156
11157 // opcode
11158 return accum + 1
11159 }, 0.0)
11160
11161 var buffer = new Buffer(bufferSize)
11162 var offset = 0
11163
11164 chunks.forEach(function (chunk) {
11165 // data chunk
11166 if (Buffer.isBuffer(chunk)) {
11167 offset += bufferutils.writePushDataInt(buffer, chunk.length, offset)
11168
11169 chunk.copy(buffer, offset)
11170 offset += chunk.length
11171
11172 // opcode
11173 } else {
11174 buffer.writeUInt8(chunk, offset)
11175 offset += 1
11176 }
11177 })
11178
11179 assert.equal(offset, buffer.length, 'Could not decode chunks')
11180 return new Script(buffer, chunks)
11181}
11182
11183Script.fromHex = function (hex) {
11184 return Script.fromBuffer(new Buffer(hex, 'hex'))
11185}
11186
11187Script.EMPTY = Script.fromChunks([])
11188
11189Script.prototype.getHash = function () {
11190 return crypto.hash160(this.buffer)
11191}
11192
11193// FIXME: doesn't work for data chunks, maybe time to use buffertools.compare...
11194Script.prototype.without = function (needle) {
11195 return Script.fromChunks(this.chunks.filter(function (op) {
11196 return op !== needle
11197 }))
11198}
11199
11200var reverseOps = []
11201for (var op in opcodes) {
11202 var code = opcodes[op]
11203 reverseOps[code] = op
11204}
11205
11206Script.prototype.toASM = function () {
11207 return this.chunks.map(function (chunk) {
11208 // data chunk
11209 if (Buffer.isBuffer(chunk)) {
11210 return chunk.toString('hex')
11211
11212 // opcode
11213 } else {
11214 return reverseOps[chunk]
11215 }
11216 }).join(' ')
11217}
11218
11219Script.prototype.toBuffer = function () {
11220 return this.buffer
11221}
11222
11223Script.prototype.toHex = function () {
11224 return this.toBuffer().toString('hex')
11225}
11226
11227module.exports = Script
11228
11229}).call(this,require("buffer").Buffer)
11230},{"./bufferutils":57,"./crypto":58,"./opcodes":67,"assert":5,"buffer":7,"typeforce":53}],69:[function(require,module,exports){
11231(function (Buffer){
11232var assert = require('assert')
11233var ops = require('./opcodes')
11234var typeForce = require('typeforce')
11235
11236var ecurve = require('ecurve')
11237var curve = ecurve.getCurveByName('secp256k1')
11238
11239var ECSignature = require('./ecsignature')
11240var Script = require('./script')
11241
11242function isCanonicalPubKey (buffer) {
11243 if (!Buffer.isBuffer(buffer)) return false
11244
11245 try {
11246 ecurve.Point.decodeFrom(curve, buffer)
11247 } catch (e) {
11248 if (!(e.message.match(/Invalid sequence (length|tag)/)))
11249 throw e
11250
11251 return false
11252 }
11253
11254 return true
11255}
11256
11257function isCanonicalSignature (buffer) {
11258 if (!Buffer.isBuffer(buffer)) return false
11259
11260 try {
11261 ECSignature.parseScriptSignature(buffer)
11262 } catch (e) {
11263 if (!(e.message.match(/Not a DER sequence|Invalid sequence length|Expected a DER integer|R length is zero|S length is zero|R value excessively padded|S value excessively padded|R value is negative|S value is negative|Invalid hashType/))) {
11264 throw e
11265 }
11266
11267 return false
11268 }
11269
11270 return true
11271}
11272
11273function isPubKeyHashInput (script) {
11274 return script.chunks.length === 2 &&
11275 isCanonicalSignature(script.chunks[0]) &&
11276 isCanonicalPubKey(script.chunks[1])
11277}
11278
11279function isPubKeyHashOutput (script) {
11280 return script.chunks.length === 5 &&
11281 script.chunks[0] === ops.OP_DUP &&
11282 script.chunks[1] === ops.OP_HASH160 &&
11283 Buffer.isBuffer(script.chunks[2]) &&
11284 script.chunks[2].length === 20 &&
11285 script.chunks[3] === ops.OP_EQUALVERIFY &&
11286 script.chunks[4] === ops.OP_CHECKSIG
11287}
11288
11289function isPubKeyInput (script) {
11290 return script.chunks.length === 1 &&
11291 isCanonicalSignature(script.chunks[0])
11292}
11293
11294function isPubKeyOutput (script) {
11295 return script.chunks.length === 2 &&
11296 isCanonicalPubKey(script.chunks[0]) &&
11297 script.chunks[1] === ops.OP_CHECKSIG
11298}
11299
11300function isScriptHashInput (script, allowIncomplete) {
11301 if (script.chunks.length < 2) return false
11302
11303 var lastChunk = script.chunks[script.chunks.length - 1]
11304 if (!Buffer.isBuffer(lastChunk)) return false
11305
11306 var scriptSig = Script.fromChunks(script.chunks.slice(0, -1))
11307 var redeemScript = Script.fromBuffer(lastChunk)
11308
11309 // is redeemScript a valid script?
11310 if (redeemScript.chunks.length === 0) return false
11311
11312 return classifyInput(scriptSig, allowIncomplete) === classifyOutput(redeemScript)
11313}
11314
11315function isScriptHashOutput (script) {
11316 return script.chunks.length === 3 &&
11317 script.chunks[0] === ops.OP_HASH160 &&
11318 Buffer.isBuffer(script.chunks[1]) &&
11319 script.chunks[1].length === 20 &&
11320 script.chunks[2] === ops.OP_EQUAL
11321}
11322
11323// allowIncomplete is to account for combining signatures
11324// See https://github.com/bitcoin/bitcoin/blob/f425050546644a36b0b8e0eb2f6934a3e0f6f80f/src/script/sign.cpp#L195-L197
11325function isMultisigInput (script, allowIncomplete) {
11326 if (script.chunks.length < 2) return false
11327 if (script.chunks[0] !== ops.OP_0) return false
11328
11329 if (allowIncomplete) {
11330 return script.chunks.slice(1).every(function (chunk) {
11331 return chunk === ops.OP_0 || isCanonicalSignature(chunk)
11332 })
11333 }
11334
11335 return script.chunks.slice(1).every(isCanonicalSignature)
11336}
11337
11338function isMultisigOutput (script) {
11339 if (script.chunks.length < 4) return false
11340 if (script.chunks[script.chunks.length - 1] !== ops.OP_CHECKMULTISIG) return false
11341
11342 var mOp = script.chunks[0]
11343 if (mOp === ops.OP_0) return false
11344 if (mOp < ops.OP_1) return false
11345 if (mOp > ops.OP_16) return false
11346
11347 var nOp = script.chunks[script.chunks.length - 2]
11348 if (nOp === ops.OP_0) return false
11349 if (nOp < ops.OP_1) return false
11350 if (nOp > ops.OP_16) return false
11351
11352 var m = mOp - (ops.OP_1 - 1)
11353 var n = nOp - (ops.OP_1 - 1)
11354 if (n < m) return false
11355
11356 var pubKeys = script.chunks.slice(1, -2)
11357 if (n < pubKeys.length) return false
11358
11359 return pubKeys.every(isCanonicalPubKey)
11360}
11361
11362function isNullDataOutput (script) {
11363 return script.chunks[0] === ops.OP_RETURN
11364}
11365
11366function classifyOutput (script) {
11367 typeForce('Script', script)
11368
11369 if (isPubKeyHashOutput(script)) {
11370 return 'pubkeyhash'
11371 } else if (isScriptHashOutput(script)) {
11372 return 'scripthash'
11373 } else if (isMultisigOutput(script)) {
11374 return 'multisig'
11375 } else if (isPubKeyOutput(script)) {
11376 return 'pubkey'
11377 } else if (isNullDataOutput(script)) {
11378 return 'nulldata'
11379 }
11380
11381 return 'nonstandard'
11382}
11383
11384function classifyInput (script, allowIncomplete) {
11385 typeForce('Script', script)
11386
11387 if (isPubKeyHashInput(script)) {
11388 return 'pubkeyhash'
11389 } else if (isMultisigInput(script, allowIncomplete)) {
11390 return 'multisig'
11391 } else if (isScriptHashInput(script, allowIncomplete)) {
11392 return 'scripthash'
11393 } else if (isPubKeyInput(script)) {
11394 return 'pubkey'
11395 }
11396
11397 return 'nonstandard'
11398}
11399
11400// Standard Script Templates
11401// {pubKey} OP_CHECKSIG
11402function pubKeyOutput (pubKey) {
11403 return Script.fromChunks([
11404 pubKey.toBuffer(),
11405 ops.OP_CHECKSIG
11406 ])
11407}
11408
11409// OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
11410function pubKeyHashOutput (hash) {
11411 typeForce('Buffer', hash)
11412
11413 return Script.fromChunks([
11414 ops.OP_DUP,
11415 ops.OP_HASH160,
11416 hash,
11417 ops.OP_EQUALVERIFY,
11418 ops.OP_CHECKSIG
11419 ])
11420}
11421
11422// OP_HASH160 {scriptHash} OP_EQUAL
11423function scriptHashOutput (hash) {
11424 typeForce('Buffer', hash)
11425
11426 return Script.fromChunks([
11427 ops.OP_HASH160,
11428 hash,
11429 ops.OP_EQUAL
11430 ])
11431}
11432
11433// m [pubKeys ...] n OP_CHECKMULTISIG
11434function multisigOutput (m, pubKeys) {
11435 typeForce(['ECPubKey'], pubKeys)
11436
11437 assert(pubKeys.length >= m, 'Not enough pubKeys provided')
11438
11439 var pubKeyBuffers = pubKeys.map(function (pubKey) {
11440 return pubKey.toBuffer()
11441 })
11442 var n = pubKeys.length
11443
11444 return Script.fromChunks([].concat(
11445 (ops.OP_1 - 1) + m,
11446 pubKeyBuffers,
11447 (ops.OP_1 - 1) + n,
11448 ops.OP_CHECKMULTISIG
11449 ))
11450}
11451
11452// {signature}
11453function pubKeyInput (signature) {
11454 typeForce('Buffer', signature)
11455
11456 return Script.fromChunks([signature])
11457}
11458
11459// {signature} {pubKey}
11460function pubKeyHashInput (signature, pubKey) {
11461 typeForce('Buffer', signature)
11462
11463 return Script.fromChunks([signature, pubKey.toBuffer()])
11464}
11465
11466// <scriptSig> {serialized scriptPubKey script}
11467function scriptHashInput (scriptSig, scriptPubKey) {
11468 return Script.fromChunks([].concat(
11469 scriptSig.chunks,
11470 scriptPubKey.toBuffer()
11471 ))
11472}
11473
11474// OP_0 [signatures ...]
11475function multisigInput (signatures, scriptPubKey) {
11476 if (scriptPubKey) {
11477 assert(isMultisigOutput(scriptPubKey))
11478
11479 var mOp = scriptPubKey.chunks[0]
11480 var nOp = scriptPubKey.chunks[scriptPubKey.chunks.length - 2]
11481 var m = mOp - (ops.OP_1 - 1)
11482 var n = nOp - (ops.OP_1 - 1)
11483
11484 assert(signatures.length >= m, 'Not enough signatures provided')
11485 assert(signatures.length <= n, 'Too many signatures provided')
11486 }
11487
11488 return Script.fromChunks([].concat(ops.OP_0, signatures))
11489}
11490
11491function nullDataOutput (data) {
11492 return Script.fromChunks([ops.OP_RETURN, data])
11493}
11494
11495module.exports = {
11496 isCanonicalPubKey: isCanonicalPubKey,
11497 isCanonicalSignature: isCanonicalSignature,
11498 isPubKeyHashInput: isPubKeyHashInput,
11499 isPubKeyHashOutput: isPubKeyHashOutput,
11500 isPubKeyInput: isPubKeyInput,
11501 isPubKeyOutput: isPubKeyOutput,
11502 isScriptHashInput: isScriptHashInput,
11503 isScriptHashOutput: isScriptHashOutput,
11504 isMultisigInput: isMultisigInput,
11505 isMultisigOutput: isMultisigOutput,
11506 isNullDataOutput: isNullDataOutput,
11507 classifyOutput: classifyOutput,
11508 classifyInput: classifyInput,
11509 pubKeyOutput: pubKeyOutput,
11510 pubKeyHashOutput: pubKeyHashOutput,
11511 scriptHashOutput: scriptHashOutput,
11512 multisigOutput: multisigOutput,
11513 pubKeyInput: pubKeyInput,
11514 pubKeyHashInput: pubKeyHashInput,
11515 scriptHashInput: scriptHashInput,
11516 multisigInput: multisigInput,
11517 dataOutput: function (data) {
11518 console.warn('dataOutput is deprecated, use nullDataOutput by 2.0.0')
11519 return nullDataOutput(data)
11520 },
11521 nullDataOutput: nullDataOutput
11522}
11523
11524}).call(this,require("buffer").Buffer)
11525},{"./ecsignature":62,"./opcodes":67,"./script":68,"assert":5,"buffer":7,"ecurve":49,"typeforce":53}],70:[function(require,module,exports){
11526(function (Buffer){
11527var assert = require('assert')
11528var bufferutils = require('./bufferutils')
11529var crypto = require('./crypto')
11530var typeForce = require('typeforce')
11531var opcodes = require('./opcodes')
11532var scripts = require('./scripts')
11533
11534var Address = require('./address')
11535var ECSignature = require('./ecsignature')
11536var Script = require('./script')
11537
11538function Transaction () {
11539 this.version = 1
11540 this.locktime = 0
11541 this.ins = []
11542 this.outs = []
11543}
11544
11545Transaction.DEFAULT_SEQUENCE = 0xffffffff
11546Transaction.SIGHASH_ALL = 0x01
11547Transaction.SIGHASH_NONE = 0x02
11548Transaction.SIGHASH_SINGLE = 0x03
11549Transaction.SIGHASH_ANYONECANPAY = 0x80
11550
11551Transaction.fromBuffer = function (buffer, __disableAssert) {
11552 var offset = 0
11553 function readSlice (n) {
11554 offset += n
11555 return buffer.slice(offset - n, offset)
11556 }
11557
11558 function readUInt32 () {
11559 var i = buffer.readUInt32LE(offset)
11560 offset += 4
11561 return i
11562 }
11563
11564 function readUInt64 () {
11565 var i = bufferutils.readUInt64LE(buffer, offset)
11566 offset += 8
11567 return i
11568 }
11569
11570 function readVarInt () {
11571 var vi = bufferutils.readVarInt(buffer, offset)
11572 offset += vi.size
11573 return vi.number
11574 }
11575
11576 function readScript () {
11577 return Script.fromBuffer(readSlice(readVarInt()))
11578 }
11579
11580 function readGenerationScript () {
11581 return new Script(readSlice(readVarInt()), [])
11582 }
11583
11584 var tx = new Transaction()
11585 tx.version = readUInt32()
11586
11587 var vinLen = readVarInt()
11588 for (var i = 0; i < vinLen; ++i) {
11589 var hash = readSlice(32)
11590
11591 if (Transaction.isCoinbaseHash(hash)) {
11592 tx.ins.push({
11593 hash: hash,
11594 index: readUInt32(),
11595 script: readGenerationScript(),
11596 sequence: readUInt32()
11597 })
11598 } else {
11599 tx.ins.push({
11600 hash: hash,
11601 index: readUInt32(),
11602 script: readScript(),
11603 sequence: readUInt32()
11604 })
11605 }
11606 }
11607
11608 var voutLen = readVarInt()
11609 for (i = 0; i < voutLen; ++i) {
11610 tx.outs.push({
11611 value: readUInt64(),
11612 script: readScript()
11613 })
11614 }
11615
11616 tx.locktime = readUInt32()
11617
11618 if (!__disableAssert) {
11619 assert.equal(offset, buffer.length, 'Transaction has unexpected data')
11620 }
11621
11622 return tx
11623}
11624
11625Transaction.fromHex = function (hex) {
11626 return Transaction.fromBuffer(new Buffer(hex, 'hex'))
11627}
11628
11629Transaction.isCoinbaseHash = function (buffer) {
11630 return Array.prototype.every.call(buffer, function (x) {
11631 return x === 0
11632 })
11633}
11634
11635/**
11636 * Create a new txIn.
11637 *
11638 * Can be called with any of:
11639 *
11640 * - A transaction and an index
11641 * - A transaction hash and an index
11642 *
11643 * Note that this method does not sign the created input.
11644 */
11645Transaction.prototype.addInput = function (hash, index, sequence, script) {
11646 if (sequence === undefined || sequence === null) {
11647 sequence = Transaction.DEFAULT_SEQUENCE
11648 }
11649
11650 script = script || Script.EMPTY
11651
11652 if (typeof hash === 'string') {
11653 // TxId hex is big-endian, we need little-endian
11654 hash = bufferutils.reverse(new Buffer(hash, 'hex'))
11655 } else if (hash instanceof Transaction) {
11656 hash = hash.getHash()
11657 }
11658
11659 typeForce('Buffer', hash)
11660 typeForce('Number', index)
11661 typeForce('Number', sequence)
11662 typeForce('Script', script)
11663
11664 assert.equal(hash.length, 32, 'Expected hash length of 32, got ' + hash.length)
11665
11666 // Add the input and return the input's index
11667 return (this.ins.push({
11668 hash: hash,
11669 index: index,
11670 script: script,
11671 sequence: sequence
11672 }) - 1)
11673}
11674
11675/**
11676 * Create a new txOut.
11677 *
11678 * Can be called with:
11679 *
11680 * - A base58 address string and a value
11681 * - An Address object and a value
11682 * - A scriptPubKey Script and a value
11683 */
11684Transaction.prototype.addOutput = function (scriptPubKey, value) {
11685 // Attempt to get a valid address if it's a base58 address string
11686 if (typeof scriptPubKey === 'string') {
11687 scriptPubKey = Address.fromBase58Check(scriptPubKey)
11688 }
11689
11690 // Attempt to get a valid script if it's an Address object
11691 if (scriptPubKey instanceof Address) {
11692 scriptPubKey = scriptPubKey.toOutputScript()
11693 }
11694
11695 typeForce('Script', scriptPubKey)
11696 typeForce('Number', value)
11697
11698 // Add the output and return the output's index
11699 return (this.outs.push({
11700 script: scriptPubKey,
11701 value: value
11702 }) - 1)
11703}
11704
11705Transaction.prototype.clone = function () {
11706 var newTx = new Transaction()
11707 newTx.version = this.version
11708 newTx.locktime = this.locktime
11709
11710 newTx.ins = this.ins.map(function (txIn) {
11711 return {
11712 hash: txIn.hash,
11713 index: txIn.index,
11714 script: txIn.script,
11715 sequence: txIn.sequence
11716 }
11717 })
11718
11719 newTx.outs = this.outs.map(function (txOut) {
11720 return {
11721 script: txOut.script,
11722 value: txOut.value
11723 }
11724 })
11725
11726 return newTx
11727}
11728
11729/**
11730 * Hash transaction for signing a specific input.
11731 *
11732 * Bitcoin uses a different hash for each signed transaction input. This
11733 * method copies the transaction, makes the necessary changes based on the
11734 * hashType, serializes and finally hashes the result. This hash can then be
11735 * used to sign the transaction input in question.
11736 */
11737Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
11738 // FIXME: remove in 2.x.y
11739 if (arguments[0] instanceof Script) {
11740 console.warn('hashForSignature(prevOutScript, inIndex, ...) has been deprecated. Use hashForSignature(inIndex, prevOutScript, ...)')
11741
11742 // swap the arguments (must be stored in tmp, arguments is special)
11743 var tmp = arguments[0]
11744 inIndex = arguments[1]
11745 prevOutScript = tmp
11746 }
11747
11748 typeForce('Number', inIndex)
11749 typeForce('Script', prevOutScript)
11750 typeForce('Number', hashType)
11751
11752 assert(inIndex >= 0, 'Invalid vin index')
11753 assert(inIndex < this.ins.length, 'Invalid vin index')
11754
11755 var txTmp = this.clone()
11756 var hashScript = prevOutScript.without(opcodes.OP_CODESEPARATOR)
11757
11758 // Blank out other inputs' signatures
11759 txTmp.ins.forEach(function (txIn) {
11760 txIn.script = Script.EMPTY
11761 })
11762 txTmp.ins[inIndex].script = hashScript
11763
11764 var hashTypeModifier = hashType & 0x1f
11765
11766 if (hashTypeModifier === Transaction.SIGHASH_NONE) {
11767 assert(false, 'SIGHASH_NONE not yet supported')
11768 } else if (hashTypeModifier === Transaction.SIGHASH_SINGLE) {
11769 assert(false, 'SIGHASH_SINGLE not yet supported')
11770 }
11771
11772 if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
11773 assert(false, 'SIGHASH_ANYONECANPAY not yet supported')
11774 }
11775
11776 var hashTypeBuffer = new Buffer(4)
11777 hashTypeBuffer.writeInt32LE(hashType, 0)
11778
11779 var buffer = Buffer.concat([txTmp.toBuffer(), hashTypeBuffer])
11780 return crypto.hash256(buffer)
11781}
11782
11783Transaction.prototype.getHash = function () {
11784 return crypto.hash256(this.toBuffer())
11785}
11786
11787Transaction.prototype.getId = function () {
11788 // TxHash is little-endian, we need big-endian
11789 return bufferutils.reverse(this.getHash()).toString('hex')
11790}
11791
11792Transaction.prototype.toBuffer = function () {
11793 function scriptSize (script) {
11794 var length = script.buffer.length
11795
11796 return bufferutils.varIntSize(length) + length
11797 }
11798
11799 var buffer = new Buffer(
11800 8 +
11801 bufferutils.varIntSize(this.ins.length) +
11802 bufferutils.varIntSize(this.outs.length) +
11803 this.ins.reduce(function (sum, input) { return sum + 40 + scriptSize(input.script) }, 0) +
11804 this.outs.reduce(function (sum, output) { return sum + 8 + scriptSize(output.script) }, 0)
11805 )
11806
11807 var offset = 0
11808 function writeSlice (slice) {
11809 slice.copy(buffer, offset)
11810 offset += slice.length
11811 }
11812
11813 function writeUInt32 (i) {
11814 buffer.writeUInt32LE(i, offset)
11815 offset += 4
11816 }
11817
11818 function writeUInt64 (i) {
11819 bufferutils.writeUInt64LE(buffer, i, offset)
11820 offset += 8
11821 }
11822
11823 function writeVarInt (i) {
11824 var n = bufferutils.writeVarInt(buffer, i, offset)
11825 offset += n
11826 }
11827
11828 writeUInt32(this.version)
11829 writeVarInt(this.ins.length)
11830
11831 this.ins.forEach(function (txIn) {
11832 writeSlice(txIn.hash)
11833 writeUInt32(txIn.index)
11834 writeVarInt(txIn.script.buffer.length)
11835 writeSlice(txIn.script.buffer)
11836 writeUInt32(txIn.sequence)
11837 })
11838
11839 writeVarInt(this.outs.length)
11840 this.outs.forEach(function (txOut) {
11841 writeUInt64(txOut.value)
11842 writeVarInt(txOut.script.buffer.length)
11843 writeSlice(txOut.script.buffer)
11844 })
11845
11846 writeUInt32(this.locktime)
11847
11848 return buffer
11849}
11850
11851Transaction.prototype.toHex = function () {
11852 return this.toBuffer().toString('hex')
11853}
11854
11855Transaction.prototype.setInputScript = function (index, script) {
11856 typeForce('Number', index)
11857 typeForce('Script', script)
11858
11859 this.ins[index].script = script
11860}
11861
11862// FIXME: remove in 2.x.y
11863Transaction.prototype.sign = function (index, privKey, hashType) {
11864 console.warn('Transaction.prototype.sign is deprecated. Use TransactionBuilder instead.')
11865
11866 var prevOutScript = privKey.pub.getAddress().toOutputScript()
11867 var signature = this.signInput(index, prevOutScript, privKey, hashType)
11868
11869 var scriptSig = scripts.pubKeyHashInput(signature, privKey.pub)
11870 this.setInputScript(index, scriptSig)
11871}
11872
11873// FIXME: remove in 2.x.y
11874Transaction.prototype.signInput = function (index, prevOutScript, privKey, hashType) {
11875 console.warn('Transaction.prototype.signInput is deprecated. Use TransactionBuilder instead.')
11876
11877 hashType = hashType || Transaction.SIGHASH_ALL
11878
11879 var hash = this.hashForSignature(index, prevOutScript, hashType)
11880 var signature = privKey.sign(hash)
11881
11882 return signature.toScriptSignature(hashType)
11883}
11884
11885// FIXME: remove in 2.x.y
11886Transaction.prototype.validateInput = function (index, prevOutScript, pubKey, buffer) {
11887 console.warn('Transaction.prototype.validateInput is deprecated. Use TransactionBuilder instead.')
11888
11889 var parsed = ECSignature.parseScriptSignature(buffer)
11890 var hash = this.hashForSignature(index, prevOutScript, parsed.hashType)
11891
11892 return pubKey.verify(hash, parsed.signature)
11893}
11894
11895module.exports = Transaction
11896
11897}).call(this,require("buffer").Buffer)
11898},{"./address":54,"./bufferutils":57,"./crypto":58,"./ecsignature":62,"./opcodes":67,"./script":68,"./scripts":69,"assert":5,"buffer":7,"typeforce":53}],71:[function(require,module,exports){
11899(function (Buffer){
11900var assert = require('assert')
11901var ops = require('./opcodes')
11902var scripts = require('./scripts')
11903
11904var ECPubKey = require('./ecpubkey')
11905var ECSignature = require('./ecsignature')
11906var Script = require('./script')
11907var Transaction = require('./transaction')
11908
11909function extractInput (txIn) {
11910 var redeemScript
11911 var scriptSig = txIn.script
11912 var prevOutScript
11913 var prevOutType = scripts.classifyInput(scriptSig, true)
11914 var scriptType
11915
11916 // Re-classify if scriptHash
11917 if (prevOutType === 'scripthash') {
11918 redeemScript = Script.fromBuffer(scriptSig.chunks.slice(-1)[0])
11919 prevOutScript = scripts.scriptHashOutput(redeemScript.getHash())
11920
11921 scriptSig = Script.fromChunks(scriptSig.chunks.slice(0, -1))
11922 scriptType = scripts.classifyInput(scriptSig, true)
11923 } else {
11924 scriptType = prevOutType
11925 }
11926
11927 // Extract hashType, pubKeys and signatures
11928 var hashType, parsed, pubKeys, signatures
11929
11930 switch (scriptType) {
11931 case 'pubkeyhash': {
11932 parsed = ECSignature.parseScriptSignature(scriptSig.chunks[0])
11933 hashType = parsed.hashType
11934 pubKeys = [ECPubKey.fromBuffer(scriptSig.chunks[1])]
11935 signatures = [parsed.signature]
11936 prevOutScript = pubKeys[0].getAddress().toOutputScript()
11937
11938 break
11939 }
11940
11941 case 'pubkey': {
11942 parsed = ECSignature.parseScriptSignature(scriptSig.chunks[0])
11943 hashType = parsed.hashType
11944 signatures = [parsed.signature]
11945
11946 if (redeemScript) {
11947 pubKeys = [ECPubKey.fromBuffer(redeemScript.chunks[0])]
11948 }
11949
11950 break
11951 }
11952
11953 case 'multisig': {
11954 signatures = scriptSig.chunks.slice(1).map(function (chunk) {
11955 if (chunk === ops.OP_0) return chunk
11956
11957 var parsed = ECSignature.parseScriptSignature(chunk)
11958 hashType = parsed.hashType
11959
11960 return parsed.signature
11961 })
11962
11963 if (redeemScript) {
11964 pubKeys = redeemScript.chunks.slice(1, -2).map(ECPubKey.fromBuffer)
11965 }
11966
11967 break
11968 }
11969 }
11970
11971 return {
11972 hashType: hashType,
11973 prevOutScript: prevOutScript,
11974 prevOutType: prevOutType,
11975 pubKeys: pubKeys,
11976 redeemScript: redeemScript,
11977 scriptType: scriptType,
11978 signatures: signatures
11979 }
11980}
11981
11982function TransactionBuilder () {
11983 this.prevTxMap = {}
11984 this.prevOutScripts = {}
11985 this.prevOutTypes = {}
11986
11987 this.inputs = []
11988 this.tx = new Transaction()
11989}
11990
11991TransactionBuilder.fromTransaction = function (transaction) {
11992 var txb = new TransactionBuilder()
11993
11994 // Copy other transaction fields
11995 txb.tx.version = transaction.version
11996 txb.tx.locktime = transaction.locktime
11997
11998 // Extract/add inputs
11999 transaction.ins.forEach(function (txIn) {
12000 txb.addInput(txIn.hash, txIn.index, txIn.sequence)
12001 })
12002
12003 // Extract/add outputs
12004 transaction.outs.forEach(function (txOut) {
12005 txb.addOutput(txOut.script, txOut.value)
12006 })
12007
12008 // Extract/add signatures
12009 txb.inputs = transaction.ins.map(function (txIn) {
12010 // TODO: remove me after testcase added
12011 assert(!Transaction.isCoinbaseHash(txIn.hash), 'coinbase inputs not supported')
12012
12013 // Ignore empty scripts
12014 if (txIn.script.buffer.length === 0) return {}
12015
12016 return extractInput(txIn)
12017 })
12018
12019 return txb
12020}
12021
12022TransactionBuilder.prototype.addInput = function (prevTx, index, sequence, prevOutScript) {
12023 var prevOutHash
12024
12025 // txId
12026 if (typeof prevTx === 'string') {
12027 prevOutHash = new Buffer(prevTx, 'hex')
12028
12029 // TxId hex is big-endian, we want little-endian hash
12030 Array.prototype.reverse.call(prevOutHash)
12031
12032 // Transaction
12033 } else if (prevTx instanceof Transaction) {
12034 prevOutHash = prevTx.getHash()
12035 prevOutScript = prevTx.outs[index].script
12036
12037 // txHash
12038 } else {
12039 prevOutHash = prevTx
12040 }
12041
12042 var input = {}
12043 if (prevOutScript) {
12044 var prevOutType = scripts.classifyOutput(prevOutScript)
12045
12046 // if we can, extract pubKey information
12047 switch (prevOutType) {
12048 case 'multisig': {
12049 input.pubKeys = prevOutScript.chunks.slice(1, -2).map(ECPubKey.fromBuffer)
12050 break
12051 }
12052
12053 case 'pubkey': {
12054 input.pubKeys = prevOutScript.chunks.slice(0, 1).map(ECPubKey.fromBuffer)
12055 break
12056 }
12057 }
12058
12059 if (prevOutType !== 'scripthash') {
12060 input.scriptType = prevOutType
12061 }
12062
12063 input.prevOutScript = prevOutScript
12064 input.prevOutType = prevOutType
12065 }
12066
12067 assert(this.inputs.every(function (input2) {
12068 if (input2.hashType === undefined) return true
12069
12070 return input2.hashType & Transaction.SIGHASH_ANYONECANPAY
12071 }), 'No, this would invalidate signatures')
12072
12073 var prevOut = prevOutHash.toString('hex') + ':' + index
12074 assert(!(prevOut in this.prevTxMap), 'Transaction is already an input')
12075
12076 var vin = this.tx.addInput(prevOutHash, index, sequence)
12077 this.inputs[vin] = input
12078 this.prevTxMap[prevOut] = vin
12079
12080 return vin
12081}
12082
12083TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) {
12084 assert(this.inputs.every(function (input) {
12085 if (input.hashType === undefined) return true
12086
12087 return (input.hashType & 0x1f) === Transaction.SIGHASH_SINGLE
12088 }), 'No, this would invalidate signatures')
12089
12090 return this.tx.addOutput(scriptPubKey, value)
12091}
12092
12093TransactionBuilder.prototype.build = function () {
12094 return this.__build(false)
12095}
12096TransactionBuilder.prototype.buildIncomplete = function () {
12097 return this.__build(true)
12098}
12099
12100var canSignTypes = {
12101 'pubkeyhash': true,
12102 'multisig': true,
12103 'pubkey': true
12104}
12105
12106TransactionBuilder.prototype.__build = function (allowIncomplete) {
12107 if (!allowIncomplete) {
12108 assert(this.tx.ins.length > 0, 'Transaction has no inputs')
12109 assert(this.tx.outs.length > 0, 'Transaction has no outputs')
12110 }
12111
12112 var tx = this.tx.clone()
12113
12114 // Create script signatures from signature meta-data
12115 this.inputs.forEach(function (input, index) {
12116 var scriptType = input.scriptType
12117 var scriptSig
12118
12119 if (!allowIncomplete) {
12120 assert(!!scriptType, 'Transaction is not complete')
12121 assert(scriptType in canSignTypes, scriptType + ' not supported')
12122 assert(input.signatures, 'Transaction is missing signatures')
12123 }
12124
12125 if (input.signatures) {
12126 switch (scriptType) {
12127 case 'pubkeyhash': {
12128 var pkhSignature = input.signatures[0].toScriptSignature(input.hashType)
12129 scriptSig = scripts.pubKeyHashInput(pkhSignature, input.pubKeys[0])
12130 break
12131 }
12132
12133 case 'multisig': {
12134 // Array.prototype.map is sparse-compatible
12135 var msSignatures = input.signatures.map(function (signature) {
12136 return signature && signature.toScriptSignature(input.hashType)
12137 })
12138
12139 // fill in blanks with OP_0
12140 if (allowIncomplete) {
12141 for (var i = 0; i < msSignatures.length; ++i) {
12142 if (msSignatures[i]) continue
12143
12144 msSignatures[i] = ops.OP_0
12145 }
12146 } else {
12147 // Array.prototype.filter returns non-sparse array
12148 msSignatures = msSignatures.filter(function (x) { return x })
12149 }
12150
12151 var redeemScript = allowIncomplete ? undefined : input.redeemScript
12152 scriptSig = scripts.multisigInput(msSignatures, redeemScript)
12153 break
12154 }
12155
12156 case 'pubkey': {
12157 var pkSignature = input.signatures[0].toScriptSignature(input.hashType)
12158 scriptSig = scripts.pubKeyInput(pkSignature)
12159 break
12160 }
12161 }
12162 }
12163
12164 // did we build a scriptSig?
12165 if (scriptSig) {
12166 // wrap as scriptHash if necessary
12167 if (input.prevOutType === 'scripthash') {
12168 scriptSig = scripts.scriptHashInput(scriptSig, input.redeemScript)
12169 }
12170
12171 tx.setInputScript(index, scriptSig)
12172 }
12173 })
12174
12175 return tx
12176}
12177
12178TransactionBuilder.prototype.sign = function (index, privKey, redeemScript, hashType) {
12179 assert(index in this.inputs, 'No input at index: ' + index)
12180 hashType = hashType || Transaction.SIGHASH_ALL
12181
12182 var input = this.inputs[index]
12183 var canSign = input.hashType &&
12184 input.prevOutScript &&
12185 input.prevOutType &&
12186 input.pubKeys &&
12187 input.scriptType &&
12188 input.signatures
12189
12190 // are we almost ready to sign?
12191 if (canSign) {
12192 // if redeemScript was provided, enforce consistency
12193 if (redeemScript) {
12194 assert.deepEqual(input.redeemScript, redeemScript, 'Inconsistent redeemScript')
12195 }
12196
12197 assert.equal(input.hashType, hashType, 'Inconsistent hashType')
12198
12199 // no? prepare
12200 } else {
12201 // must be pay-to-scriptHash?
12202 if (redeemScript) {
12203 // if we have a prevOutScript, enforce scriptHash equality to the redeemScript
12204 if (input.prevOutScript) {
12205 assert.equal(input.prevOutType, 'scripthash', 'PrevOutScript must be P2SH')
12206
12207 var scriptHash = input.prevOutScript.chunks[1]
12208 assert.deepEqual(scriptHash, redeemScript.getHash(), 'RedeemScript does not match ' + scriptHash.toString('hex'))
12209 }
12210
12211 var scriptType = scripts.classifyOutput(redeemScript)
12212 assert(scriptType in canSignTypes, 'RedeemScript not supported (' + scriptType + ')')
12213
12214 var pubKeys = []
12215 switch (scriptType) {
12216 case 'multisig': {
12217 pubKeys = redeemScript.chunks.slice(1, -2).map(ECPubKey.fromBuffer)
12218 break
12219 }
12220
12221 case 'pubkeyhash': {
12222 var pkh1 = redeemScript.chunks[2]
12223 var pkh2 = privKey.pub.getAddress().hash
12224
12225 assert.deepEqual(pkh1, pkh2, 'privateKey cannot sign for this input')
12226 pubKeys = [privKey.pub]
12227 break
12228 }
12229
12230 case 'pubkey': {
12231 pubKeys = redeemScript.chunks.slice(0, 1).map(ECPubKey.fromBuffer)
12232 break
12233 }
12234 }
12235
12236 if (!input.prevOutScript) {
12237 input.prevOutScript = scripts.scriptHashOutput(redeemScript.getHash())
12238 input.prevOutType = 'scripthash'
12239 }
12240
12241 input.pubKeys = pubKeys
12242 input.redeemScript = redeemScript
12243 input.scriptType = scriptType
12244
12245 // cannot be pay-to-scriptHash
12246 } else {
12247 assert.notEqual(input.prevOutType, 'scripthash', 'PrevOutScript is P2SH, missing redeemScript')
12248
12249 // can we otherwise sign this?
12250 if (input.scriptType) {
12251 assert(input.pubKeys, input.scriptType + ' not supported')
12252
12253 // we know nothin' Jon Snow, assume pubKeyHash
12254 } else {
12255 input.prevOutScript = privKey.pub.getAddress().toOutputScript()
12256 input.prevOutType = 'pubkeyhash'
12257 input.pubKeys = [privKey.pub]
12258 input.scriptType = input.prevOutType
12259 }
12260 }
12261
12262 input.hashType = hashType
12263 input.signatures = input.signatures || []
12264 }
12265
12266 var signatureScript = input.redeemScript || input.prevOutScript
12267 var signatureHash = this.tx.hashForSignature(index, signatureScript, hashType)
12268
12269 // enforce signature order matches public keys
12270 if (input.scriptType === 'multisig' && input.redeemScript && input.signatures.length !== input.pubKeys.length) {
12271 // maintain a local copy of unmatched signatures
12272 var unmatched = input.signatures.slice()
12273
12274 input.signatures = input.pubKeys.map(function (pubKey) {
12275 var match
12276
12277 // check for any matching signatures
12278 unmatched.some(function (signature, i) {
12279 if (!pubKey.verify(signatureHash, signature)) return false
12280 match = signature
12281
12282 // remove matched signature from unmatched
12283 unmatched.splice(i, 1)
12284
12285 return true
12286 })
12287
12288 return match || undefined
12289 })
12290 }
12291
12292 // enforce in order signing of public keys
12293 assert(input.pubKeys.some(function (pubKey, i) {
12294 if (!privKey.pub.Q.equals(pubKey.Q)) return false
12295
12296 assert(!input.signatures[i], 'Signature already exists')
12297 var signature = privKey.sign(signatureHash)
12298 input.signatures[i] = signature
12299
12300 return true
12301 }, this), 'privateKey cannot sign for this input')
12302}
12303
12304module.exports = TransactionBuilder
12305
12306}).call(this,require("buffer").Buffer)
12307},{"./ecpubkey":61,"./ecsignature":62,"./opcodes":67,"./script":68,"./scripts":69,"./transaction":70,"assert":5,"buffer":7}],72:[function(require,module,exports){
12308(function (Buffer){
12309var assert = require('assert')
12310var bufferutils = require('./bufferutils')
12311var typeForce = require('typeforce')
12312var networks = require('./networks')
12313var randomBytes = require('randombytes')
12314
12315var Address = require('./address')
12316var HDNode = require('./hdnode')
12317var TransactionBuilder = require('./transaction_builder')
12318var Script = require('./script')
12319
12320function Wallet (seed, network) {
12321 console.warn('Wallet is deprecated and will be removed in 2.0.0, see #296')
12322
12323 seed = seed || randomBytes(32)
12324 network = network || networks.bitcoin
12325
12326 // Stored in a closure to make accidental serialization less likely
12327 var masterKey = HDNode.fromSeedBuffer(seed, network)
12328
12329 // HD first-level child derivation method should be hardened
12330 // See https://bitcointalk.org/index.php?topic=405179.msg4415254#msg4415254
12331 var accountZero = masterKey.deriveHardened(0)
12332 var externalAccount = accountZero.derive(0)
12333 var internalAccount = accountZero.derive(1)
12334
12335 this.addresses = []
12336 this.changeAddresses = []
12337 this.network = network
12338 this.unspents = []
12339
12340 // FIXME: remove in 2.0.0
12341 this.unspentMap = {}
12342
12343 // FIXME: remove in 2.0.0
12344 var me = this
12345 this.newMasterKey = function (seed) {
12346 console.warn('newMasterKey is deprecated, please make a new Wallet instance instead')
12347
12348 seed = seed || randomBytes(32)
12349 masterKey = HDNode.fromSeedBuffer(seed, network)
12350
12351 accountZero = masterKey.deriveHardened(0)
12352 externalAccount = accountZero.derive(0)
12353 internalAccount = accountZero.derive(1)
12354
12355 me.addresses = []
12356 me.changeAddresses = []
12357
12358 me.unspents = []
12359 me.unspentMap = {}
12360 }
12361
12362 this.getMasterKey = function () {
12363 return masterKey
12364 }
12365 this.getAccountZero = function () {
12366 return accountZero
12367 }
12368 this.getExternalAccount = function () {
12369 return externalAccount
12370 }
12371 this.getInternalAccount = function () {
12372 return internalAccount
12373 }
12374}
12375
12376Wallet.prototype.createTransaction = function (to, value, options) {
12377 // FIXME: remove in 2.0.0
12378 if (typeof options !== 'object') {
12379 if (options !== undefined) {
12380 console.warn('Non options object parameters are deprecated, use options object instead')
12381
12382 options = {
12383 fixedFee: arguments[2],
12384 changeAddress: arguments[3]
12385 }
12386 }
12387 }
12388
12389 options = options || {}
12390
12391 assert(value > this.network.dustThreshold, value + ' must be above dust threshold (' + this.network.dustThreshold + ' Satoshis)')
12392
12393 var changeAddress = options.changeAddress
12394 var fixedFee = options.fixedFee
12395 var minConf = options.minConf === undefined ? 0 : options.minConf // FIXME: change minConf:1 by default in 2.0.0
12396
12397 // filter by minConf, then pending and sort by descending value
12398 var unspents = this.unspents.filter(function (unspent) {
12399 return unspent.confirmations >= minConf
12400 }).filter(function (unspent) {
12401 return !unspent.pending
12402 }).sort(function (o1, o2) {
12403 return o2.value - o1.value
12404 })
12405
12406 var accum = 0
12407 var addresses = []
12408 var subTotal = value
12409
12410 var txb = new TransactionBuilder()
12411 txb.addOutput(to, value)
12412
12413 for (var i = 0; i < unspents.length; ++i) {
12414 var unspent = unspents[i]
12415 addresses.push(unspent.address)
12416
12417 txb.addInput(unspent.txHash, unspent.index)
12418
12419 var fee = fixedFee === undefined ? estimatePaddedFee(txb.buildIncomplete(), this.network) : fixedFee
12420
12421 accum += unspent.value
12422 subTotal = value + fee
12423
12424 if (accum >= subTotal) {
12425 var change = accum - subTotal
12426
12427 if (change > this.network.dustThreshold) {
12428 txb.addOutput(changeAddress || this.getChangeAddress(), change)
12429 }
12430
12431 break
12432 }
12433 }
12434
12435 assert(accum >= subTotal, 'Not enough funds (incl. fee): ' + accum + ' < ' + subTotal)
12436
12437 return this.signWith(txb, addresses).build()
12438}
12439
12440// FIXME: remove in 2.0.0
12441Wallet.prototype.processPendingTx = function (tx) {
12442 this.__processTx(tx, true)
12443}
12444
12445// FIXME: remove in 2.0.0
12446Wallet.prototype.processConfirmedTx = function (tx) {
12447 this.__processTx(tx, false)
12448}
12449
12450// FIXME: remove in 2.0.0
12451Wallet.prototype.__processTx = function (tx, isPending) {
12452 console.warn('processTransaction is considered harmful, see issue #260 for more information')
12453
12454 var txId = tx.getId()
12455 var txHash = tx.getHash()
12456
12457 tx.outs.forEach(function (txOut, i) {
12458 var address
12459
12460 try {
12461 address = Address.fromOutputScript(txOut.script, this.network).toString()
12462 } catch (e) {
12463 if (!(e.message.match(/has no matching Address/)))
12464 throw e
12465 }
12466
12467 var myAddresses = this.addresses.concat(this.changeAddresses)
12468 if (myAddresses.indexOf(address) > -1) {
12469 var lookup = txId + ':' + i
12470 if (lookup in this.unspentMap) return
12471
12472 // its unique, add it
12473 var unspent = {
12474 address: address,
12475 confirmations: 0, // no way to determine this without more information
12476 index: i,
12477 txHash: txHash,
12478 txId: txId,
12479 value: txOut.value,
12480 pending: isPending
12481 }
12482
12483 this.unspentMap[lookup] = unspent
12484 this.unspents.push(unspent)
12485 }
12486 }, this)
12487
12488 tx.ins.forEach(function (txIn) {
12489 // copy and convert to big-endian hex
12490 var txInId = bufferutils.reverse(txIn.hash).toString('hex')
12491
12492 var lookup = txInId + ':' + txIn.index
12493 if (!(lookup in this.unspentMap)) return
12494
12495 var unspent = this.unspentMap[lookup]
12496
12497 if (isPending) {
12498 unspent.pending = true
12499 unspent.spent = true
12500 } else {
12501 delete this.unspentMap[lookup]
12502
12503 this.unspents = this.unspents.filter(function (unspent2) {
12504 return unspent !== unspent2
12505 })
12506 }
12507 }, this)
12508}
12509
12510Wallet.prototype.generateAddress = function () {
12511 var k = this.addresses.length
12512 var address = this.getExternalAccount().derive(k).getAddress()
12513
12514 this.addresses.push(address.toString())
12515
12516 return this.getReceiveAddress()
12517}
12518
12519Wallet.prototype.generateChangeAddress = function () {
12520 var k = this.changeAddresses.length
12521 var address = this.getInternalAccount().derive(k).getAddress()
12522
12523 this.changeAddresses.push(address.toString())
12524
12525 return this.getChangeAddress()
12526}
12527
12528Wallet.prototype.getAddress = function () {
12529 if (this.addresses.length === 0) {
12530 this.generateAddress()
12531 }
12532
12533 return this.addresses[this.addresses.length - 1]
12534}
12535
12536Wallet.prototype.getBalance = function (minConf) {
12537 minConf = minConf || 0
12538
12539 return this.unspents.filter(function (unspent) {
12540 return unspent.confirmations >= minConf
12541
12542 // FIXME: remove spent filter in 2.0.0
12543 }).filter(function (unspent) {
12544 return !unspent.spent
12545 }).reduce(function (accum, unspent) {
12546 return accum + unspent.value
12547 }, 0)
12548}
12549
12550Wallet.prototype.getChangeAddress = function () {
12551 if (this.changeAddresses.length === 0) {
12552 this.generateChangeAddress()
12553 }
12554
12555 return this.changeAddresses[this.changeAddresses.length - 1]
12556}
12557
12558Wallet.prototype.getInternalPrivateKey = function (index) {
12559 return this.getInternalAccount().derive(index).privKey
12560}
12561
12562Wallet.prototype.getPrivateKey = function (index) {
12563 return this.getExternalAccount().derive(index).privKey
12564}
12565
12566Wallet.prototype.getPrivateKeyForAddress = function (address) {
12567 var index
12568
12569 if ((index = this.addresses.indexOf(address)) > -1) {
12570 return this.getPrivateKey(index)
12571 }
12572
12573 if ((index = this.changeAddresses.indexOf(address)) > -1) {
12574 return this.getInternalPrivateKey(index)
12575 }
12576
12577 assert(false, 'Unknown address. Make sure the address is from the keychain and has been generated')
12578}
12579
12580Wallet.prototype.getUnspentOutputs = function (minConf) {
12581 minConf = minConf || 0
12582
12583 return this.unspents.filter(function (unspent) {
12584 return unspent.confirmations >= minConf
12585
12586 // FIXME: remove spent filter in 2.0.0
12587 }).filter(function (unspent) {
12588 return !unspent.spent
12589 }).map(function (unspent) {
12590 return {
12591 address: unspent.address,
12592 confirmations: unspent.confirmations,
12593 index: unspent.index,
12594 txId: unspent.txId,
12595 value: unspent.value,
12596
12597 // FIXME: remove in 2.0.0
12598 hash: unspent.txId,
12599 pending: unspent.pending
12600 }
12601 })
12602}
12603
12604Wallet.prototype.setUnspentOutputs = function (unspents) {
12605 this.unspentMap = {}
12606 this.unspents = unspents.map(function (unspent) {
12607 // FIXME: remove unspent.hash in 2.0.0
12608 var txId = unspent.txId || unspent.hash
12609 var index = unspent.index
12610
12611 // FIXME: remove in 2.0.0
12612 if (unspent.hash !== undefined) {
12613 console.warn('unspent.hash is deprecated, use unspent.txId instead')
12614 }
12615
12616 // FIXME: remove in 2.0.0
12617 if (index === undefined) {
12618 console.warn('unspent.outputIndex is deprecated, use unspent.index instead')
12619 index = unspent.outputIndex
12620 }
12621
12622 typeForce('String', txId)
12623 typeForce('Number', index)
12624 typeForce('Number', unspent.value)
12625
12626 assert.equal(txId.length, 64, 'Expected valid txId, got ' + txId)
12627 assert.doesNotThrow(function () {
12628 Address.fromBase58Check(unspent.address)
12629 }, 'Expected Base58 Address, got ' + unspent.address)
12630 assert(isFinite(index), 'Expected finite index, got ' + index)
12631
12632 // FIXME: remove branch in 2.0.0
12633 if (unspent.confirmations !== undefined) {
12634 typeForce('Number', unspent.confirmations)
12635 }
12636
12637 var txHash = bufferutils.reverse(new Buffer(txId, 'hex'))
12638
12639 unspent = {
12640 address: unspent.address,
12641 confirmations: unspent.confirmations || 0,
12642 index: index,
12643 txHash: txHash,
12644 txId: txId,
12645 value: unspent.value,
12646
12647 // FIXME: remove in 2.0.0
12648 pending: unspent.pending || false
12649 }
12650
12651 // FIXME: remove in 2.0.0
12652 this.unspentMap[txId + ':' + index] = unspent
12653
12654 return unspent
12655 }, this)
12656}
12657
12658Wallet.prototype.signWith = function (tx, addresses) {
12659 addresses.forEach(function (address, i) {
12660 var privKey = this.getPrivateKeyForAddress(address)
12661
12662 tx.sign(i, privKey)
12663 }, this)
12664
12665 return tx
12666}
12667
12668function estimatePaddedFee (tx, network) {
12669 var tmpTx = tx.clone()
12670 tmpTx.addOutput(Script.EMPTY, network.dustSoftThreshold || 0)
12671
12672 return network.estimateFee(tmpTx)
12673}
12674
12675// FIXME: 1.0.0 shims, remove in 2.0.0
12676Wallet.prototype.getReceiveAddress = Wallet.prototype.getAddress
12677Wallet.prototype.createTx = Wallet.prototype.createTransaction
12678
12679module.exports = Wallet
12680
12681}).call(this,require("buffer").Buffer)
12682},{"./address":54,"./bufferutils":57,"./hdnode":63,"./networks":66,"./script":68,"./transaction_builder":71,"assert":5,"buffer":7,"randombytes":52,"typeforce":53}]},{},[64])(64)
12683}); \ No newline at end of file
diff --git a/src/js/index.js b/src/js/index.js
index 9ea5bb5..5eb4b29 100644
--- a/src/js/index.js
+++ b/src/js/index.js
@@ -3,7 +3,7 @@
3 var mnemonic = new Mnemonic("english"); 3 var mnemonic = new Mnemonic("english");
4 var bip32RootKey = null; 4 var bip32RootKey = null;
5 var bip32ExtendedKey = null; 5 var bip32ExtendedKey = null;
6 var network = Bitcoin.networks.bitcoin; 6 var network = bitcoin.networks.bitcoin;
7 var addressRowTemplate = $("#address-row-template"); 7 var addressRowTemplate = $("#address-row-template");
8 8
9 var showIndex = true; 9 var showIndex = true;
@@ -187,7 +187,7 @@
187 187
188 function calcBip32Seed(phrase, passphrase, path) { 188 function calcBip32Seed(phrase, passphrase, path) {
189 var seed = mnemonic.toSeed(phrase, passphrase); 189 var seed = mnemonic.toSeed(phrase, passphrase);
190 bip32RootKey = Bitcoin.HDNode.fromSeedHex(seed, network); 190 bip32RootKey = bitcoin.HDNode.fromSeedHex(seed, network);
191 bip32ExtendedKey = bip32RootKey; 191 bip32ExtendedKey = bip32RootKey;
192 // Derive the key from the path 192 // Derive the key from the path
193 var pathBits = path.split("/"); 193 var pathBits = path.split("/");
@@ -399,7 +399,7 @@
399 { 399 {
400 name: "Bitcoin", 400 name: "Bitcoin",
401 onSelect: function() { 401 onSelect: function() {
402 network = Bitcoin.networks.bitcoin; 402 network = bitcoin.networks.bitcoin;
403 DOM.bip44coin.val(0); 403 DOM.bip44coin.val(0);
404 DOM.myceliumPath.val("m/44'/0'/0'/0"); 404 DOM.myceliumPath.val("m/44'/0'/0'/0");
405 }, 405 },
@@ -407,7 +407,7 @@
407 { 407 {
408 name: "Bitcoin Testnet", 408 name: "Bitcoin Testnet",
409 onSelect: function() { 409 onSelect: function() {
410 network = Bitcoin.networks.testnet; 410 network = bitcoin.networks.testnet;
411 DOM.bip44coin.val(1); 411 DOM.bip44coin.val(1);
412 DOM.myceliumPath.val("m/44'/1'/0'/0"); 412 DOM.myceliumPath.val("m/44'/1'/0'/0");
413 }, 413 },
@@ -415,14 +415,14 @@
415 { 415 {
416 name: "Litecoin", 416 name: "Litecoin",
417 onSelect: function() { 417 onSelect: function() {
418 network = Bitcoin.networks.litecoin; 418 network = bitcoin.networks.litecoin;
419 DOM.bip44coin.val(2); 419 DOM.bip44coin.val(2);
420 }, 420 },
421 }, 421 },
422 { 422 {
423 name: "Dogecoin", 423 name: "Dogecoin",
424 onSelect: function() { 424 onSelect: function() {
425 network = Bitcoin.networks.dogecoin; 425 network = bitcoin.networks.dogecoin;
426 DOM.bip44coin.val(3); 426 DOM.bip44coin.val(3);
427 }, 427 },
428 }, 428 },