aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorIan Coleman <coleman.ian@gmail.com>2017-07-31 16:49:11 +1000
committerIan Coleman <coleman.ian@gmail.com>2017-08-02 17:11:39 +1000
commita0091a40c46d1ece61193ee84c0a1b7de771e447 (patch)
treec323ff7b6f64fc24decabae8aafa1d7e7c95e66e /src
parent039a98ba5afc254d0ef6fb3dcc97f4080e2a413a (diff)
downloadBIP39-a0091a40c46d1ece61193ee84c0a1b7de771e447.tar.gz
BIP39-a0091a40c46d1ece61193ee84c0a1b7de771e447.tar.zst
BIP39-a0091a40c46d1ece61193ee84c0a1b7de771e447.zip
Upgrade bitcoinjs from v1.5.7 to v3.1.1
Diffstat (limited to 'src')
-rw-r--r--src/index.html2
-rw-r--r--src/js/bitcoinjs-1-5-7.js12683
-rw-r--r--src/js/bitcoinjs-3-1-1.js14830
-rw-r--r--src/js/bitcoinjs-extensions.js107
-rw-r--r--src/js/index.js62
5 files changed, 14950 insertions, 12734 deletions
diff --git a/src/index.html b/src/index.html
index ed03279..b73b92a 100644
--- a/src/index.html
+++ b/src/index.html
@@ -686,7 +686,7 @@
686 <script src="js/bootstrap.min.js"></script> 686 <script src="js/bootstrap.min.js"></script>
687 <script src="js/levenshtein.js"></script> 687 <script src="js/levenshtein.js"></script>
688 <script src="js/jquery.qrcode.min.js"></script> 688 <script src="js/jquery.qrcode.min.js"></script>
689 <script src="js/bitcoinjs-1-5-7.js"></script> 689 <script src="js/bitcoinjs-3-1-1.js"></script>
690 <script src="js/bitcoinjs-extensions.js"></script> 690 <script src="js/bitcoinjs-extensions.js"></script>
691 <script src="js/ethereumjs-util.js"></script> 691 <script src="js/ethereumjs-util.js"></script>
692 <script src="js/ripple-util.js"></script> 692 <script src="js/ripple-util.js"></script>
diff --git a/src/js/bitcoinjs-1-5-7.js b/src/js/bitcoinjs-1-5-7.js
deleted file mode 100644
index 7b7e8e8..0000000
--- a/src/js/bitcoinjs-1-5-7.js
+++ /dev/null
@@ -1,12683 +0,0 @@
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/bitcoinjs-3-1-1.js b/src/js/bitcoinjs-3-1-1.js
new file mode 100644
index 0000000..e75e15d
--- /dev/null
+++ b/src/js/bitcoinjs-3-1-1.js
@@ -0,0 +1,14830 @@
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.bitcoinjs = 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(function (global){
3'use strict';
4
5// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
6// original notice:
7
8/*!
9 * The buffer module from node.js, for the browser.
10 *
11 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
12 * @license MIT
13 */
14function compare(a, b) {
15 if (a === b) {
16 return 0;
17 }
18
19 var x = a.length;
20 var y = b.length;
21
22 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
23 if (a[i] !== b[i]) {
24 x = a[i];
25 y = b[i];
26 break;
27 }
28 }
29
30 if (x < y) {
31 return -1;
32 }
33 if (y < x) {
34 return 1;
35 }
36 return 0;
37}
38function isBuffer(b) {
39 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
40 return global.Buffer.isBuffer(b);
41 }
42 return !!(b != null && b._isBuffer);
43}
44
45// based on node assert, original notice:
46
47// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
48//
49// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
50//
51// Originally from narwhal.js (http://narwhaljs.org)
52// Copyright (c) 2009 Thomas Robinson <280north.com>
53//
54// Permission is hereby granted, free of charge, to any person obtaining a copy
55// of this software and associated documentation files (the 'Software'), to
56// deal in the Software without restriction, including without limitation the
57// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
58// sell copies of the Software, and to permit persons to whom the Software is
59// furnished to do so, subject to the following conditions:
60//
61// The above copyright notice and this permission notice shall be included in
62// all copies or substantial portions of the Software.
63//
64// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
65// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
66// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
67// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
68// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
69// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70
71var util = require('util/');
72var hasOwn = Object.prototype.hasOwnProperty;
73var pSlice = Array.prototype.slice;
74var functionsHaveNames = (function () {
75 return function foo() {}.name === 'foo';
76}());
77function pToString (obj) {
78 return Object.prototype.toString.call(obj);
79}
80function isView(arrbuf) {
81 if (isBuffer(arrbuf)) {
82 return false;
83 }
84 if (typeof global.ArrayBuffer !== 'function') {
85 return false;
86 }
87 if (typeof ArrayBuffer.isView === 'function') {
88 return ArrayBuffer.isView(arrbuf);
89 }
90 if (!arrbuf) {
91 return false;
92 }
93 if (arrbuf instanceof DataView) {
94 return true;
95 }
96 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
97 return true;
98 }
99 return false;
100}
101// 1. The assert module provides functions that throw
102// AssertionError's when particular conditions are not met. The
103// assert module must conform to the following interface.
104
105var assert = module.exports = ok;
106
107// 2. The AssertionError is defined in assert.
108// new assert.AssertionError({ message: message,
109// actual: actual,
110// expected: expected })
111
112var regex = /\s*function\s+([^\(\s]*)\s*/;
113// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
114function getName(func) {
115 if (!util.isFunction(func)) {
116 return;
117 }
118 if (functionsHaveNames) {
119 return func.name;
120 }
121 var str = func.toString();
122 var match = str.match(regex);
123 return match && match[1];
124}
125assert.AssertionError = function AssertionError(options) {
126 this.name = 'AssertionError';
127 this.actual = options.actual;
128 this.expected = options.expected;
129 this.operator = options.operator;
130 if (options.message) {
131 this.message = options.message;
132 this.generatedMessage = false;
133 } else {
134 this.message = getMessage(this);
135 this.generatedMessage = true;
136 }
137 var stackStartFunction = options.stackStartFunction || fail;
138 if (Error.captureStackTrace) {
139 Error.captureStackTrace(this, stackStartFunction);
140 } else {
141 // non v8 browsers so we can have a stacktrace
142 var err = new Error();
143 if (err.stack) {
144 var out = err.stack;
145
146 // try to strip useless frames
147 var fn_name = getName(stackStartFunction);
148 var idx = out.indexOf('\n' + fn_name);
149 if (idx >= 0) {
150 // once we have located the function frame
151 // we need to strip out everything before it (and its line)
152 var next_line = out.indexOf('\n', idx + 1);
153 out = out.substring(next_line + 1);
154 }
155
156 this.stack = out;
157 }
158 }
159};
160
161// assert.AssertionError instanceof Error
162util.inherits(assert.AssertionError, Error);
163
164function truncate(s, n) {
165 if (typeof s === 'string') {
166 return s.length < n ? s : s.slice(0, n);
167 } else {
168 return s;
169 }
170}
171function inspect(something) {
172 if (functionsHaveNames || !util.isFunction(something)) {
173 return util.inspect(something);
174 }
175 var rawname = getName(something);
176 var name = rawname ? ': ' + rawname : '';
177 return '[Function' + name + ']';
178}
179function getMessage(self) {
180 return truncate(inspect(self.actual), 128) + ' ' +
181 self.operator + ' ' +
182 truncate(inspect(self.expected), 128);
183}
184
185// At present only the three keys mentioned above are used and
186// understood by the spec. Implementations or sub modules can pass
187// other keys to the AssertionError's constructor - they will be
188// ignored.
189
190// 3. All of the following functions must throw an AssertionError
191// when a corresponding condition is not met, with a message that
192// may be undefined if not provided. All assertion methods provide
193// both the actual and expected values to the assertion error for
194// display purposes.
195
196function fail(actual, expected, message, operator, stackStartFunction) {
197 throw new assert.AssertionError({
198 message: message,
199 actual: actual,
200 expected: expected,
201 operator: operator,
202 stackStartFunction: stackStartFunction
203 });
204}
205
206// EXTENSION! allows for well behaved errors defined elsewhere.
207assert.fail = fail;
208
209// 4. Pure assertion tests whether a value is truthy, as determined
210// by !!guard.
211// assert.ok(guard, message_opt);
212// This statement is equivalent to assert.equal(true, !!guard,
213// message_opt);. To test strictly for the value true, use
214// assert.strictEqual(true, guard, message_opt);.
215
216function ok(value, message) {
217 if (!value) fail(value, true, message, '==', assert.ok);
218}
219assert.ok = ok;
220
221// 5. The equality assertion tests shallow, coercive equality with
222// ==.
223// assert.equal(actual, expected, message_opt);
224
225assert.equal = function equal(actual, expected, message) {
226 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
227};
228
229// 6. The non-equality assertion tests for whether two objects are not equal
230// with != assert.notEqual(actual, expected, message_opt);
231
232assert.notEqual = function notEqual(actual, expected, message) {
233 if (actual == expected) {
234 fail(actual, expected, message, '!=', assert.notEqual);
235 }
236};
237
238// 7. The equivalence assertion tests a deep equality relation.
239// assert.deepEqual(actual, expected, message_opt);
240
241assert.deepEqual = function deepEqual(actual, expected, message) {
242 if (!_deepEqual(actual, expected, false)) {
243 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
244 }
245};
246
247assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
248 if (!_deepEqual(actual, expected, true)) {
249 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
250 }
251};
252
253function _deepEqual(actual, expected, strict, memos) {
254 // 7.1. All identical values are equivalent, as determined by ===.
255 if (actual === expected) {
256 return true;
257 } else if (isBuffer(actual) && isBuffer(expected)) {
258 return compare(actual, expected) === 0;
259
260 // 7.2. If the expected value is a Date object, the actual value is
261 // equivalent if it is also a Date object that refers to the same time.
262 } else if (util.isDate(actual) && util.isDate(expected)) {
263 return actual.getTime() === expected.getTime();
264
265 // 7.3 If the expected value is a RegExp object, the actual value is
266 // equivalent if it is also a RegExp object with the same source and
267 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
268 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
269 return actual.source === expected.source &&
270 actual.global === expected.global &&
271 actual.multiline === expected.multiline &&
272 actual.lastIndex === expected.lastIndex &&
273 actual.ignoreCase === expected.ignoreCase;
274
275 // 7.4. Other pairs that do not both pass typeof value == 'object',
276 // equivalence is determined by ==.
277 } else if ((actual === null || typeof actual !== 'object') &&
278 (expected === null || typeof expected !== 'object')) {
279 return strict ? actual === expected : actual == expected;
280
281 // If both values are instances of typed arrays, wrap their underlying
282 // ArrayBuffers in a Buffer each to increase performance
283 // This optimization requires the arrays to have the same type as checked by
284 // Object.prototype.toString (aka pToString). Never perform binary
285 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
286 // bit patterns are not identical.
287 } else if (isView(actual) && isView(expected) &&
288 pToString(actual) === pToString(expected) &&
289 !(actual instanceof Float32Array ||
290 actual instanceof Float64Array)) {
291 return compare(new Uint8Array(actual.buffer),
292 new Uint8Array(expected.buffer)) === 0;
293
294 // 7.5 For all other Object pairs, including Array objects, equivalence is
295 // determined by having the same number of owned properties (as verified
296 // with Object.prototype.hasOwnProperty.call), the same set of keys
297 // (although not necessarily the same order), equivalent values for every
298 // corresponding key, and an identical 'prototype' property. Note: this
299 // accounts for both named and indexed properties on Arrays.
300 } else if (isBuffer(actual) !== isBuffer(expected)) {
301 return false;
302 } else {
303 memos = memos || {actual: [], expected: []};
304
305 var actualIndex = memos.actual.indexOf(actual);
306 if (actualIndex !== -1) {
307 if (actualIndex === memos.expected.indexOf(expected)) {
308 return true;
309 }
310 }
311
312 memos.actual.push(actual);
313 memos.expected.push(expected);
314
315 return objEquiv(actual, expected, strict, memos);
316 }
317}
318
319function isArguments(object) {
320 return Object.prototype.toString.call(object) == '[object Arguments]';
321}
322
323function objEquiv(a, b, strict, actualVisitedObjects) {
324 if (a === null || a === undefined || b === null || b === undefined)
325 return false;
326 // if one is a primitive, the other must be same
327 if (util.isPrimitive(a) || util.isPrimitive(b))
328 return a === b;
329 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
330 return false;
331 var aIsArgs = isArguments(a);
332 var bIsArgs = isArguments(b);
333 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
334 return false;
335 if (aIsArgs) {
336 a = pSlice.call(a);
337 b = pSlice.call(b);
338 return _deepEqual(a, b, strict);
339 }
340 var ka = objectKeys(a);
341 var kb = objectKeys(b);
342 var key, i;
343 // having the same number of owned properties (keys incorporates
344 // hasOwnProperty)
345 if (ka.length !== kb.length)
346 return false;
347 //the same set of keys (although not necessarily the same order),
348 ka.sort();
349 kb.sort();
350 //~~~cheap key test
351 for (i = ka.length - 1; i >= 0; i--) {
352 if (ka[i] !== kb[i])
353 return false;
354 }
355 //equivalent values for every corresponding key, and
356 //~~~possibly expensive deep test
357 for (i = ka.length - 1; i >= 0; i--) {
358 key = ka[i];
359 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
360 return false;
361 }
362 return true;
363}
364
365// 8. The non-equivalence assertion tests for any deep inequality.
366// assert.notDeepEqual(actual, expected, message_opt);
367
368assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
369 if (_deepEqual(actual, expected, false)) {
370 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
371 }
372};
373
374assert.notDeepStrictEqual = notDeepStrictEqual;
375function notDeepStrictEqual(actual, expected, message) {
376 if (_deepEqual(actual, expected, true)) {
377 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
378 }
379}
380
381
382// 9. The strict equality assertion tests strict equality, as determined by ===.
383// assert.strictEqual(actual, expected, message_opt);
384
385assert.strictEqual = function strictEqual(actual, expected, message) {
386 if (actual !== expected) {
387 fail(actual, expected, message, '===', assert.strictEqual);
388 }
389};
390
391// 10. The strict non-equality assertion tests for strict inequality, as
392// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
393
394assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
395 if (actual === expected) {
396 fail(actual, expected, message, '!==', assert.notStrictEqual);
397 }
398};
399
400function expectedException(actual, expected) {
401 if (!actual || !expected) {
402 return false;
403 }
404
405 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
406 return expected.test(actual);
407 }
408
409 try {
410 if (actual instanceof expected) {
411 return true;
412 }
413 } catch (e) {
414 // Ignore. The instanceof check doesn't work for arrow functions.
415 }
416
417 if (Error.isPrototypeOf(expected)) {
418 return false;
419 }
420
421 return expected.call({}, actual) === true;
422}
423
424function _tryBlock(block) {
425 var error;
426 try {
427 block();
428 } catch (e) {
429 error = e;
430 }
431 return error;
432}
433
434function _throws(shouldThrow, block, expected, message) {
435 var actual;
436
437 if (typeof block !== 'function') {
438 throw new TypeError('"block" argument must be a function');
439 }
440
441 if (typeof expected === 'string') {
442 message = expected;
443 expected = null;
444 }
445
446 actual = _tryBlock(block);
447
448 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
449 (message ? ' ' + message : '.');
450
451 if (shouldThrow && !actual) {
452 fail(actual, expected, 'Missing expected exception' + message);
453 }
454
455 var userProvidedMessage = typeof message === 'string';
456 var isUnwantedException = !shouldThrow && util.isError(actual);
457 var isUnexpectedException = !shouldThrow && actual && !expected;
458
459 if ((isUnwantedException &&
460 userProvidedMessage &&
461 expectedException(actual, expected)) ||
462 isUnexpectedException) {
463 fail(actual, expected, 'Got unwanted exception' + message);
464 }
465
466 if ((shouldThrow && actual && expected &&
467 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
468 throw actual;
469 }
470}
471
472// 11. Expected to throw an error:
473// assert.throws(block, Error_opt, message_opt);
474
475assert.throws = function(block, /*optional*/error, /*optional*/message) {
476 _throws(true, block, error, message);
477};
478
479// EXTENSION! This is annoying to write outside this module.
480assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
481 _throws(false, block, error, message);
482};
483
484assert.ifError = function(err) { if (err) throw err; };
485
486var objectKeys = Object.keys || function (obj) {
487 var keys = [];
488 for (var key in obj) {
489 if (hasOwn.call(obj, key)) keys.push(key);
490 }
491 return keys;
492};
493
494}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
495},{"util/":32}],2:[function(require,module,exports){
496'use strict'
497
498exports.byteLength = byteLength
499exports.toByteArray = toByteArray
500exports.fromByteArray = fromByteArray
501
502var lookup = []
503var revLookup = []
504var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
505
506var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
507for (var i = 0, len = code.length; i < len; ++i) {
508 lookup[i] = code[i]
509 revLookup[code.charCodeAt(i)] = i
510}
511
512revLookup['-'.charCodeAt(0)] = 62
513revLookup['_'.charCodeAt(0)] = 63
514
515function placeHoldersCount (b64) {
516 var len = b64.length
517 if (len % 4 > 0) {
518 throw new Error('Invalid string. Length must be a multiple of 4')
519 }
520
521 // the number of equal signs (place holders)
522 // if there are two placeholders, than the two characters before it
523 // represent one byte
524 // if there is only one, then the three characters before it represent 2 bytes
525 // this is just a cheap hack to not do indexOf twice
526 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
527}
528
529function byteLength (b64) {
530 // base64 is 4/3 + up to two characters of the original data
531 return (b64.length * 3 / 4) - placeHoldersCount(b64)
532}
533
534function toByteArray (b64) {
535 var i, l, tmp, placeHolders, arr
536 var len = b64.length
537 placeHolders = placeHoldersCount(b64)
538
539 arr = new Arr((len * 3 / 4) - placeHolders)
540
541 // if there are placeholders, only get up to the last complete 4 chars
542 l = placeHolders > 0 ? len - 4 : len
543
544 var L = 0
545
546 for (i = 0; i < l; i += 4) {
547 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
548 arr[L++] = (tmp >> 16) & 0xFF
549 arr[L++] = (tmp >> 8) & 0xFF
550 arr[L++] = tmp & 0xFF
551 }
552
553 if (placeHolders === 2) {
554 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
555 arr[L++] = tmp & 0xFF
556 } else if (placeHolders === 1) {
557 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
558 arr[L++] = (tmp >> 8) & 0xFF
559 arr[L++] = tmp & 0xFF
560 }
561
562 return arr
563}
564
565function tripletToBase64 (num) {
566 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
567}
568
569function encodeChunk (uint8, start, end) {
570 var tmp
571 var output = []
572 for (var i = start; i < end; i += 3) {
573 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
574 output.push(tripletToBase64(tmp))
575 }
576 return output.join('')
577}
578
579function fromByteArray (uint8) {
580 var tmp
581 var len = uint8.length
582 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
583 var output = ''
584 var parts = []
585 var maxChunkLength = 16383 // must be multiple of 3
586
587 // go through the array every three bytes, we'll deal with trailing stuff later
588 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
589 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
590 }
591
592 // pad the end with zeros, but make sure to not forget the extra bytes
593 if (extraBytes === 1) {
594 tmp = uint8[len - 1]
595 output += lookup[tmp >> 2]
596 output += lookup[(tmp << 4) & 0x3F]
597 output += '=='
598 } else if (extraBytes === 2) {
599 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
600 output += lookup[tmp >> 10]
601 output += lookup[(tmp >> 4) & 0x3F]
602 output += lookup[(tmp << 2) & 0x3F]
603 output += '='
604 }
605
606 parts.push(output)
607
608 return parts.join('')
609}
610
611},{}],3:[function(require,module,exports){
612
613},{}],4:[function(require,module,exports){
614/*!
615 * The buffer module from node.js, for the browser.
616 *
617 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
618 * @license MIT
619 */
620/* eslint-disable no-proto */
621
622'use strict'
623
624var base64 = require('base64-js')
625var ieee754 = require('ieee754')
626
627exports.Buffer = Buffer
628exports.SlowBuffer = SlowBuffer
629exports.INSPECT_MAX_BYTES = 50
630
631var K_MAX_LENGTH = 0x7fffffff
632exports.kMaxLength = K_MAX_LENGTH
633
634/**
635 * If `Buffer.TYPED_ARRAY_SUPPORT`:
636 * === true Use Uint8Array implementation (fastest)
637 * === false Print warning and recommend using `buffer` v4.x which has an Object
638 * implementation (most compatible, even IE6)
639 *
640 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
641 * Opera 11.6+, iOS 4.2+.
642 *
643 * We report that the browser does not support typed arrays if the are not subclassable
644 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
645 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
646 * for __proto__ and has a buggy typed array implementation.
647 */
648Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
649
650if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
651 typeof console.error === 'function') {
652 console.error(
653 'This browser lacks typed array (Uint8Array) support which is required by ' +
654 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
655 )
656}
657
658function typedArraySupport () {
659 // Can typed array instances can be augmented?
660 try {
661 var arr = new Uint8Array(1)
662 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
663 return arr.foo() === 42
664 } catch (e) {
665 return false
666 }
667}
668
669function createBuffer (length) {
670 if (length > K_MAX_LENGTH) {
671 throw new RangeError('Invalid typed array length')
672 }
673 // Return an augmented `Uint8Array` instance
674 var buf = new Uint8Array(length)
675 buf.__proto__ = Buffer.prototype
676 return buf
677}
678
679/**
680 * The Buffer constructor returns instances of `Uint8Array` that have their
681 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
682 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
683 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
684 * returns a single octet.
685 *
686 * The `Uint8Array` prototype remains unmodified.
687 */
688
689function Buffer (arg, encodingOrOffset, length) {
690 // Common case.
691 if (typeof arg === 'number') {
692 if (typeof encodingOrOffset === 'string') {
693 throw new Error(
694 'If encoding is specified then the first argument must be a string'
695 )
696 }
697 return allocUnsafe(arg)
698 }
699 return from(arg, encodingOrOffset, length)
700}
701
702// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
703if (typeof Symbol !== 'undefined' && Symbol.species &&
704 Buffer[Symbol.species] === Buffer) {
705 Object.defineProperty(Buffer, Symbol.species, {
706 value: null,
707 configurable: true,
708 enumerable: false,
709 writable: false
710 })
711}
712
713Buffer.poolSize = 8192 // not used by this implementation
714
715function from (value, encodingOrOffset, length) {
716 if (typeof value === 'number') {
717 throw new TypeError('"value" argument must not be a number')
718 }
719
720 if (value instanceof ArrayBuffer) {
721 return fromArrayBuffer(value, encodingOrOffset, length)
722 }
723
724 if (typeof value === 'string') {
725 return fromString(value, encodingOrOffset)
726 }
727
728 return fromObject(value)
729}
730
731/**
732 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
733 * if value is a number.
734 * Buffer.from(str[, encoding])
735 * Buffer.from(array)
736 * Buffer.from(buffer)
737 * Buffer.from(arrayBuffer[, byteOffset[, length]])
738 **/
739Buffer.from = function (value, encodingOrOffset, length) {
740 return from(value, encodingOrOffset, length)
741}
742
743// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
744// https://github.com/feross/buffer/pull/148
745Buffer.prototype.__proto__ = Uint8Array.prototype
746Buffer.__proto__ = Uint8Array
747
748function assertSize (size) {
749 if (typeof size !== 'number') {
750 throw new TypeError('"size" argument must be a number')
751 } else if (size < 0) {
752 throw new RangeError('"size" argument must not be negative')
753 }
754}
755
756function alloc (size, fill, encoding) {
757 assertSize(size)
758 if (size <= 0) {
759 return createBuffer(size)
760 }
761 if (fill !== undefined) {
762 // Only pay attention to encoding if it's a string. This
763 // prevents accidentally sending in a number that would
764 // be interpretted as a start offset.
765 return typeof encoding === 'string'
766 ? createBuffer(size).fill(fill, encoding)
767 : createBuffer(size).fill(fill)
768 }
769 return createBuffer(size)
770}
771
772/**
773 * Creates a new filled Buffer instance.
774 * alloc(size[, fill[, encoding]])
775 **/
776Buffer.alloc = function (size, fill, encoding) {
777 return alloc(size, fill, encoding)
778}
779
780function allocUnsafe (size) {
781 assertSize(size)
782 return createBuffer(size < 0 ? 0 : checked(size) | 0)
783}
784
785/**
786 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
787 * */
788Buffer.allocUnsafe = function (size) {
789 return allocUnsafe(size)
790}
791/**
792 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
793 */
794Buffer.allocUnsafeSlow = function (size) {
795 return allocUnsafe(size)
796}
797
798function fromString (string, encoding) {
799 if (typeof encoding !== 'string' || encoding === '') {
800 encoding = 'utf8'
801 }
802
803 if (!Buffer.isEncoding(encoding)) {
804 throw new TypeError('"encoding" must be a valid string encoding')
805 }
806
807 var length = byteLength(string, encoding) | 0
808 var buf = createBuffer(length)
809
810 var actual = buf.write(string, encoding)
811
812 if (actual !== length) {
813 // Writing a hex string, for example, that contains invalid characters will
814 // cause everything after the first invalid character to be ignored. (e.g.
815 // 'abxxcd' will be treated as 'ab')
816 buf = buf.slice(0, actual)
817 }
818
819 return buf
820}
821
822function fromArrayLike (array) {
823 var length = array.length < 0 ? 0 : checked(array.length) | 0
824 var buf = createBuffer(length)
825 for (var i = 0; i < length; i += 1) {
826 buf[i] = array[i] & 255
827 }
828 return buf
829}
830
831function fromArrayBuffer (array, byteOffset, length) {
832 if (byteOffset < 0 || array.byteLength < byteOffset) {
833 throw new RangeError('\'offset\' is out of bounds')
834 }
835
836 if (array.byteLength < byteOffset + (length || 0)) {
837 throw new RangeError('\'length\' is out of bounds')
838 }
839
840 var buf
841 if (byteOffset === undefined && length === undefined) {
842 buf = new Uint8Array(array)
843 } else if (length === undefined) {
844 buf = new Uint8Array(array, byteOffset)
845 } else {
846 buf = new Uint8Array(array, byteOffset, length)
847 }
848
849 // Return an augmented `Uint8Array` instance
850 buf.__proto__ = Buffer.prototype
851 return buf
852}
853
854function fromObject (obj) {
855 if (Buffer.isBuffer(obj)) {
856 var len = checked(obj.length) | 0
857 var buf = createBuffer(len)
858
859 if (buf.length === 0) {
860 return buf
861 }
862
863 obj.copy(buf, 0, 0, len)
864 return buf
865 }
866
867 if (obj) {
868 if (isArrayBufferView(obj) || 'length' in obj) {
869 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
870 return createBuffer(0)
871 }
872 return fromArrayLike(obj)
873 }
874
875 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
876 return fromArrayLike(obj.data)
877 }
878 }
879
880 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
881}
882
883function checked (length) {
884 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
885 // length is NaN (which is otherwise coerced to zero.)
886 if (length >= K_MAX_LENGTH) {
887 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
888 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
889 }
890 return length | 0
891}
892
893function SlowBuffer (length) {
894 if (+length != length) { // eslint-disable-line eqeqeq
895 length = 0
896 }
897 return Buffer.alloc(+length)
898}
899
900Buffer.isBuffer = function isBuffer (b) {
901 return b != null && b._isBuffer === true
902}
903
904Buffer.compare = function compare (a, b) {
905 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
906 throw new TypeError('Arguments must be Buffers')
907 }
908
909 if (a === b) return 0
910
911 var x = a.length
912 var y = b.length
913
914 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
915 if (a[i] !== b[i]) {
916 x = a[i]
917 y = b[i]
918 break
919 }
920 }
921
922 if (x < y) return -1
923 if (y < x) return 1
924 return 0
925}
926
927Buffer.isEncoding = function isEncoding (encoding) {
928 switch (String(encoding).toLowerCase()) {
929 case 'hex':
930 case 'utf8':
931 case 'utf-8':
932 case 'ascii':
933 case 'latin1':
934 case 'binary':
935 case 'base64':
936 case 'ucs2':
937 case 'ucs-2':
938 case 'utf16le':
939 case 'utf-16le':
940 return true
941 default:
942 return false
943 }
944}
945
946Buffer.concat = function concat (list, length) {
947 if (!Array.isArray(list)) {
948 throw new TypeError('"list" argument must be an Array of Buffers')
949 }
950
951 if (list.length === 0) {
952 return Buffer.alloc(0)
953 }
954
955 var i
956 if (length === undefined) {
957 length = 0
958 for (i = 0; i < list.length; ++i) {
959 length += list[i].length
960 }
961 }
962
963 var buffer = Buffer.allocUnsafe(length)
964 var pos = 0
965 for (i = 0; i < list.length; ++i) {
966 var buf = list[i]
967 if (!Buffer.isBuffer(buf)) {
968 throw new TypeError('"list" argument must be an Array of Buffers')
969 }
970 buf.copy(buffer, pos)
971 pos += buf.length
972 }
973 return buffer
974}
975
976function byteLength (string, encoding) {
977 if (Buffer.isBuffer(string)) {
978 return string.length
979 }
980 if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
981 return string.byteLength
982 }
983 if (typeof string !== 'string') {
984 string = '' + string
985 }
986
987 var len = string.length
988 if (len === 0) return 0
989
990 // Use a for loop to avoid recursion
991 var loweredCase = false
992 for (;;) {
993 switch (encoding) {
994 case 'ascii':
995 case 'latin1':
996 case 'binary':
997 return len
998 case 'utf8':
999 case 'utf-8':
1000 case undefined:
1001 return utf8ToBytes(string).length
1002 case 'ucs2':
1003 case 'ucs-2':
1004 case 'utf16le':
1005 case 'utf-16le':
1006 return len * 2
1007 case 'hex':
1008 return len >>> 1
1009 case 'base64':
1010 return base64ToBytes(string).length
1011 default:
1012 if (loweredCase) return utf8ToBytes(string).length // assume utf8
1013 encoding = ('' + encoding).toLowerCase()
1014 loweredCase = true
1015 }
1016 }
1017}
1018Buffer.byteLength = byteLength
1019
1020function slowToString (encoding, start, end) {
1021 var loweredCase = false
1022
1023 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1024 // property of a typed array.
1025
1026 // This behaves neither like String nor Uint8Array in that we set start/end
1027 // to their upper/lower bounds if the value passed is out of range.
1028 // undefined is handled specially as per ECMA-262 6th Edition,
1029 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1030 if (start === undefined || start < 0) {
1031 start = 0
1032 }
1033 // Return early if start > this.length. Done here to prevent potential uint32
1034 // coercion fail below.
1035 if (start > this.length) {
1036 return ''
1037 }
1038
1039 if (end === undefined || end > this.length) {
1040 end = this.length
1041 }
1042
1043 if (end <= 0) {
1044 return ''
1045 }
1046
1047 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1048 end >>>= 0
1049 start >>>= 0
1050
1051 if (end <= start) {
1052 return ''
1053 }
1054
1055 if (!encoding) encoding = 'utf8'
1056
1057 while (true) {
1058 switch (encoding) {
1059 case 'hex':
1060 return hexSlice(this, start, end)
1061
1062 case 'utf8':
1063 case 'utf-8':
1064 return utf8Slice(this, start, end)
1065
1066 case 'ascii':
1067 return asciiSlice(this, start, end)
1068
1069 case 'latin1':
1070 case 'binary':
1071 return latin1Slice(this, start, end)
1072
1073 case 'base64':
1074 return base64Slice(this, start, end)
1075
1076 case 'ucs2':
1077 case 'ucs-2':
1078 case 'utf16le':
1079 case 'utf-16le':
1080 return utf16leSlice(this, start, end)
1081
1082 default:
1083 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1084 encoding = (encoding + '').toLowerCase()
1085 loweredCase = true
1086 }
1087 }
1088}
1089
1090// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1091// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1092// reliably in a browserify context because there could be multiple different
1093// copies of the 'buffer' package in use. This method works even for Buffer
1094// instances that were created from another copy of the `buffer` package.
1095// See: https://github.com/feross/buffer/issues/154
1096Buffer.prototype._isBuffer = true
1097
1098function swap (b, n, m) {
1099 var i = b[n]
1100 b[n] = b[m]
1101 b[m] = i
1102}
1103
1104Buffer.prototype.swap16 = function swap16 () {
1105 var len = this.length
1106 if (len % 2 !== 0) {
1107 throw new RangeError('Buffer size must be a multiple of 16-bits')
1108 }
1109 for (var i = 0; i < len; i += 2) {
1110 swap(this, i, i + 1)
1111 }
1112 return this
1113}
1114
1115Buffer.prototype.swap32 = function swap32 () {
1116 var len = this.length
1117 if (len % 4 !== 0) {
1118 throw new RangeError('Buffer size must be a multiple of 32-bits')
1119 }
1120 for (var i = 0; i < len; i += 4) {
1121 swap(this, i, i + 3)
1122 swap(this, i + 1, i + 2)
1123 }
1124 return this
1125}
1126
1127Buffer.prototype.swap64 = function swap64 () {
1128 var len = this.length
1129 if (len % 8 !== 0) {
1130 throw new RangeError('Buffer size must be a multiple of 64-bits')
1131 }
1132 for (var i = 0; i < len; i += 8) {
1133 swap(this, i, i + 7)
1134 swap(this, i + 1, i + 6)
1135 swap(this, i + 2, i + 5)
1136 swap(this, i + 3, i + 4)
1137 }
1138 return this
1139}
1140
1141Buffer.prototype.toString = function toString () {
1142 var length = this.length
1143 if (length === 0) return ''
1144 if (arguments.length === 0) return utf8Slice(this, 0, length)
1145 return slowToString.apply(this, arguments)
1146}
1147
1148Buffer.prototype.equals = function equals (b) {
1149 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1150 if (this === b) return true
1151 return Buffer.compare(this, b) === 0
1152}
1153
1154Buffer.prototype.inspect = function inspect () {
1155 var str = ''
1156 var max = exports.INSPECT_MAX_BYTES
1157 if (this.length > 0) {
1158 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1159 if (this.length > max) str += ' ... '
1160 }
1161 return '<Buffer ' + str + '>'
1162}
1163
1164Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1165 if (!Buffer.isBuffer(target)) {
1166 throw new TypeError('Argument must be a Buffer')
1167 }
1168
1169 if (start === undefined) {
1170 start = 0
1171 }
1172 if (end === undefined) {
1173 end = target ? target.length : 0
1174 }
1175 if (thisStart === undefined) {
1176 thisStart = 0
1177 }
1178 if (thisEnd === undefined) {
1179 thisEnd = this.length
1180 }
1181
1182 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1183 throw new RangeError('out of range index')
1184 }
1185
1186 if (thisStart >= thisEnd && start >= end) {
1187 return 0
1188 }
1189 if (thisStart >= thisEnd) {
1190 return -1
1191 }
1192 if (start >= end) {
1193 return 1
1194 }
1195
1196 start >>>= 0
1197 end >>>= 0
1198 thisStart >>>= 0
1199 thisEnd >>>= 0
1200
1201 if (this === target) return 0
1202
1203 var x = thisEnd - thisStart
1204 var y = end - start
1205 var len = Math.min(x, y)
1206
1207 var thisCopy = this.slice(thisStart, thisEnd)
1208 var targetCopy = target.slice(start, end)
1209
1210 for (var i = 0; i < len; ++i) {
1211 if (thisCopy[i] !== targetCopy[i]) {
1212 x = thisCopy[i]
1213 y = targetCopy[i]
1214 break
1215 }
1216 }
1217
1218 if (x < y) return -1
1219 if (y < x) return 1
1220 return 0
1221}
1222
1223// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1224// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1225//
1226// Arguments:
1227// - buffer - a Buffer to search
1228// - val - a string, Buffer, or number
1229// - byteOffset - an index into `buffer`; will be clamped to an int32
1230// - encoding - an optional encoding, relevant is val is a string
1231// - dir - true for indexOf, false for lastIndexOf
1232function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1233 // Empty buffer means no match
1234 if (buffer.length === 0) return -1
1235
1236 // Normalize byteOffset
1237 if (typeof byteOffset === 'string') {
1238 encoding = byteOffset
1239 byteOffset = 0
1240 } else if (byteOffset > 0x7fffffff) {
1241 byteOffset = 0x7fffffff
1242 } else if (byteOffset < -0x80000000) {
1243 byteOffset = -0x80000000
1244 }
1245 byteOffset = +byteOffset // Coerce to Number.
1246 if (numberIsNaN(byteOffset)) {
1247 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1248 byteOffset = dir ? 0 : (buffer.length - 1)
1249 }
1250
1251 // Normalize byteOffset: negative offsets start from the end of the buffer
1252 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1253 if (byteOffset >= buffer.length) {
1254 if (dir) return -1
1255 else byteOffset = buffer.length - 1
1256 } else if (byteOffset < 0) {
1257 if (dir) byteOffset = 0
1258 else return -1
1259 }
1260
1261 // Normalize val
1262 if (typeof val === 'string') {
1263 val = Buffer.from(val, encoding)
1264 }
1265
1266 // Finally, search either indexOf (if dir is true) or lastIndexOf
1267 if (Buffer.isBuffer(val)) {
1268 // Special case: looking for empty string/buffer always fails
1269 if (val.length === 0) {
1270 return -1
1271 }
1272 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1273 } else if (typeof val === 'number') {
1274 val = val & 0xFF // Search for a byte value [0-255]
1275 if (typeof Uint8Array.prototype.indexOf === 'function') {
1276 if (dir) {
1277 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1278 } else {
1279 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1280 }
1281 }
1282 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1283 }
1284
1285 throw new TypeError('val must be string, number or Buffer')
1286}
1287
1288function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1289 var indexSize = 1
1290 var arrLength = arr.length
1291 var valLength = val.length
1292
1293 if (encoding !== undefined) {
1294 encoding = String(encoding).toLowerCase()
1295 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1296 encoding === 'utf16le' || encoding === 'utf-16le') {
1297 if (arr.length < 2 || val.length < 2) {
1298 return -1
1299 }
1300 indexSize = 2
1301 arrLength /= 2
1302 valLength /= 2
1303 byteOffset /= 2
1304 }
1305 }
1306
1307 function read (buf, i) {
1308 if (indexSize === 1) {
1309 return buf[i]
1310 } else {
1311 return buf.readUInt16BE(i * indexSize)
1312 }
1313 }
1314
1315 var i
1316 if (dir) {
1317 var foundIndex = -1
1318 for (i = byteOffset; i < arrLength; i++) {
1319 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1320 if (foundIndex === -1) foundIndex = i
1321 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1322 } else {
1323 if (foundIndex !== -1) i -= i - foundIndex
1324 foundIndex = -1
1325 }
1326 }
1327 } else {
1328 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1329 for (i = byteOffset; i >= 0; i--) {
1330 var found = true
1331 for (var j = 0; j < valLength; j++) {
1332 if (read(arr, i + j) !== read(val, j)) {
1333 found = false
1334 break
1335 }
1336 }
1337 if (found) return i
1338 }
1339 }
1340
1341 return -1
1342}
1343
1344Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1345 return this.indexOf(val, byteOffset, encoding) !== -1
1346}
1347
1348Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1349 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1350}
1351
1352Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1353 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1354}
1355
1356function hexWrite (buf, string, offset, length) {
1357 offset = Number(offset) || 0
1358 var remaining = buf.length - offset
1359 if (!length) {
1360 length = remaining
1361 } else {
1362 length = Number(length)
1363 if (length > remaining) {
1364 length = remaining
1365 }
1366 }
1367
1368 // must be an even number of digits
1369 var strLen = string.length
1370 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1371
1372 if (length > strLen / 2) {
1373 length = strLen / 2
1374 }
1375 for (var i = 0; i < length; ++i) {
1376 var parsed = parseInt(string.substr(i * 2, 2), 16)
1377 if (numberIsNaN(parsed)) return i
1378 buf[offset + i] = parsed
1379 }
1380 return i
1381}
1382
1383function utf8Write (buf, string, offset, length) {
1384 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1385}
1386
1387function asciiWrite (buf, string, offset, length) {
1388 return blitBuffer(asciiToBytes(string), buf, offset, length)
1389}
1390
1391function latin1Write (buf, string, offset, length) {
1392 return asciiWrite(buf, string, offset, length)
1393}
1394
1395function base64Write (buf, string, offset, length) {
1396 return blitBuffer(base64ToBytes(string), buf, offset, length)
1397}
1398
1399function ucs2Write (buf, string, offset, length) {
1400 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1401}
1402
1403Buffer.prototype.write = function write (string, offset, length, encoding) {
1404 // Buffer#write(string)
1405 if (offset === undefined) {
1406 encoding = 'utf8'
1407 length = this.length
1408 offset = 0
1409 // Buffer#write(string, encoding)
1410 } else if (length === undefined && typeof offset === 'string') {
1411 encoding = offset
1412 length = this.length
1413 offset = 0
1414 // Buffer#write(string, offset[, length][, encoding])
1415 } else if (isFinite(offset)) {
1416 offset = offset >>> 0
1417 if (isFinite(length)) {
1418 length = length >>> 0
1419 if (encoding === undefined) encoding = 'utf8'
1420 } else {
1421 encoding = length
1422 length = undefined
1423 }
1424 } else {
1425 throw new Error(
1426 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1427 )
1428 }
1429
1430 var remaining = this.length - offset
1431 if (length === undefined || length > remaining) length = remaining
1432
1433 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1434 throw new RangeError('Attempt to write outside buffer bounds')
1435 }
1436
1437 if (!encoding) encoding = 'utf8'
1438
1439 var loweredCase = false
1440 for (;;) {
1441 switch (encoding) {
1442 case 'hex':
1443 return hexWrite(this, string, offset, length)
1444
1445 case 'utf8':
1446 case 'utf-8':
1447 return utf8Write(this, string, offset, length)
1448
1449 case 'ascii':
1450 return asciiWrite(this, string, offset, length)
1451
1452 case 'latin1':
1453 case 'binary':
1454 return latin1Write(this, string, offset, length)
1455
1456 case 'base64':
1457 // Warning: maxLength not taken into account in base64Write
1458 return base64Write(this, string, offset, length)
1459
1460 case 'ucs2':
1461 case 'ucs-2':
1462 case 'utf16le':
1463 case 'utf-16le':
1464 return ucs2Write(this, string, offset, length)
1465
1466 default:
1467 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1468 encoding = ('' + encoding).toLowerCase()
1469 loweredCase = true
1470 }
1471 }
1472}
1473
1474Buffer.prototype.toJSON = function toJSON () {
1475 return {
1476 type: 'Buffer',
1477 data: Array.prototype.slice.call(this._arr || this, 0)
1478 }
1479}
1480
1481function base64Slice (buf, start, end) {
1482 if (start === 0 && end === buf.length) {
1483 return base64.fromByteArray(buf)
1484 } else {
1485 return base64.fromByteArray(buf.slice(start, end))
1486 }
1487}
1488
1489function utf8Slice (buf, start, end) {
1490 end = Math.min(buf.length, end)
1491 var res = []
1492
1493 var i = start
1494 while (i < end) {
1495 var firstByte = buf[i]
1496 var codePoint = null
1497 var bytesPerSequence = (firstByte > 0xEF) ? 4
1498 : (firstByte > 0xDF) ? 3
1499 : (firstByte > 0xBF) ? 2
1500 : 1
1501
1502 if (i + bytesPerSequence <= end) {
1503 var secondByte, thirdByte, fourthByte, tempCodePoint
1504
1505 switch (bytesPerSequence) {
1506 case 1:
1507 if (firstByte < 0x80) {
1508 codePoint = firstByte
1509 }
1510 break
1511 case 2:
1512 secondByte = buf[i + 1]
1513 if ((secondByte & 0xC0) === 0x80) {
1514 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1515 if (tempCodePoint > 0x7F) {
1516 codePoint = tempCodePoint
1517 }
1518 }
1519 break
1520 case 3:
1521 secondByte = buf[i + 1]
1522 thirdByte = buf[i + 2]
1523 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1524 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1525 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1526 codePoint = tempCodePoint
1527 }
1528 }
1529 break
1530 case 4:
1531 secondByte = buf[i + 1]
1532 thirdByte = buf[i + 2]
1533 fourthByte = buf[i + 3]
1534 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1535 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1536 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1537 codePoint = tempCodePoint
1538 }
1539 }
1540 }
1541 }
1542
1543 if (codePoint === null) {
1544 // we did not generate a valid codePoint so insert a
1545 // replacement char (U+FFFD) and advance only 1 byte
1546 codePoint = 0xFFFD
1547 bytesPerSequence = 1
1548 } else if (codePoint > 0xFFFF) {
1549 // encode to utf16 (surrogate pair dance)
1550 codePoint -= 0x10000
1551 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1552 codePoint = 0xDC00 | codePoint & 0x3FF
1553 }
1554
1555 res.push(codePoint)
1556 i += bytesPerSequence
1557 }
1558
1559 return decodeCodePointsArray(res)
1560}
1561
1562// Based on http://stackoverflow.com/a/22747272/680742, the browser with
1563// the lowest limit is Chrome, with 0x10000 args.
1564// We go 1 magnitude less, for safety
1565var MAX_ARGUMENTS_LENGTH = 0x1000
1566
1567function decodeCodePointsArray (codePoints) {
1568 var len = codePoints.length
1569 if (len <= MAX_ARGUMENTS_LENGTH) {
1570 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1571 }
1572
1573 // Decode in chunks to avoid "call stack size exceeded".
1574 var res = ''
1575 var i = 0
1576 while (i < len) {
1577 res += String.fromCharCode.apply(
1578 String,
1579 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1580 )
1581 }
1582 return res
1583}
1584
1585function asciiSlice (buf, start, end) {
1586 var ret = ''
1587 end = Math.min(buf.length, end)
1588
1589 for (var i = start; i < end; ++i) {
1590 ret += String.fromCharCode(buf[i] & 0x7F)
1591 }
1592 return ret
1593}
1594
1595function latin1Slice (buf, start, end) {
1596 var ret = ''
1597 end = Math.min(buf.length, end)
1598
1599 for (var i = start; i < end; ++i) {
1600 ret += String.fromCharCode(buf[i])
1601 }
1602 return ret
1603}
1604
1605function hexSlice (buf, start, end) {
1606 var len = buf.length
1607
1608 if (!start || start < 0) start = 0
1609 if (!end || end < 0 || end > len) end = len
1610
1611 var out = ''
1612 for (var i = start; i < end; ++i) {
1613 out += toHex(buf[i])
1614 }
1615 return out
1616}
1617
1618function utf16leSlice (buf, start, end) {
1619 var bytes = buf.slice(start, end)
1620 var res = ''
1621 for (var i = 0; i < bytes.length; i += 2) {
1622 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1623 }
1624 return res
1625}
1626
1627Buffer.prototype.slice = function slice (start, end) {
1628 var len = this.length
1629 start = ~~start
1630 end = end === undefined ? len : ~~end
1631
1632 if (start < 0) {
1633 start += len
1634 if (start < 0) start = 0
1635 } else if (start > len) {
1636 start = len
1637 }
1638
1639 if (end < 0) {
1640 end += len
1641 if (end < 0) end = 0
1642 } else if (end > len) {
1643 end = len
1644 }
1645
1646 if (end < start) end = start
1647
1648 var newBuf = this.subarray(start, end)
1649 // Return an augmented `Uint8Array` instance
1650 newBuf.__proto__ = Buffer.prototype
1651 return newBuf
1652}
1653
1654/*
1655 * Need to make sure that buffer isn't trying to write out of bounds.
1656 */
1657function checkOffset (offset, ext, length) {
1658 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1659 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1660}
1661
1662Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1663 offset = offset >>> 0
1664 byteLength = byteLength >>> 0
1665 if (!noAssert) checkOffset(offset, byteLength, this.length)
1666
1667 var val = this[offset]
1668 var mul = 1
1669 var i = 0
1670 while (++i < byteLength && (mul *= 0x100)) {
1671 val += this[offset + i] * mul
1672 }
1673
1674 return val
1675}
1676
1677Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1678 offset = offset >>> 0
1679 byteLength = byteLength >>> 0
1680 if (!noAssert) {
1681 checkOffset(offset, byteLength, this.length)
1682 }
1683
1684 var val = this[offset + --byteLength]
1685 var mul = 1
1686 while (byteLength > 0 && (mul *= 0x100)) {
1687 val += this[offset + --byteLength] * mul
1688 }
1689
1690 return val
1691}
1692
1693Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1694 offset = offset >>> 0
1695 if (!noAssert) checkOffset(offset, 1, this.length)
1696 return this[offset]
1697}
1698
1699Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1700 offset = offset >>> 0
1701 if (!noAssert) checkOffset(offset, 2, this.length)
1702 return this[offset] | (this[offset + 1] << 8)
1703}
1704
1705Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1706 offset = offset >>> 0
1707 if (!noAssert) checkOffset(offset, 2, this.length)
1708 return (this[offset] << 8) | this[offset + 1]
1709}
1710
1711Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1712 offset = offset >>> 0
1713 if (!noAssert) checkOffset(offset, 4, this.length)
1714
1715 return ((this[offset]) |
1716 (this[offset + 1] << 8) |
1717 (this[offset + 2] << 16)) +
1718 (this[offset + 3] * 0x1000000)
1719}
1720
1721Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1722 offset = offset >>> 0
1723 if (!noAssert) checkOffset(offset, 4, this.length)
1724
1725 return (this[offset] * 0x1000000) +
1726 ((this[offset + 1] << 16) |
1727 (this[offset + 2] << 8) |
1728 this[offset + 3])
1729}
1730
1731Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1732 offset = offset >>> 0
1733 byteLength = byteLength >>> 0
1734 if (!noAssert) checkOffset(offset, byteLength, this.length)
1735
1736 var val = this[offset]
1737 var mul = 1
1738 var i = 0
1739 while (++i < byteLength && (mul *= 0x100)) {
1740 val += this[offset + i] * mul
1741 }
1742 mul *= 0x80
1743
1744 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1745
1746 return val
1747}
1748
1749Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1750 offset = offset >>> 0
1751 byteLength = byteLength >>> 0
1752 if (!noAssert) checkOffset(offset, byteLength, this.length)
1753
1754 var i = byteLength
1755 var mul = 1
1756 var val = this[offset + --i]
1757 while (i > 0 && (mul *= 0x100)) {
1758 val += this[offset + --i] * mul
1759 }
1760 mul *= 0x80
1761
1762 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1763
1764 return val
1765}
1766
1767Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1768 offset = offset >>> 0
1769 if (!noAssert) checkOffset(offset, 1, this.length)
1770 if (!(this[offset] & 0x80)) return (this[offset])
1771 return ((0xff - this[offset] + 1) * -1)
1772}
1773
1774Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1775 offset = offset >>> 0
1776 if (!noAssert) checkOffset(offset, 2, this.length)
1777 var val = this[offset] | (this[offset + 1] << 8)
1778 return (val & 0x8000) ? val | 0xFFFF0000 : val
1779}
1780
1781Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1782 offset = offset >>> 0
1783 if (!noAssert) checkOffset(offset, 2, this.length)
1784 var val = this[offset + 1] | (this[offset] << 8)
1785 return (val & 0x8000) ? val | 0xFFFF0000 : val
1786}
1787
1788Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1789 offset = offset >>> 0
1790 if (!noAssert) checkOffset(offset, 4, this.length)
1791
1792 return (this[offset]) |
1793 (this[offset + 1] << 8) |
1794 (this[offset + 2] << 16) |
1795 (this[offset + 3] << 24)
1796}
1797
1798Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1799 offset = offset >>> 0
1800 if (!noAssert) checkOffset(offset, 4, this.length)
1801
1802 return (this[offset] << 24) |
1803 (this[offset + 1] << 16) |
1804 (this[offset + 2] << 8) |
1805 (this[offset + 3])
1806}
1807
1808Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1809 offset = offset >>> 0
1810 if (!noAssert) checkOffset(offset, 4, this.length)
1811 return ieee754.read(this, offset, true, 23, 4)
1812}
1813
1814Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1815 offset = offset >>> 0
1816 if (!noAssert) checkOffset(offset, 4, this.length)
1817 return ieee754.read(this, offset, false, 23, 4)
1818}
1819
1820Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1821 offset = offset >>> 0
1822 if (!noAssert) checkOffset(offset, 8, this.length)
1823 return ieee754.read(this, offset, true, 52, 8)
1824}
1825
1826Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1827 offset = offset >>> 0
1828 if (!noAssert) checkOffset(offset, 8, this.length)
1829 return ieee754.read(this, offset, false, 52, 8)
1830}
1831
1832function checkInt (buf, value, offset, ext, max, min) {
1833 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1834 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1835 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1836}
1837
1838Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1839 value = +value
1840 offset = offset >>> 0
1841 byteLength = byteLength >>> 0
1842 if (!noAssert) {
1843 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1844 checkInt(this, value, offset, byteLength, maxBytes, 0)
1845 }
1846
1847 var mul = 1
1848 var i = 0
1849 this[offset] = value & 0xFF
1850 while (++i < byteLength && (mul *= 0x100)) {
1851 this[offset + i] = (value / mul) & 0xFF
1852 }
1853
1854 return offset + byteLength
1855}
1856
1857Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1858 value = +value
1859 offset = offset >>> 0
1860 byteLength = byteLength >>> 0
1861 if (!noAssert) {
1862 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1863 checkInt(this, value, offset, byteLength, maxBytes, 0)
1864 }
1865
1866 var i = byteLength - 1
1867 var mul = 1
1868 this[offset + i] = value & 0xFF
1869 while (--i >= 0 && (mul *= 0x100)) {
1870 this[offset + i] = (value / mul) & 0xFF
1871 }
1872
1873 return offset + byteLength
1874}
1875
1876Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1877 value = +value
1878 offset = offset >>> 0
1879 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1880 this[offset] = (value & 0xff)
1881 return offset + 1
1882}
1883
1884Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1885 value = +value
1886 offset = offset >>> 0
1887 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1888 this[offset] = (value & 0xff)
1889 this[offset + 1] = (value >>> 8)
1890 return offset + 2
1891}
1892
1893Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1894 value = +value
1895 offset = offset >>> 0
1896 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1897 this[offset] = (value >>> 8)
1898 this[offset + 1] = (value & 0xff)
1899 return offset + 2
1900}
1901
1902Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1903 value = +value
1904 offset = offset >>> 0
1905 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1906 this[offset + 3] = (value >>> 24)
1907 this[offset + 2] = (value >>> 16)
1908 this[offset + 1] = (value >>> 8)
1909 this[offset] = (value & 0xff)
1910 return offset + 4
1911}
1912
1913Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1914 value = +value
1915 offset = offset >>> 0
1916 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1917 this[offset] = (value >>> 24)
1918 this[offset + 1] = (value >>> 16)
1919 this[offset + 2] = (value >>> 8)
1920 this[offset + 3] = (value & 0xff)
1921 return offset + 4
1922}
1923
1924Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1925 value = +value
1926 offset = offset >>> 0
1927 if (!noAssert) {
1928 var limit = Math.pow(2, (8 * byteLength) - 1)
1929
1930 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1931 }
1932
1933 var i = 0
1934 var mul = 1
1935 var sub = 0
1936 this[offset] = value & 0xFF
1937 while (++i < byteLength && (mul *= 0x100)) {
1938 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1939 sub = 1
1940 }
1941 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1942 }
1943
1944 return offset + byteLength
1945}
1946
1947Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1948 value = +value
1949 offset = offset >>> 0
1950 if (!noAssert) {
1951 var limit = Math.pow(2, (8 * byteLength) - 1)
1952
1953 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1954 }
1955
1956 var i = byteLength - 1
1957 var mul = 1
1958 var sub = 0
1959 this[offset + i] = value & 0xFF
1960 while (--i >= 0 && (mul *= 0x100)) {
1961 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1962 sub = 1
1963 }
1964 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1965 }
1966
1967 return offset + byteLength
1968}
1969
1970Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1971 value = +value
1972 offset = offset >>> 0
1973 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1974 if (value < 0) value = 0xff + value + 1
1975 this[offset] = (value & 0xff)
1976 return offset + 1
1977}
1978
1979Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1980 value = +value
1981 offset = offset >>> 0
1982 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1983 this[offset] = (value & 0xff)
1984 this[offset + 1] = (value >>> 8)
1985 return offset + 2
1986}
1987
1988Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1989 value = +value
1990 offset = offset >>> 0
1991 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1992 this[offset] = (value >>> 8)
1993 this[offset + 1] = (value & 0xff)
1994 return offset + 2
1995}
1996
1997Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1998 value = +value
1999 offset = offset >>> 0
2000 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2001 this[offset] = (value & 0xff)
2002 this[offset + 1] = (value >>> 8)
2003 this[offset + 2] = (value >>> 16)
2004 this[offset + 3] = (value >>> 24)
2005 return offset + 4
2006}
2007
2008Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2009 value = +value
2010 offset = offset >>> 0
2011 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2012 if (value < 0) value = 0xffffffff + value + 1
2013 this[offset] = (value >>> 24)
2014 this[offset + 1] = (value >>> 16)
2015 this[offset + 2] = (value >>> 8)
2016 this[offset + 3] = (value & 0xff)
2017 return offset + 4
2018}
2019
2020function checkIEEE754 (buf, value, offset, ext, max, min) {
2021 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2022 if (offset < 0) throw new RangeError('Index out of range')
2023}
2024
2025function writeFloat (buf, value, offset, littleEndian, noAssert) {
2026 value = +value
2027 offset = offset >>> 0
2028 if (!noAssert) {
2029 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2030 }
2031 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2032 return offset + 4
2033}
2034
2035Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2036 return writeFloat(this, value, offset, true, noAssert)
2037}
2038
2039Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2040 return writeFloat(this, value, offset, false, noAssert)
2041}
2042
2043function writeDouble (buf, value, offset, littleEndian, noAssert) {
2044 value = +value
2045 offset = offset >>> 0
2046 if (!noAssert) {
2047 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2048 }
2049 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2050 return offset + 8
2051}
2052
2053Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2054 return writeDouble(this, value, offset, true, noAssert)
2055}
2056
2057Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2058 return writeDouble(this, value, offset, false, noAssert)
2059}
2060
2061// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2062Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2063 if (!start) start = 0
2064 if (!end && end !== 0) end = this.length
2065 if (targetStart >= target.length) targetStart = target.length
2066 if (!targetStart) targetStart = 0
2067 if (end > 0 && end < start) end = start
2068
2069 // Copy 0 bytes; we're done
2070 if (end === start) return 0
2071 if (target.length === 0 || this.length === 0) return 0
2072
2073 // Fatal error conditions
2074 if (targetStart < 0) {
2075 throw new RangeError('targetStart out of bounds')
2076 }
2077 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2078 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2079
2080 // Are we oob?
2081 if (end > this.length) end = this.length
2082 if (target.length - targetStart < end - start) {
2083 end = target.length - targetStart + start
2084 }
2085
2086 var len = end - start
2087 var i
2088
2089 if (this === target && start < targetStart && targetStart < end) {
2090 // descending copy from end
2091 for (i = len - 1; i >= 0; --i) {
2092 target[i + targetStart] = this[i + start]
2093 }
2094 } else if (len < 1000) {
2095 // ascending copy from start
2096 for (i = 0; i < len; ++i) {
2097 target[i + targetStart] = this[i + start]
2098 }
2099 } else {
2100 Uint8Array.prototype.set.call(
2101 target,
2102 this.subarray(start, start + len),
2103 targetStart
2104 )
2105 }
2106
2107 return len
2108}
2109
2110// Usage:
2111// buffer.fill(number[, offset[, end]])
2112// buffer.fill(buffer[, offset[, end]])
2113// buffer.fill(string[, offset[, end]][, encoding])
2114Buffer.prototype.fill = function fill (val, start, end, encoding) {
2115 // Handle string cases:
2116 if (typeof val === 'string') {
2117 if (typeof start === 'string') {
2118 encoding = start
2119 start = 0
2120 end = this.length
2121 } else if (typeof end === 'string') {
2122 encoding = end
2123 end = this.length
2124 }
2125 if (val.length === 1) {
2126 var code = val.charCodeAt(0)
2127 if (code < 256) {
2128 val = code
2129 }
2130 }
2131 if (encoding !== undefined && typeof encoding !== 'string') {
2132 throw new TypeError('encoding must be a string')
2133 }
2134 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2135 throw new TypeError('Unknown encoding: ' + encoding)
2136 }
2137 } else if (typeof val === 'number') {
2138 val = val & 255
2139 }
2140
2141 // Invalid ranges are not set to a default, so can range check early.
2142 if (start < 0 || this.length < start || this.length < end) {
2143 throw new RangeError('Out of range index')
2144 }
2145
2146 if (end <= start) {
2147 return this
2148 }
2149
2150 start = start >>> 0
2151 end = end === undefined ? this.length : end >>> 0
2152
2153 if (!val) val = 0
2154
2155 var i
2156 if (typeof val === 'number') {
2157 for (i = start; i < end; ++i) {
2158 this[i] = val
2159 }
2160 } else {
2161 var bytes = Buffer.isBuffer(val)
2162 ? val
2163 : new Buffer(val, encoding)
2164 var len = bytes.length
2165 for (i = 0; i < end - start; ++i) {
2166 this[i + start] = bytes[i % len]
2167 }
2168 }
2169
2170 return this
2171}
2172
2173// HELPER FUNCTIONS
2174// ================
2175
2176var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2177
2178function base64clean (str) {
2179 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2180 str = str.trim().replace(INVALID_BASE64_RE, '')
2181 // Node converts strings with length < 2 to ''
2182 if (str.length < 2) return ''
2183 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2184 while (str.length % 4 !== 0) {
2185 str = str + '='
2186 }
2187 return str
2188}
2189
2190function toHex (n) {
2191 if (n < 16) return '0' + n.toString(16)
2192 return n.toString(16)
2193}
2194
2195function utf8ToBytes (string, units) {
2196 units = units || Infinity
2197 var codePoint
2198 var length = string.length
2199 var leadSurrogate = null
2200 var bytes = []
2201
2202 for (var i = 0; i < length; ++i) {
2203 codePoint = string.charCodeAt(i)
2204
2205 // is surrogate component
2206 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2207 // last char was a lead
2208 if (!leadSurrogate) {
2209 // no lead yet
2210 if (codePoint > 0xDBFF) {
2211 // unexpected trail
2212 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2213 continue
2214 } else if (i + 1 === length) {
2215 // unpaired lead
2216 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2217 continue
2218 }
2219
2220 // valid lead
2221 leadSurrogate = codePoint
2222
2223 continue
2224 }
2225
2226 // 2 leads in a row
2227 if (codePoint < 0xDC00) {
2228 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2229 leadSurrogate = codePoint
2230 continue
2231 }
2232
2233 // valid surrogate pair
2234 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2235 } else if (leadSurrogate) {
2236 // valid bmp char, but last char was a lead
2237 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2238 }
2239
2240 leadSurrogate = null
2241
2242 // encode utf8
2243 if (codePoint < 0x80) {
2244 if ((units -= 1) < 0) break
2245 bytes.push(codePoint)
2246 } else if (codePoint < 0x800) {
2247 if ((units -= 2) < 0) break
2248 bytes.push(
2249 codePoint >> 0x6 | 0xC0,
2250 codePoint & 0x3F | 0x80
2251 )
2252 } else if (codePoint < 0x10000) {
2253 if ((units -= 3) < 0) break
2254 bytes.push(
2255 codePoint >> 0xC | 0xE0,
2256 codePoint >> 0x6 & 0x3F | 0x80,
2257 codePoint & 0x3F | 0x80
2258 )
2259 } else if (codePoint < 0x110000) {
2260 if ((units -= 4) < 0) break
2261 bytes.push(
2262 codePoint >> 0x12 | 0xF0,
2263 codePoint >> 0xC & 0x3F | 0x80,
2264 codePoint >> 0x6 & 0x3F | 0x80,
2265 codePoint & 0x3F | 0x80
2266 )
2267 } else {
2268 throw new Error('Invalid code point')
2269 }
2270 }
2271
2272 return bytes
2273}
2274
2275function asciiToBytes (str) {
2276 var byteArray = []
2277 for (var i = 0; i < str.length; ++i) {
2278 // Node's code seems to be doing this and not & 0x7F..
2279 byteArray.push(str.charCodeAt(i) & 0xFF)
2280 }
2281 return byteArray
2282}
2283
2284function utf16leToBytes (str, units) {
2285 var c, hi, lo
2286 var byteArray = []
2287 for (var i = 0; i < str.length; ++i) {
2288 if ((units -= 2) < 0) break
2289
2290 c = str.charCodeAt(i)
2291 hi = c >> 8
2292 lo = c % 256
2293 byteArray.push(lo)
2294 byteArray.push(hi)
2295 }
2296
2297 return byteArray
2298}
2299
2300function base64ToBytes (str) {
2301 return base64.toByteArray(base64clean(str))
2302}
2303
2304function blitBuffer (src, dst, offset, length) {
2305 for (var i = 0; i < length; ++i) {
2306 if ((i + offset >= dst.length) || (i >= src.length)) break
2307 dst[i + offset] = src[i]
2308 }
2309 return i
2310}
2311
2312// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2313function isArrayBufferView (obj) {
2314 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2315}
2316
2317function numberIsNaN (obj) {
2318 return obj !== obj // eslint-disable-line no-self-compare
2319}
2320
2321},{"base64-js":2,"ieee754":7}],5:[function(require,module,exports){
2322(function (Buffer){
2323// Copyright Joyent, Inc. and other Node contributors.
2324//
2325// Permission is hereby granted, free of charge, to any person obtaining a
2326// copy of this software and associated documentation files (the
2327// "Software"), to deal in the Software without restriction, including
2328// without limitation the rights to use, copy, modify, merge, publish,
2329// distribute, sublicense, and/or sell copies of the Software, and to permit
2330// persons to whom the Software is furnished to do so, subject to the
2331// following conditions:
2332//
2333// The above copyright notice and this permission notice shall be included
2334// in all copies or substantial portions of the Software.
2335//
2336// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2337// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2338// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2339// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2340// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2341// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2342// USE OR OTHER DEALINGS IN THE SOFTWARE.
2343
2344// NOTE: These type checking functions intentionally don't use `instanceof`
2345// because it is fragile and can be easily faked with `Object.create()`.
2346
2347function isArray(arg) {
2348 if (Array.isArray) {
2349 return Array.isArray(arg);
2350 }
2351 return objectToString(arg) === '[object Array]';
2352}
2353exports.isArray = isArray;
2354
2355function isBoolean(arg) {
2356 return typeof arg === 'boolean';
2357}
2358exports.isBoolean = isBoolean;
2359
2360function isNull(arg) {
2361 return arg === null;
2362}
2363exports.isNull = isNull;
2364
2365function isNullOrUndefined(arg) {
2366 return arg == null;
2367}
2368exports.isNullOrUndefined = isNullOrUndefined;
2369
2370function isNumber(arg) {
2371 return typeof arg === 'number';
2372}
2373exports.isNumber = isNumber;
2374
2375function isString(arg) {
2376 return typeof arg === 'string';
2377}
2378exports.isString = isString;
2379
2380function isSymbol(arg) {
2381 return typeof arg === 'symbol';
2382}
2383exports.isSymbol = isSymbol;
2384
2385function isUndefined(arg) {
2386 return arg === void 0;
2387}
2388exports.isUndefined = isUndefined;
2389
2390function isRegExp(re) {
2391 return objectToString(re) === '[object RegExp]';
2392}
2393exports.isRegExp = isRegExp;
2394
2395function isObject(arg) {
2396 return typeof arg === 'object' && arg !== null;
2397}
2398exports.isObject = isObject;
2399
2400function isDate(d) {
2401 return objectToString(d) === '[object Date]';
2402}
2403exports.isDate = isDate;
2404
2405function isError(e) {
2406 return (objectToString(e) === '[object Error]' || e instanceof Error);
2407}
2408exports.isError = isError;
2409
2410function isFunction(arg) {
2411 return typeof arg === 'function';
2412}
2413exports.isFunction = isFunction;
2414
2415function isPrimitive(arg) {
2416 return arg === null ||
2417 typeof arg === 'boolean' ||
2418 typeof arg === 'number' ||
2419 typeof arg === 'string' ||
2420 typeof arg === 'symbol' || // ES6 symbol
2421 typeof arg === 'undefined';
2422}
2423exports.isPrimitive = isPrimitive;
2424
2425exports.isBuffer = Buffer.isBuffer;
2426
2427function objectToString(o) {
2428 return Object.prototype.toString.call(o);
2429}
2430
2431}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
2432},{"../../is-buffer/index.js":9}],6:[function(require,module,exports){
2433// Copyright Joyent, Inc. and other Node contributors.
2434//
2435// Permission is hereby granted, free of charge, to any person obtaining a
2436// copy of this software and associated documentation files (the
2437// "Software"), to deal in the Software without restriction, including
2438// without limitation the rights to use, copy, modify, merge, publish,
2439// distribute, sublicense, and/or sell copies of the Software, and to permit
2440// persons to whom the Software is furnished to do so, subject to the
2441// following conditions:
2442//
2443// The above copyright notice and this permission notice shall be included
2444// in all copies or substantial portions of the Software.
2445//
2446// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2447// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2448// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2449// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2450// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2451// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2452// USE OR OTHER DEALINGS IN THE SOFTWARE.
2453
2454function EventEmitter() {
2455 this._events = this._events || {};
2456 this._maxListeners = this._maxListeners || undefined;
2457}
2458module.exports = EventEmitter;
2459
2460// Backwards-compat with node 0.10.x
2461EventEmitter.EventEmitter = EventEmitter;
2462
2463EventEmitter.prototype._events = undefined;
2464EventEmitter.prototype._maxListeners = undefined;
2465
2466// By default EventEmitters will print a warning if more than 10 listeners are
2467// added to it. This is a useful default which helps finding memory leaks.
2468EventEmitter.defaultMaxListeners = 10;
2469
2470// Obviously not all Emitters should be limited to 10. This function allows
2471// that to be increased. Set to zero for unlimited.
2472EventEmitter.prototype.setMaxListeners = function(n) {
2473 if (!isNumber(n) || n < 0 || isNaN(n))
2474 throw TypeError('n must be a positive number');
2475 this._maxListeners = n;
2476 return this;
2477};
2478
2479EventEmitter.prototype.emit = function(type) {
2480 var er, handler, len, args, i, listeners;
2481
2482 if (!this._events)
2483 this._events = {};
2484
2485 // If there is no 'error' event listener then throw.
2486 if (type === 'error') {
2487 if (!this._events.error ||
2488 (isObject(this._events.error) && !this._events.error.length)) {
2489 er = arguments[1];
2490 if (er instanceof Error) {
2491 throw er; // Unhandled 'error' event
2492 } else {
2493 // At least give some kind of context to the user
2494 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
2495 err.context = er;
2496 throw err;
2497 }
2498 }
2499 }
2500
2501 handler = this._events[type];
2502
2503 if (isUndefined(handler))
2504 return false;
2505
2506 if (isFunction(handler)) {
2507 switch (arguments.length) {
2508 // fast cases
2509 case 1:
2510 handler.call(this);
2511 break;
2512 case 2:
2513 handler.call(this, arguments[1]);
2514 break;
2515 case 3:
2516 handler.call(this, arguments[1], arguments[2]);
2517 break;
2518 // slower
2519 default:
2520 args = Array.prototype.slice.call(arguments, 1);
2521 handler.apply(this, args);
2522 }
2523 } else if (isObject(handler)) {
2524 args = Array.prototype.slice.call(arguments, 1);
2525 listeners = handler.slice();
2526 len = listeners.length;
2527 for (i = 0; i < len; i++)
2528 listeners[i].apply(this, args);
2529 }
2530
2531 return true;
2532};
2533
2534EventEmitter.prototype.addListener = function(type, listener) {
2535 var m;
2536
2537 if (!isFunction(listener))
2538 throw TypeError('listener must be a function');
2539
2540 if (!this._events)
2541 this._events = {};
2542
2543 // To avoid recursion in the case that type === "newListener"! Before
2544 // adding it to the listeners, first emit "newListener".
2545 if (this._events.newListener)
2546 this.emit('newListener', type,
2547 isFunction(listener.listener) ?
2548 listener.listener : listener);
2549
2550 if (!this._events[type])
2551 // Optimize the case of one listener. Don't need the extra array object.
2552 this._events[type] = listener;
2553 else if (isObject(this._events[type]))
2554 // If we've already got an array, just append.
2555 this._events[type].push(listener);
2556 else
2557 // Adding the second element, need to change to array.
2558 this._events[type] = [this._events[type], listener];
2559
2560 // Check for listener leak
2561 if (isObject(this._events[type]) && !this._events[type].warned) {
2562 if (!isUndefined(this._maxListeners)) {
2563 m = this._maxListeners;
2564 } else {
2565 m = EventEmitter.defaultMaxListeners;
2566 }
2567
2568 if (m && m > 0 && this._events[type].length > m) {
2569 this._events[type].warned = true;
2570 console.error('(node) warning: possible EventEmitter memory ' +
2571 'leak detected. %d listeners added. ' +
2572 'Use emitter.setMaxListeners() to increase limit.',
2573 this._events[type].length);
2574 if (typeof console.trace === 'function') {
2575 // not supported in IE 10
2576 console.trace();
2577 }
2578 }
2579 }
2580
2581 return this;
2582};
2583
2584EventEmitter.prototype.on = EventEmitter.prototype.addListener;
2585
2586EventEmitter.prototype.once = function(type, listener) {
2587 if (!isFunction(listener))
2588 throw TypeError('listener must be a function');
2589
2590 var fired = false;
2591
2592 function g() {
2593 this.removeListener(type, g);
2594
2595 if (!fired) {
2596 fired = true;
2597 listener.apply(this, arguments);
2598 }
2599 }
2600
2601 g.listener = listener;
2602 this.on(type, g);
2603
2604 return this;
2605};
2606
2607// emits a 'removeListener' event iff the listener was removed
2608EventEmitter.prototype.removeListener = function(type, listener) {
2609 var list, position, length, i;
2610
2611 if (!isFunction(listener))
2612 throw TypeError('listener must be a function');
2613
2614 if (!this._events || !this._events[type])
2615 return this;
2616
2617 list = this._events[type];
2618 length = list.length;
2619 position = -1;
2620
2621 if (list === listener ||
2622 (isFunction(list.listener) && list.listener === listener)) {
2623 delete this._events[type];
2624 if (this._events.removeListener)
2625 this.emit('removeListener', type, listener);
2626
2627 } else if (isObject(list)) {
2628 for (i = length; i-- > 0;) {
2629 if (list[i] === listener ||
2630 (list[i].listener && list[i].listener === listener)) {
2631 position = i;
2632 break;
2633 }
2634 }
2635
2636 if (position < 0)
2637 return this;
2638
2639 if (list.length === 1) {
2640 list.length = 0;
2641 delete this._events[type];
2642 } else {
2643 list.splice(position, 1);
2644 }
2645
2646 if (this._events.removeListener)
2647 this.emit('removeListener', type, listener);
2648 }
2649
2650 return this;
2651};
2652
2653EventEmitter.prototype.removeAllListeners = function(type) {
2654 var key, listeners;
2655
2656 if (!this._events)
2657 return this;
2658
2659 // not listening for removeListener, no need to emit
2660 if (!this._events.removeListener) {
2661 if (arguments.length === 0)
2662 this._events = {};
2663 else if (this._events[type])
2664 delete this._events[type];
2665 return this;
2666 }
2667
2668 // emit removeListener for all listeners on all events
2669 if (arguments.length === 0) {
2670 for (key in this._events) {
2671 if (key === 'removeListener') continue;
2672 this.removeAllListeners(key);
2673 }
2674 this.removeAllListeners('removeListener');
2675 this._events = {};
2676 return this;
2677 }
2678
2679 listeners = this._events[type];
2680
2681 if (isFunction(listeners)) {
2682 this.removeListener(type, listeners);
2683 } else if (listeners) {
2684 // LIFO order
2685 while (listeners.length)
2686 this.removeListener(type, listeners[listeners.length - 1]);
2687 }
2688 delete this._events[type];
2689
2690 return this;
2691};
2692
2693EventEmitter.prototype.listeners = function(type) {
2694 var ret;
2695 if (!this._events || !this._events[type])
2696 ret = [];
2697 else if (isFunction(this._events[type]))
2698 ret = [this._events[type]];
2699 else
2700 ret = this._events[type].slice();
2701 return ret;
2702};
2703
2704EventEmitter.prototype.listenerCount = function(type) {
2705 if (this._events) {
2706 var evlistener = this._events[type];
2707
2708 if (isFunction(evlistener))
2709 return 1;
2710 else if (evlistener)
2711 return evlistener.length;
2712 }
2713 return 0;
2714};
2715
2716EventEmitter.listenerCount = function(emitter, type) {
2717 return emitter.listenerCount(type);
2718};
2719
2720function isFunction(arg) {
2721 return typeof arg === 'function';
2722}
2723
2724function isNumber(arg) {
2725 return typeof arg === 'number';
2726}
2727
2728function isObject(arg) {
2729 return typeof arg === 'object' && arg !== null;
2730}
2731
2732function isUndefined(arg) {
2733 return arg === void 0;
2734}
2735
2736},{}],7:[function(require,module,exports){
2737exports.read = function (buffer, offset, isLE, mLen, nBytes) {
2738 var e, m
2739 var eLen = nBytes * 8 - mLen - 1
2740 var eMax = (1 << eLen) - 1
2741 var eBias = eMax >> 1
2742 var nBits = -7
2743 var i = isLE ? (nBytes - 1) : 0
2744 var d = isLE ? -1 : 1
2745 var s = buffer[offset + i]
2746
2747 i += d
2748
2749 e = s & ((1 << (-nBits)) - 1)
2750 s >>= (-nBits)
2751 nBits += eLen
2752 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2753
2754 m = e & ((1 << (-nBits)) - 1)
2755 e >>= (-nBits)
2756 nBits += mLen
2757 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2758
2759 if (e === 0) {
2760 e = 1 - eBias
2761 } else if (e === eMax) {
2762 return m ? NaN : ((s ? -1 : 1) * Infinity)
2763 } else {
2764 m = m + Math.pow(2, mLen)
2765 e = e - eBias
2766 }
2767 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
2768}
2769
2770exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
2771 var e, m, c
2772 var eLen = nBytes * 8 - mLen - 1
2773 var eMax = (1 << eLen) - 1
2774 var eBias = eMax >> 1
2775 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
2776 var i = isLE ? 0 : (nBytes - 1)
2777 var d = isLE ? 1 : -1
2778 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
2779
2780 value = Math.abs(value)
2781
2782 if (isNaN(value) || value === Infinity) {
2783 m = isNaN(value) ? 1 : 0
2784 e = eMax
2785 } else {
2786 e = Math.floor(Math.log(value) / Math.LN2)
2787 if (value * (c = Math.pow(2, -e)) < 1) {
2788 e--
2789 c *= 2
2790 }
2791 if (e + eBias >= 1) {
2792 value += rt / c
2793 } else {
2794 value += rt * Math.pow(2, 1 - eBias)
2795 }
2796 if (value * c >= 2) {
2797 e++
2798 c /= 2
2799 }
2800
2801 if (e + eBias >= eMax) {
2802 m = 0
2803 e = eMax
2804 } else if (e + eBias >= 1) {
2805 m = (value * c - 1) * Math.pow(2, mLen)
2806 e = e + eBias
2807 } else {
2808 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
2809 e = 0
2810 }
2811 }
2812
2813 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2814
2815 e = (e << mLen) | m
2816 eLen += mLen
2817 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2818
2819 buffer[offset + i - d] |= s * 128
2820}
2821
2822},{}],8:[function(require,module,exports){
2823if (typeof Object.create === 'function') {
2824 // implementation from standard node.js 'util' module
2825 module.exports = function inherits(ctor, superCtor) {
2826 ctor.super_ = superCtor
2827 ctor.prototype = Object.create(superCtor.prototype, {
2828 constructor: {
2829 value: ctor,
2830 enumerable: false,
2831 writable: true,
2832 configurable: true
2833 }
2834 });
2835 };
2836} else {
2837 // old school shim for old browsers
2838 module.exports = function inherits(ctor, superCtor) {
2839 ctor.super_ = superCtor
2840 var TempCtor = function () {}
2841 TempCtor.prototype = superCtor.prototype
2842 ctor.prototype = new TempCtor()
2843 ctor.prototype.constructor = ctor
2844 }
2845}
2846
2847},{}],9:[function(require,module,exports){
2848/*!
2849 * Determine if an object is a Buffer
2850 *
2851 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2852 * @license MIT
2853 */
2854
2855// The _isBuffer check is for Safari 5-7 support, because it's missing
2856// Object.prototype.constructor. Remove this eventually
2857module.exports = function (obj) {
2858 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
2859}
2860
2861function isBuffer (obj) {
2862 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
2863}
2864
2865// For Node v0.10 support. Remove this eventually.
2866function isSlowBuffer (obj) {
2867 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
2868}
2869
2870},{}],10:[function(require,module,exports){
2871var toString = {}.toString;
2872
2873module.exports = Array.isArray || function (arr) {
2874 return toString.call(arr) == '[object Array]';
2875};
2876
2877},{}],11:[function(require,module,exports){
2878(function (process){
2879'use strict';
2880
2881if (!process.version ||
2882 process.version.indexOf('v0.') === 0 ||
2883 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
2884 module.exports = nextTick;
2885} else {
2886 module.exports = process.nextTick;
2887}
2888
2889function nextTick(fn, arg1, arg2, arg3) {
2890 if (typeof fn !== 'function') {
2891 throw new TypeError('"callback" argument must be a function');
2892 }
2893 var len = arguments.length;
2894 var args, i;
2895 switch (len) {
2896 case 0:
2897 case 1:
2898 return process.nextTick(fn);
2899 case 2:
2900 return process.nextTick(function afterTickOne() {
2901 fn.call(null, arg1);
2902 });
2903 case 3:
2904 return process.nextTick(function afterTickTwo() {
2905 fn.call(null, arg1, arg2);
2906 });
2907 case 4:
2908 return process.nextTick(function afterTickThree() {
2909 fn.call(null, arg1, arg2, arg3);
2910 });
2911 default:
2912 args = new Array(len - 1);
2913 i = 0;
2914 while (i < args.length) {
2915 args[i++] = arguments[i];
2916 }
2917 return process.nextTick(function afterTick() {
2918 fn.apply(null, args);
2919 });
2920 }
2921}
2922
2923}).call(this,require('_process'))
2924},{"_process":12}],12:[function(require,module,exports){
2925// shim for using process in browser
2926var process = module.exports = {};
2927
2928// cached from whatever global is present so that test runners that stub it
2929// don't break things. But we need to wrap it in a try catch in case it is
2930// wrapped in strict mode code which doesn't define any globals. It's inside a
2931// function because try/catches deoptimize in certain engines.
2932
2933var cachedSetTimeout;
2934var cachedClearTimeout;
2935
2936function defaultSetTimout() {
2937 throw new Error('setTimeout has not been defined');
2938}
2939function defaultClearTimeout () {
2940 throw new Error('clearTimeout has not been defined');
2941}
2942(function () {
2943 try {
2944 if (typeof setTimeout === 'function') {
2945 cachedSetTimeout = setTimeout;
2946 } else {
2947 cachedSetTimeout = defaultSetTimout;
2948 }
2949 } catch (e) {
2950 cachedSetTimeout = defaultSetTimout;
2951 }
2952 try {
2953 if (typeof clearTimeout === 'function') {
2954 cachedClearTimeout = clearTimeout;
2955 } else {
2956 cachedClearTimeout = defaultClearTimeout;
2957 }
2958 } catch (e) {
2959 cachedClearTimeout = defaultClearTimeout;
2960 }
2961} ())
2962function runTimeout(fun) {
2963 if (cachedSetTimeout === setTimeout) {
2964 //normal enviroments in sane situations
2965 return setTimeout(fun, 0);
2966 }
2967 // if setTimeout wasn't available but was latter defined
2968 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
2969 cachedSetTimeout = setTimeout;
2970 return setTimeout(fun, 0);
2971 }
2972 try {
2973 // when when somebody has screwed with setTimeout but no I.E. maddness
2974 return cachedSetTimeout(fun, 0);
2975 } catch(e){
2976 try {
2977 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
2978 return cachedSetTimeout.call(null, fun, 0);
2979 } catch(e){
2980 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
2981 return cachedSetTimeout.call(this, fun, 0);
2982 }
2983 }
2984
2985
2986}
2987function runClearTimeout(marker) {
2988 if (cachedClearTimeout === clearTimeout) {
2989 //normal enviroments in sane situations
2990 return clearTimeout(marker);
2991 }
2992 // if clearTimeout wasn't available but was latter defined
2993 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
2994 cachedClearTimeout = clearTimeout;
2995 return clearTimeout(marker);
2996 }
2997 try {
2998 // when when somebody has screwed with setTimeout but no I.E. maddness
2999 return cachedClearTimeout(marker);
3000 } catch (e){
3001 try {
3002 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3003 return cachedClearTimeout.call(null, marker);
3004 } catch (e){
3005 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
3006 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
3007 return cachedClearTimeout.call(this, marker);
3008 }
3009 }
3010
3011
3012
3013}
3014var queue = [];
3015var draining = false;
3016var currentQueue;
3017var queueIndex = -1;
3018
3019function cleanUpNextTick() {
3020 if (!draining || !currentQueue) {
3021 return;
3022 }
3023 draining = false;
3024 if (currentQueue.length) {
3025 queue = currentQueue.concat(queue);
3026 } else {
3027 queueIndex = -1;
3028 }
3029 if (queue.length) {
3030 drainQueue();
3031 }
3032}
3033
3034function drainQueue() {
3035 if (draining) {
3036 return;
3037 }
3038 var timeout = runTimeout(cleanUpNextTick);
3039 draining = true;
3040
3041 var len = queue.length;
3042 while(len) {
3043 currentQueue = queue;
3044 queue = [];
3045 while (++queueIndex < len) {
3046 if (currentQueue) {
3047 currentQueue[queueIndex].run();
3048 }
3049 }
3050 queueIndex = -1;
3051 len = queue.length;
3052 }
3053 currentQueue = null;
3054 draining = false;
3055 runClearTimeout(timeout);
3056}
3057
3058process.nextTick = function (fun) {
3059 var args = new Array(arguments.length - 1);
3060 if (arguments.length > 1) {
3061 for (var i = 1; i < arguments.length; i++) {
3062 args[i - 1] = arguments[i];
3063 }
3064 }
3065 queue.push(new Item(fun, args));
3066 if (queue.length === 1 && !draining) {
3067 runTimeout(drainQueue);
3068 }
3069};
3070
3071// v8 likes predictible objects
3072function Item(fun, array) {
3073 this.fun = fun;
3074 this.array = array;
3075}
3076Item.prototype.run = function () {
3077 this.fun.apply(null, this.array);
3078};
3079process.title = 'browser';
3080process.browser = true;
3081process.env = {};
3082process.argv = [];
3083process.version = ''; // empty string to avoid regexp issues
3084process.versions = {};
3085
3086function noop() {}
3087
3088process.on = noop;
3089process.addListener = noop;
3090process.once = noop;
3091process.off = noop;
3092process.removeListener = noop;
3093process.removeAllListeners = noop;
3094process.emit = noop;
3095process.prependListener = noop;
3096process.prependOnceListener = noop;
3097
3098process.listeners = function (name) { return [] }
3099
3100process.binding = function (name) {
3101 throw new Error('process.binding is not supported');
3102};
3103
3104process.cwd = function () { return '/' };
3105process.chdir = function (dir) {
3106 throw new Error('process.chdir is not supported');
3107};
3108process.umask = function() { return 0; };
3109
3110},{}],13:[function(require,module,exports){
3111module.exports = require('./lib/_stream_duplex.js');
3112
3113},{"./lib/_stream_duplex.js":14}],14:[function(require,module,exports){
3114// Copyright Joyent, Inc. and other Node contributors.
3115//
3116// Permission is hereby granted, free of charge, to any person obtaining a
3117// copy of this software and associated documentation files (the
3118// "Software"), to deal in the Software without restriction, including
3119// without limitation the rights to use, copy, modify, merge, publish,
3120// distribute, sublicense, and/or sell copies of the Software, and to permit
3121// persons to whom the Software is furnished to do so, subject to the
3122// following conditions:
3123//
3124// The above copyright notice and this permission notice shall be included
3125// in all copies or substantial portions of the Software.
3126//
3127// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3128// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3129// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3130// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3131// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3132// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3133// USE OR OTHER DEALINGS IN THE SOFTWARE.
3134
3135// a duplex stream is just a stream that is both readable and writable.
3136// Since JS doesn't have multiple prototypal inheritance, this class
3137// prototypally inherits from Readable, and then parasitically from
3138// Writable.
3139
3140'use strict';
3141
3142/*<replacement>*/
3143
3144var processNextTick = require('process-nextick-args');
3145/*</replacement>*/
3146
3147/*<replacement>*/
3148var objectKeys = Object.keys || function (obj) {
3149 var keys = [];
3150 for (var key in obj) {
3151 keys.push(key);
3152 }return keys;
3153};
3154/*</replacement>*/
3155
3156module.exports = Duplex;
3157
3158/*<replacement>*/
3159var util = require('core-util-is');
3160util.inherits = require('inherits');
3161/*</replacement>*/
3162
3163var Readable = require('./_stream_readable');
3164var Writable = require('./_stream_writable');
3165
3166util.inherits(Duplex, Readable);
3167
3168var keys = objectKeys(Writable.prototype);
3169for (var v = 0; v < keys.length; v++) {
3170 var method = keys[v];
3171 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
3172}
3173
3174function Duplex(options) {
3175 if (!(this instanceof Duplex)) return new Duplex(options);
3176
3177 Readable.call(this, options);
3178 Writable.call(this, options);
3179
3180 if (options && options.readable === false) this.readable = false;
3181
3182 if (options && options.writable === false) this.writable = false;
3183
3184 this.allowHalfOpen = true;
3185 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
3186
3187 this.once('end', onend);
3188}
3189
3190// the no-half-open enforcer
3191function onend() {
3192 // if we allow half-open state, or if the writable side ended,
3193 // then we're ok.
3194 if (this.allowHalfOpen || this._writableState.ended) return;
3195
3196 // no more data can be written.
3197 // But allow more writes to happen in this tick.
3198 processNextTick(onEndNT, this);
3199}
3200
3201function onEndNT(self) {
3202 self.end();
3203}
3204
3205Object.defineProperty(Duplex.prototype, 'destroyed', {
3206 get: function () {
3207 if (this._readableState === undefined || this._writableState === undefined) {
3208 return false;
3209 }
3210 return this._readableState.destroyed && this._writableState.destroyed;
3211 },
3212 set: function (value) {
3213 // we ignore the value if the stream
3214 // has not been initialized yet
3215 if (this._readableState === undefined || this._writableState === undefined) {
3216 return;
3217 }
3218
3219 // backward compatibility, the user is explicitly
3220 // managing destroyed
3221 this._readableState.destroyed = value;
3222 this._writableState.destroyed = value;
3223 }
3224});
3225
3226Duplex.prototype._destroy = function (err, cb) {
3227 this.push(null);
3228 this.end();
3229
3230 processNextTick(cb, err);
3231};
3232
3233function forEach(xs, f) {
3234 for (var i = 0, l = xs.length; i < l; i++) {
3235 f(xs[i], i);
3236 }
3237}
3238},{"./_stream_readable":16,"./_stream_writable":18,"core-util-is":5,"inherits":8,"process-nextick-args":11}],15:[function(require,module,exports){
3239// Copyright Joyent, Inc. and other Node contributors.
3240//
3241// Permission is hereby granted, free of charge, to any person obtaining a
3242// copy of this software and associated documentation files (the
3243// "Software"), to deal in the Software without restriction, including
3244// without limitation the rights to use, copy, modify, merge, publish,
3245// distribute, sublicense, and/or sell copies of the Software, and to permit
3246// persons to whom the Software is furnished to do so, subject to the
3247// following conditions:
3248//
3249// The above copyright notice and this permission notice shall be included
3250// in all copies or substantial portions of the Software.
3251//
3252// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3253// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3254// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3255// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3256// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3257// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3258// USE OR OTHER DEALINGS IN THE SOFTWARE.
3259
3260// a passthrough stream.
3261// basically just the most minimal sort of Transform stream.
3262// Every written chunk gets output as-is.
3263
3264'use strict';
3265
3266module.exports = PassThrough;
3267
3268var Transform = require('./_stream_transform');
3269
3270/*<replacement>*/
3271var util = require('core-util-is');
3272util.inherits = require('inherits');
3273/*</replacement>*/
3274
3275util.inherits(PassThrough, Transform);
3276
3277function PassThrough(options) {
3278 if (!(this instanceof PassThrough)) return new PassThrough(options);
3279
3280 Transform.call(this, options);
3281}
3282
3283PassThrough.prototype._transform = function (chunk, encoding, cb) {
3284 cb(null, chunk);
3285};
3286},{"./_stream_transform":17,"core-util-is":5,"inherits":8}],16:[function(require,module,exports){
3287(function (process,global){
3288// Copyright Joyent, Inc. and other Node contributors.
3289//
3290// Permission is hereby granted, free of charge, to any person obtaining a
3291// copy of this software and associated documentation files (the
3292// "Software"), to deal in the Software without restriction, including
3293// without limitation the rights to use, copy, modify, merge, publish,
3294// distribute, sublicense, and/or sell copies of the Software, and to permit
3295// persons to whom the Software is furnished to do so, subject to the
3296// following conditions:
3297//
3298// The above copyright notice and this permission notice shall be included
3299// in all copies or substantial portions of the Software.
3300//
3301// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3302// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3303// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3304// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3305// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3306// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3307// USE OR OTHER DEALINGS IN THE SOFTWARE.
3308
3309'use strict';
3310
3311/*<replacement>*/
3312
3313var processNextTick = require('process-nextick-args');
3314/*</replacement>*/
3315
3316module.exports = Readable;
3317
3318/*<replacement>*/
3319var isArray = require('isarray');
3320/*</replacement>*/
3321
3322/*<replacement>*/
3323var Duplex;
3324/*</replacement>*/
3325
3326Readable.ReadableState = ReadableState;
3327
3328/*<replacement>*/
3329var EE = require('events').EventEmitter;
3330
3331var EElistenerCount = function (emitter, type) {
3332 return emitter.listeners(type).length;
3333};
3334/*</replacement>*/
3335
3336/*<replacement>*/
3337var Stream = require('./internal/streams/stream');
3338/*</replacement>*/
3339
3340// TODO(bmeurer): Change this back to const once hole checks are
3341// properly optimized away early in Ignition+TurboFan.
3342/*<replacement>*/
3343var Buffer = require('safe-buffer').Buffer;
3344var OurUint8Array = global.Uint8Array || function () {};
3345function _uint8ArrayToBuffer(chunk) {
3346 return Buffer.from(chunk);
3347}
3348function _isUint8Array(obj) {
3349 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
3350}
3351/*</replacement>*/
3352
3353/*<replacement>*/
3354var util = require('core-util-is');
3355util.inherits = require('inherits');
3356/*</replacement>*/
3357
3358/*<replacement>*/
3359var debugUtil = require('util');
3360var debug = void 0;
3361if (debugUtil && debugUtil.debuglog) {
3362 debug = debugUtil.debuglog('stream');
3363} else {
3364 debug = function () {};
3365}
3366/*</replacement>*/
3367
3368var BufferList = require('./internal/streams/BufferList');
3369var destroyImpl = require('./internal/streams/destroy');
3370var StringDecoder;
3371
3372util.inherits(Readable, Stream);
3373
3374var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
3375
3376function prependListener(emitter, event, fn) {
3377 // Sadly this is not cacheable as some libraries bundle their own
3378 // event emitter implementation with them.
3379 if (typeof emitter.prependListener === 'function') {
3380 return emitter.prependListener(event, fn);
3381 } else {
3382 // This is a hack to make sure that our error handler is attached before any
3383 // userland ones. NEVER DO THIS. This is here only because this code needs
3384 // to continue to work with older versions of Node.js that do not include
3385 // the prependListener() method. The goal is to eventually remove this hack.
3386 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
3387 }
3388}
3389
3390function ReadableState(options, stream) {
3391 Duplex = Duplex || require('./_stream_duplex');
3392
3393 options = options || {};
3394
3395 // object stream flag. Used to make read(n) ignore n and to
3396 // make all the buffer merging and length checks go away
3397 this.objectMode = !!options.objectMode;
3398
3399 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
3400
3401 // the point at which it stops calling _read() to fill the buffer
3402 // Note: 0 is a valid value, means "don't call _read preemptively ever"
3403 var hwm = options.highWaterMark;
3404 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
3405 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
3406
3407 // cast to ints.
3408 this.highWaterMark = Math.floor(this.highWaterMark);
3409
3410 // A linked list is used to store data chunks instead of an array because the
3411 // linked list can remove elements from the beginning faster than
3412 // array.shift()
3413 this.buffer = new BufferList();
3414 this.length = 0;
3415 this.pipes = null;
3416 this.pipesCount = 0;
3417 this.flowing = null;
3418 this.ended = false;
3419 this.endEmitted = false;
3420 this.reading = false;
3421
3422 // a flag to be able to tell if the event 'readable'/'data' is emitted
3423 // immediately, or on a later tick. We set this to true at first, because
3424 // any actions that shouldn't happen until "later" should generally also
3425 // not happen before the first read call.
3426 this.sync = true;
3427
3428 // whenever we return null, then we set a flag to say
3429 // that we're awaiting a 'readable' event emission.
3430 this.needReadable = false;
3431 this.emittedReadable = false;
3432 this.readableListening = false;
3433 this.resumeScheduled = false;
3434
3435 // has it been destroyed
3436 this.destroyed = false;
3437
3438 // Crypto is kind of old and crusty. Historically, its default string
3439 // encoding is 'binary' so we have to make this configurable.
3440 // Everything else in the universe uses 'utf8', though.
3441 this.defaultEncoding = options.defaultEncoding || 'utf8';
3442
3443 // the number of writers that are awaiting a drain event in .pipe()s
3444 this.awaitDrain = 0;
3445
3446 // if true, a maybeReadMore has been scheduled
3447 this.readingMore = false;
3448
3449 this.decoder = null;
3450 this.encoding = null;
3451 if (options.encoding) {
3452 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
3453 this.decoder = new StringDecoder(options.encoding);
3454 this.encoding = options.encoding;
3455 }
3456}
3457
3458function Readable(options) {
3459 Duplex = Duplex || require('./_stream_duplex');
3460
3461 if (!(this instanceof Readable)) return new Readable(options);
3462
3463 this._readableState = new ReadableState(options, this);
3464
3465 // legacy
3466 this.readable = true;
3467
3468 if (options) {
3469 if (typeof options.read === 'function') this._read = options.read;
3470
3471 if (typeof options.destroy === 'function') this._destroy = options.destroy;
3472 }
3473
3474 Stream.call(this);
3475}
3476
3477Object.defineProperty(Readable.prototype, 'destroyed', {
3478 get: function () {
3479 if (this._readableState === undefined) {
3480 return false;
3481 }
3482 return this._readableState.destroyed;
3483 },
3484 set: function (value) {
3485 // we ignore the value if the stream
3486 // has not been initialized yet
3487 if (!this._readableState) {
3488 return;
3489 }
3490
3491 // backward compatibility, the user is explicitly
3492 // managing destroyed
3493 this._readableState.destroyed = value;
3494 }
3495});
3496
3497Readable.prototype.destroy = destroyImpl.destroy;
3498Readable.prototype._undestroy = destroyImpl.undestroy;
3499Readable.prototype._destroy = function (err, cb) {
3500 this.push(null);
3501 cb(err);
3502};
3503
3504// Manually shove something into the read() buffer.
3505// This returns true if the highWaterMark has not been hit yet,
3506// similar to how Writable.write() returns true if you should
3507// write() some more.
3508Readable.prototype.push = function (chunk, encoding) {
3509 var state = this._readableState;
3510 var skipChunkCheck;
3511
3512 if (!state.objectMode) {
3513 if (typeof chunk === 'string') {
3514 encoding = encoding || state.defaultEncoding;
3515 if (encoding !== state.encoding) {
3516 chunk = Buffer.from(chunk, encoding);
3517 encoding = '';
3518 }
3519 skipChunkCheck = true;
3520 }
3521 } else {
3522 skipChunkCheck = true;
3523 }
3524
3525 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
3526};
3527
3528// Unshift should *always* be something directly out of read()
3529Readable.prototype.unshift = function (chunk) {
3530 return readableAddChunk(this, chunk, null, true, false);
3531};
3532
3533function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
3534 var state = stream._readableState;
3535 if (chunk === null) {
3536 state.reading = false;
3537 onEofChunk(stream, state);
3538 } else {
3539 var er;
3540 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
3541 if (er) {
3542 stream.emit('error', er);
3543 } else if (state.objectMode || chunk && chunk.length > 0) {
3544 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
3545 chunk = _uint8ArrayToBuffer(chunk);
3546 }
3547
3548 if (addToFront) {
3549 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
3550 } else if (state.ended) {
3551 stream.emit('error', new Error('stream.push() after EOF'));
3552 } else {
3553 state.reading = false;
3554 if (state.decoder && !encoding) {
3555 chunk = state.decoder.write(chunk);
3556 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
3557 } else {
3558 addChunk(stream, state, chunk, false);
3559 }
3560 }
3561 } else if (!addToFront) {
3562 state.reading = false;
3563 }
3564 }
3565
3566 return needMoreData(state);
3567}
3568
3569function addChunk(stream, state, chunk, addToFront) {
3570 if (state.flowing && state.length === 0 && !state.sync) {
3571 stream.emit('data', chunk);
3572 stream.read(0);
3573 } else {
3574 // update the buffer info.
3575 state.length += state.objectMode ? 1 : chunk.length;
3576 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
3577
3578 if (state.needReadable) emitReadable(stream);
3579 }
3580 maybeReadMore(stream, state);
3581}
3582
3583function chunkInvalid(state, chunk) {
3584 var er;
3585 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
3586 er = new TypeError('Invalid non-string/buffer chunk');
3587 }
3588 return er;
3589}
3590
3591// if it's past the high water mark, we can push in some more.
3592// Also, if we have no data yet, we can stand some
3593// more bytes. This is to work around cases where hwm=0,
3594// such as the repl. Also, if the push() triggered a
3595// readable event, and the user called read(largeNumber) such that
3596// needReadable was set, then we ought to push more, so that another
3597// 'readable' event will be triggered.
3598function needMoreData(state) {
3599 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
3600}
3601
3602Readable.prototype.isPaused = function () {
3603 return this._readableState.flowing === false;
3604};
3605
3606// backwards compatibility.
3607Readable.prototype.setEncoding = function (enc) {
3608 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
3609 this._readableState.decoder = new StringDecoder(enc);
3610 this._readableState.encoding = enc;
3611 return this;
3612};
3613
3614// Don't raise the hwm > 8MB
3615var MAX_HWM = 0x800000;
3616function computeNewHighWaterMark(n) {
3617 if (n >= MAX_HWM) {
3618 n = MAX_HWM;
3619 } else {
3620 // Get the next highest power of 2 to prevent increasing hwm excessively in
3621 // tiny amounts
3622 n--;
3623 n |= n >>> 1;
3624 n |= n >>> 2;
3625 n |= n >>> 4;
3626 n |= n >>> 8;
3627 n |= n >>> 16;
3628 n++;
3629 }
3630 return n;
3631}
3632
3633// This function is designed to be inlinable, so please take care when making
3634// changes to the function body.
3635function howMuchToRead(n, state) {
3636 if (n <= 0 || state.length === 0 && state.ended) return 0;
3637 if (state.objectMode) return 1;
3638 if (n !== n) {
3639 // Only flow one buffer at a time
3640 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
3641 }
3642 // If we're asking for more than the current hwm, then raise the hwm.
3643 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
3644 if (n <= state.length) return n;
3645 // Don't have enough
3646 if (!state.ended) {
3647 state.needReadable = true;
3648 return 0;
3649 }
3650 return state.length;
3651}
3652
3653// you can override either this method, or the async _read(n) below.
3654Readable.prototype.read = function (n) {
3655 debug('read', n);
3656 n = parseInt(n, 10);
3657 var state = this._readableState;
3658 var nOrig = n;
3659
3660 if (n !== 0) state.emittedReadable = false;
3661
3662 // if we're doing read(0) to trigger a readable event, but we
3663 // already have a bunch of data in the buffer, then just trigger
3664 // the 'readable' event and move on.
3665 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
3666 debug('read: emitReadable', state.length, state.ended);
3667 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
3668 return null;
3669 }
3670
3671 n = howMuchToRead(n, state);
3672
3673 // if we've ended, and we're now clear, then finish it up.
3674 if (n === 0 && state.ended) {
3675 if (state.length === 0) endReadable(this);
3676 return null;
3677 }
3678
3679 // All the actual chunk generation logic needs to be
3680 // *below* the call to _read. The reason is that in certain
3681 // synthetic stream cases, such as passthrough streams, _read
3682 // may be a completely synchronous operation which may change
3683 // the state of the read buffer, providing enough data when
3684 // before there was *not* enough.
3685 //
3686 // So, the steps are:
3687 // 1. Figure out what the state of things will be after we do
3688 // a read from the buffer.
3689 //
3690 // 2. If that resulting state will trigger a _read, then call _read.
3691 // Note that this may be asynchronous, or synchronous. Yes, it is
3692 // deeply ugly to write APIs this way, but that still doesn't mean
3693 // that the Readable class should behave improperly, as streams are
3694 // designed to be sync/async agnostic.
3695 // Take note if the _read call is sync or async (ie, if the read call
3696 // has returned yet), so that we know whether or not it's safe to emit
3697 // 'readable' etc.
3698 //
3699 // 3. Actually pull the requested chunks out of the buffer and return.
3700
3701 // if we need a readable event, then we need to do some reading.
3702 var doRead = state.needReadable;
3703 debug('need readable', doRead);
3704
3705 // if we currently have less than the highWaterMark, then also read some
3706 if (state.length === 0 || state.length - n < state.highWaterMark) {
3707 doRead = true;
3708 debug('length less than watermark', doRead);
3709 }
3710
3711 // however, if we've ended, then there's no point, and if we're already
3712 // reading, then it's unnecessary.
3713 if (state.ended || state.reading) {
3714 doRead = false;
3715 debug('reading or ended', doRead);
3716 } else if (doRead) {
3717 debug('do read');
3718 state.reading = true;
3719 state.sync = true;
3720 // if the length is currently zero, then we *need* a readable event.
3721 if (state.length === 0) state.needReadable = true;
3722 // call internal read method
3723 this._read(state.highWaterMark);
3724 state.sync = false;
3725 // If _read pushed data synchronously, then `reading` will be false,
3726 // and we need to re-evaluate how much data we can return to the user.
3727 if (!state.reading) n = howMuchToRead(nOrig, state);
3728 }
3729
3730 var ret;
3731 if (n > 0) ret = fromList(n, state);else ret = null;
3732
3733 if (ret === null) {
3734 state.needReadable = true;
3735 n = 0;
3736 } else {
3737 state.length -= n;
3738 }
3739
3740 if (state.length === 0) {
3741 // If we have nothing in the buffer, then we want to know
3742 // as soon as we *do* get something into the buffer.
3743 if (!state.ended) state.needReadable = true;
3744
3745 // If we tried to read() past the EOF, then emit end on the next tick.
3746 if (nOrig !== n && state.ended) endReadable(this);
3747 }
3748
3749 if (ret !== null) this.emit('data', ret);
3750
3751 return ret;
3752};
3753
3754function onEofChunk(stream, state) {
3755 if (state.ended) return;
3756 if (state.decoder) {
3757 var chunk = state.decoder.end();
3758 if (chunk && chunk.length) {
3759 state.buffer.push(chunk);
3760 state.length += state.objectMode ? 1 : chunk.length;
3761 }
3762 }
3763 state.ended = true;
3764
3765 // emit 'readable' now to make sure it gets picked up.
3766 emitReadable(stream);
3767}
3768
3769// Don't emit readable right away in sync mode, because this can trigger
3770// another read() call => stack overflow. This way, it might trigger
3771// a nextTick recursion warning, but that's not so bad.
3772function emitReadable(stream) {
3773 var state = stream._readableState;
3774 state.needReadable = false;
3775 if (!state.emittedReadable) {
3776 debug('emitReadable', state.flowing);
3777 state.emittedReadable = true;
3778 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
3779 }
3780}
3781
3782function emitReadable_(stream) {
3783 debug('emit readable');
3784 stream.emit('readable');
3785 flow(stream);
3786}
3787
3788// at this point, the user has presumably seen the 'readable' event,
3789// and called read() to consume some data. that may have triggered
3790// in turn another _read(n) call, in which case reading = true if
3791// it's in progress.
3792// However, if we're not ended, or reading, and the length < hwm,
3793// then go ahead and try to read some more preemptively.
3794function maybeReadMore(stream, state) {
3795 if (!state.readingMore) {
3796 state.readingMore = true;
3797 processNextTick(maybeReadMore_, stream, state);
3798 }
3799}
3800
3801function maybeReadMore_(stream, state) {
3802 var len = state.length;
3803 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
3804 debug('maybeReadMore read 0');
3805 stream.read(0);
3806 if (len === state.length)
3807 // didn't get any data, stop spinning.
3808 break;else len = state.length;
3809 }
3810 state.readingMore = false;
3811}
3812
3813// abstract method. to be overridden in specific implementation classes.
3814// call cb(er, data) where data is <= n in length.
3815// for virtual (non-string, non-buffer) streams, "length" is somewhat
3816// arbitrary, and perhaps not very meaningful.
3817Readable.prototype._read = function (n) {
3818 this.emit('error', new Error('_read() is not implemented'));
3819};
3820
3821Readable.prototype.pipe = function (dest, pipeOpts) {
3822 var src = this;
3823 var state = this._readableState;
3824
3825 switch (state.pipesCount) {
3826 case 0:
3827 state.pipes = dest;
3828 break;
3829 case 1:
3830 state.pipes = [state.pipes, dest];
3831 break;
3832 default:
3833 state.pipes.push(dest);
3834 break;
3835 }
3836 state.pipesCount += 1;
3837 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
3838
3839 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
3840
3841 var endFn = doEnd ? onend : unpipe;
3842 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
3843
3844 dest.on('unpipe', onunpipe);
3845 function onunpipe(readable, unpipeInfo) {
3846 debug('onunpipe');
3847 if (readable === src) {
3848 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
3849 unpipeInfo.hasUnpiped = true;
3850 cleanup();
3851 }
3852 }
3853 }
3854
3855 function onend() {
3856 debug('onend');
3857 dest.end();
3858 }
3859
3860 // when the dest drains, it reduces the awaitDrain counter
3861 // on the source. This would be more elegant with a .once()
3862 // handler in flow(), but adding and removing repeatedly is
3863 // too slow.
3864 var ondrain = pipeOnDrain(src);
3865 dest.on('drain', ondrain);
3866
3867 var cleanedUp = false;
3868 function cleanup() {
3869 debug('cleanup');
3870 // cleanup event handlers once the pipe is broken
3871 dest.removeListener('close', onclose);
3872 dest.removeListener('finish', onfinish);
3873 dest.removeListener('drain', ondrain);
3874 dest.removeListener('error', onerror);
3875 dest.removeListener('unpipe', onunpipe);
3876 src.removeListener('end', onend);
3877 src.removeListener('end', unpipe);
3878 src.removeListener('data', ondata);
3879
3880 cleanedUp = true;
3881
3882 // if the reader is waiting for a drain event from this
3883 // specific writer, then it would cause it to never start
3884 // flowing again.
3885 // So, if this is awaiting a drain, then we just call it now.
3886 // If we don't know, then assume that we are waiting for one.
3887 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
3888 }
3889
3890 // If the user pushes more data while we're writing to dest then we'll end up
3891 // in ondata again. However, we only want to increase awaitDrain once because
3892 // dest will only emit one 'drain' event for the multiple writes.
3893 // => Introduce a guard on increasing awaitDrain.
3894 var increasedAwaitDrain = false;
3895 src.on('data', ondata);
3896 function ondata(chunk) {
3897 debug('ondata');
3898 increasedAwaitDrain = false;
3899 var ret = dest.write(chunk);
3900 if (false === ret && !increasedAwaitDrain) {
3901 // If the user unpiped during `dest.write()`, it is possible
3902 // to get stuck in a permanently paused state if that write
3903 // also returned false.
3904 // => Check whether `dest` is still a piping destination.
3905 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
3906 debug('false write response, pause', src._readableState.awaitDrain);
3907 src._readableState.awaitDrain++;
3908 increasedAwaitDrain = true;
3909 }
3910 src.pause();
3911 }
3912 }
3913
3914 // if the dest has an error, then stop piping into it.
3915 // however, don't suppress the throwing behavior for this.
3916 function onerror(er) {
3917 debug('onerror', er);
3918 unpipe();
3919 dest.removeListener('error', onerror);
3920 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
3921 }
3922
3923 // Make sure our error handler is attached before userland ones.
3924 prependListener(dest, 'error', onerror);
3925
3926 // Both close and finish should trigger unpipe, but only once.
3927 function onclose() {
3928 dest.removeListener('finish', onfinish);
3929 unpipe();
3930 }
3931 dest.once('close', onclose);
3932 function onfinish() {
3933 debug('onfinish');
3934 dest.removeListener('close', onclose);
3935 unpipe();
3936 }
3937 dest.once('finish', onfinish);
3938
3939 function unpipe() {
3940 debug('unpipe');
3941 src.unpipe(dest);
3942 }
3943
3944 // tell the dest that it's being piped to
3945 dest.emit('pipe', src);
3946
3947 // start the flow if it hasn't been started already.
3948 if (!state.flowing) {
3949 debug('pipe resume');
3950 src.resume();
3951 }
3952
3953 return dest;
3954};
3955
3956function pipeOnDrain(src) {
3957 return function () {
3958 var state = src._readableState;
3959 debug('pipeOnDrain', state.awaitDrain);
3960 if (state.awaitDrain) state.awaitDrain--;
3961 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
3962 state.flowing = true;
3963 flow(src);
3964 }
3965 };
3966}
3967
3968Readable.prototype.unpipe = function (dest) {
3969 var state = this._readableState;
3970 var unpipeInfo = { hasUnpiped: false };
3971
3972 // if we're not piping anywhere, then do nothing.
3973 if (state.pipesCount === 0) return this;
3974
3975 // just one destination. most common case.
3976 if (state.pipesCount === 1) {
3977 // passed in one, but it's not the right one.
3978 if (dest && dest !== state.pipes) return this;
3979
3980 if (!dest) dest = state.pipes;
3981
3982 // got a match.
3983 state.pipes = null;
3984 state.pipesCount = 0;
3985 state.flowing = false;
3986 if (dest) dest.emit('unpipe', this, unpipeInfo);
3987 return this;
3988 }
3989
3990 // slow case. multiple pipe destinations.
3991
3992 if (!dest) {
3993 // remove all.
3994 var dests = state.pipes;
3995 var len = state.pipesCount;
3996 state.pipes = null;
3997 state.pipesCount = 0;
3998 state.flowing = false;
3999
4000 for (var i = 0; i < len; i++) {
4001 dests[i].emit('unpipe', this, unpipeInfo);
4002 }return this;
4003 }
4004
4005 // try to find the right one.
4006 var index = indexOf(state.pipes, dest);
4007 if (index === -1) return this;
4008
4009 state.pipes.splice(index, 1);
4010 state.pipesCount -= 1;
4011 if (state.pipesCount === 1) state.pipes = state.pipes[0];
4012
4013 dest.emit('unpipe', this, unpipeInfo);
4014
4015 return this;
4016};
4017
4018// set up data events if they are asked for
4019// Ensure readable listeners eventually get something
4020Readable.prototype.on = function (ev, fn) {
4021 var res = Stream.prototype.on.call(this, ev, fn);
4022
4023 if (ev === 'data') {
4024 // Start flowing on next tick if stream isn't explicitly paused
4025 if (this._readableState.flowing !== false) this.resume();
4026 } else if (ev === 'readable') {
4027 var state = this._readableState;
4028 if (!state.endEmitted && !state.readableListening) {
4029 state.readableListening = state.needReadable = true;
4030 state.emittedReadable = false;
4031 if (!state.reading) {
4032 processNextTick(nReadingNextTick, this);
4033 } else if (state.length) {
4034 emitReadable(this);
4035 }
4036 }
4037 }
4038
4039 return res;
4040};
4041Readable.prototype.addListener = Readable.prototype.on;
4042
4043function nReadingNextTick(self) {
4044 debug('readable nexttick read 0');
4045 self.read(0);
4046}
4047
4048// pause() and resume() are remnants of the legacy readable stream API
4049// If the user uses them, then switch into old mode.
4050Readable.prototype.resume = function () {
4051 var state = this._readableState;
4052 if (!state.flowing) {
4053 debug('resume');
4054 state.flowing = true;
4055 resume(this, state);
4056 }
4057 return this;
4058};
4059
4060function resume(stream, state) {
4061 if (!state.resumeScheduled) {
4062 state.resumeScheduled = true;
4063 processNextTick(resume_, stream, state);
4064 }
4065}
4066
4067function resume_(stream, state) {
4068 if (!state.reading) {
4069 debug('resume read 0');
4070 stream.read(0);
4071 }
4072
4073 state.resumeScheduled = false;
4074 state.awaitDrain = 0;
4075 stream.emit('resume');
4076 flow(stream);
4077 if (state.flowing && !state.reading) stream.read(0);
4078}
4079
4080Readable.prototype.pause = function () {
4081 debug('call pause flowing=%j', this._readableState.flowing);
4082 if (false !== this._readableState.flowing) {
4083 debug('pause');
4084 this._readableState.flowing = false;
4085 this.emit('pause');
4086 }
4087 return this;
4088};
4089
4090function flow(stream) {
4091 var state = stream._readableState;
4092 debug('flow', state.flowing);
4093 while (state.flowing && stream.read() !== null) {}
4094}
4095
4096// wrap an old-style stream as the async data source.
4097// This is *not* part of the readable stream interface.
4098// It is an ugly unfortunate mess of history.
4099Readable.prototype.wrap = function (stream) {
4100 var state = this._readableState;
4101 var paused = false;
4102
4103 var self = this;
4104 stream.on('end', function () {
4105 debug('wrapped end');
4106 if (state.decoder && !state.ended) {
4107 var chunk = state.decoder.end();
4108 if (chunk && chunk.length) self.push(chunk);
4109 }
4110
4111 self.push(null);
4112 });
4113
4114 stream.on('data', function (chunk) {
4115 debug('wrapped data');
4116 if (state.decoder) chunk = state.decoder.write(chunk);
4117
4118 // don't skip over falsy values in objectMode
4119 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
4120
4121 var ret = self.push(chunk);
4122 if (!ret) {
4123 paused = true;
4124 stream.pause();
4125 }
4126 });
4127
4128 // proxy all the other methods.
4129 // important when wrapping filters and duplexes.
4130 for (var i in stream) {
4131 if (this[i] === undefined && typeof stream[i] === 'function') {
4132 this[i] = function (method) {
4133 return function () {
4134 return stream[method].apply(stream, arguments);
4135 };
4136 }(i);
4137 }
4138 }
4139
4140 // proxy certain important events.
4141 for (var n = 0; n < kProxyEvents.length; n++) {
4142 stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
4143 }
4144
4145 // when we try to consume some more bytes, simply unpause the
4146 // underlying stream.
4147 self._read = function (n) {
4148 debug('wrapped _read', n);
4149 if (paused) {
4150 paused = false;
4151 stream.resume();
4152 }
4153 };
4154
4155 return self;
4156};
4157
4158// exposed for testing purposes only.
4159Readable._fromList = fromList;
4160
4161// Pluck off n bytes from an array of buffers.
4162// Length is the combined lengths of all the buffers in the list.
4163// This function is designed to be inlinable, so please take care when making
4164// changes to the function body.
4165function fromList(n, state) {
4166 // nothing buffered
4167 if (state.length === 0) return null;
4168
4169 var ret;
4170 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
4171 // read it all, truncate the list
4172 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
4173 state.buffer.clear();
4174 } else {
4175 // read part of list
4176 ret = fromListPartial(n, state.buffer, state.decoder);
4177 }
4178
4179 return ret;
4180}
4181
4182// Extracts only enough buffered data to satisfy the amount requested.
4183// This function is designed to be inlinable, so please take care when making
4184// changes to the function body.
4185function fromListPartial(n, list, hasStrings) {
4186 var ret;
4187 if (n < list.head.data.length) {
4188 // slice is the same for buffers and strings
4189 ret = list.head.data.slice(0, n);
4190 list.head.data = list.head.data.slice(n);
4191 } else if (n === list.head.data.length) {
4192 // first chunk is a perfect match
4193 ret = list.shift();
4194 } else {
4195 // result spans more than one buffer
4196 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
4197 }
4198 return ret;
4199}
4200
4201// Copies a specified amount of characters from the list of buffered data
4202// chunks.
4203// This function is designed to be inlinable, so please take care when making
4204// changes to the function body.
4205function copyFromBufferString(n, list) {
4206 var p = list.head;
4207 var c = 1;
4208 var ret = p.data;
4209 n -= ret.length;
4210 while (p = p.next) {
4211 var str = p.data;
4212 var nb = n > str.length ? str.length : n;
4213 if (nb === str.length) ret += str;else ret += str.slice(0, n);
4214 n -= nb;
4215 if (n === 0) {
4216 if (nb === str.length) {
4217 ++c;
4218 if (p.next) list.head = p.next;else list.head = list.tail = null;
4219 } else {
4220 list.head = p;
4221 p.data = str.slice(nb);
4222 }
4223 break;
4224 }
4225 ++c;
4226 }
4227 list.length -= c;
4228 return ret;
4229}
4230
4231// Copies a specified amount of bytes from the list of buffered data chunks.
4232// This function is designed to be inlinable, so please take care when making
4233// changes to the function body.
4234function copyFromBuffer(n, list) {
4235 var ret = Buffer.allocUnsafe(n);
4236 var p = list.head;
4237 var c = 1;
4238 p.data.copy(ret);
4239 n -= p.data.length;
4240 while (p = p.next) {
4241 var buf = p.data;
4242 var nb = n > buf.length ? buf.length : n;
4243 buf.copy(ret, ret.length - n, 0, nb);
4244 n -= nb;
4245 if (n === 0) {
4246 if (nb === buf.length) {
4247 ++c;
4248 if (p.next) list.head = p.next;else list.head = list.tail = null;
4249 } else {
4250 list.head = p;
4251 p.data = buf.slice(nb);
4252 }
4253 break;
4254 }
4255 ++c;
4256 }
4257 list.length -= c;
4258 return ret;
4259}
4260
4261function endReadable(stream) {
4262 var state = stream._readableState;
4263
4264 // If we get here before consuming all the bytes, then that is a
4265 // bug in node. Should never happen.
4266 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
4267
4268 if (!state.endEmitted) {
4269 state.ended = true;
4270 processNextTick(endReadableNT, state, stream);
4271 }
4272}
4273
4274function endReadableNT(state, stream) {
4275 // Check that we didn't get one last unshift.
4276 if (!state.endEmitted && state.length === 0) {
4277 state.endEmitted = true;
4278 stream.readable = false;
4279 stream.emit('end');
4280 }
4281}
4282
4283function forEach(xs, f) {
4284 for (var i = 0, l = xs.length; i < l; i++) {
4285 f(xs[i], i);
4286 }
4287}
4288
4289function indexOf(xs, x) {
4290 for (var i = 0, l = xs.length; i < l; i++) {
4291 if (xs[i] === x) return i;
4292 }
4293 return -1;
4294}
4295}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4296},{"./_stream_duplex":14,"./internal/streams/BufferList":19,"./internal/streams/destroy":20,"./internal/streams/stream":21,"_process":12,"core-util-is":5,"events":6,"inherits":8,"isarray":10,"process-nextick-args":11,"safe-buffer":26,"string_decoder/":28,"util":3}],17:[function(require,module,exports){
4297// Copyright Joyent, Inc. and other Node contributors.
4298//
4299// Permission is hereby granted, free of charge, to any person obtaining a
4300// copy of this software and associated documentation files (the
4301// "Software"), to deal in the Software without restriction, including
4302// without limitation the rights to use, copy, modify, merge, publish,
4303// distribute, sublicense, and/or sell copies of the Software, and to permit
4304// persons to whom the Software is furnished to do so, subject to the
4305// following conditions:
4306//
4307// The above copyright notice and this permission notice shall be included
4308// in all copies or substantial portions of the Software.
4309//
4310// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4311// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4312// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4313// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4314// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4315// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4316// USE OR OTHER DEALINGS IN THE SOFTWARE.
4317
4318// a transform stream is a readable/writable stream where you do
4319// something with the data. Sometimes it's called a "filter",
4320// but that's not a great name for it, since that implies a thing where
4321// some bits pass through, and others are simply ignored. (That would
4322// be a valid example of a transform, of course.)
4323//
4324// While the output is causally related to the input, it's not a
4325// necessarily symmetric or synchronous transformation. For example,
4326// a zlib stream might take multiple plain-text writes(), and then
4327// emit a single compressed chunk some time in the future.
4328//
4329// Here's how this works:
4330//
4331// The Transform stream has all the aspects of the readable and writable
4332// stream classes. When you write(chunk), that calls _write(chunk,cb)
4333// internally, and returns false if there's a lot of pending writes
4334// buffered up. When you call read(), that calls _read(n) until
4335// there's enough pending readable data buffered up.
4336//
4337// In a transform stream, the written data is placed in a buffer. When
4338// _read(n) is called, it transforms the queued up data, calling the
4339// buffered _write cb's as it consumes chunks. If consuming a single
4340// written chunk would result in multiple output chunks, then the first
4341// outputted bit calls the readcb, and subsequent chunks just go into
4342// the read buffer, and will cause it to emit 'readable' if necessary.
4343//
4344// This way, back-pressure is actually determined by the reading side,
4345// since _read has to be called to start processing a new chunk. However,
4346// a pathological inflate type of transform can cause excessive buffering
4347// here. For example, imagine a stream where every byte of input is
4348// interpreted as an integer from 0-255, and then results in that many
4349// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
4350// 1kb of data being output. In this case, you could write a very small
4351// amount of input, and end up with a very large amount of output. In
4352// such a pathological inflating mechanism, there'd be no way to tell
4353// the system to stop doing the transform. A single 4MB write could
4354// cause the system to run out of memory.
4355//
4356// However, even in such a pathological case, only a single written chunk
4357// would be consumed, and then the rest would wait (un-transformed) until
4358// the results of the previous transformed chunk were consumed.
4359
4360'use strict';
4361
4362module.exports = Transform;
4363
4364var Duplex = require('./_stream_duplex');
4365
4366/*<replacement>*/
4367var util = require('core-util-is');
4368util.inherits = require('inherits');
4369/*</replacement>*/
4370
4371util.inherits(Transform, Duplex);
4372
4373function TransformState(stream) {
4374 this.afterTransform = function (er, data) {
4375 return afterTransform(stream, er, data);
4376 };
4377
4378 this.needTransform = false;
4379 this.transforming = false;
4380 this.writecb = null;
4381 this.writechunk = null;
4382 this.writeencoding = null;
4383}
4384
4385function afterTransform(stream, er, data) {
4386 var ts = stream._transformState;
4387 ts.transforming = false;
4388
4389 var cb = ts.writecb;
4390
4391 if (!cb) {
4392 return stream.emit('error', new Error('write callback called multiple times'));
4393 }
4394
4395 ts.writechunk = null;
4396 ts.writecb = null;
4397
4398 if (data !== null && data !== undefined) stream.push(data);
4399
4400 cb(er);
4401
4402 var rs = stream._readableState;
4403 rs.reading = false;
4404 if (rs.needReadable || rs.length < rs.highWaterMark) {
4405 stream._read(rs.highWaterMark);
4406 }
4407}
4408
4409function Transform(options) {
4410 if (!(this instanceof Transform)) return new Transform(options);
4411
4412 Duplex.call(this, options);
4413
4414 this._transformState = new TransformState(this);
4415
4416 var stream = this;
4417
4418 // start out asking for a readable event once data is transformed.
4419 this._readableState.needReadable = true;
4420
4421 // we have implemented the _read method, and done the other things
4422 // that Readable wants before the first _read call, so unset the
4423 // sync guard flag.
4424 this._readableState.sync = false;
4425
4426 if (options) {
4427 if (typeof options.transform === 'function') this._transform = options.transform;
4428
4429 if (typeof options.flush === 'function') this._flush = options.flush;
4430 }
4431
4432 // When the writable side finishes, then flush out anything remaining.
4433 this.once('prefinish', function () {
4434 if (typeof this._flush === 'function') this._flush(function (er, data) {
4435 done(stream, er, data);
4436 });else done(stream);
4437 });
4438}
4439
4440Transform.prototype.push = function (chunk, encoding) {
4441 this._transformState.needTransform = false;
4442 return Duplex.prototype.push.call(this, chunk, encoding);
4443};
4444
4445// This is the part where you do stuff!
4446// override this function in implementation classes.
4447// 'chunk' is an input chunk.
4448//
4449// Call `push(newChunk)` to pass along transformed output
4450// to the readable side. You may call 'push' zero or more times.
4451//
4452// Call `cb(err)` when you are done with this chunk. If you pass
4453// an error, then that'll put the hurt on the whole operation. If you
4454// never call cb(), then you'll never get another chunk.
4455Transform.prototype._transform = function (chunk, encoding, cb) {
4456 throw new Error('_transform() is not implemented');
4457};
4458
4459Transform.prototype._write = function (chunk, encoding, cb) {
4460 var ts = this._transformState;
4461 ts.writecb = cb;
4462 ts.writechunk = chunk;
4463 ts.writeencoding = encoding;
4464 if (!ts.transforming) {
4465 var rs = this._readableState;
4466 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
4467 }
4468};
4469
4470// Doesn't matter what the args are here.
4471// _transform does all the work.
4472// That we got here means that the readable side wants more data.
4473Transform.prototype._read = function (n) {
4474 var ts = this._transformState;
4475
4476 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
4477 ts.transforming = true;
4478 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
4479 } else {
4480 // mark that we need a transform, so that any data that comes in
4481 // will get processed, now that we've asked for it.
4482 ts.needTransform = true;
4483 }
4484};
4485
4486Transform.prototype._destroy = function (err, cb) {
4487 var _this = this;
4488
4489 Duplex.prototype._destroy.call(this, err, function (err2) {
4490 cb(err2);
4491 _this.emit('close');
4492 });
4493};
4494
4495function done(stream, er, data) {
4496 if (er) return stream.emit('error', er);
4497
4498 if (data !== null && data !== undefined) stream.push(data);
4499
4500 // if there's nothing in the write buffer, then that means
4501 // that nothing more will ever be provided
4502 var ws = stream._writableState;
4503 var ts = stream._transformState;
4504
4505 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
4506
4507 if (ts.transforming) throw new Error('Calling transform done when still transforming');
4508
4509 return stream.push(null);
4510}
4511},{"./_stream_duplex":14,"core-util-is":5,"inherits":8}],18:[function(require,module,exports){
4512(function (process,global){
4513// Copyright Joyent, Inc. and other Node contributors.
4514//
4515// Permission is hereby granted, free of charge, to any person obtaining a
4516// copy of this software and associated documentation files (the
4517// "Software"), to deal in the Software without restriction, including
4518// without limitation the rights to use, copy, modify, merge, publish,
4519// distribute, sublicense, and/or sell copies of the Software, and to permit
4520// persons to whom the Software is furnished to do so, subject to the
4521// following conditions:
4522//
4523// The above copyright notice and this permission notice shall be included
4524// in all copies or substantial portions of the Software.
4525//
4526// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4527// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4528// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4529// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4530// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4531// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4532// USE OR OTHER DEALINGS IN THE SOFTWARE.
4533
4534// A bit simpler than readable streams.
4535// Implement an async ._write(chunk, encoding, cb), and it'll handle all
4536// the drain event emission and buffering.
4537
4538'use strict';
4539
4540/*<replacement>*/
4541
4542var processNextTick = require('process-nextick-args');
4543/*</replacement>*/
4544
4545module.exports = Writable;
4546
4547/* <replacement> */
4548function WriteReq(chunk, encoding, cb) {
4549 this.chunk = chunk;
4550 this.encoding = encoding;
4551 this.callback = cb;
4552 this.next = null;
4553}
4554
4555// It seems a linked list but it is not
4556// there will be only 2 of these for each stream
4557function CorkedRequest(state) {
4558 var _this = this;
4559
4560 this.next = null;
4561 this.entry = null;
4562 this.finish = function () {
4563 onCorkedFinish(_this, state);
4564 };
4565}
4566/* </replacement> */
4567
4568/*<replacement>*/
4569var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
4570/*</replacement>*/
4571
4572/*<replacement>*/
4573var Duplex;
4574/*</replacement>*/
4575
4576Writable.WritableState = WritableState;
4577
4578/*<replacement>*/
4579var util = require('core-util-is');
4580util.inherits = require('inherits');
4581/*</replacement>*/
4582
4583/*<replacement>*/
4584var internalUtil = {
4585 deprecate: require('util-deprecate')
4586};
4587/*</replacement>*/
4588
4589/*<replacement>*/
4590var Stream = require('./internal/streams/stream');
4591/*</replacement>*/
4592
4593/*<replacement>*/
4594var Buffer = require('safe-buffer').Buffer;
4595var OurUint8Array = global.Uint8Array || function () {};
4596function _uint8ArrayToBuffer(chunk) {
4597 return Buffer.from(chunk);
4598}
4599function _isUint8Array(obj) {
4600 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
4601}
4602/*</replacement>*/
4603
4604var destroyImpl = require('./internal/streams/destroy');
4605
4606util.inherits(Writable, Stream);
4607
4608function nop() {}
4609
4610function WritableState(options, stream) {
4611 Duplex = Duplex || require('./_stream_duplex');
4612
4613 options = options || {};
4614
4615 // object stream flag to indicate whether or not this stream
4616 // contains buffers or objects.
4617 this.objectMode = !!options.objectMode;
4618
4619 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
4620
4621 // the point at which write() starts returning false
4622 // Note: 0 is a valid value, means that we always return false if
4623 // the entire buffer is not flushed immediately on write()
4624 var hwm = options.highWaterMark;
4625 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
4626 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
4627
4628 // cast to ints.
4629 this.highWaterMark = Math.floor(this.highWaterMark);
4630
4631 // if _final has been called
4632 this.finalCalled = false;
4633
4634 // drain event flag.
4635 this.needDrain = false;
4636 // at the start of calling end()
4637 this.ending = false;
4638 // when end() has been called, and returned
4639 this.ended = false;
4640 // when 'finish' is emitted
4641 this.finished = false;
4642
4643 // has it been destroyed
4644 this.destroyed = false;
4645
4646 // should we decode strings into buffers before passing to _write?
4647 // this is here so that some node-core streams can optimize string
4648 // handling at a lower level.
4649 var noDecode = options.decodeStrings === false;
4650 this.decodeStrings = !noDecode;
4651
4652 // Crypto is kind of old and crusty. Historically, its default string
4653 // encoding is 'binary' so we have to make this configurable.
4654 // Everything else in the universe uses 'utf8', though.
4655 this.defaultEncoding = options.defaultEncoding || 'utf8';
4656
4657 // not an actual buffer we keep track of, but a measurement
4658 // of how much we're waiting to get pushed to some underlying
4659 // socket or file.
4660 this.length = 0;
4661
4662 // a flag to see when we're in the middle of a write.
4663 this.writing = false;
4664
4665 // when true all writes will be buffered until .uncork() call
4666 this.corked = 0;
4667
4668 // a flag to be able to tell if the onwrite cb is called immediately,
4669 // or on a later tick. We set this to true at first, because any
4670 // actions that shouldn't happen until "later" should generally also
4671 // not happen before the first write call.
4672 this.sync = true;
4673
4674 // a flag to know if we're processing previously buffered items, which
4675 // may call the _write() callback in the same tick, so that we don't
4676 // end up in an overlapped onwrite situation.
4677 this.bufferProcessing = false;
4678
4679 // the callback that's passed to _write(chunk,cb)
4680 this.onwrite = function (er) {
4681 onwrite(stream, er);
4682 };
4683
4684 // the callback that the user supplies to write(chunk,encoding,cb)
4685 this.writecb = null;
4686
4687 // the amount that is being written when _write is called.
4688 this.writelen = 0;
4689
4690 this.bufferedRequest = null;
4691 this.lastBufferedRequest = null;
4692
4693 // number of pending user-supplied write callbacks
4694 // this must be 0 before 'finish' can be emitted
4695 this.pendingcb = 0;
4696
4697 // emit prefinish if the only thing we're waiting for is _write cbs
4698 // This is relevant for synchronous Transform streams
4699 this.prefinished = false;
4700
4701 // True if the error was already emitted and should not be thrown again
4702 this.errorEmitted = false;
4703
4704 // count buffered requests
4705 this.bufferedRequestCount = 0;
4706
4707 // allocate the first CorkedRequest, there is always
4708 // one allocated and free to use, and we maintain at most two
4709 this.corkedRequestsFree = new CorkedRequest(this);
4710}
4711
4712WritableState.prototype.getBuffer = function getBuffer() {
4713 var current = this.bufferedRequest;
4714 var out = [];
4715 while (current) {
4716 out.push(current);
4717 current = current.next;
4718 }
4719 return out;
4720};
4721
4722(function () {
4723 try {
4724 Object.defineProperty(WritableState.prototype, 'buffer', {
4725 get: internalUtil.deprecate(function () {
4726 return this.getBuffer();
4727 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
4728 });
4729 } catch (_) {}
4730})();
4731
4732// Test _writableState for inheritance to account for Duplex streams,
4733// whose prototype chain only points to Readable.
4734var realHasInstance;
4735if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
4736 realHasInstance = Function.prototype[Symbol.hasInstance];
4737 Object.defineProperty(Writable, Symbol.hasInstance, {
4738 value: function (object) {
4739 if (realHasInstance.call(this, object)) return true;
4740
4741 return object && object._writableState instanceof WritableState;
4742 }
4743 });
4744} else {
4745 realHasInstance = function (object) {
4746 return object instanceof this;
4747 };
4748}
4749
4750function Writable(options) {
4751 Duplex = Duplex || require('./_stream_duplex');
4752
4753 // Writable ctor is applied to Duplexes, too.
4754 // `realHasInstance` is necessary because using plain `instanceof`
4755 // would return false, as no `_writableState` property is attached.
4756
4757 // Trying to use the custom `instanceof` for Writable here will also break the
4758 // Node.js LazyTransform implementation, which has a non-trivial getter for
4759 // `_writableState` that would lead to infinite recursion.
4760 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
4761 return new Writable(options);
4762 }
4763
4764 this._writableState = new WritableState(options, this);
4765
4766 // legacy.
4767 this.writable = true;
4768
4769 if (options) {
4770 if (typeof options.write === 'function') this._write = options.write;
4771
4772 if (typeof options.writev === 'function') this._writev = options.writev;
4773
4774 if (typeof options.destroy === 'function') this._destroy = options.destroy;
4775
4776 if (typeof options.final === 'function') this._final = options.final;
4777 }
4778
4779 Stream.call(this);
4780}
4781
4782// Otherwise people can pipe Writable streams, which is just wrong.
4783Writable.prototype.pipe = function () {
4784 this.emit('error', new Error('Cannot pipe, not readable'));
4785};
4786
4787function writeAfterEnd(stream, cb) {
4788 var er = new Error('write after end');
4789 // TODO: defer error events consistently everywhere, not just the cb
4790 stream.emit('error', er);
4791 processNextTick(cb, er);
4792}
4793
4794// Checks that a user-supplied chunk is valid, especially for the particular
4795// mode the stream is in. Currently this means that `null` is never accepted
4796// and undefined/non-string values are only allowed in object mode.
4797function validChunk(stream, state, chunk, cb) {
4798 var valid = true;
4799 var er = false;
4800
4801 if (chunk === null) {
4802 er = new TypeError('May not write null values to stream');
4803 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
4804 er = new TypeError('Invalid non-string/buffer chunk');
4805 }
4806 if (er) {
4807 stream.emit('error', er);
4808 processNextTick(cb, er);
4809 valid = false;
4810 }
4811 return valid;
4812}
4813
4814Writable.prototype.write = function (chunk, encoding, cb) {
4815 var state = this._writableState;
4816 var ret = false;
4817 var isBuf = _isUint8Array(chunk) && !state.objectMode;
4818
4819 if (isBuf && !Buffer.isBuffer(chunk)) {
4820 chunk = _uint8ArrayToBuffer(chunk);
4821 }
4822
4823 if (typeof encoding === 'function') {
4824 cb = encoding;
4825 encoding = null;
4826 }
4827
4828 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
4829
4830 if (typeof cb !== 'function') cb = nop;
4831
4832 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
4833 state.pendingcb++;
4834 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
4835 }
4836
4837 return ret;
4838};
4839
4840Writable.prototype.cork = function () {
4841 var state = this._writableState;
4842
4843 state.corked++;
4844};
4845
4846Writable.prototype.uncork = function () {
4847 var state = this._writableState;
4848
4849 if (state.corked) {
4850 state.corked--;
4851
4852 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
4853 }
4854};
4855
4856Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
4857 // node::ParseEncoding() requires lower case.
4858 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
4859 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
4860 this._writableState.defaultEncoding = encoding;
4861 return this;
4862};
4863
4864function decodeChunk(state, chunk, encoding) {
4865 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
4866 chunk = Buffer.from(chunk, encoding);
4867 }
4868 return chunk;
4869}
4870
4871// if we're already writing something, then just put this
4872// in the queue, and wait our turn. Otherwise, call _write
4873// If we return false, then we need a drain event, so set that flag.
4874function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
4875 if (!isBuf) {
4876 var newChunk = decodeChunk(state, chunk, encoding);
4877 if (chunk !== newChunk) {
4878 isBuf = true;
4879 encoding = 'buffer';
4880 chunk = newChunk;
4881 }
4882 }
4883 var len = state.objectMode ? 1 : chunk.length;
4884
4885 state.length += len;
4886
4887 var ret = state.length < state.highWaterMark;
4888 // we must ensure that previous needDrain will not be reset to false.
4889 if (!ret) state.needDrain = true;
4890
4891 if (state.writing || state.corked) {
4892 var last = state.lastBufferedRequest;
4893 state.lastBufferedRequest = {
4894 chunk: chunk,
4895 encoding: encoding,
4896 isBuf: isBuf,
4897 callback: cb,
4898 next: null
4899 };
4900 if (last) {
4901 last.next = state.lastBufferedRequest;
4902 } else {
4903 state.bufferedRequest = state.lastBufferedRequest;
4904 }
4905 state.bufferedRequestCount += 1;
4906 } else {
4907 doWrite(stream, state, false, len, chunk, encoding, cb);
4908 }
4909
4910 return ret;
4911}
4912
4913function doWrite(stream, state, writev, len, chunk, encoding, cb) {
4914 state.writelen = len;
4915 state.writecb = cb;
4916 state.writing = true;
4917 state.sync = true;
4918 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
4919 state.sync = false;
4920}
4921
4922function onwriteError(stream, state, sync, er, cb) {
4923 --state.pendingcb;
4924
4925 if (sync) {
4926 // defer the callback if we are being called synchronously
4927 // to avoid piling up things on the stack
4928 processNextTick(cb, er);
4929 // this can emit finish, and it will always happen
4930 // after error
4931 processNextTick(finishMaybe, stream, state);
4932 stream._writableState.errorEmitted = true;
4933 stream.emit('error', er);
4934 } else {
4935 // the caller expect this to happen before if
4936 // it is async
4937 cb(er);
4938 stream._writableState.errorEmitted = true;
4939 stream.emit('error', er);
4940 // this can emit finish, but finish must
4941 // always follow error
4942 finishMaybe(stream, state);
4943 }
4944}
4945
4946function onwriteStateUpdate(state) {
4947 state.writing = false;
4948 state.writecb = null;
4949 state.length -= state.writelen;
4950 state.writelen = 0;
4951}
4952
4953function onwrite(stream, er) {
4954 var state = stream._writableState;
4955 var sync = state.sync;
4956 var cb = state.writecb;
4957
4958 onwriteStateUpdate(state);
4959
4960 if (er) onwriteError(stream, state, sync, er, cb);else {
4961 // Check if we're actually ready to finish, but don't emit yet
4962 var finished = needFinish(state);
4963
4964 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
4965 clearBuffer(stream, state);
4966 }
4967
4968 if (sync) {
4969 /*<replacement>*/
4970 asyncWrite(afterWrite, stream, state, finished, cb);
4971 /*</replacement>*/
4972 } else {
4973 afterWrite(stream, state, finished, cb);
4974 }
4975 }
4976}
4977
4978function afterWrite(stream, state, finished, cb) {
4979 if (!finished) onwriteDrain(stream, state);
4980 state.pendingcb--;
4981 cb();
4982 finishMaybe(stream, state);
4983}
4984
4985// Must force callback to be called on nextTick, so that we don't
4986// emit 'drain' before the write() consumer gets the 'false' return
4987// value, and has a chance to attach a 'drain' listener.
4988function onwriteDrain(stream, state) {
4989 if (state.length === 0 && state.needDrain) {
4990 state.needDrain = false;
4991 stream.emit('drain');
4992 }
4993}
4994
4995// if there's something in the buffer waiting, then process it
4996function clearBuffer(stream, state) {
4997 state.bufferProcessing = true;
4998 var entry = state.bufferedRequest;
4999
5000 if (stream._writev && entry && entry.next) {
5001 // Fast case, write everything using _writev()
5002 var l = state.bufferedRequestCount;
5003 var buffer = new Array(l);
5004 var holder = state.corkedRequestsFree;
5005 holder.entry = entry;
5006
5007 var count = 0;
5008 var allBuffers = true;
5009 while (entry) {
5010 buffer[count] = entry;
5011 if (!entry.isBuf) allBuffers = false;
5012 entry = entry.next;
5013 count += 1;
5014 }
5015 buffer.allBuffers = allBuffers;
5016
5017 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
5018
5019 // doWrite is almost always async, defer these to save a bit of time
5020 // as the hot path ends with doWrite
5021 state.pendingcb++;
5022 state.lastBufferedRequest = null;
5023 if (holder.next) {
5024 state.corkedRequestsFree = holder.next;
5025 holder.next = null;
5026 } else {
5027 state.corkedRequestsFree = new CorkedRequest(state);
5028 }
5029 } else {
5030 // Slow case, write chunks one-by-one
5031 while (entry) {
5032 var chunk = entry.chunk;
5033 var encoding = entry.encoding;
5034 var cb = entry.callback;
5035 var len = state.objectMode ? 1 : chunk.length;
5036
5037 doWrite(stream, state, false, len, chunk, encoding, cb);
5038 entry = entry.next;
5039 // if we didn't call the onwrite immediately, then
5040 // it means that we need to wait until it does.
5041 // also, that means that the chunk and cb are currently
5042 // being processed, so move the buffer counter past them.
5043 if (state.writing) {
5044 break;
5045 }
5046 }
5047
5048 if (entry === null) state.lastBufferedRequest = null;
5049 }
5050
5051 state.bufferedRequestCount = 0;
5052 state.bufferedRequest = entry;
5053 state.bufferProcessing = false;
5054}
5055
5056Writable.prototype._write = function (chunk, encoding, cb) {
5057 cb(new Error('_write() is not implemented'));
5058};
5059
5060Writable.prototype._writev = null;
5061
5062Writable.prototype.end = function (chunk, encoding, cb) {
5063 var state = this._writableState;
5064
5065 if (typeof chunk === 'function') {
5066 cb = chunk;
5067 chunk = null;
5068 encoding = null;
5069 } else if (typeof encoding === 'function') {
5070 cb = encoding;
5071 encoding = null;
5072 }
5073
5074 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
5075
5076 // .end() fully uncorks
5077 if (state.corked) {
5078 state.corked = 1;
5079 this.uncork();
5080 }
5081
5082 // ignore unnecessary end() calls.
5083 if (!state.ending && !state.finished) endWritable(this, state, cb);
5084};
5085
5086function needFinish(state) {
5087 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
5088}
5089function callFinal(stream, state) {
5090 stream._final(function (err) {
5091 state.pendingcb--;
5092 if (err) {
5093 stream.emit('error', err);
5094 }
5095 state.prefinished = true;
5096 stream.emit('prefinish');
5097 finishMaybe(stream, state);
5098 });
5099}
5100function prefinish(stream, state) {
5101 if (!state.prefinished && !state.finalCalled) {
5102 if (typeof stream._final === 'function') {
5103 state.pendingcb++;
5104 state.finalCalled = true;
5105 processNextTick(callFinal, stream, state);
5106 } else {
5107 state.prefinished = true;
5108 stream.emit('prefinish');
5109 }
5110 }
5111}
5112
5113function finishMaybe(stream, state) {
5114 var need = needFinish(state);
5115 if (need) {
5116 prefinish(stream, state);
5117 if (state.pendingcb === 0) {
5118 state.finished = true;
5119 stream.emit('finish');
5120 }
5121 }
5122 return need;
5123}
5124
5125function endWritable(stream, state, cb) {
5126 state.ending = true;
5127 finishMaybe(stream, state);
5128 if (cb) {
5129 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
5130 }
5131 state.ended = true;
5132 stream.writable = false;
5133}
5134
5135function onCorkedFinish(corkReq, state, err) {
5136 var entry = corkReq.entry;
5137 corkReq.entry = null;
5138 while (entry) {
5139 var cb = entry.callback;
5140 state.pendingcb--;
5141 cb(err);
5142 entry = entry.next;
5143 }
5144 if (state.corkedRequestsFree) {
5145 state.corkedRequestsFree.next = corkReq;
5146 } else {
5147 state.corkedRequestsFree = corkReq;
5148 }
5149}
5150
5151Object.defineProperty(Writable.prototype, 'destroyed', {
5152 get: function () {
5153 if (this._writableState === undefined) {
5154 return false;
5155 }
5156 return this._writableState.destroyed;
5157 },
5158 set: function (value) {
5159 // we ignore the value if the stream
5160 // has not been initialized yet
5161 if (!this._writableState) {
5162 return;
5163 }
5164
5165 // backward compatibility, the user is explicitly
5166 // managing destroyed
5167 this._writableState.destroyed = value;
5168 }
5169});
5170
5171Writable.prototype.destroy = destroyImpl.destroy;
5172Writable.prototype._undestroy = destroyImpl.undestroy;
5173Writable.prototype._destroy = function (err, cb) {
5174 this.end();
5175 cb(err);
5176};
5177}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5178},{"./_stream_duplex":14,"./internal/streams/destroy":20,"./internal/streams/stream":21,"_process":12,"core-util-is":5,"inherits":8,"process-nextick-args":11,"safe-buffer":26,"util-deprecate":29}],19:[function(require,module,exports){
5179'use strict';
5180
5181/*<replacement>*/
5182
5183function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
5184
5185var Buffer = require('safe-buffer').Buffer;
5186/*</replacement>*/
5187
5188function copyBuffer(src, target, offset) {
5189 src.copy(target, offset);
5190}
5191
5192module.exports = function () {
5193 function BufferList() {
5194 _classCallCheck(this, BufferList);
5195
5196 this.head = null;
5197 this.tail = null;
5198 this.length = 0;
5199 }
5200
5201 BufferList.prototype.push = function push(v) {
5202 var entry = { data: v, next: null };
5203 if (this.length > 0) this.tail.next = entry;else this.head = entry;
5204 this.tail = entry;
5205 ++this.length;
5206 };
5207
5208 BufferList.prototype.unshift = function unshift(v) {
5209 var entry = { data: v, next: this.head };
5210 if (this.length === 0) this.tail = entry;
5211 this.head = entry;
5212 ++this.length;
5213 };
5214
5215 BufferList.prototype.shift = function shift() {
5216 if (this.length === 0) return;
5217 var ret = this.head.data;
5218 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
5219 --this.length;
5220 return ret;
5221 };
5222
5223 BufferList.prototype.clear = function clear() {
5224 this.head = this.tail = null;
5225 this.length = 0;
5226 };
5227
5228 BufferList.prototype.join = function join(s) {
5229 if (this.length === 0) return '';
5230 var p = this.head;
5231 var ret = '' + p.data;
5232 while (p = p.next) {
5233 ret += s + p.data;
5234 }return ret;
5235 };
5236
5237 BufferList.prototype.concat = function concat(n) {
5238 if (this.length === 0) return Buffer.alloc(0);
5239 if (this.length === 1) return this.head.data;
5240 var ret = Buffer.allocUnsafe(n >>> 0);
5241 var p = this.head;
5242 var i = 0;
5243 while (p) {
5244 copyBuffer(p.data, ret, i);
5245 i += p.data.length;
5246 p = p.next;
5247 }
5248 return ret;
5249 };
5250
5251 return BufferList;
5252}();
5253},{"safe-buffer":26}],20:[function(require,module,exports){
5254'use strict';
5255
5256/*<replacement>*/
5257
5258var processNextTick = require('process-nextick-args');
5259/*</replacement>*/
5260
5261// undocumented cb() API, needed for core, not for public API
5262function destroy(err, cb) {
5263 var _this = this;
5264
5265 var readableDestroyed = this._readableState && this._readableState.destroyed;
5266 var writableDestroyed = this._writableState && this._writableState.destroyed;
5267
5268 if (readableDestroyed || writableDestroyed) {
5269 if (cb) {
5270 cb(err);
5271 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
5272 processNextTick(emitErrorNT, this, err);
5273 }
5274 return;
5275 }
5276
5277 // we set destroyed to true before firing error callbacks in order
5278 // to make it re-entrance safe in case destroy() is called within callbacks
5279
5280 if (this._readableState) {
5281 this._readableState.destroyed = true;
5282 }
5283
5284 // if this is a duplex stream mark the writable part as destroyed as well
5285 if (this._writableState) {
5286 this._writableState.destroyed = true;
5287 }
5288
5289 this._destroy(err || null, function (err) {
5290 if (!cb && err) {
5291 processNextTick(emitErrorNT, _this, err);
5292 if (_this._writableState) {
5293 _this._writableState.errorEmitted = true;
5294 }
5295 } else if (cb) {
5296 cb(err);
5297 }
5298 });
5299}
5300
5301function undestroy() {
5302 if (this._readableState) {
5303 this._readableState.destroyed = false;
5304 this._readableState.reading = false;
5305 this._readableState.ended = false;
5306 this._readableState.endEmitted = false;
5307 }
5308
5309 if (this._writableState) {
5310 this._writableState.destroyed = false;
5311 this._writableState.ended = false;
5312 this._writableState.ending = false;
5313 this._writableState.finished = false;
5314 this._writableState.errorEmitted = false;
5315 }
5316}
5317
5318function emitErrorNT(self, err) {
5319 self.emit('error', err);
5320}
5321
5322module.exports = {
5323 destroy: destroy,
5324 undestroy: undestroy
5325};
5326},{"process-nextick-args":11}],21:[function(require,module,exports){
5327module.exports = require('events').EventEmitter;
5328
5329},{"events":6}],22:[function(require,module,exports){
5330module.exports = require('./readable').PassThrough
5331
5332},{"./readable":23}],23:[function(require,module,exports){
5333exports = module.exports = require('./lib/_stream_readable.js');
5334exports.Stream = exports;
5335exports.Readable = exports;
5336exports.Writable = require('./lib/_stream_writable.js');
5337exports.Duplex = require('./lib/_stream_duplex.js');
5338exports.Transform = require('./lib/_stream_transform.js');
5339exports.PassThrough = require('./lib/_stream_passthrough.js');
5340
5341},{"./lib/_stream_duplex.js":14,"./lib/_stream_passthrough.js":15,"./lib/_stream_readable.js":16,"./lib/_stream_transform.js":17,"./lib/_stream_writable.js":18}],24:[function(require,module,exports){
5342module.exports = require('./readable').Transform
5343
5344},{"./readable":23}],25:[function(require,module,exports){
5345module.exports = require('./lib/_stream_writable.js');
5346
5347},{"./lib/_stream_writable.js":18}],26:[function(require,module,exports){
5348/* eslint-disable node/no-deprecated-api */
5349var buffer = require('buffer')
5350var Buffer = buffer.Buffer
5351
5352// alternative to using Object.keys for old browsers
5353function copyProps (src, dst) {
5354 for (var key in src) {
5355 dst[key] = src[key]
5356 }
5357}
5358if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
5359 module.exports = buffer
5360} else {
5361 // Copy properties from require('buffer')
5362 copyProps(buffer, exports)
5363 exports.Buffer = SafeBuffer
5364}
5365
5366function SafeBuffer (arg, encodingOrOffset, length) {
5367 return Buffer(arg, encodingOrOffset, length)
5368}
5369
5370// Copy static methods from Buffer
5371copyProps(Buffer, SafeBuffer)
5372
5373SafeBuffer.from = function (arg, encodingOrOffset, length) {
5374 if (typeof arg === 'number') {
5375 throw new TypeError('Argument must not be a number')
5376 }
5377 return Buffer(arg, encodingOrOffset, length)
5378}
5379
5380SafeBuffer.alloc = function (size, fill, encoding) {
5381 if (typeof size !== 'number') {
5382 throw new TypeError('Argument must be a number')
5383 }
5384 var buf = Buffer(size)
5385 if (fill !== undefined) {
5386 if (typeof encoding === 'string') {
5387 buf.fill(fill, encoding)
5388 } else {
5389 buf.fill(fill)
5390 }
5391 } else {
5392 buf.fill(0)
5393 }
5394 return buf
5395}
5396
5397SafeBuffer.allocUnsafe = function (size) {
5398 if (typeof size !== 'number') {
5399 throw new TypeError('Argument must be a number')
5400 }
5401 return Buffer(size)
5402}
5403
5404SafeBuffer.allocUnsafeSlow = function (size) {
5405 if (typeof size !== 'number') {
5406 throw new TypeError('Argument must be a number')
5407 }
5408 return buffer.SlowBuffer(size)
5409}
5410
5411},{"buffer":4}],27:[function(require,module,exports){
5412// Copyright Joyent, Inc. and other Node contributors.
5413//
5414// Permission is hereby granted, free of charge, to any person obtaining a
5415// copy of this software and associated documentation files (the
5416// "Software"), to deal in the Software without restriction, including
5417// without limitation the rights to use, copy, modify, merge, publish,
5418// distribute, sublicense, and/or sell copies of the Software, and to permit
5419// persons to whom the Software is furnished to do so, subject to the
5420// following conditions:
5421//
5422// The above copyright notice and this permission notice shall be included
5423// in all copies or substantial portions of the Software.
5424//
5425// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5426// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5427// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5428// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5429// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5430// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5431// USE OR OTHER DEALINGS IN THE SOFTWARE.
5432
5433module.exports = Stream;
5434
5435var EE = require('events').EventEmitter;
5436var inherits = require('inherits');
5437
5438inherits(Stream, EE);
5439Stream.Readable = require('readable-stream/readable.js');
5440Stream.Writable = require('readable-stream/writable.js');
5441Stream.Duplex = require('readable-stream/duplex.js');
5442Stream.Transform = require('readable-stream/transform.js');
5443Stream.PassThrough = require('readable-stream/passthrough.js');
5444
5445// Backwards-compat with node 0.4.x
5446Stream.Stream = Stream;
5447
5448
5449
5450// old-style streams. Note that the pipe method (the only relevant
5451// part of this class) is overridden in the Readable class.
5452
5453function Stream() {
5454 EE.call(this);
5455}
5456
5457Stream.prototype.pipe = function(dest, options) {
5458 var source = this;
5459
5460 function ondata(chunk) {
5461 if (dest.writable) {
5462 if (false === dest.write(chunk) && source.pause) {
5463 source.pause();
5464 }
5465 }
5466 }
5467
5468 source.on('data', ondata);
5469
5470 function ondrain() {
5471 if (source.readable && source.resume) {
5472 source.resume();
5473 }
5474 }
5475
5476 dest.on('drain', ondrain);
5477
5478 // If the 'end' option is not supplied, dest.end() will be called when
5479 // source gets the 'end' or 'close' events. Only dest.end() once.
5480 if (!dest._isStdio && (!options || options.end !== false)) {
5481 source.on('end', onend);
5482 source.on('close', onclose);
5483 }
5484
5485 var didOnEnd = false;
5486 function onend() {
5487 if (didOnEnd) return;
5488 didOnEnd = true;
5489
5490 dest.end();
5491 }
5492
5493
5494 function onclose() {
5495 if (didOnEnd) return;
5496 didOnEnd = true;
5497
5498 if (typeof dest.destroy === 'function') dest.destroy();
5499 }
5500
5501 // don't leave dangling pipes when there are errors.
5502 function onerror(er) {
5503 cleanup();
5504 if (EE.listenerCount(this, 'error') === 0) {
5505 throw er; // Unhandled stream error in pipe.
5506 }
5507 }
5508
5509 source.on('error', onerror);
5510 dest.on('error', onerror);
5511
5512 // remove all the event listeners that were added.
5513 function cleanup() {
5514 source.removeListener('data', ondata);
5515 dest.removeListener('drain', ondrain);
5516
5517 source.removeListener('end', onend);
5518 source.removeListener('close', onclose);
5519
5520 source.removeListener('error', onerror);
5521 dest.removeListener('error', onerror);
5522
5523 source.removeListener('end', cleanup);
5524 source.removeListener('close', cleanup);
5525
5526 dest.removeListener('close', cleanup);
5527 }
5528
5529 source.on('end', cleanup);
5530 source.on('close', cleanup);
5531
5532 dest.on('close', cleanup);
5533
5534 dest.emit('pipe', source);
5535
5536 // Allow for unix-like usage: A.pipe(B).pipe(C)
5537 return dest;
5538};
5539
5540},{"events":6,"inherits":8,"readable-stream/duplex.js":13,"readable-stream/passthrough.js":22,"readable-stream/readable.js":23,"readable-stream/transform.js":24,"readable-stream/writable.js":25}],28:[function(require,module,exports){
5541'use strict';
5542
5543var Buffer = require('safe-buffer').Buffer;
5544
5545var isEncoding = Buffer.isEncoding || function (encoding) {
5546 encoding = '' + encoding;
5547 switch (encoding && encoding.toLowerCase()) {
5548 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':
5549 return true;
5550 default:
5551 return false;
5552 }
5553};
5554
5555function _normalizeEncoding(enc) {
5556 if (!enc) return 'utf8';
5557 var retried;
5558 while (true) {
5559 switch (enc) {
5560 case 'utf8':
5561 case 'utf-8':
5562 return 'utf8';
5563 case 'ucs2':
5564 case 'ucs-2':
5565 case 'utf16le':
5566 case 'utf-16le':
5567 return 'utf16le';
5568 case 'latin1':
5569 case 'binary':
5570 return 'latin1';
5571 case 'base64':
5572 case 'ascii':
5573 case 'hex':
5574 return enc;
5575 default:
5576 if (retried) return; // undefined
5577 enc = ('' + enc).toLowerCase();
5578 retried = true;
5579 }
5580 }
5581};
5582
5583// Do not cache `Buffer.isEncoding` when checking encoding names as some
5584// modules monkey-patch it to support additional encodings
5585function normalizeEncoding(enc) {
5586 var nenc = _normalizeEncoding(enc);
5587 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
5588 return nenc || enc;
5589}
5590
5591// StringDecoder provides an interface for efficiently splitting a series of
5592// buffers into a series of JS strings without breaking apart multi-byte
5593// characters.
5594exports.StringDecoder = StringDecoder;
5595function StringDecoder(encoding) {
5596 this.encoding = normalizeEncoding(encoding);
5597 var nb;
5598 switch (this.encoding) {
5599 case 'utf16le':
5600 this.text = utf16Text;
5601 this.end = utf16End;
5602 nb = 4;
5603 break;
5604 case 'utf8':
5605 this.fillLast = utf8FillLast;
5606 nb = 4;
5607 break;
5608 case 'base64':
5609 this.text = base64Text;
5610 this.end = base64End;
5611 nb = 3;
5612 break;
5613 default:
5614 this.write = simpleWrite;
5615 this.end = simpleEnd;
5616 return;
5617 }
5618 this.lastNeed = 0;
5619 this.lastTotal = 0;
5620 this.lastChar = Buffer.allocUnsafe(nb);
5621}
5622
5623StringDecoder.prototype.write = function (buf) {
5624 if (buf.length === 0) return '';
5625 var r;
5626 var i;
5627 if (this.lastNeed) {
5628 r = this.fillLast(buf);
5629 if (r === undefined) return '';
5630 i = this.lastNeed;
5631 this.lastNeed = 0;
5632 } else {
5633 i = 0;
5634 }
5635 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
5636 return r || '';
5637};
5638
5639StringDecoder.prototype.end = utf8End;
5640
5641// Returns only complete characters in a Buffer
5642StringDecoder.prototype.text = utf8Text;
5643
5644// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
5645StringDecoder.prototype.fillLast = function (buf) {
5646 if (this.lastNeed <= buf.length) {
5647 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
5648 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
5649 }
5650 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
5651 this.lastNeed -= buf.length;
5652};
5653
5654// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
5655// continuation byte.
5656function utf8CheckByte(byte) {
5657 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
5658 return -1;
5659}
5660
5661// Checks at most 3 bytes at the end of a Buffer in order to detect an
5662// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
5663// needed to complete the UTF-8 character (if applicable) are returned.
5664function utf8CheckIncomplete(self, buf, i) {
5665 var j = buf.length - 1;
5666 if (j < i) return 0;
5667 var nb = utf8CheckByte(buf[j]);
5668 if (nb >= 0) {
5669 if (nb > 0) self.lastNeed = nb - 1;
5670 return nb;
5671 }
5672 if (--j < i) return 0;
5673 nb = utf8CheckByte(buf[j]);
5674 if (nb >= 0) {
5675 if (nb > 0) self.lastNeed = nb - 2;
5676 return nb;
5677 }
5678 if (--j < i) return 0;
5679 nb = utf8CheckByte(buf[j]);
5680 if (nb >= 0) {
5681 if (nb > 0) {
5682 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
5683 }
5684 return nb;
5685 }
5686 return 0;
5687}
5688
5689// Validates as many continuation bytes for a multi-byte UTF-8 character as
5690// needed or are available. If we see a non-continuation byte where we expect
5691// one, we "replace" the validated continuation bytes we've seen so far with
5692// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
5693// behavior. The continuation byte check is included three times in the case
5694// where all of the continuation bytes for a character exist in the same buffer.
5695// It is also done this way as a slight performance increase instead of using a
5696// loop.
5697function utf8CheckExtraBytes(self, buf, p) {
5698 if ((buf[0] & 0xC0) !== 0x80) {
5699 self.lastNeed = 0;
5700 return '\ufffd'.repeat(p);
5701 }
5702 if (self.lastNeed > 1 && buf.length > 1) {
5703 if ((buf[1] & 0xC0) !== 0x80) {
5704 self.lastNeed = 1;
5705 return '\ufffd'.repeat(p + 1);
5706 }
5707 if (self.lastNeed > 2 && buf.length > 2) {
5708 if ((buf[2] & 0xC0) !== 0x80) {
5709 self.lastNeed = 2;
5710 return '\ufffd'.repeat(p + 2);
5711 }
5712 }
5713 }
5714}
5715
5716// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
5717function utf8FillLast(buf) {
5718 var p = this.lastTotal - this.lastNeed;
5719 var r = utf8CheckExtraBytes(this, buf, p);
5720 if (r !== undefined) return r;
5721 if (this.lastNeed <= buf.length) {
5722 buf.copy(this.lastChar, p, 0, this.lastNeed);
5723 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
5724 }
5725 buf.copy(this.lastChar, p, 0, buf.length);
5726 this.lastNeed -= buf.length;
5727}
5728
5729// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
5730// partial character, the character's bytes are buffered until the required
5731// number of bytes are available.
5732function utf8Text(buf, i) {
5733 var total = utf8CheckIncomplete(this, buf, i);
5734 if (!this.lastNeed) return buf.toString('utf8', i);
5735 this.lastTotal = total;
5736 var end = buf.length - (total - this.lastNeed);
5737 buf.copy(this.lastChar, 0, end);
5738 return buf.toString('utf8', i, end);
5739}
5740
5741// For UTF-8, a replacement character for each buffered byte of a (partial)
5742// character needs to be added to the output.
5743function utf8End(buf) {
5744 var r = buf && buf.length ? this.write(buf) : '';
5745 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
5746 return r;
5747}
5748
5749// UTF-16LE typically needs two bytes per character, but even if we have an even
5750// number of bytes available, we need to check if we end on a leading/high
5751// surrogate. In that case, we need to wait for the next two bytes in order to
5752// decode the last character properly.
5753function utf16Text(buf, i) {
5754 if ((buf.length - i) % 2 === 0) {
5755 var r = buf.toString('utf16le', i);
5756 if (r) {
5757 var c = r.charCodeAt(r.length - 1);
5758 if (c >= 0xD800 && c <= 0xDBFF) {
5759 this.lastNeed = 2;
5760 this.lastTotal = 4;
5761 this.lastChar[0] = buf[buf.length - 2];
5762 this.lastChar[1] = buf[buf.length - 1];
5763 return r.slice(0, -1);
5764 }
5765 }
5766 return r;
5767 }
5768 this.lastNeed = 1;
5769 this.lastTotal = 2;
5770 this.lastChar[0] = buf[buf.length - 1];
5771 return buf.toString('utf16le', i, buf.length - 1);
5772}
5773
5774// For UTF-16LE we do not explicitly append special replacement characters if we
5775// end on a partial character, we simply let v8 handle that.
5776function utf16End(buf) {
5777 var r = buf && buf.length ? this.write(buf) : '';
5778 if (this.lastNeed) {
5779 var end = this.lastTotal - this.lastNeed;
5780 return r + this.lastChar.toString('utf16le', 0, end);
5781 }
5782 return r;
5783}
5784
5785function base64Text(buf, i) {
5786 var n = (buf.length - i) % 3;
5787 if (n === 0) return buf.toString('base64', i);
5788 this.lastNeed = 3 - n;
5789 this.lastTotal = 3;
5790 if (n === 1) {
5791 this.lastChar[0] = buf[buf.length - 1];
5792 } else {
5793 this.lastChar[0] = buf[buf.length - 2];
5794 this.lastChar[1] = buf[buf.length - 1];
5795 }
5796 return buf.toString('base64', i, buf.length - n);
5797}
5798
5799function base64End(buf) {
5800 var r = buf && buf.length ? this.write(buf) : '';
5801 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
5802 return r;
5803}
5804
5805// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
5806function simpleWrite(buf) {
5807 return buf.toString(this.encoding);
5808}
5809
5810function simpleEnd(buf) {
5811 return buf && buf.length ? this.write(buf) : '';
5812}
5813},{"safe-buffer":26}],29:[function(require,module,exports){
5814(function (global){
5815
5816/**
5817 * Module exports.
5818 */
5819
5820module.exports = deprecate;
5821
5822/**
5823 * Mark that a method should not be used.
5824 * Returns a modified function which warns once by default.
5825 *
5826 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
5827 *
5828 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
5829 * will throw an Error when invoked.
5830 *
5831 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
5832 * will invoke `console.trace()` instead of `console.error()`.
5833 *
5834 * @param {Function} fn - the function to deprecate
5835 * @param {String} msg - the string to print to the console when `fn` is invoked
5836 * @returns {Function} a new "deprecated" version of `fn`
5837 * @api public
5838 */
5839
5840function deprecate (fn, msg) {
5841 if (config('noDeprecation')) {
5842 return fn;
5843 }
5844
5845 var warned = false;
5846 function deprecated() {
5847 if (!warned) {
5848 if (config('throwDeprecation')) {
5849 throw new Error(msg);
5850 } else if (config('traceDeprecation')) {
5851 console.trace(msg);
5852 } else {
5853 console.warn(msg);
5854 }
5855 warned = true;
5856 }
5857 return fn.apply(this, arguments);
5858 }
5859
5860 return deprecated;
5861}
5862
5863/**
5864 * Checks `localStorage` for boolean values for the given `name`.
5865 *
5866 * @param {String} name
5867 * @returns {Boolean}
5868 * @api private
5869 */
5870
5871function config (name) {
5872 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
5873 try {
5874 if (!global.localStorage) return false;
5875 } catch (_) {
5876 return false;
5877 }
5878 var val = global.localStorage[name];
5879 if (null == val) return false;
5880 return String(val).toLowerCase() === 'true';
5881}
5882
5883}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5884},{}],30:[function(require,module,exports){
5885arguments[4][8][0].apply(exports,arguments)
5886},{"dup":8}],31:[function(require,module,exports){
5887module.exports = function isBuffer(arg) {
5888 return arg && typeof arg === 'object'
5889 && typeof arg.copy === 'function'
5890 && typeof arg.fill === 'function'
5891 && typeof arg.readUInt8 === 'function';
5892}
5893},{}],32:[function(require,module,exports){
5894(function (process,global){
5895// Copyright Joyent, Inc. and other Node contributors.
5896//
5897// Permission is hereby granted, free of charge, to any person obtaining a
5898// copy of this software and associated documentation files (the
5899// "Software"), to deal in the Software without restriction, including
5900// without limitation the rights to use, copy, modify, merge, publish,
5901// distribute, sublicense, and/or sell copies of the Software, and to permit
5902// persons to whom the Software is furnished to do so, subject to the
5903// following conditions:
5904//
5905// The above copyright notice and this permission notice shall be included
5906// in all copies or substantial portions of the Software.
5907//
5908// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5909// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5910// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5911// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5912// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5913// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5914// USE OR OTHER DEALINGS IN THE SOFTWARE.
5915
5916var formatRegExp = /%[sdj%]/g;
5917exports.format = function(f) {
5918 if (!isString(f)) {
5919 var objects = [];
5920 for (var i = 0; i < arguments.length; i++) {
5921 objects.push(inspect(arguments[i]));
5922 }
5923 return objects.join(' ');
5924 }
5925
5926 var i = 1;
5927 var args = arguments;
5928 var len = args.length;
5929 var str = String(f).replace(formatRegExp, function(x) {
5930 if (x === '%%') return '%';
5931 if (i >= len) return x;
5932 switch (x) {
5933 case '%s': return String(args[i++]);
5934 case '%d': return Number(args[i++]);
5935 case '%j':
5936 try {
5937 return JSON.stringify(args[i++]);
5938 } catch (_) {
5939 return '[Circular]';
5940 }
5941 default:
5942 return x;
5943 }
5944 });
5945 for (var x = args[i]; i < len; x = args[++i]) {
5946 if (isNull(x) || !isObject(x)) {
5947 str += ' ' + x;
5948 } else {
5949 str += ' ' + inspect(x);
5950 }
5951 }
5952 return str;
5953};
5954
5955
5956// Mark that a method should not be used.
5957// Returns a modified function which warns once by default.
5958// If --no-deprecation is set, then it is a no-op.
5959exports.deprecate = function(fn, msg) {
5960 // Allow for deprecating things in the process of starting up.
5961 if (isUndefined(global.process)) {
5962 return function() {
5963 return exports.deprecate(fn, msg).apply(this, arguments);
5964 };
5965 }
5966
5967 if (process.noDeprecation === true) {
5968 return fn;
5969 }
5970
5971 var warned = false;
5972 function deprecated() {
5973 if (!warned) {
5974 if (process.throwDeprecation) {
5975 throw new Error(msg);
5976 } else if (process.traceDeprecation) {
5977 console.trace(msg);
5978 } else {
5979 console.error(msg);
5980 }
5981 warned = true;
5982 }
5983 return fn.apply(this, arguments);
5984 }
5985
5986 return deprecated;
5987};
5988
5989
5990var debugs = {};
5991var debugEnviron;
5992exports.debuglog = function(set) {
5993 if (isUndefined(debugEnviron))
5994 debugEnviron = process.env.NODE_DEBUG || '';
5995 set = set.toUpperCase();
5996 if (!debugs[set]) {
5997 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
5998 var pid = process.pid;
5999 debugs[set] = function() {
6000 var msg = exports.format.apply(exports, arguments);
6001 console.error('%s %d: %s', set, pid, msg);
6002 };
6003 } else {
6004 debugs[set] = function() {};
6005 }
6006 }
6007 return debugs[set];
6008};
6009
6010
6011/**
6012 * Echos the value of a value. Trys to print the value out
6013 * in the best way possible given the different types.
6014 *
6015 * @param {Object} obj The object to print out.
6016 * @param {Object} opts Optional options object that alters the output.
6017 */
6018/* legacy: obj, showHidden, depth, colors*/
6019function inspect(obj, opts) {
6020 // default options
6021 var ctx = {
6022 seen: [],
6023 stylize: stylizeNoColor
6024 };
6025 // legacy...
6026 if (arguments.length >= 3) ctx.depth = arguments[2];
6027 if (arguments.length >= 4) ctx.colors = arguments[3];
6028 if (isBoolean(opts)) {
6029 // legacy...
6030 ctx.showHidden = opts;
6031 } else if (opts) {
6032 // got an "options" object
6033 exports._extend(ctx, opts);
6034 }
6035 // set default options
6036 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
6037 if (isUndefined(ctx.depth)) ctx.depth = 2;
6038 if (isUndefined(ctx.colors)) ctx.colors = false;
6039 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
6040 if (ctx.colors) ctx.stylize = stylizeWithColor;
6041 return formatValue(ctx, obj, ctx.depth);
6042}
6043exports.inspect = inspect;
6044
6045
6046// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
6047inspect.colors = {
6048 'bold' : [1, 22],
6049 'italic' : [3, 23],
6050 'underline' : [4, 24],
6051 'inverse' : [7, 27],
6052 'white' : [37, 39],
6053 'grey' : [90, 39],
6054 'black' : [30, 39],
6055 'blue' : [34, 39],
6056 'cyan' : [36, 39],
6057 'green' : [32, 39],
6058 'magenta' : [35, 39],
6059 'red' : [31, 39],
6060 'yellow' : [33, 39]
6061};
6062
6063// Don't use 'blue' not visible on cmd.exe
6064inspect.styles = {
6065 'special': 'cyan',
6066 'number': 'yellow',
6067 'boolean': 'yellow',
6068 'undefined': 'grey',
6069 'null': 'bold',
6070 'string': 'green',
6071 'date': 'magenta',
6072 // "name": intentionally not styling
6073 'regexp': 'red'
6074};
6075
6076
6077function stylizeWithColor(str, styleType) {
6078 var style = inspect.styles[styleType];
6079
6080 if (style) {
6081 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
6082 '\u001b[' + inspect.colors[style][1] + 'm';
6083 } else {
6084 return str;
6085 }
6086}
6087
6088
6089function stylizeNoColor(str, styleType) {
6090 return str;
6091}
6092
6093
6094function arrayToHash(array) {
6095 var hash = {};
6096
6097 array.forEach(function(val, idx) {
6098 hash[val] = true;
6099 });
6100
6101 return hash;
6102}
6103
6104
6105function formatValue(ctx, value, recurseTimes) {
6106 // Provide a hook for user-specified inspect functions.
6107 // Check that value is an object with an inspect function on it
6108 if (ctx.customInspect &&
6109 value &&
6110 isFunction(value.inspect) &&
6111 // Filter out the util module, it's inspect function is special
6112 value.inspect !== exports.inspect &&
6113 // Also filter out any prototype objects using the circular check.
6114 !(value.constructor && value.constructor.prototype === value)) {
6115 var ret = value.inspect(recurseTimes, ctx);
6116 if (!isString(ret)) {
6117 ret = formatValue(ctx, ret, recurseTimes);
6118 }
6119 return ret;
6120 }
6121
6122 // Primitive types cannot have properties
6123 var primitive = formatPrimitive(ctx, value);
6124 if (primitive) {
6125 return primitive;
6126 }
6127
6128 // Look up the keys of the object.
6129 var keys = Object.keys(value);
6130 var visibleKeys = arrayToHash(keys);
6131
6132 if (ctx.showHidden) {
6133 keys = Object.getOwnPropertyNames(value);
6134 }
6135
6136 // IE doesn't make error fields non-enumerable
6137 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
6138 if (isError(value)
6139 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
6140 return formatError(value);
6141 }
6142
6143 // Some type of object without properties can be shortcutted.
6144 if (keys.length === 0) {
6145 if (isFunction(value)) {
6146 var name = value.name ? ': ' + value.name : '';
6147 return ctx.stylize('[Function' + name + ']', 'special');
6148 }
6149 if (isRegExp(value)) {
6150 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6151 }
6152 if (isDate(value)) {
6153 return ctx.stylize(Date.prototype.toString.call(value), 'date');
6154 }
6155 if (isError(value)) {
6156 return formatError(value);
6157 }
6158 }
6159
6160 var base = '', array = false, braces = ['{', '}'];
6161
6162 // Make Array say that they are Array
6163 if (isArray(value)) {
6164 array = true;
6165 braces = ['[', ']'];
6166 }
6167
6168 // Make functions say that they are functions
6169 if (isFunction(value)) {
6170 var n = value.name ? ': ' + value.name : '';
6171 base = ' [Function' + n + ']';
6172 }
6173
6174 // Make RegExps say that they are RegExps
6175 if (isRegExp(value)) {
6176 base = ' ' + RegExp.prototype.toString.call(value);
6177 }
6178
6179 // Make dates with properties first say the date
6180 if (isDate(value)) {
6181 base = ' ' + Date.prototype.toUTCString.call(value);
6182 }
6183
6184 // Make error with message first say the error
6185 if (isError(value)) {
6186 base = ' ' + formatError(value);
6187 }
6188
6189 if (keys.length === 0 && (!array || value.length == 0)) {
6190 return braces[0] + base + braces[1];
6191 }
6192
6193 if (recurseTimes < 0) {
6194 if (isRegExp(value)) {
6195 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6196 } else {
6197 return ctx.stylize('[Object]', 'special');
6198 }
6199 }
6200
6201 ctx.seen.push(value);
6202
6203 var output;
6204 if (array) {
6205 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
6206 } else {
6207 output = keys.map(function(key) {
6208 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
6209 });
6210 }
6211
6212 ctx.seen.pop();
6213
6214 return reduceToSingleString(output, base, braces);
6215}
6216
6217
6218function formatPrimitive(ctx, value) {
6219 if (isUndefined(value))
6220 return ctx.stylize('undefined', 'undefined');
6221 if (isString(value)) {
6222 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
6223 .replace(/'/g, "\\'")
6224 .replace(/\\"/g, '"') + '\'';
6225 return ctx.stylize(simple, 'string');
6226 }
6227 if (isNumber(value))
6228 return ctx.stylize('' + value, 'number');
6229 if (isBoolean(value))
6230 return ctx.stylize('' + value, 'boolean');
6231 // For some reason typeof null is "object", so special case here.
6232 if (isNull(value))
6233 return ctx.stylize('null', 'null');
6234}
6235
6236
6237function formatError(value) {
6238 return '[' + Error.prototype.toString.call(value) + ']';
6239}
6240
6241
6242function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
6243 var output = [];
6244 for (var i = 0, l = value.length; i < l; ++i) {
6245 if (hasOwnProperty(value, String(i))) {
6246 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
6247 String(i), true));
6248 } else {
6249 output.push('');
6250 }
6251 }
6252 keys.forEach(function(key) {
6253 if (!key.match(/^\d+$/)) {
6254 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
6255 key, true));
6256 }
6257 });
6258 return output;
6259}
6260
6261
6262function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
6263 var name, str, desc;
6264 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
6265 if (desc.get) {
6266 if (desc.set) {
6267 str = ctx.stylize('[Getter/Setter]', 'special');
6268 } else {
6269 str = ctx.stylize('[Getter]', 'special');
6270 }
6271 } else {
6272 if (desc.set) {
6273 str = ctx.stylize('[Setter]', 'special');
6274 }
6275 }
6276 if (!hasOwnProperty(visibleKeys, key)) {
6277 name = '[' + key + ']';
6278 }
6279 if (!str) {
6280 if (ctx.seen.indexOf(desc.value) < 0) {
6281 if (isNull(recurseTimes)) {
6282 str = formatValue(ctx, desc.value, null);
6283 } else {
6284 str = formatValue(ctx, desc.value, recurseTimes - 1);
6285 }
6286 if (str.indexOf('\n') > -1) {
6287 if (array) {
6288 str = str.split('\n').map(function(line) {
6289 return ' ' + line;
6290 }).join('\n').substr(2);
6291 } else {
6292 str = '\n' + str.split('\n').map(function(line) {
6293 return ' ' + line;
6294 }).join('\n');
6295 }
6296 }
6297 } else {
6298 str = ctx.stylize('[Circular]', 'special');
6299 }
6300 }
6301 if (isUndefined(name)) {
6302 if (array && key.match(/^\d+$/)) {
6303 return str;
6304 }
6305 name = JSON.stringify('' + key);
6306 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
6307 name = name.substr(1, name.length - 2);
6308 name = ctx.stylize(name, 'name');
6309 } else {
6310 name = name.replace(/'/g, "\\'")
6311 .replace(/\\"/g, '"')
6312 .replace(/(^"|"$)/g, "'");
6313 name = ctx.stylize(name, 'string');
6314 }
6315 }
6316
6317 return name + ': ' + str;
6318}
6319
6320
6321function reduceToSingleString(output, base, braces) {
6322 var numLinesEst = 0;
6323 var length = output.reduce(function(prev, cur) {
6324 numLinesEst++;
6325 if (cur.indexOf('\n') >= 0) numLinesEst++;
6326 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
6327 }, 0);
6328
6329 if (length > 60) {
6330 return braces[0] +
6331 (base === '' ? '' : base + '\n ') +
6332 ' ' +
6333 output.join(',\n ') +
6334 ' ' +
6335 braces[1];
6336 }
6337
6338 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
6339}
6340
6341
6342// NOTE: These type checking functions intentionally don't use `instanceof`
6343// because it is fragile and can be easily faked with `Object.create()`.
6344function isArray(ar) {
6345 return Array.isArray(ar);
6346}
6347exports.isArray = isArray;
6348
6349function isBoolean(arg) {
6350 return typeof arg === 'boolean';
6351}
6352exports.isBoolean = isBoolean;
6353
6354function isNull(arg) {
6355 return arg === null;
6356}
6357exports.isNull = isNull;
6358
6359function isNullOrUndefined(arg) {
6360 return arg == null;
6361}
6362exports.isNullOrUndefined = isNullOrUndefined;
6363
6364function isNumber(arg) {
6365 return typeof arg === 'number';
6366}
6367exports.isNumber = isNumber;
6368
6369function isString(arg) {
6370 return typeof arg === 'string';
6371}
6372exports.isString = isString;
6373
6374function isSymbol(arg) {
6375 return typeof arg === 'symbol';
6376}
6377exports.isSymbol = isSymbol;
6378
6379function isUndefined(arg) {
6380 return arg === void 0;
6381}
6382exports.isUndefined = isUndefined;
6383
6384function isRegExp(re) {
6385 return isObject(re) && objectToString(re) === '[object RegExp]';
6386}
6387exports.isRegExp = isRegExp;
6388
6389function isObject(arg) {
6390 return typeof arg === 'object' && arg !== null;
6391}
6392exports.isObject = isObject;
6393
6394function isDate(d) {
6395 return isObject(d) && objectToString(d) === '[object Date]';
6396}
6397exports.isDate = isDate;
6398
6399function isError(e) {
6400 return isObject(e) &&
6401 (objectToString(e) === '[object Error]' || e instanceof Error);
6402}
6403exports.isError = isError;
6404
6405function isFunction(arg) {
6406 return typeof arg === 'function';
6407}
6408exports.isFunction = isFunction;
6409
6410function isPrimitive(arg) {
6411 return arg === null ||
6412 typeof arg === 'boolean' ||
6413 typeof arg === 'number' ||
6414 typeof arg === 'string' ||
6415 typeof arg === 'symbol' || // ES6 symbol
6416 typeof arg === 'undefined';
6417}
6418exports.isPrimitive = isPrimitive;
6419
6420exports.isBuffer = require('./support/isBuffer');
6421
6422function objectToString(o) {
6423 return Object.prototype.toString.call(o);
6424}
6425
6426
6427function pad(n) {
6428 return n < 10 ? '0' + n.toString(10) : n.toString(10);
6429}
6430
6431
6432var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
6433 'Oct', 'Nov', 'Dec'];
6434
6435// 26 Feb 16:19:34
6436function timestamp() {
6437 var d = new Date();
6438 var time = [pad(d.getHours()),
6439 pad(d.getMinutes()),
6440 pad(d.getSeconds())].join(':');
6441 return [d.getDate(), months[d.getMonth()], time].join(' ');
6442}
6443
6444
6445// log is just a thin wrapper to console.log that prepends a timestamp
6446exports.log = function() {
6447 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
6448};
6449
6450
6451/**
6452 * Inherit the prototype methods from one constructor into another.
6453 *
6454 * The Function.prototype.inherits from lang.js rewritten as a standalone
6455 * function (not on Function.prototype). NOTE: If this file is to be loaded
6456 * during bootstrapping this function needs to be rewritten using some native
6457 * functions as prototype setup using normal JavaScript does not work as
6458 * expected during bootstrapping (see mirror.js in r114903).
6459 *
6460 * @param {function} ctor Constructor function which needs to inherit the
6461 * prototype.
6462 * @param {function} superCtor Constructor function to inherit prototype from.
6463 */
6464exports.inherits = require('inherits');
6465
6466exports._extend = function(origin, add) {
6467 // Don't do anything if add isn't an object
6468 if (!add || !isObject(add)) return origin;
6469
6470 var keys = Object.keys(add);
6471 var i = keys.length;
6472 while (i--) {
6473 origin[keys[i]] = add[keys[i]];
6474 }
6475 return origin;
6476};
6477
6478function hasOwnProperty(obj, prop) {
6479 return Object.prototype.hasOwnProperty.call(obj, prop);
6480}
6481
6482}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6483},{"./support/isBuffer":31,"_process":12,"inherits":30}],33:[function(require,module,exports){
6484module.exports = {
6485 base58: require('bs58'),
6486 bitcoin: require('bitcoinjs-lib'),
6487 ecurve: require('ecurve'),
6488 BigInteger: require('bigi')
6489}
6490
6491},{"bigi":37,"bitcoinjs-lib":50,"bs58":79,"ecurve":89}],34:[function(require,module,exports){
6492// base-x encoding
6493// Forked from https://github.com/cryptocoinjs/bs58
6494// Originally written by Mike Hearn for BitcoinJ
6495// Copyright (c) 2011 Google Inc
6496// Ported to JavaScript by Stefan Thomas
6497// Merged Buffer refactorings from base58-native by Stephen Pair
6498// Copyright (c) 2013 BitPay Inc
6499
6500var Buffer = require('safe-buffer').Buffer
6501
6502module.exports = function base (ALPHABET) {
6503 var ALPHABET_MAP = {}
6504 var BASE = ALPHABET.length
6505 var LEADER = ALPHABET.charAt(0)
6506
6507 // pre-compute lookup table
6508 for (var z = 0; z < ALPHABET.length; z++) {
6509 var x = ALPHABET.charAt(z)
6510
6511 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
6512 ALPHABET_MAP[x] = z
6513 }
6514
6515 function encode (source) {
6516 if (source.length === 0) return ''
6517
6518 var digits = [0]
6519 for (var i = 0; i < source.length; ++i) {
6520 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
6521 carry += digits[j] << 8
6522 digits[j] = carry % BASE
6523 carry = (carry / BASE) | 0
6524 }
6525
6526 while (carry > 0) {
6527 digits.push(carry % BASE)
6528 carry = (carry / BASE) | 0
6529 }
6530 }
6531
6532 var string = ''
6533
6534 // deal with leading zeros
6535 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += ALPHABET[0]
6536 // convert digits to a string
6537 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
6538
6539 return string
6540 }
6541
6542 function decodeUnsafe (string) {
6543 if (string.length === 0) return Buffer.allocUnsafe(0)
6544
6545 var bytes = [0]
6546 for (var i = 0; i < string.length; i++) {
6547 var value = ALPHABET_MAP[string[i]]
6548 if (value === undefined) return
6549
6550 for (var j = 0, carry = value; j < bytes.length; ++j) {
6551 carry += bytes[j] * BASE
6552 bytes[j] = carry & 0xff
6553 carry >>= 8
6554 }
6555
6556 while (carry > 0) {
6557 bytes.push(carry & 0xff)
6558 carry >>= 8
6559 }
6560 }
6561
6562 // deal with leading zeros
6563 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
6564 bytes.push(0)
6565 }
6566
6567 return Buffer.from(bytes.reverse())
6568 }
6569
6570 function decode (string) {
6571 var buffer = decodeUnsafe(string)
6572 if (buffer) return buffer
6573
6574 throw new Error('Non-base' + BASE + ' character')
6575 }
6576
6577 return {
6578 encode: encode,
6579 decodeUnsafe: decodeUnsafe,
6580 decode: decode
6581 }
6582}
6583
6584},{"safe-buffer":98}],35:[function(require,module,exports){
6585// (public) Constructor
6586function BigInteger(a, b, c) {
6587 if (!(this instanceof BigInteger))
6588 return new BigInteger(a, b, c)
6589
6590 if (a != null) {
6591 if ("number" == typeof a) this.fromNumber(a, b, c)
6592 else if (b == null && "string" != typeof a) this.fromString(a, 256)
6593 else this.fromString(a, b)
6594 }
6595}
6596
6597var proto = BigInteger.prototype
6598
6599// duck-typed isBigInteger
6600proto.__bigi = require('../package.json').version
6601BigInteger.isBigInteger = function (obj, check_ver) {
6602 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
6603}
6604
6605// Bits per digit
6606var dbits
6607
6608// am: Compute w_j += (x*this_i), propagate carries,
6609// c is initial carry, returns final carry.
6610// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
6611// We need to select the fastest one that works in this environment.
6612
6613// am1: use a single mult and divide to get the high bits,
6614// max digit bits should be 26 because
6615// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
6616function am1(i, x, w, j, c, n) {
6617 while (--n >= 0) {
6618 var v = x * this[i++] + w[j] + c
6619 c = Math.floor(v / 0x4000000)
6620 w[j++] = v & 0x3ffffff
6621 }
6622 return c
6623}
6624// am2 avoids a big mult-and-extract completely.
6625// Max digit bits should be <= 30 because we do bitwise ops
6626// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
6627function am2(i, x, w, j, c, n) {
6628 var xl = x & 0x7fff,
6629 xh = x >> 15
6630 while (--n >= 0) {
6631 var l = this[i] & 0x7fff
6632 var h = this[i++] >> 15
6633 var m = xh * l + h * xl
6634 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
6635 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
6636 w[j++] = l & 0x3fffffff
6637 }
6638 return c
6639}
6640// Alternately, set max digit bits to 28 since some
6641// browsers slow down when dealing with 32-bit numbers.
6642function am3(i, x, w, j, c, n) {
6643 var xl = x & 0x3fff,
6644 xh = x >> 14
6645 while (--n >= 0) {
6646 var l = this[i] & 0x3fff
6647 var h = this[i++] >> 14
6648 var m = xh * l + h * xl
6649 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
6650 c = (l >> 28) + (m >> 14) + xh * h
6651 w[j++] = l & 0xfffffff
6652 }
6653 return c
6654}
6655
6656// wtf?
6657BigInteger.prototype.am = am1
6658dbits = 26
6659
6660BigInteger.prototype.DB = dbits
6661BigInteger.prototype.DM = ((1 << dbits) - 1)
6662var DV = BigInteger.prototype.DV = (1 << dbits)
6663
6664var BI_FP = 52
6665BigInteger.prototype.FV = Math.pow(2, BI_FP)
6666BigInteger.prototype.F1 = BI_FP - dbits
6667BigInteger.prototype.F2 = 2 * dbits - BI_FP
6668
6669// Digit conversions
6670var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
6671var BI_RC = new Array()
6672var rr, vv
6673rr = "0".charCodeAt(0)
6674for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
6675rr = "a".charCodeAt(0)
6676for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
6677rr = "A".charCodeAt(0)
6678for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
6679
6680function int2char(n) {
6681 return BI_RM.charAt(n)
6682}
6683
6684function intAt(s, i) {
6685 var c = BI_RC[s.charCodeAt(i)]
6686 return (c == null) ? -1 : c
6687}
6688
6689// (protected) copy this to r
6690function bnpCopyTo(r) {
6691 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
6692 r.t = this.t
6693 r.s = this.s
6694}
6695
6696// (protected) set from integer value x, -DV <= x < DV
6697function bnpFromInt(x) {
6698 this.t = 1
6699 this.s = (x < 0) ? -1 : 0
6700 if (x > 0) this[0] = x
6701 else if (x < -1) this[0] = x + DV
6702 else this.t = 0
6703}
6704
6705// return bigint initialized to value
6706function nbv(i) {
6707 var r = new BigInteger()
6708 r.fromInt(i)
6709 return r
6710}
6711
6712// (protected) set from string and radix
6713function bnpFromString(s, b) {
6714 var self = this
6715
6716 var k
6717 if (b == 16) k = 4
6718 else if (b == 8) k = 3
6719 else if (b == 256) k = 8; // byte array
6720 else if (b == 2) k = 1
6721 else if (b == 32) k = 5
6722 else if (b == 4) k = 2
6723 else {
6724 self.fromRadix(s, b)
6725 return
6726 }
6727 self.t = 0
6728 self.s = 0
6729 var i = s.length,
6730 mi = false,
6731 sh = 0
6732 while (--i >= 0) {
6733 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
6734 if (x < 0) {
6735 if (s.charAt(i) == "-") mi = true
6736 continue
6737 }
6738 mi = false
6739 if (sh == 0)
6740 self[self.t++] = x
6741 else if (sh + k > self.DB) {
6742 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
6743 self[self.t++] = (x >> (self.DB - sh))
6744 } else
6745 self[self.t - 1] |= x << sh
6746 sh += k
6747 if (sh >= self.DB) sh -= self.DB
6748 }
6749 if (k == 8 && (s[0] & 0x80) != 0) {
6750 self.s = -1
6751 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
6752 }
6753 self.clamp()
6754 if (mi) BigInteger.ZERO.subTo(self, self)
6755}
6756
6757// (protected) clamp off excess high words
6758function bnpClamp() {
6759 var c = this.s & this.DM
6760 while (this.t > 0 && this[this.t - 1] == c)--this.t
6761}
6762
6763// (public) return string representation in given radix
6764function bnToString(b) {
6765 var self = this
6766 if (self.s < 0) return "-" + self.negate()
6767 .toString(b)
6768 var k
6769 if (b == 16) k = 4
6770 else if (b == 8) k = 3
6771 else if (b == 2) k = 1
6772 else if (b == 32) k = 5
6773 else if (b == 4) k = 2
6774 else return self.toRadix(b)
6775 var km = (1 << k) - 1,
6776 d, m = false,
6777 r = "",
6778 i = self.t
6779 var p = self.DB - (i * self.DB) % k
6780 if (i-- > 0) {
6781 if (p < self.DB && (d = self[i] >> p) > 0) {
6782 m = true
6783 r = int2char(d)
6784 }
6785 while (i >= 0) {
6786 if (p < k) {
6787 d = (self[i] & ((1 << p) - 1)) << (k - p)
6788 d |= self[--i] >> (p += self.DB - k)
6789 } else {
6790 d = (self[i] >> (p -= k)) & km
6791 if (p <= 0) {
6792 p += self.DB
6793 --i
6794 }
6795 }
6796 if (d > 0) m = true
6797 if (m) r += int2char(d)
6798 }
6799 }
6800 return m ? r : "0"
6801}
6802
6803// (public) -this
6804function bnNegate() {
6805 var r = new BigInteger()
6806 BigInteger.ZERO.subTo(this, r)
6807 return r
6808}
6809
6810// (public) |this|
6811function bnAbs() {
6812 return (this.s < 0) ? this.negate() : this
6813}
6814
6815// (public) return + if this > a, - if this < a, 0 if equal
6816function bnCompareTo(a) {
6817 var r = this.s - a.s
6818 if (r != 0) return r
6819 var i = this.t
6820 r = i - a.t
6821 if (r != 0) return (this.s < 0) ? -r : r
6822 while (--i >= 0)
6823 if ((r = this[i] - a[i]) != 0) return r
6824 return 0
6825}
6826
6827// returns bit length of the integer x
6828function nbits(x) {
6829 var r = 1,
6830 t
6831 if ((t = x >>> 16) != 0) {
6832 x = t
6833 r += 16
6834 }
6835 if ((t = x >> 8) != 0) {
6836 x = t
6837 r += 8
6838 }
6839 if ((t = x >> 4) != 0) {
6840 x = t
6841 r += 4
6842 }
6843 if ((t = x >> 2) != 0) {
6844 x = t
6845 r += 2
6846 }
6847 if ((t = x >> 1) != 0) {
6848 x = t
6849 r += 1
6850 }
6851 return r
6852}
6853
6854// (public) return the number of bits in "this"
6855function bnBitLength() {
6856 if (this.t <= 0) return 0
6857 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
6858}
6859
6860// (public) return the number of bytes in "this"
6861function bnByteLength() {
6862 return this.bitLength() >> 3
6863}
6864
6865// (protected) r = this << n*DB
6866function bnpDLShiftTo(n, r) {
6867 var i
6868 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
6869 for (i = n - 1; i >= 0; --i) r[i] = 0
6870 r.t = this.t + n
6871 r.s = this.s
6872}
6873
6874// (protected) r = this >> n*DB
6875function bnpDRShiftTo(n, r) {
6876 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
6877 r.t = Math.max(this.t - n, 0)
6878 r.s = this.s
6879}
6880
6881// (protected) r = this << n
6882function bnpLShiftTo(n, r) {
6883 var self = this
6884 var bs = n % self.DB
6885 var cbs = self.DB - bs
6886 var bm = (1 << cbs) - 1
6887 var ds = Math.floor(n / self.DB),
6888 c = (self.s << bs) & self.DM,
6889 i
6890 for (i = self.t - 1; i >= 0; --i) {
6891 r[i + ds + 1] = (self[i] >> cbs) | c
6892 c = (self[i] & bm) << bs
6893 }
6894 for (i = ds - 1; i >= 0; --i) r[i] = 0
6895 r[ds] = c
6896 r.t = self.t + ds + 1
6897 r.s = self.s
6898 r.clamp()
6899}
6900
6901// (protected) r = this >> n
6902function bnpRShiftTo(n, r) {
6903 var self = this
6904 r.s = self.s
6905 var ds = Math.floor(n / self.DB)
6906 if (ds >= self.t) {
6907 r.t = 0
6908 return
6909 }
6910 var bs = n % self.DB
6911 var cbs = self.DB - bs
6912 var bm = (1 << bs) - 1
6913 r[0] = self[ds] >> bs
6914 for (var i = ds + 1; i < self.t; ++i) {
6915 r[i - ds - 1] |= (self[i] & bm) << cbs
6916 r[i - ds] = self[i] >> bs
6917 }
6918 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
6919 r.t = self.t - ds
6920 r.clamp()
6921}
6922
6923// (protected) r = this - a
6924function bnpSubTo(a, r) {
6925 var self = this
6926 var i = 0,
6927 c = 0,
6928 m = Math.min(a.t, self.t)
6929 while (i < m) {
6930 c += self[i] - a[i]
6931 r[i++] = c & self.DM
6932 c >>= self.DB
6933 }
6934 if (a.t < self.t) {
6935 c -= a.s
6936 while (i < self.t) {
6937 c += self[i]
6938 r[i++] = c & self.DM
6939 c >>= self.DB
6940 }
6941 c += self.s
6942 } else {
6943 c += self.s
6944 while (i < a.t) {
6945 c -= a[i]
6946 r[i++] = c & self.DM
6947 c >>= self.DB
6948 }
6949 c -= a.s
6950 }
6951 r.s = (c < 0) ? -1 : 0
6952 if (c < -1) r[i++] = self.DV + c
6953 else if (c > 0) r[i++] = c
6954 r.t = i
6955 r.clamp()
6956}
6957
6958// (protected) r = this * a, r != this,a (HAC 14.12)
6959// "this" should be the larger one if appropriate.
6960function bnpMultiplyTo(a, r) {
6961 var x = this.abs(),
6962 y = a.abs()
6963 var i = x.t
6964 r.t = i + y.t
6965 while (--i >= 0) r[i] = 0
6966 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
6967 r.s = 0
6968 r.clamp()
6969 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
6970}
6971
6972// (protected) r = this^2, r != this (HAC 14.16)
6973function bnpSquareTo(r) {
6974 var x = this.abs()
6975 var i = r.t = 2 * x.t
6976 while (--i >= 0) r[i] = 0
6977 for (i = 0; i < x.t - 1; ++i) {
6978 var c = x.am(i, x[i], r, 2 * i, 0, 1)
6979 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
6980 r[i + x.t] -= x.DV
6981 r[i + x.t + 1] = 1
6982 }
6983 }
6984 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
6985 r.s = 0
6986 r.clamp()
6987}
6988
6989// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
6990// r != q, this != m. q or r may be null.
6991function bnpDivRemTo(m, q, r) {
6992 var self = this
6993 var pm = m.abs()
6994 if (pm.t <= 0) return
6995 var pt = self.abs()
6996 if (pt.t < pm.t) {
6997 if (q != null) q.fromInt(0)
6998 if (r != null) self.copyTo(r)
6999 return
7000 }
7001 if (r == null) r = new BigInteger()
7002 var y = new BigInteger(),
7003 ts = self.s,
7004 ms = m.s
7005 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
7006 if (nsh > 0) {
7007 pm.lShiftTo(nsh, y)
7008 pt.lShiftTo(nsh, r)
7009 } else {
7010 pm.copyTo(y)
7011 pt.copyTo(r)
7012 }
7013 var ys = y.t
7014 var y0 = y[ys - 1]
7015 if (y0 == 0) return
7016 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
7017 var d1 = self.FV / yt,
7018 d2 = (1 << self.F1) / yt,
7019 e = 1 << self.F2
7020 var i = r.t,
7021 j = i - ys,
7022 t = (q == null) ? new BigInteger() : q
7023 y.dlShiftTo(j, t)
7024 if (r.compareTo(t) >= 0) {
7025 r[r.t++] = 1
7026 r.subTo(t, r)
7027 }
7028 BigInteger.ONE.dlShiftTo(ys, t)
7029 t.subTo(y, y); // "negative" y so we can replace sub with am later
7030 while (y.t < ys) y[y.t++] = 0
7031 while (--j >= 0) {
7032 // Estimate quotient digit
7033 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
7034 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
7035 y.dlShiftTo(j, t)
7036 r.subTo(t, r)
7037 while (r[i] < --qd) r.subTo(t, r)
7038 }
7039 }
7040 if (q != null) {
7041 r.drShiftTo(ys, q)
7042 if (ts != ms) BigInteger.ZERO.subTo(q, q)
7043 }
7044 r.t = ys
7045 r.clamp()
7046 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
7047 if (ts < 0) BigInteger.ZERO.subTo(r, r)
7048}
7049
7050// (public) this mod a
7051function bnMod(a) {
7052 var r = new BigInteger()
7053 this.abs()
7054 .divRemTo(a, null, r)
7055 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
7056 return r
7057}
7058
7059// Modular reduction using "classic" algorithm
7060function Classic(m) {
7061 this.m = m
7062}
7063
7064function cConvert(x) {
7065 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
7066 else return x
7067}
7068
7069function cRevert(x) {
7070 return x
7071}
7072
7073function cReduce(x) {
7074 x.divRemTo(this.m, null, x)
7075}
7076
7077function cMulTo(x, y, r) {
7078 x.multiplyTo(y, r)
7079 this.reduce(r)
7080}
7081
7082function cSqrTo(x, r) {
7083 x.squareTo(r)
7084 this.reduce(r)
7085}
7086
7087Classic.prototype.convert = cConvert
7088Classic.prototype.revert = cRevert
7089Classic.prototype.reduce = cReduce
7090Classic.prototype.mulTo = cMulTo
7091Classic.prototype.sqrTo = cSqrTo
7092
7093// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
7094// justification:
7095// xy == 1 (mod m)
7096// xy = 1+km
7097// xy(2-xy) = (1+km)(1-km)
7098// x[y(2-xy)] = 1-k^2m^2
7099// x[y(2-xy)] == 1 (mod m^2)
7100// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
7101// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
7102// JS multiply "overflows" differently from C/C++, so care is needed here.
7103function bnpInvDigit() {
7104 if (this.t < 1) return 0
7105 var x = this[0]
7106 if ((x & 1) == 0) return 0
7107 var y = x & 3; // y == 1/x mod 2^2
7108 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
7109 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
7110 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
7111 // last step - calculate inverse mod DV directly
7112 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
7113 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
7114 // we really want the negative inverse, and -DV < y < DV
7115 return (y > 0) ? this.DV - y : -y
7116}
7117
7118// Montgomery reduction
7119function Montgomery(m) {
7120 this.m = m
7121 this.mp = m.invDigit()
7122 this.mpl = this.mp & 0x7fff
7123 this.mph = this.mp >> 15
7124 this.um = (1 << (m.DB - 15)) - 1
7125 this.mt2 = 2 * m.t
7126}
7127
7128// xR mod m
7129function montConvert(x) {
7130 var r = new BigInteger()
7131 x.abs()
7132 .dlShiftTo(this.m.t, r)
7133 r.divRemTo(this.m, null, r)
7134 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
7135 return r
7136}
7137
7138// x/R mod m
7139function montRevert(x) {
7140 var r = new BigInteger()
7141 x.copyTo(r)
7142 this.reduce(r)
7143 return r
7144}
7145
7146// x = x/R mod m (HAC 14.32)
7147function montReduce(x) {
7148 while (x.t <= this.mt2) // pad x so am has enough room later
7149 x[x.t++] = 0
7150 for (var i = 0; i < this.m.t; ++i) {
7151 // faster way of calculating u0 = x[i]*mp mod DV
7152 var j = x[i] & 0x7fff
7153 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
7154 // use am to combine the multiply-shift-add into one call
7155 j = i + this.m.t
7156 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
7157 // propagate carry
7158 while (x[j] >= x.DV) {
7159 x[j] -= x.DV
7160 x[++j]++
7161 }
7162 }
7163 x.clamp()
7164 x.drShiftTo(this.m.t, x)
7165 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
7166}
7167
7168// r = "x^2/R mod m"; x != r
7169function montSqrTo(x, r) {
7170 x.squareTo(r)
7171 this.reduce(r)
7172}
7173
7174// r = "xy/R mod m"; x,y != r
7175function montMulTo(x, y, r) {
7176 x.multiplyTo(y, r)
7177 this.reduce(r)
7178}
7179
7180Montgomery.prototype.convert = montConvert
7181Montgomery.prototype.revert = montRevert
7182Montgomery.prototype.reduce = montReduce
7183Montgomery.prototype.mulTo = montMulTo
7184Montgomery.prototype.sqrTo = montSqrTo
7185
7186// (protected) true iff this is even
7187function bnpIsEven() {
7188 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
7189}
7190
7191// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
7192function bnpExp(e, z) {
7193 if (e > 0xffffffff || e < 1) return BigInteger.ONE
7194 var r = new BigInteger(),
7195 r2 = new BigInteger(),
7196 g = z.convert(this),
7197 i = nbits(e) - 1
7198 g.copyTo(r)
7199 while (--i >= 0) {
7200 z.sqrTo(r, r2)
7201 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
7202 else {
7203 var t = r
7204 r = r2
7205 r2 = t
7206 }
7207 }
7208 return z.revert(r)
7209}
7210
7211// (public) this^e % m, 0 <= e < 2^32
7212function bnModPowInt(e, m) {
7213 var z
7214 if (e < 256 || m.isEven()) z = new Classic(m)
7215 else z = new Montgomery(m)
7216 return this.exp(e, z)
7217}
7218
7219// protected
7220proto.copyTo = bnpCopyTo
7221proto.fromInt = bnpFromInt
7222proto.fromString = bnpFromString
7223proto.clamp = bnpClamp
7224proto.dlShiftTo = bnpDLShiftTo
7225proto.drShiftTo = bnpDRShiftTo
7226proto.lShiftTo = bnpLShiftTo
7227proto.rShiftTo = bnpRShiftTo
7228proto.subTo = bnpSubTo
7229proto.multiplyTo = bnpMultiplyTo
7230proto.squareTo = bnpSquareTo
7231proto.divRemTo = bnpDivRemTo
7232proto.invDigit = bnpInvDigit
7233proto.isEven = bnpIsEven
7234proto.exp = bnpExp
7235
7236// public
7237proto.toString = bnToString
7238proto.negate = bnNegate
7239proto.abs = bnAbs
7240proto.compareTo = bnCompareTo
7241proto.bitLength = bnBitLength
7242proto.byteLength = bnByteLength
7243proto.mod = bnMod
7244proto.modPowInt = bnModPowInt
7245
7246// (public)
7247function bnClone() {
7248 var r = new BigInteger()
7249 this.copyTo(r)
7250 return r
7251}
7252
7253// (public) return value as integer
7254function bnIntValue() {
7255 if (this.s < 0) {
7256 if (this.t == 1) return this[0] - this.DV
7257 else if (this.t == 0) return -1
7258 } else if (this.t == 1) return this[0]
7259 else if (this.t == 0) return 0
7260 // assumes 16 < DB < 32
7261 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
7262}
7263
7264// (public) return value as byte
7265function bnByteValue() {
7266 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
7267}
7268
7269// (public) return value as short (assumes DB>=16)
7270function bnShortValue() {
7271 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
7272}
7273
7274// (protected) return x s.t. r^x < DV
7275function bnpChunkSize(r) {
7276 return Math.floor(Math.LN2 * this.DB / Math.log(r))
7277}
7278
7279// (public) 0 if this == 0, 1 if this > 0
7280function bnSigNum() {
7281 if (this.s < 0) return -1
7282 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
7283 else return 1
7284}
7285
7286// (protected) convert to radix string
7287function bnpToRadix(b) {
7288 if (b == null) b = 10
7289 if (this.signum() == 0 || b < 2 || b > 36) return "0"
7290 var cs = this.chunkSize(b)
7291 var a = Math.pow(b, cs)
7292 var d = nbv(a),
7293 y = new BigInteger(),
7294 z = new BigInteger(),
7295 r = ""
7296 this.divRemTo(d, y, z)
7297 while (y.signum() > 0) {
7298 r = (a + z.intValue())
7299 .toString(b)
7300 .substr(1) + r
7301 y.divRemTo(d, y, z)
7302 }
7303 return z.intValue()
7304 .toString(b) + r
7305}
7306
7307// (protected) convert from radix string
7308function bnpFromRadix(s, b) {
7309 var self = this
7310 self.fromInt(0)
7311 if (b == null) b = 10
7312 var cs = self.chunkSize(b)
7313 var d = Math.pow(b, cs),
7314 mi = false,
7315 j = 0,
7316 w = 0
7317 for (var i = 0; i < s.length; ++i) {
7318 var x = intAt(s, i)
7319 if (x < 0) {
7320 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
7321 continue
7322 }
7323 w = b * w + x
7324 if (++j >= cs) {
7325 self.dMultiply(d)
7326 self.dAddOffset(w, 0)
7327 j = 0
7328 w = 0
7329 }
7330 }
7331 if (j > 0) {
7332 self.dMultiply(Math.pow(b, j))
7333 self.dAddOffset(w, 0)
7334 }
7335 if (mi) BigInteger.ZERO.subTo(self, self)
7336}
7337
7338// (protected) alternate constructor
7339function bnpFromNumber(a, b, c) {
7340 var self = this
7341 if ("number" == typeof b) {
7342 // new BigInteger(int,int,RNG)
7343 if (a < 2) self.fromInt(1)
7344 else {
7345 self.fromNumber(a, c)
7346 if (!self.testBit(a - 1)) // force MSB set
7347 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
7348 if (self.isEven()) self.dAddOffset(1, 0); // force odd
7349 while (!self.isProbablePrime(b)) {
7350 self.dAddOffset(2, 0)
7351 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
7352 }
7353 }
7354 } else {
7355 // new BigInteger(int,RNG)
7356 var x = new Array(),
7357 t = a & 7
7358 x.length = (a >> 3) + 1
7359 b.nextBytes(x)
7360 if (t > 0) x[0] &= ((1 << t) - 1)
7361 else x[0] = 0
7362 self.fromString(x, 256)
7363 }
7364}
7365
7366// (public) convert to bigendian byte array
7367function bnToByteArray() {
7368 var self = this
7369 var i = self.t,
7370 r = new Array()
7371 r[0] = self.s
7372 var p = self.DB - (i * self.DB) % 8,
7373 d, k = 0
7374 if (i-- > 0) {
7375 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
7376 r[k++] = d | (self.s << (self.DB - p))
7377 while (i >= 0) {
7378 if (p < 8) {
7379 d = (self[i] & ((1 << p) - 1)) << (8 - p)
7380 d |= self[--i] >> (p += self.DB - 8)
7381 } else {
7382 d = (self[i] >> (p -= 8)) & 0xff
7383 if (p <= 0) {
7384 p += self.DB
7385 --i
7386 }
7387 }
7388 if ((d & 0x80) != 0) d |= -256
7389 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
7390 if (k > 0 || d != self.s) r[k++] = d
7391 }
7392 }
7393 return r
7394}
7395
7396function bnEquals(a) {
7397 return (this.compareTo(a) == 0)
7398}
7399
7400function bnMin(a) {
7401 return (this.compareTo(a) < 0) ? this : a
7402}
7403
7404function bnMax(a) {
7405 return (this.compareTo(a) > 0) ? this : a
7406}
7407
7408// (protected) r = this op a (bitwise)
7409function bnpBitwiseTo(a, op, r) {
7410 var self = this
7411 var i, f, m = Math.min(a.t, self.t)
7412 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
7413 if (a.t < self.t) {
7414 f = a.s & self.DM
7415 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
7416 r.t = self.t
7417 } else {
7418 f = self.s & self.DM
7419 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
7420 r.t = a.t
7421 }
7422 r.s = op(self.s, a.s)
7423 r.clamp()
7424}
7425
7426// (public) this & a
7427function op_and(x, y) {
7428 return x & y
7429}
7430
7431function bnAnd(a) {
7432 var r = new BigInteger()
7433 this.bitwiseTo(a, op_and, r)
7434 return r
7435}
7436
7437// (public) this | a
7438function op_or(x, y) {
7439 return x | y
7440}
7441
7442function bnOr(a) {
7443 var r = new BigInteger()
7444 this.bitwiseTo(a, op_or, r)
7445 return r
7446}
7447
7448// (public) this ^ a
7449function op_xor(x, y) {
7450 return x ^ y
7451}
7452
7453function bnXor(a) {
7454 var r = new BigInteger()
7455 this.bitwiseTo(a, op_xor, r)
7456 return r
7457}
7458
7459// (public) this & ~a
7460function op_andnot(x, y) {
7461 return x & ~y
7462}
7463
7464function bnAndNot(a) {
7465 var r = new BigInteger()
7466 this.bitwiseTo(a, op_andnot, r)
7467 return r
7468}
7469
7470// (public) ~this
7471function bnNot() {
7472 var r = new BigInteger()
7473 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
7474 r.t = this.t
7475 r.s = ~this.s
7476 return r
7477}
7478
7479// (public) this << n
7480function bnShiftLeft(n) {
7481 var r = new BigInteger()
7482 if (n < 0) this.rShiftTo(-n, r)
7483 else this.lShiftTo(n, r)
7484 return r
7485}
7486
7487// (public) this >> n
7488function bnShiftRight(n) {
7489 var r = new BigInteger()
7490 if (n < 0) this.lShiftTo(-n, r)
7491 else this.rShiftTo(n, r)
7492 return r
7493}
7494
7495// return index of lowest 1-bit in x, x < 2^31
7496function lbit(x) {
7497 if (x == 0) return -1
7498 var r = 0
7499 if ((x & 0xffff) == 0) {
7500 x >>= 16
7501 r += 16
7502 }
7503 if ((x & 0xff) == 0) {
7504 x >>= 8
7505 r += 8
7506 }
7507 if ((x & 0xf) == 0) {
7508 x >>= 4
7509 r += 4
7510 }
7511 if ((x & 3) == 0) {
7512 x >>= 2
7513 r += 2
7514 }
7515 if ((x & 1) == 0)++r
7516 return r
7517}
7518
7519// (public) returns index of lowest 1-bit (or -1 if none)
7520function bnGetLowestSetBit() {
7521 for (var i = 0; i < this.t; ++i)
7522 if (this[i] != 0) return i * this.DB + lbit(this[i])
7523 if (this.s < 0) return this.t * this.DB
7524 return -1
7525}
7526
7527// return number of 1 bits in x
7528function cbit(x) {
7529 var r = 0
7530 while (x != 0) {
7531 x &= x - 1
7532 ++r
7533 }
7534 return r
7535}
7536
7537// (public) return number of set bits
7538function bnBitCount() {
7539 var r = 0,
7540 x = this.s & this.DM
7541 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
7542 return r
7543}
7544
7545// (public) true iff nth bit is set
7546function bnTestBit(n) {
7547 var j = Math.floor(n / this.DB)
7548 if (j >= this.t) return (this.s != 0)
7549 return ((this[j] & (1 << (n % this.DB))) != 0)
7550}
7551
7552// (protected) this op (1<<n)
7553function bnpChangeBit(n, op) {
7554 var r = BigInteger.ONE.shiftLeft(n)
7555 this.bitwiseTo(r, op, r)
7556 return r
7557}
7558
7559// (public) this | (1<<n)
7560function bnSetBit(n) {
7561 return this.changeBit(n, op_or)
7562}
7563
7564// (public) this & ~(1<<n)
7565function bnClearBit(n) {
7566 return this.changeBit(n, op_andnot)
7567}
7568
7569// (public) this ^ (1<<n)
7570function bnFlipBit(n) {
7571 return this.changeBit(n, op_xor)
7572}
7573
7574// (protected) r = this + a
7575function bnpAddTo(a, r) {
7576 var self = this
7577
7578 var i = 0,
7579 c = 0,
7580 m = Math.min(a.t, self.t)
7581 while (i < m) {
7582 c += self[i] + a[i]
7583 r[i++] = c & self.DM
7584 c >>= self.DB
7585 }
7586 if (a.t < self.t) {
7587 c += a.s
7588 while (i < self.t) {
7589 c += self[i]
7590 r[i++] = c & self.DM
7591 c >>= self.DB
7592 }
7593 c += self.s
7594 } else {
7595 c += self.s
7596 while (i < a.t) {
7597 c += a[i]
7598 r[i++] = c & self.DM
7599 c >>= self.DB
7600 }
7601 c += a.s
7602 }
7603 r.s = (c < 0) ? -1 : 0
7604 if (c > 0) r[i++] = c
7605 else if (c < -1) r[i++] = self.DV + c
7606 r.t = i
7607 r.clamp()
7608}
7609
7610// (public) this + a
7611function bnAdd(a) {
7612 var r = new BigInteger()
7613 this.addTo(a, r)
7614 return r
7615}
7616
7617// (public) this - a
7618function bnSubtract(a) {
7619 var r = new BigInteger()
7620 this.subTo(a, r)
7621 return r
7622}
7623
7624// (public) this * a
7625function bnMultiply(a) {
7626 var r = new BigInteger()
7627 this.multiplyTo(a, r)
7628 return r
7629}
7630
7631// (public) this^2
7632function bnSquare() {
7633 var r = new BigInteger()
7634 this.squareTo(r)
7635 return r
7636}
7637
7638// (public) this / a
7639function bnDivide(a) {
7640 var r = new BigInteger()
7641 this.divRemTo(a, r, null)
7642 return r
7643}
7644
7645// (public) this % a
7646function bnRemainder(a) {
7647 var r = new BigInteger()
7648 this.divRemTo(a, null, r)
7649 return r
7650}
7651
7652// (public) [this/a,this%a]
7653function bnDivideAndRemainder(a) {
7654 var q = new BigInteger(),
7655 r = new BigInteger()
7656 this.divRemTo(a, q, r)
7657 return new Array(q, r)
7658}
7659
7660// (protected) this *= n, this >= 0, 1 < n < DV
7661function bnpDMultiply(n) {
7662 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
7663 ++this.t
7664 this.clamp()
7665}
7666
7667// (protected) this += n << w words, this >= 0
7668function bnpDAddOffset(n, w) {
7669 if (n == 0) return
7670 while (this.t <= w) this[this.t++] = 0
7671 this[w] += n
7672 while (this[w] >= this.DV) {
7673 this[w] -= this.DV
7674 if (++w >= this.t) this[this.t++] = 0
7675 ++this[w]
7676 }
7677}
7678
7679// A "null" reducer
7680function NullExp() {}
7681
7682function nNop(x) {
7683 return x
7684}
7685
7686function nMulTo(x, y, r) {
7687 x.multiplyTo(y, r)
7688}
7689
7690function nSqrTo(x, r) {
7691 x.squareTo(r)
7692}
7693
7694NullExp.prototype.convert = nNop
7695NullExp.prototype.revert = nNop
7696NullExp.prototype.mulTo = nMulTo
7697NullExp.prototype.sqrTo = nSqrTo
7698
7699// (public) this^e
7700function bnPow(e) {
7701 return this.exp(e, new NullExp())
7702}
7703
7704// (protected) r = lower n words of "this * a", a.t <= n
7705// "this" should be the larger one if appropriate.
7706function bnpMultiplyLowerTo(a, n, r) {
7707 var i = Math.min(this.t + a.t, n)
7708 r.s = 0; // assumes a,this >= 0
7709 r.t = i
7710 while (i > 0) r[--i] = 0
7711 var j
7712 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
7713 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
7714 r.clamp()
7715}
7716
7717// (protected) r = "this * a" without lower n words, n > 0
7718// "this" should be the larger one if appropriate.
7719function bnpMultiplyUpperTo(a, n, r) {
7720 --n
7721 var i = r.t = this.t + a.t - n
7722 r.s = 0; // assumes a,this >= 0
7723 while (--i >= 0) r[i] = 0
7724 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
7725 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
7726 r.clamp()
7727 r.drShiftTo(1, r)
7728}
7729
7730// Barrett modular reduction
7731function Barrett(m) {
7732 // setup Barrett
7733 this.r2 = new BigInteger()
7734 this.q3 = new BigInteger()
7735 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
7736 this.mu = this.r2.divide(m)
7737 this.m = m
7738}
7739
7740function barrettConvert(x) {
7741 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
7742 else if (x.compareTo(this.m) < 0) return x
7743 else {
7744 var r = new BigInteger()
7745 x.copyTo(r)
7746 this.reduce(r)
7747 return r
7748 }
7749}
7750
7751function barrettRevert(x) {
7752 return x
7753}
7754
7755// x = x mod m (HAC 14.42)
7756function barrettReduce(x) {
7757 var self = this
7758 x.drShiftTo(self.m.t - 1, self.r2)
7759 if (x.t > self.m.t + 1) {
7760 x.t = self.m.t + 1
7761 x.clamp()
7762 }
7763 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
7764 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
7765 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
7766 x.subTo(self.r2, x)
7767 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
7768}
7769
7770// r = x^2 mod m; x != r
7771function barrettSqrTo(x, r) {
7772 x.squareTo(r)
7773 this.reduce(r)
7774}
7775
7776// r = x*y mod m; x,y != r
7777function barrettMulTo(x, y, r) {
7778 x.multiplyTo(y, r)
7779 this.reduce(r)
7780}
7781
7782Barrett.prototype.convert = barrettConvert
7783Barrett.prototype.revert = barrettRevert
7784Barrett.prototype.reduce = barrettReduce
7785Barrett.prototype.mulTo = barrettMulTo
7786Barrett.prototype.sqrTo = barrettSqrTo
7787
7788// (public) this^e % m (HAC 14.85)
7789function bnModPow(e, m) {
7790 var i = e.bitLength(),
7791 k, r = nbv(1),
7792 z
7793 if (i <= 0) return r
7794 else if (i < 18) k = 1
7795 else if (i < 48) k = 3
7796 else if (i < 144) k = 4
7797 else if (i < 768) k = 5
7798 else k = 6
7799 if (i < 8)
7800 z = new Classic(m)
7801 else if (m.isEven())
7802 z = new Barrett(m)
7803 else
7804 z = new Montgomery(m)
7805
7806 // precomputation
7807 var g = new Array(),
7808 n = 3,
7809 k1 = k - 1,
7810 km = (1 << k) - 1
7811 g[1] = z.convert(this)
7812 if (k > 1) {
7813 var g2 = new BigInteger()
7814 z.sqrTo(g[1], g2)
7815 while (n <= km) {
7816 g[n] = new BigInteger()
7817 z.mulTo(g2, g[n - 2], g[n])
7818 n += 2
7819 }
7820 }
7821
7822 var j = e.t - 1,
7823 w, is1 = true,
7824 r2 = new BigInteger(),
7825 t
7826 i = nbits(e[j]) - 1
7827 while (j >= 0) {
7828 if (i >= k1) w = (e[j] >> (i - k1)) & km
7829 else {
7830 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
7831 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
7832 }
7833
7834 n = k
7835 while ((w & 1) == 0) {
7836 w >>= 1
7837 --n
7838 }
7839 if ((i -= n) < 0) {
7840 i += this.DB
7841 --j
7842 }
7843 if (is1) { // ret == 1, don't bother squaring or multiplying it
7844 g[w].copyTo(r)
7845 is1 = false
7846 } else {
7847 while (n > 1) {
7848 z.sqrTo(r, r2)
7849 z.sqrTo(r2, r)
7850 n -= 2
7851 }
7852 if (n > 0) z.sqrTo(r, r2)
7853 else {
7854 t = r
7855 r = r2
7856 r2 = t
7857 }
7858 z.mulTo(r2, g[w], r)
7859 }
7860
7861 while (j >= 0 && (e[j] & (1 << i)) == 0) {
7862 z.sqrTo(r, r2)
7863 t = r
7864 r = r2
7865 r2 = t
7866 if (--i < 0) {
7867 i = this.DB - 1
7868 --j
7869 }
7870 }
7871 }
7872 return z.revert(r)
7873}
7874
7875// (public) gcd(this,a) (HAC 14.54)
7876function bnGCD(a) {
7877 var x = (this.s < 0) ? this.negate() : this.clone()
7878 var y = (a.s < 0) ? a.negate() : a.clone()
7879 if (x.compareTo(y) < 0) {
7880 var t = x
7881 x = y
7882 y = t
7883 }
7884 var i = x.getLowestSetBit(),
7885 g = y.getLowestSetBit()
7886 if (g < 0) return x
7887 if (i < g) g = i
7888 if (g > 0) {
7889 x.rShiftTo(g, x)
7890 y.rShiftTo(g, y)
7891 }
7892 while (x.signum() > 0) {
7893 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
7894 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
7895 if (x.compareTo(y) >= 0) {
7896 x.subTo(y, x)
7897 x.rShiftTo(1, x)
7898 } else {
7899 y.subTo(x, y)
7900 y.rShiftTo(1, y)
7901 }
7902 }
7903 if (g > 0) y.lShiftTo(g, y)
7904 return y
7905}
7906
7907// (protected) this % n, n < 2^26
7908function bnpModInt(n) {
7909 if (n <= 0) return 0
7910 var d = this.DV % n,
7911 r = (this.s < 0) ? n - 1 : 0
7912 if (this.t > 0)
7913 if (d == 0) r = this[0] % n
7914 else
7915 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
7916 return r
7917}
7918
7919// (public) 1/this % m (HAC 14.61)
7920function bnModInverse(m) {
7921 var ac = m.isEven()
7922 if (this.signum() === 0) throw new Error('division by zero')
7923 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO
7924 var u = m.clone(),
7925 v = this.clone()
7926 var a = nbv(1),
7927 b = nbv(0),
7928 c = nbv(0),
7929 d = nbv(1)
7930 while (u.signum() != 0) {
7931 while (u.isEven()) {
7932 u.rShiftTo(1, u)
7933 if (ac) {
7934 if (!a.isEven() || !b.isEven()) {
7935 a.addTo(this, a)
7936 b.subTo(m, b)
7937 }
7938 a.rShiftTo(1, a)
7939 } else if (!b.isEven()) b.subTo(m, b)
7940 b.rShiftTo(1, b)
7941 }
7942 while (v.isEven()) {
7943 v.rShiftTo(1, v)
7944 if (ac) {
7945 if (!c.isEven() || !d.isEven()) {
7946 c.addTo(this, c)
7947 d.subTo(m, d)
7948 }
7949 c.rShiftTo(1, c)
7950 } else if (!d.isEven()) d.subTo(m, d)
7951 d.rShiftTo(1, d)
7952 }
7953 if (u.compareTo(v) >= 0) {
7954 u.subTo(v, u)
7955 if (ac) a.subTo(c, a)
7956 b.subTo(d, b)
7957 } else {
7958 v.subTo(u, v)
7959 if (ac) c.subTo(a, c)
7960 d.subTo(b, d)
7961 }
7962 }
7963 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
7964 while (d.compareTo(m) >= 0) d.subTo(m, d)
7965 while (d.signum() < 0) d.addTo(m, d)
7966 return d
7967}
7968
7969var lowprimes = [
7970 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
7971 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
7972 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
7973 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
7974 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
7975 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
7976 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
7977 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
7978 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
7979 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
7980 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
7981]
7982
7983var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
7984
7985// (public) test primality with certainty >= 1-.5^t
7986function bnIsProbablePrime(t) {
7987 var i, x = this.abs()
7988 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
7989 for (i = 0; i < lowprimes.length; ++i)
7990 if (x[0] == lowprimes[i]) return true
7991 return false
7992 }
7993 if (x.isEven()) return false
7994 i = 1
7995 while (i < lowprimes.length) {
7996 var m = lowprimes[i],
7997 j = i + 1
7998 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
7999 m = x.modInt(m)
8000 while (i < j) if (m % lowprimes[i++] == 0) return false
8001 }
8002 return x.millerRabin(t)
8003}
8004
8005// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
8006function bnpMillerRabin(t) {
8007 var n1 = this.subtract(BigInteger.ONE)
8008 var k = n1.getLowestSetBit()
8009 if (k <= 0) return false
8010 var r = n1.shiftRight(k)
8011 t = (t + 1) >> 1
8012 if (t > lowprimes.length) t = lowprimes.length
8013 var a = new BigInteger(null)
8014 var j, bases = []
8015 for (var i = 0; i < t; ++i) {
8016 for (;;) {
8017 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
8018 if (bases.indexOf(j) == -1) break
8019 }
8020 bases.push(j)
8021 a.fromInt(j)
8022 var y = a.modPow(r, this)
8023 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
8024 var j = 1
8025 while (j++ < k && y.compareTo(n1) != 0) {
8026 y = y.modPowInt(2, this)
8027 if (y.compareTo(BigInteger.ONE) == 0) return false
8028 }
8029 if (y.compareTo(n1) != 0) return false
8030 }
8031 }
8032 return true
8033}
8034
8035// protected
8036proto.chunkSize = bnpChunkSize
8037proto.toRadix = bnpToRadix
8038proto.fromRadix = bnpFromRadix
8039proto.fromNumber = bnpFromNumber
8040proto.bitwiseTo = bnpBitwiseTo
8041proto.changeBit = bnpChangeBit
8042proto.addTo = bnpAddTo
8043proto.dMultiply = bnpDMultiply
8044proto.dAddOffset = bnpDAddOffset
8045proto.multiplyLowerTo = bnpMultiplyLowerTo
8046proto.multiplyUpperTo = bnpMultiplyUpperTo
8047proto.modInt = bnpModInt
8048proto.millerRabin = bnpMillerRabin
8049
8050// public
8051proto.clone = bnClone
8052proto.intValue = bnIntValue
8053proto.byteValue = bnByteValue
8054proto.shortValue = bnShortValue
8055proto.signum = bnSigNum
8056proto.toByteArray = bnToByteArray
8057proto.equals = bnEquals
8058proto.min = bnMin
8059proto.max = bnMax
8060proto.and = bnAnd
8061proto.or = bnOr
8062proto.xor = bnXor
8063proto.andNot = bnAndNot
8064proto.not = bnNot
8065proto.shiftLeft = bnShiftLeft
8066proto.shiftRight = bnShiftRight
8067proto.getLowestSetBit = bnGetLowestSetBit
8068proto.bitCount = bnBitCount
8069proto.testBit = bnTestBit
8070proto.setBit = bnSetBit
8071proto.clearBit = bnClearBit
8072proto.flipBit = bnFlipBit
8073proto.add = bnAdd
8074proto.subtract = bnSubtract
8075proto.multiply = bnMultiply
8076proto.divide = bnDivide
8077proto.remainder = bnRemainder
8078proto.divideAndRemainder = bnDivideAndRemainder
8079proto.modPow = bnModPow
8080proto.modInverse = bnModInverse
8081proto.pow = bnPow
8082proto.gcd = bnGCD
8083proto.isProbablePrime = bnIsProbablePrime
8084
8085// JSBN-specific extension
8086proto.square = bnSquare
8087
8088// constants
8089BigInteger.ZERO = nbv(0)
8090BigInteger.ONE = nbv(1)
8091BigInteger.valueOf = nbv
8092
8093module.exports = BigInteger
8094
8095},{"../package.json":38}],36:[function(require,module,exports){
8096(function (Buffer){
8097// FIXME: Kind of a weird way to throw exceptions, consider removing
8098var assert = require('assert')
8099var BigInteger = require('./bigi')
8100
8101/**
8102 * Turns a byte array into a big integer.
8103 *
8104 * This function will interpret a byte array as a big integer in big
8105 * endian notation.
8106 */
8107BigInteger.fromByteArrayUnsigned = function(byteArray) {
8108 // BigInteger expects a DER integer conformant byte array
8109 if (byteArray[0] & 0x80) {
8110 return new BigInteger([0].concat(byteArray))
8111 }
8112
8113 return new BigInteger(byteArray)
8114}
8115
8116/**
8117 * Returns a byte array representation of the big integer.
8118 *
8119 * This returns the absolute of the contained value in big endian
8120 * form. A value of zero results in an empty array.
8121 */
8122BigInteger.prototype.toByteArrayUnsigned = function() {
8123 var byteArray = this.toByteArray()
8124 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
8125}
8126
8127BigInteger.fromDERInteger = function(byteArray) {
8128 return new BigInteger(byteArray)
8129}
8130
8131/*
8132 * Converts BigInteger to a DER integer representation.
8133 *
8134 * The format for this value uses the most significant bit as a sign
8135 * bit. If the most significant bit is already set and the integer is
8136 * positive, a 0x00 is prepended.
8137 *
8138 * Examples:
8139 *
8140 * 0 => 0x00
8141 * 1 => 0x01
8142 * -1 => 0xff
8143 * 127 => 0x7f
8144 * -127 => 0x81
8145 * 128 => 0x0080
8146 * -128 => 0x80
8147 * 255 => 0x00ff
8148 * -255 => 0xff01
8149 * 16300 => 0x3fac
8150 * -16300 => 0xc054
8151 * 62300 => 0x00f35c
8152 * -62300 => 0xff0ca4
8153*/
8154BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
8155
8156BigInteger.fromBuffer = function(buffer) {
8157 // BigInteger expects a DER integer conformant byte array
8158 if (buffer[0] & 0x80) {
8159 var byteArray = Array.prototype.slice.call(buffer)
8160
8161 return new BigInteger([0].concat(byteArray))
8162 }
8163
8164 return new BigInteger(buffer)
8165}
8166
8167BigInteger.fromHex = function(hex) {
8168 if (hex === '') return BigInteger.ZERO
8169
8170 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
8171 assert.equal(hex.length % 2, 0, 'Incomplete hex')
8172 return new BigInteger(hex, 16)
8173}
8174
8175BigInteger.prototype.toBuffer = function(size) {
8176 var byteArray = this.toByteArrayUnsigned()
8177 var zeros = []
8178
8179 var padding = size - byteArray.length
8180 while (zeros.length < padding) zeros.push(0)
8181
8182 return new Buffer(zeros.concat(byteArray))
8183}
8184
8185BigInteger.prototype.toHex = function(size) {
8186 return this.toBuffer(size).toString('hex')
8187}
8188
8189}).call(this,require("buffer").Buffer)
8190},{"./bigi":35,"assert":1,"buffer":4}],37:[function(require,module,exports){
8191var BigInteger = require('./bigi')
8192
8193//addons
8194require('./convert')
8195
8196module.exports = BigInteger
8197},{"./bigi":35,"./convert":36}],38:[function(require,module,exports){
8198module.exports={
8199 "_args": [
8200 [
8201 "bigi",
8202 "/home/ian/git/bitcoin/bitcoinjs-lib-browser"
8203 ]
8204 ],
8205 "_from": "bigi@latest",
8206 "_id": "bigi@1.4.2",
8207 "_inCache": true,
8208 "_installable": true,
8209 "_location": "/bigi",
8210 "_nodeVersion": "6.1.0",
8211 "_npmOperationalInternal": {
8212 "host": "packages-12-west.internal.npmjs.com",
8213 "tmp": "tmp/bigi-1.4.2.tgz_1469584192413_0.6801238611806184"
8214 },
8215 "_npmUser": {
8216 "email": "jprichardson@gmail.com",
8217 "name": "jprichardson"
8218 },
8219 "_npmVersion": "3.8.6",
8220 "_phantomChildren": {},
8221 "_requested": {
8222 "name": "bigi",
8223 "raw": "bigi",
8224 "rawSpec": "",
8225 "scope": null,
8226 "spec": "latest",
8227 "type": "tag"
8228 },
8229 "_requiredBy": [
8230 "#USER",
8231 "/bitcoinjs-lib",
8232 "/ecurve"
8233 ],
8234 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz",
8235 "_shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
8236 "_shrinkwrap": null,
8237 "_spec": "bigi",
8238 "_where": "/home/ian/git/bitcoin/bitcoinjs-lib-browser",
8239 "bugs": {
8240 "url": "https://github.com/cryptocoinjs/bigi/issues"
8241 },
8242 "dependencies": {},
8243 "description": "Big integers.",
8244 "devDependencies": {
8245 "coveralls": "^2.11.2",
8246 "istanbul": "^0.3.5",
8247 "jshint": "^2.5.1",
8248 "mocha": "^2.1.0",
8249 "mochify": "^2.1.0"
8250 },
8251 "directories": {},
8252 "dist": {
8253 "shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
8254 "tarball": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz"
8255 },
8256 "gitHead": "c25308081c896ff84702303722bf5ecd8b3f78e3",
8257 "homepage": "https://github.com/cryptocoinjs/bigi#readme",
8258 "keywords": [
8259 "cryptography",
8260 "math",
8261 "bitcoin",
8262 "arbitrary",
8263 "precision",
8264 "arithmetic",
8265 "big",
8266 "integer",
8267 "int",
8268 "number",
8269 "biginteger",
8270 "bigint",
8271 "bignumber",
8272 "decimal",
8273 "float"
8274 ],
8275 "main": "./lib/index.js",
8276 "maintainers": [
8277 {
8278 "email": "boydb@midnightdesign.ws",
8279 "name": "midnightlightning"
8280 },
8281 {
8282 "email": "sidazhang89@gmail.com",
8283 "name": "sidazhang"
8284 },
8285 {
8286 "email": "npm@shesek.info",
8287 "name": "nadav"
8288 },
8289 {
8290 "email": "jprichardson@gmail.com",
8291 "name": "jprichardson"
8292 }
8293 ],
8294 "name": "bigi",
8295 "optionalDependencies": {},
8296 "readme": "ERROR: No README data found!",
8297 "repository": {
8298 "type": "git",
8299 "url": "git+https://github.com/cryptocoinjs/bigi.git"
8300 },
8301 "scripts": {
8302 "browser-test": "mochify --wd -R spec",
8303 "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
8304 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info",
8305 "jshint": "jshint --config jshint.json lib/*.js ; true",
8306 "test": "_mocha -- test/*.js",
8307 "unit": "mocha"
8308 },
8309 "testling": {
8310 "browsers": [
8311 "ie/9..latest",
8312 "firefox/latest",
8313 "chrome/latest",
8314 "safari/6.0..latest",
8315 "iphone/6.0..latest",
8316 "android-browser/4.2..latest"
8317 ],
8318 "files": "test/*.js",
8319 "harness": "mocha"
8320 },
8321 "version": "1.4.2"
8322}
8323
8324},{}],39:[function(require,module,exports){
8325// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
8326// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
8327// NOTE: SIGHASH byte ignored AND restricted, truncate before use
8328
8329var Buffer = require('safe-buffer').Buffer
8330
8331function check (buffer) {
8332 if (buffer.length < 8) return false
8333 if (buffer.length > 72) return false
8334 if (buffer[0] !== 0x30) return false
8335 if (buffer[1] !== buffer.length - 2) return false
8336 if (buffer[2] !== 0x02) return false
8337
8338 var lenR = buffer[3]
8339 if (lenR === 0) return false
8340 if (5 + lenR >= buffer.length) return false
8341 if (buffer[4 + lenR] !== 0x02) return false
8342
8343 var lenS = buffer[5 + lenR]
8344 if (lenS === 0) return false
8345 if ((6 + lenR + lenS) !== buffer.length) return false
8346
8347 if (buffer[4] & 0x80) return false
8348 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false
8349
8350 if (buffer[lenR + 6] & 0x80) return false
8351 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false
8352 return true
8353}
8354
8355function decode (buffer) {
8356 if (buffer.length < 8) throw new Error('DER sequence length is too short')
8357 if (buffer.length > 72) throw new Error('DER sequence length is too long')
8358 if (buffer[0] !== 0x30) throw new Error('Expected DER sequence')
8359 if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid')
8360 if (buffer[2] !== 0x02) throw new Error('Expected DER integer')
8361
8362 var lenR = buffer[3]
8363 if (lenR === 0) throw new Error('R length is zero')
8364 if (5 + lenR >= buffer.length) throw new Error('R length is too long')
8365 if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)')
8366
8367 var lenS = buffer[5 + lenR]
8368 if (lenS === 0) throw new Error('S length is zero')
8369 if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid')
8370
8371 if (buffer[4] & 0x80) throw new Error('R value is negative')
8372 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded')
8373
8374 if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative')
8375 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded')
8376
8377 // non-BIP66 - extract R, S values
8378 return {
8379 r: buffer.slice(4, 4 + lenR),
8380 s: buffer.slice(6 + lenR)
8381 }
8382}
8383
8384/*
8385 * Expects r and s to be positive DER integers.
8386 *
8387 * The DER format uses the most significant bit as a sign bit (& 0x80).
8388 * If the significant bit is set AND the integer is positive, a 0x00 is prepended.
8389 *
8390 * Examples:
8391 *
8392 * 0 => 0x00
8393 * 1 => 0x01
8394 * -1 => 0xff
8395 * 127 => 0x7f
8396 * -127 => 0x81
8397 * 128 => 0x0080
8398 * -128 => 0x80
8399 * 255 => 0x00ff
8400 * -255 => 0xff01
8401 * 16300 => 0x3fac
8402 * -16300 => 0xc054
8403 * 62300 => 0x00f35c
8404 * -62300 => 0xff0ca4
8405*/
8406function encode (r, s) {
8407 var lenR = r.length
8408 var lenS = s.length
8409 if (lenR === 0) throw new Error('R length is zero')
8410 if (lenS === 0) throw new Error('S length is zero')
8411 if (lenR > 33) throw new Error('R length is too long')
8412 if (lenS > 33) throw new Error('S length is too long')
8413 if (r[0] & 0x80) throw new Error('R value is negative')
8414 if (s[0] & 0x80) throw new Error('S value is negative')
8415 if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded')
8416 if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded')
8417
8418 var signature = Buffer.allocUnsafe(6 + lenR + lenS)
8419
8420 // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
8421 signature[0] = 0x30
8422 signature[1] = signature.length - 2
8423 signature[2] = 0x02
8424 signature[3] = r.length
8425 r.copy(signature, 4)
8426 signature[4 + lenR] = 0x02
8427 signature[5 + lenR] = s.length
8428 s.copy(signature, 6 + lenR)
8429
8430 return signature
8431}
8432
8433module.exports = {
8434 check: check,
8435 decode: decode,
8436 encode: encode
8437}
8438
8439},{"safe-buffer":98}],40:[function(require,module,exports){
8440module.exports={
8441 "OP_FALSE": 0,
8442 "OP_0": 0,
8443 "OP_PUSHDATA1": 76,
8444 "OP_PUSHDATA2": 77,
8445 "OP_PUSHDATA4": 78,
8446 "OP_1NEGATE": 79,
8447 "OP_RESERVED": 80,
8448 "OP_1": 81,
8449 "OP_TRUE": 81,
8450 "OP_2": 82,
8451 "OP_3": 83,
8452 "OP_4": 84,
8453 "OP_5": 85,
8454 "OP_6": 86,
8455 "OP_7": 87,
8456 "OP_8": 88,
8457 "OP_9": 89,
8458 "OP_10": 90,
8459 "OP_11": 91,
8460 "OP_12": 92,
8461 "OP_13": 93,
8462 "OP_14": 94,
8463 "OP_15": 95,
8464 "OP_16": 96,
8465
8466 "OP_NOP": 97,
8467 "OP_VER": 98,
8468 "OP_IF": 99,
8469 "OP_NOTIF": 100,
8470 "OP_VERIF": 101,
8471 "OP_VERNOTIF": 102,
8472 "OP_ELSE": 103,
8473 "OP_ENDIF": 104,
8474 "OP_VERIFY": 105,
8475 "OP_RETURN": 106,
8476
8477 "OP_TOALTSTACK": 107,
8478 "OP_FROMALTSTACK": 108,
8479 "OP_2DROP": 109,
8480 "OP_2DUP": 110,
8481 "OP_3DUP": 111,
8482 "OP_2OVER": 112,
8483 "OP_2ROT": 113,
8484 "OP_2SWAP": 114,
8485 "OP_IFDUP": 115,
8486 "OP_DEPTH": 116,
8487 "OP_DROP": 117,
8488 "OP_DUP": 118,
8489 "OP_NIP": 119,
8490 "OP_OVER": 120,
8491 "OP_PICK": 121,
8492 "OP_ROLL": 122,
8493 "OP_ROT": 123,
8494 "OP_SWAP": 124,
8495 "OP_TUCK": 125,
8496
8497 "OP_CAT": 126,
8498 "OP_SUBSTR": 127,
8499 "OP_LEFT": 128,
8500 "OP_RIGHT": 129,
8501 "OP_SIZE": 130,
8502
8503 "OP_INVERT": 131,
8504 "OP_AND": 132,
8505 "OP_OR": 133,
8506 "OP_XOR": 134,
8507 "OP_EQUAL": 135,
8508 "OP_EQUALVERIFY": 136,
8509 "OP_RESERVED1": 137,
8510 "OP_RESERVED2": 138,
8511
8512 "OP_1ADD": 139,
8513 "OP_1SUB": 140,
8514 "OP_2MUL": 141,
8515 "OP_2DIV": 142,
8516 "OP_NEGATE": 143,
8517 "OP_ABS": 144,
8518 "OP_NOT": 145,
8519 "OP_0NOTEQUAL": 146,
8520 "OP_ADD": 147,
8521 "OP_SUB": 148,
8522 "OP_MUL": 149,
8523 "OP_DIV": 150,
8524 "OP_MOD": 151,
8525 "OP_LSHIFT": 152,
8526 "OP_RSHIFT": 153,
8527
8528 "OP_BOOLAND": 154,
8529 "OP_BOOLOR": 155,
8530 "OP_NUMEQUAL": 156,
8531 "OP_NUMEQUALVERIFY": 157,
8532 "OP_NUMNOTEQUAL": 158,
8533 "OP_LESSTHAN": 159,
8534 "OP_GREATERTHAN": 160,
8535 "OP_LESSTHANOREQUAL": 161,
8536 "OP_GREATERTHANOREQUAL": 162,
8537 "OP_MIN": 163,
8538 "OP_MAX": 164,
8539
8540 "OP_WITHIN": 165,
8541
8542 "OP_RIPEMD160": 166,
8543 "OP_SHA1": 167,
8544 "OP_SHA256": 168,
8545 "OP_HASH160": 169,
8546 "OP_HASH256": 170,
8547 "OP_CODESEPARATOR": 171,
8548 "OP_CHECKSIG": 172,
8549 "OP_CHECKSIGVERIFY": 173,
8550 "OP_CHECKMULTISIG": 174,
8551 "OP_CHECKMULTISIGVERIFY": 175,
8552
8553 "OP_NOP1": 176,
8554 "OP_NOP2": 177,
8555 "OP_CHECKLOCKTIMEVERIFY": 177,
8556
8557 "OP_NOP3": 178,
8558 "OP_NOP4": 179,
8559 "OP_NOP5": 180,
8560 "OP_NOP6": 181,
8561 "OP_NOP7": 182,
8562 "OP_NOP8": 183,
8563 "OP_NOP9": 184,
8564 "OP_NOP10": 185,
8565
8566 "OP_PUBKEYHASH": 253,
8567 "OP_PUBKEY": 254,
8568 "OP_INVALIDOPCODE": 255
8569}
8570
8571},{}],41:[function(require,module,exports){
8572var OPS = require('./index.json')
8573
8574var map = {}
8575for (var op in OPS) {
8576 var code = OPS[op]
8577 map[code] = op
8578}
8579
8580module.exports = map
8581
8582},{"./index.json":40}],42:[function(require,module,exports){
8583var Buffer = require('safe-buffer').Buffer
8584var bs58check = require('bs58check')
8585var bscript = require('./script')
8586var networks = require('./networks')
8587var typeforce = require('typeforce')
8588var types = require('./types')
8589
8590function fromBase58Check (address) {
8591 var payload = bs58check.decode(address)
8592 if (payload.length < 21) throw new TypeError(address + ' is too short')
8593 if (payload.length > 21) throw new TypeError(address + ' is too long')
8594
8595 var version = payload.readUInt8(0)
8596 var hash = payload.slice(1)
8597
8598 return { hash: hash, version: version }
8599}
8600
8601function toBase58Check (hash, version) {
8602 typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments)
8603
8604 var payload = Buffer.allocUnsafe(21)
8605 payload.writeUInt8(version, 0)
8606 hash.copy(payload, 1)
8607
8608 return bs58check.encode(payload)
8609}
8610
8611function fromOutputScript (outputScript, network) {
8612 network = network || networks.bitcoin
8613
8614 if (bscript.pubKeyHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(3, 23), network.pubKeyHash)
8615 if (bscript.scriptHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(2, 22), network.scriptHash)
8616
8617 throw new Error(bscript.toASM(outputScript) + ' has no matching Address')
8618}
8619
8620function toOutputScript (address, network) {
8621 network = network || networks.bitcoin
8622
8623 var decode = fromBase58Check(address)
8624 if (decode.version === network.pubKeyHash) return bscript.pubKeyHash.output.encode(decode.hash)
8625 if (decode.version === network.scriptHash) return bscript.scriptHash.output.encode(decode.hash)
8626
8627 throw new Error(address + ' has no matching Script')
8628}
8629
8630module.exports = {
8631 fromBase58Check: fromBase58Check,
8632 fromOutputScript: fromOutputScript,
8633 toBase58Check: toBase58Check,
8634 toOutputScript: toOutputScript
8635}
8636
8637},{"./networks":51,"./script":52,"./types":78,"bs58check":80,"safe-buffer":98,"typeforce":109}],43:[function(require,module,exports){
8638var Buffer = require('safe-buffer').Buffer
8639var bcrypto = require('./crypto')
8640var fastMerkleRoot = require('merkle-lib/fastRoot')
8641var typeforce = require('typeforce')
8642var types = require('./types')
8643var varuint = require('varuint-bitcoin')
8644
8645var Transaction = require('./transaction')
8646
8647function Block () {
8648 this.version = 1
8649 this.prevHash = null
8650 this.merkleRoot = null
8651 this.timestamp = 0
8652 this.bits = 0
8653 this.nonce = 0
8654}
8655
8656Block.fromBuffer = function (buffer) {
8657 if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)')
8658
8659 var offset = 0
8660 function readSlice (n) {
8661 offset += n
8662 return buffer.slice(offset - n, offset)
8663 }
8664
8665 function readUInt32 () {
8666 var i = buffer.readUInt32LE(offset)
8667 offset += 4
8668 return i
8669 }
8670
8671 function readInt32 () {
8672 var i = buffer.readInt32LE(offset)
8673 offset += 4
8674 return i
8675 }
8676
8677 var block = new Block()
8678 block.version = readInt32()
8679 block.prevHash = readSlice(32)
8680 block.merkleRoot = readSlice(32)
8681 block.timestamp = readUInt32()
8682 block.bits = readUInt32()
8683 block.nonce = readUInt32()
8684
8685 if (buffer.length === 80) return block
8686
8687 function readVarInt () {
8688 var vi = varuint.decode(buffer, offset)
8689 offset += varuint.decode.bytes
8690 return vi
8691 }
8692
8693 function readTransaction () {
8694 var tx = Transaction.fromBuffer(buffer.slice(offset), true)
8695 offset += tx.byteLength()
8696 return tx
8697 }
8698
8699 var nTransactions = readVarInt()
8700 block.transactions = []
8701
8702 for (var i = 0; i < nTransactions; ++i) {
8703 var tx = readTransaction()
8704 block.transactions.push(tx)
8705 }
8706
8707 return block
8708}
8709
8710Block.prototype.byteLength = function (headersOnly) {
8711 if (headersOnly || !this.transactions) return 80
8712
8713 return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) {
8714 return a + x.byteLength()
8715 }, 0)
8716}
8717
8718Block.fromHex = function (hex) {
8719 return Block.fromBuffer(Buffer.from(hex, 'hex'))
8720}
8721
8722Block.prototype.getHash = function () {
8723 return bcrypto.hash256(this.toBuffer(true))
8724}
8725
8726Block.prototype.getId = function () {
8727 return this.getHash().reverse().toString('hex')
8728}
8729
8730Block.prototype.getUTCDate = function () {
8731 var date = new Date(0) // epoch
8732 date.setUTCSeconds(this.timestamp)
8733
8734 return date
8735}
8736
8737// TODO: buffer, offset compatibility
8738Block.prototype.toBuffer = function (headersOnly) {
8739 var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly))
8740
8741 var offset = 0
8742 function writeSlice (slice) {
8743 slice.copy(buffer, offset)
8744 offset += slice.length
8745 }
8746
8747 function writeInt32 (i) {
8748 buffer.writeInt32LE(i, offset)
8749 offset += 4
8750 }
8751 function writeUInt32 (i) {
8752 buffer.writeUInt32LE(i, offset)
8753 offset += 4
8754 }
8755
8756 writeInt32(this.version)
8757 writeSlice(this.prevHash)
8758 writeSlice(this.merkleRoot)
8759 writeUInt32(this.timestamp)
8760 writeUInt32(this.bits)
8761 writeUInt32(this.nonce)
8762
8763 if (headersOnly || !this.transactions) return buffer
8764
8765 varuint.encode(this.transactions.length, buffer, offset)
8766 offset += varuint.encode.bytes
8767
8768 this.transactions.forEach(function (tx) {
8769 var txSize = tx.byteLength() // TODO: extract from toBuffer?
8770 tx.toBuffer(buffer, offset)
8771 offset += txSize
8772 })
8773
8774 return buffer
8775}
8776
8777Block.prototype.toHex = function (headersOnly) {
8778 return this.toBuffer(headersOnly).toString('hex')
8779}
8780
8781Block.calculateTarget = function (bits) {
8782 var exponent = ((bits & 0xff000000) >> 24) - 3
8783 var mantissa = bits & 0x007fffff
8784 var target = Buffer.alloc(32, 0)
8785 target.writeUInt32BE(mantissa, 28 - exponent)
8786 return target
8787}
8788
8789Block.calculateMerkleRoot = function (transactions) {
8790 typeforce([{ getHash: types.Function }], transactions)
8791 if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions')
8792
8793 var hashes = transactions.map(function (transaction) {
8794 return transaction.getHash()
8795 })
8796
8797 return fastMerkleRoot(hashes, bcrypto.hash256)
8798}
8799
8800Block.prototype.checkMerkleRoot = function () {
8801 if (!this.transactions) return false
8802
8803 var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions)
8804 return this.merkleRoot.compare(actualMerkleRoot) === 0
8805}
8806
8807Block.prototype.checkProofOfWork = function () {
8808 var hash = this.getHash().reverse()
8809 var target = Block.calculateTarget(this.bits)
8810
8811 return hash.compare(target) <= 0
8812}
8813
8814module.exports = Block
8815
8816},{"./crypto":45,"./transaction":76,"./types":78,"merkle-lib/fastRoot":94,"safe-buffer":98,"typeforce":109,"varuint-bitcoin":111}],44:[function(require,module,exports){
8817var pushdata = require('pushdata-bitcoin')
8818var varuint = require('varuint-bitcoin')
8819
8820// https://github.com/feross/buffer/blob/master/index.js#L1127
8821function verifuint (value, max) {
8822 if (typeof value !== 'number') throw new Error('cannot write a non-number as a number')
8823 if (value < 0) throw new Error('specified a negative value for writing an unsigned value')
8824 if (value > max) throw new Error('RangeError: value out of range')
8825 if (Math.floor(value) !== value) throw new Error('value has a fractional component')
8826}
8827
8828function readUInt64LE (buffer, offset) {
8829 var a = buffer.readUInt32LE(offset)
8830 var b = buffer.readUInt32LE(offset + 4)
8831 b *= 0x100000000
8832
8833 verifuint(b + a, 0x001fffffffffffff)
8834
8835 return b + a
8836}
8837
8838function writeUInt64LE (buffer, value, offset) {
8839 verifuint(value, 0x001fffffffffffff)
8840
8841 buffer.writeInt32LE(value & -1, offset)
8842 buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4)
8843 return offset + 8
8844}
8845
8846// TODO: remove in 4.0.0?
8847function readVarInt (buffer, offset) {
8848 var result = varuint.decode(buffer, offset)
8849
8850 return {
8851 number: result,
8852 size: varuint.decode.bytes
8853 }
8854}
8855
8856// TODO: remove in 4.0.0?
8857function writeVarInt (buffer, number, offset) {
8858 varuint.encode(number, buffer, offset)
8859 return varuint.encode.bytes
8860}
8861
8862module.exports = {
8863 pushDataSize: pushdata.encodingLength,
8864 readPushDataInt: pushdata.decode,
8865 readUInt64LE: readUInt64LE,
8866 readVarInt: readVarInt,
8867 varIntBuffer: varuint.encode,
8868 varIntSize: varuint.encodingLength,
8869 writePushDataInt: pushdata.encode,
8870 writeUInt64LE: writeUInt64LE,
8871 writeVarInt: writeVarInt
8872}
8873
8874},{"pushdata-bitcoin":95,"varuint-bitcoin":111}],45:[function(require,module,exports){
8875var createHash = require('create-hash')
8876
8877function ripemd160 (buffer) {
8878 return createHash('rmd160').update(buffer).digest()
8879}
8880
8881function sha1 (buffer) {
8882 return createHash('sha1').update(buffer).digest()
8883}
8884
8885function sha256 (buffer) {
8886 return createHash('sha256').update(buffer).digest()
8887}
8888
8889function hash160 (buffer) {
8890 return ripemd160(sha256(buffer))
8891}
8892
8893function hash256 (buffer) {
8894 return sha256(sha256(buffer))
8895}
8896
8897module.exports = {
8898 hash160: hash160,
8899 hash256: hash256,
8900 ripemd160: ripemd160,
8901 sha1: sha1,
8902 sha256: sha256
8903}
8904
8905},{"create-hash":82}],46:[function(require,module,exports){
8906var Buffer = require('safe-buffer').Buffer
8907var createHmac = require('create-hmac')
8908var typeforce = require('typeforce')
8909var types = require('./types')
8910
8911var BigInteger = require('bigi')
8912var ECSignature = require('./ecsignature')
8913
8914var ZERO = Buffer.alloc(1, 0)
8915var ONE = Buffer.alloc(1, 1)
8916
8917var ecurve = require('ecurve')
8918var secp256k1 = ecurve.getCurveByName('secp256k1')
8919
8920// https://tools.ietf.org/html/rfc6979#section-3.2
8921function deterministicGenerateK (hash, x, checkSig) {
8922 typeforce(types.tuple(
8923 types.Hash256bit,
8924 types.Buffer256bit,
8925 types.Function
8926 ), arguments)
8927
8928 // Step A, ignored as hash already provided
8929 // Step B
8930 // Step C
8931 var k = Buffer.alloc(32, 0)
8932 var v = Buffer.alloc(32, 1)
8933
8934 // Step D
8935 k = createHmac('sha256', k)
8936 .update(v)
8937 .update(ZERO)
8938 .update(x)
8939 .update(hash)
8940 .digest()
8941
8942 // Step E
8943 v = createHmac('sha256', k).update(v).digest()
8944
8945 // Step F
8946 k = createHmac('sha256', k)
8947 .update(v)
8948 .update(ONE)
8949 .update(x)
8950 .update(hash)
8951 .digest()
8952
8953 // Step G
8954 v = createHmac('sha256', k).update(v).digest()
8955
8956 // Step H1/H2a, ignored as tlen === qlen (256 bit)
8957 // Step H2b
8958 v = createHmac('sha256', k).update(v).digest()
8959
8960 var T = BigInteger.fromBuffer(v)
8961
8962 // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA
8963 while (T.signum() <= 0 || T.compareTo(secp256k1.n) >= 0 || !checkSig(T)) {
8964 k = createHmac('sha256', k)
8965 .update(v)
8966 .update(ZERO)
8967 .digest()
8968
8969 v = createHmac('sha256', k).update(v).digest()
8970
8971 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
8972 // Step H2b again
8973 v = createHmac('sha256', k).update(v).digest()
8974 T = BigInteger.fromBuffer(v)
8975 }
8976
8977 return T
8978}
8979
8980var N_OVER_TWO = secp256k1.n.shiftRight(1)
8981
8982function sign (hash, d) {
8983 typeforce(types.tuple(types.Hash256bit, types.BigInt), arguments)
8984
8985 var x = d.toBuffer(32)
8986 var e = BigInteger.fromBuffer(hash)
8987 var n = secp256k1.n
8988 var G = secp256k1.G
8989
8990 var r, s
8991 deterministicGenerateK(hash, x, function (k) {
8992 var Q = G.multiply(k)
8993
8994 if (secp256k1.isInfinity(Q)) return false
8995
8996 r = Q.affineX.mod(n)
8997 if (r.signum() === 0) return false
8998
8999 s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
9000 if (s.signum() === 0) return false
9001
9002 return true
9003 })
9004
9005 // enforce low S values, see bip62: 'low s values in signatures'
9006 if (s.compareTo(N_OVER_TWO) > 0) {
9007 s = n.subtract(s)
9008 }
9009
9010 return new ECSignature(r, s)
9011}
9012
9013function verify (hash, signature, Q) {
9014 typeforce(types.tuple(
9015 types.Hash256bit,
9016 types.ECSignature,
9017 types.ECPoint
9018 ), arguments)
9019
9020 var n = secp256k1.n
9021 var G = secp256k1.G
9022
9023 var r = signature.r
9024 var s = signature.s
9025
9026 // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1]
9027 if (r.signum() <= 0 || r.compareTo(n) >= 0) return false
9028 if (s.signum() <= 0 || s.compareTo(n) >= 0) return false
9029
9030 // 1.4.2 H = Hash(M), already done by the user
9031 // 1.4.3 e = H
9032 var e = BigInteger.fromBuffer(hash)
9033
9034 // Compute s^-1
9035 var sInv = s.modInverse(n)
9036
9037 // 1.4.4 Compute u1 = es^−1 mod n
9038 // u2 = rs^−1 mod n
9039 var u1 = e.multiply(sInv).mod(n)
9040 var u2 = r.multiply(sInv).mod(n)
9041
9042 // 1.4.5 Compute R = (xR, yR)
9043 // R = u1G + u2Q
9044 var R = G.multiplyTwo(u1, Q, u2)
9045
9046 // 1.4.5 (cont.) Enforce R is not at infinity
9047 if (secp256k1.isInfinity(R)) return false
9048
9049 // 1.4.6 Convert the field element R.x to an integer
9050 var xR = R.affineX
9051
9052 // 1.4.7 Set v = xR mod n
9053 var v = xR.mod(n)
9054
9055 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
9056 return v.equals(r)
9057}
9058
9059module.exports = {
9060 deterministicGenerateK: deterministicGenerateK,
9061 sign: sign,
9062 verify: verify,
9063
9064 // TODO: remove
9065 __curve: secp256k1
9066}
9067
9068},{"./ecsignature":48,"./types":78,"bigi":37,"create-hmac":85,"ecurve":89,"safe-buffer":98,"typeforce":109}],47:[function(require,module,exports){
9069var baddress = require('./address')
9070var bcrypto = require('./crypto')
9071var ecdsa = require('./ecdsa')
9072var randomBytes = require('randombytes')
9073var typeforce = require('typeforce')
9074var types = require('./types')
9075var wif = require('wif')
9076
9077var NETWORKS = require('./networks')
9078var BigInteger = require('bigi')
9079
9080var ecurve = require('ecurve')
9081var secp256k1 = ecdsa.__curve
9082
9083function ECPair (d, Q, options) {
9084 if (options) {
9085 typeforce({
9086 compressed: types.maybe(types.Boolean),
9087 network: types.maybe(types.Network)
9088 }, options)
9089 }
9090
9091 options = options || {}
9092
9093 if (d) {
9094 if (d.signum() <= 0) throw new Error('Private key must be greater than 0')
9095 if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order')
9096 if (Q) throw new TypeError('Unexpected publicKey parameter')
9097
9098 this.d = d
9099 } else {
9100 typeforce(types.ECPoint, Q)
9101
9102 this.__Q = Q
9103 }
9104
9105 this.compressed = options.compressed === undefined ? true : options.compressed
9106 this.network = options.network || NETWORKS.bitcoin
9107}
9108
9109Object.defineProperty(ECPair.prototype, 'Q', {
9110 get: function () {
9111 if (!this.__Q && this.d) {
9112 this.__Q = secp256k1.G.multiply(this.d)
9113 }
9114
9115 return this.__Q
9116 }
9117})
9118
9119ECPair.fromPublicKeyBuffer = function (buffer, network) {
9120 var Q = ecurve.Point.decodeFrom(secp256k1, buffer)
9121
9122 return new ECPair(null, Q, {
9123 compressed: Q.compressed,
9124 network: network
9125 })
9126}
9127
9128ECPair.fromWIF = function (string, network) {
9129 var decoded = wif.decode(string)
9130 var version = decoded.version
9131
9132 // list of networks?
9133 if (types.Array(network)) {
9134 network = network.filter(function (x) {
9135 return version === x.wif
9136 }).pop()
9137
9138 if (!network) throw new Error('Unknown network version')
9139
9140 // otherwise, assume a network object (or default to bitcoin)
9141 } else {
9142 network = network || NETWORKS.bitcoin
9143
9144 if (version !== network.wif) throw new Error('Invalid network version')
9145 }
9146
9147 var d = BigInteger.fromBuffer(decoded.privateKey)
9148
9149 return new ECPair(d, null, {
9150 compressed: decoded.compressed,
9151 network: network
9152 })
9153}
9154
9155ECPair.makeRandom = function (options) {
9156 options = options || {}
9157
9158 var rng = options.rng || randomBytes
9159
9160 var d
9161 do {
9162 var buffer = rng(32)
9163 typeforce(types.Buffer256bit, buffer)
9164
9165 d = BigInteger.fromBuffer(buffer)
9166 } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0)
9167
9168 return new ECPair(d, null, options)
9169}
9170
9171ECPair.prototype.getAddress = function () {
9172 return baddress.toBase58Check(bcrypto.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash)
9173}
9174
9175ECPair.prototype.getNetwork = function () {
9176 return this.network
9177}
9178
9179ECPair.prototype.getPublicKeyBuffer = function () {
9180 return this.Q.getEncoded(this.compressed)
9181}
9182
9183ECPair.prototype.sign = function (hash) {
9184 if (!this.d) throw new Error('Missing private key')
9185
9186 return ecdsa.sign(hash, this.d)
9187}
9188
9189ECPair.prototype.toWIF = function () {
9190 if (!this.d) throw new Error('Missing private key')
9191
9192 return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed)
9193}
9194
9195ECPair.prototype.verify = function (hash, signature) {
9196 return ecdsa.verify(hash, signature, this.Q)
9197}
9198
9199module.exports = ECPair
9200
9201},{"./address":42,"./crypto":45,"./ecdsa":46,"./networks":51,"./types":78,"bigi":37,"ecurve":89,"randombytes":96,"typeforce":109,"wif":112}],48:[function(require,module,exports){
9202(function (Buffer){
9203var bip66 = require('bip66')
9204var typeforce = require('typeforce')
9205var types = require('./types')
9206
9207var BigInteger = require('bigi')
9208
9209function ECSignature (r, s) {
9210 typeforce(types.tuple(types.BigInt, types.BigInt), arguments)
9211
9212 this.r = r
9213 this.s = s
9214}
9215
9216ECSignature.parseCompact = function (buffer) {
9217 if (buffer.length !== 65) throw new Error('Invalid signature length')
9218
9219 var flagByte = buffer.readUInt8(0) - 27
9220 if (flagByte !== (flagByte & 7)) throw new Error('Invalid signature parameter')
9221
9222 var compressed = !!(flagByte & 4)
9223 var recoveryParam = flagByte & 3
9224
9225 var r = BigInteger.fromBuffer(buffer.slice(1, 33))
9226 var s = BigInteger.fromBuffer(buffer.slice(33))
9227
9228 return {
9229 compressed: compressed,
9230 i: recoveryParam,
9231 signature: new ECSignature(r, s)
9232 }
9233}
9234
9235ECSignature.fromDER = function (buffer) {
9236 var decode = bip66.decode(buffer)
9237 var r = BigInteger.fromDERInteger(decode.r)
9238 var s = BigInteger.fromDERInteger(decode.s)
9239
9240 return new ECSignature(r, s)
9241}
9242
9243// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
9244ECSignature.parseScriptSignature = function (buffer) {
9245 var hashType = buffer.readUInt8(buffer.length - 1)
9246 var hashTypeMod = hashType & ~0x80
9247
9248 if (hashTypeMod <= 0x00 || hashTypeMod >= 0x04) throw new Error('Invalid hashType ' + hashType)
9249
9250 return {
9251 signature: ECSignature.fromDER(buffer.slice(0, -1)),
9252 hashType: hashType
9253 }
9254}
9255
9256ECSignature.prototype.toCompact = function (i, compressed) {
9257 if (compressed) {
9258 i += 4
9259 }
9260
9261 i += 27
9262
9263 var buffer = Buffer.alloc(65)
9264 buffer.writeUInt8(i, 0)
9265 this.r.toBuffer(32).copy(buffer, 1)
9266 this.s.toBuffer(32).copy(buffer, 33)
9267
9268 return buffer
9269}
9270
9271ECSignature.prototype.toDER = function () {
9272 var r = Buffer.from(this.r.toDERInteger())
9273 var s = Buffer.from(this.s.toDERInteger())
9274
9275 return bip66.encode(r, s)
9276}
9277
9278ECSignature.prototype.toScriptSignature = function (hashType) {
9279 var hashTypeMod = hashType & ~0x80
9280 if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType)
9281
9282 var hashTypeBuffer = Buffer.alloc(1)
9283 hashTypeBuffer.writeUInt8(hashType, 0)
9284
9285 return Buffer.concat([this.toDER(), hashTypeBuffer])
9286}
9287
9288module.exports = ECSignature
9289
9290}).call(this,require("buffer").Buffer)
9291},{"./types":78,"bigi":37,"bip66":39,"buffer":4,"typeforce":109}],49:[function(require,module,exports){
9292var Buffer = require('safe-buffer').Buffer
9293var base58check = require('bs58check')
9294var bcrypto = require('./crypto')
9295var createHmac = require('create-hmac')
9296var typeforce = require('typeforce')
9297var types = require('./types')
9298var NETWORKS = require('./networks')
9299
9300var BigInteger = require('bigi')
9301var ECPair = require('./ecpair')
9302
9303var ecurve = require('ecurve')
9304var curve = ecurve.getCurveByName('secp256k1')
9305
9306function HDNode (keyPair, chainCode) {
9307 typeforce(types.tuple('ECPair', types.Buffer256bit), arguments)
9308
9309 if (!keyPair.compressed) throw new TypeError('BIP32 only allows compressed keyPairs')
9310
9311 this.keyPair = keyPair
9312 this.chainCode = chainCode
9313 this.depth = 0
9314 this.index = 0
9315 this.parentFingerprint = 0x00000000
9316}
9317
9318HDNode.HIGHEST_BIT = 0x80000000
9319HDNode.LENGTH = 78
9320HDNode.MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8')
9321
9322HDNode.fromSeedBuffer = function (seed, network) {
9323 typeforce(types.tuple(types.Buffer, types.maybe(types.Network)), arguments)
9324
9325 if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits')
9326 if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits')
9327
9328 var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest()
9329 var IL = I.slice(0, 32)
9330 var IR = I.slice(32)
9331
9332 // In case IL is 0 or >= n, the master key is invalid
9333 // This is handled by the ECPair constructor
9334 var pIL = BigInteger.fromBuffer(IL)
9335 var keyPair = new ECPair(pIL, null, {
9336 network: network
9337 })
9338
9339 return new HDNode(keyPair, IR)
9340}
9341
9342HDNode.fromSeedHex = function (hex, network) {
9343 return HDNode.fromSeedBuffer(Buffer.from(hex, 'hex'), network)
9344}
9345
9346HDNode.fromBase58 = function (string, networks) {
9347 var buffer = base58check.decode(string)
9348 if (buffer.length !== 78) throw new Error('Invalid buffer length')
9349
9350 // 4 bytes: version bytes
9351 var version = buffer.readUInt32BE(0)
9352 var network
9353
9354 // list of networks?
9355 if (Array.isArray(networks)) {
9356 network = networks.filter(function (x) {
9357 return version === x.bip32.private ||
9358 version === x.bip32.public
9359 }).pop()
9360
9361 if (!network) throw new Error('Unknown network version')
9362
9363 // otherwise, assume a network object (or default to bitcoin)
9364 } else {
9365 network = networks || NETWORKS.bitcoin
9366 }
9367
9368 if (version !== network.bip32.private &&
9369 version !== network.bip32.public) throw new Error('Invalid network version')
9370
9371 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
9372 var depth = buffer[4]
9373
9374 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9375 var parentFingerprint = buffer.readUInt32BE(5)
9376 if (depth === 0) {
9377 if (parentFingerprint !== 0x00000000) throw new Error('Invalid parent fingerprint')
9378 }
9379
9380 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
9381 // This is encoded in MSB order. (0x00000000 if master key)
9382 var index = buffer.readUInt32BE(9)
9383 if (depth === 0 && index !== 0) throw new Error('Invalid index')
9384
9385 // 32 bytes: the chain code
9386 var chainCode = buffer.slice(13, 45)
9387 var keyPair
9388
9389 // 33 bytes: private key data (0x00 + k)
9390 if (version === network.bip32.private) {
9391 if (buffer.readUInt8(45) !== 0x00) throw new Error('Invalid private key')
9392
9393 var d = BigInteger.fromBuffer(buffer.slice(46, 78))
9394 keyPair = new ECPair(d, null, { network: network })
9395
9396 // 33 bytes: public key data (0x02 + X or 0x03 + X)
9397 } else {
9398 var Q = ecurve.Point.decodeFrom(curve, buffer.slice(45, 78))
9399 // Q.compressed is assumed, if somehow this assumption is broken, `new HDNode` will throw
9400
9401 // Verify that the X coordinate in the public point corresponds to a point on the curve.
9402 // If not, the extended public key is invalid.
9403 curve.validate(Q)
9404
9405 keyPair = new ECPair(null, Q, { network: network })
9406 }
9407
9408 var hd = new HDNode(keyPair, chainCode)
9409 hd.depth = depth
9410 hd.index = index
9411 hd.parentFingerprint = parentFingerprint
9412
9413 return hd
9414}
9415
9416HDNode.prototype.getAddress = function () {
9417 return this.keyPair.getAddress()
9418}
9419
9420HDNode.prototype.getIdentifier = function () {
9421 return bcrypto.hash160(this.keyPair.getPublicKeyBuffer())
9422}
9423
9424HDNode.prototype.getFingerprint = function () {
9425 return this.getIdentifier().slice(0, 4)
9426}
9427
9428HDNode.prototype.getNetwork = function () {
9429 return this.keyPair.getNetwork()
9430}
9431
9432HDNode.prototype.getPublicKeyBuffer = function () {
9433 return this.keyPair.getPublicKeyBuffer()
9434}
9435
9436HDNode.prototype.neutered = function () {
9437 var neuteredKeyPair = new ECPair(null, this.keyPair.Q, {
9438 network: this.keyPair.network
9439 })
9440
9441 var neutered = new HDNode(neuteredKeyPair, this.chainCode)
9442 neutered.depth = this.depth
9443 neutered.index = this.index
9444 neutered.parentFingerprint = this.parentFingerprint
9445
9446 return neutered
9447}
9448
9449HDNode.prototype.sign = function (hash) {
9450 return this.keyPair.sign(hash)
9451}
9452
9453HDNode.prototype.verify = function (hash, signature) {
9454 return this.keyPair.verify(hash, signature)
9455}
9456
9457HDNode.prototype.toBase58 = function (__isPrivate) {
9458 if (__isPrivate !== undefined) throw new TypeError('Unsupported argument in 2.0.0')
9459
9460 // Version
9461 var network = this.keyPair.network
9462 var version = (!this.isNeutered()) ? network.bip32.private : network.bip32.public
9463 var buffer = Buffer.allocUnsafe(78)
9464
9465 // 4 bytes: version bytes
9466 buffer.writeUInt32BE(version, 0)
9467
9468 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
9469 buffer.writeUInt8(this.depth, 4)
9470
9471 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9472 buffer.writeUInt32BE(this.parentFingerprint, 5)
9473
9474 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
9475 // This is encoded in big endian. (0x00000000 if master key)
9476 buffer.writeUInt32BE(this.index, 9)
9477
9478 // 32 bytes: the chain code
9479 this.chainCode.copy(buffer, 13)
9480
9481 // 33 bytes: the public key or private key data
9482 if (!this.isNeutered()) {
9483 // 0x00 + k for private keys
9484 buffer.writeUInt8(0, 45)
9485 this.keyPair.d.toBuffer(32).copy(buffer, 46)
9486
9487 // 33 bytes: the public key
9488 } else {
9489 // X9.62 encoding for public keys
9490 this.keyPair.getPublicKeyBuffer().copy(buffer, 45)
9491 }
9492
9493 return base58check.encode(buffer)
9494}
9495
9496// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
9497HDNode.prototype.derive = function (index) {
9498 typeforce(types.UInt32, index)
9499
9500 var isHardened = index >= HDNode.HIGHEST_BIT
9501 var data = Buffer.allocUnsafe(37)
9502
9503 // Hardened child
9504 if (isHardened) {
9505 if (this.isNeutered()) throw new TypeError('Could not derive hardened child key')
9506
9507 // data = 0x00 || ser256(kpar) || ser32(index)
9508 data[0] = 0x00
9509 this.keyPair.d.toBuffer(32).copy(data, 1)
9510 data.writeUInt32BE(index, 33)
9511
9512 // Normal child
9513 } else {
9514 // data = serP(point(kpar)) || ser32(index)
9515 // = serP(Kpar) || ser32(index)
9516 this.keyPair.getPublicKeyBuffer().copy(data, 0)
9517 data.writeUInt32BE(index, 33)
9518 }
9519
9520 var I = createHmac('sha512', this.chainCode).update(data).digest()
9521 var IL = I.slice(0, 32)
9522 var IR = I.slice(32)
9523
9524 var pIL = BigInteger.fromBuffer(IL)
9525
9526 // In case parse256(IL) >= n, proceed with the next value for i
9527 if (pIL.compareTo(curve.n) >= 0) {
9528 return this.derive(index + 1)
9529 }
9530
9531 // Private parent key -> private child key
9532 var derivedKeyPair
9533 if (!this.isNeutered()) {
9534 // ki = parse256(IL) + kpar (mod n)
9535 var ki = pIL.add(this.keyPair.d).mod(curve.n)
9536
9537 // In case ki == 0, proceed with the next value for i
9538 if (ki.signum() === 0) {
9539 return this.derive(index + 1)
9540 }
9541
9542 derivedKeyPair = new ECPair(ki, null, {
9543 network: this.keyPair.network
9544 })
9545
9546 // Public parent key -> public child key
9547 } else {
9548 // Ki = point(parse256(IL)) + Kpar
9549 // = G*IL + Kpar
9550 var Ki = curve.G.multiply(pIL).add(this.keyPair.Q)
9551
9552 // In case Ki is the point at infinity, proceed with the next value for i
9553 if (curve.isInfinity(Ki)) {
9554 return this.derive(index + 1)
9555 }
9556
9557 derivedKeyPair = new ECPair(null, Ki, {
9558 network: this.keyPair.network
9559 })
9560 }
9561
9562 var hd = new HDNode(derivedKeyPair, IR)
9563 hd.depth = this.depth + 1
9564 hd.index = index
9565 hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)
9566
9567 return hd
9568}
9569
9570HDNode.prototype.deriveHardened = function (index) {
9571 typeforce(types.UInt31, index)
9572
9573 // Only derives hardened private keys by default
9574 return this.derive(index + HDNode.HIGHEST_BIT)
9575}
9576
9577// Private === not neutered
9578// Public === neutered
9579HDNode.prototype.isNeutered = function () {
9580 return !(this.keyPair.d)
9581}
9582
9583HDNode.prototype.derivePath = function (path) {
9584 typeforce(types.BIP32Path, path)
9585
9586 var splitPath = path.split('/')
9587 if (splitPath[0] === 'm') {
9588 if (this.parentFingerprint) {
9589 throw new Error('Not a master node')
9590 }
9591
9592 splitPath = splitPath.slice(1)
9593 }
9594
9595 return splitPath.reduce(function (prevHd, indexStr) {
9596 var index
9597 if (indexStr.slice(-1) === "'") {
9598 index = parseInt(indexStr.slice(0, -1), 10)
9599 return prevHd.deriveHardened(index)
9600 } else {
9601 index = parseInt(indexStr, 10)
9602 return prevHd.derive(index)
9603 }
9604 }, this)
9605}
9606
9607module.exports = HDNode
9608
9609},{"./crypto":45,"./ecpair":47,"./networks":51,"./types":78,"bigi":37,"bs58check":80,"create-hmac":85,"ecurve":89,"safe-buffer":98,"typeforce":109}],50:[function(require,module,exports){
9610module.exports = {
9611 Block: require('./block'),
9612 ECPair: require('./ecpair'),
9613 ECSignature: require('./ecsignature'),
9614 HDNode: require('./hdnode'),
9615 Transaction: require('./transaction'),
9616 TransactionBuilder: require('./transaction_builder'),
9617
9618 address: require('./address'),
9619 bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0
9620 crypto: require('./crypto'),
9621 networks: require('./networks'),
9622 opcodes: require('bitcoin-ops'),
9623 script: require('./script')
9624}
9625
9626},{"./address":42,"./block":43,"./bufferutils":44,"./crypto":45,"./ecpair":47,"./ecsignature":48,"./hdnode":49,"./networks":51,"./script":52,"./transaction":76,"./transaction_builder":77,"bitcoin-ops":40}],51:[function(require,module,exports){
9627// https://en.bitcoin.it/wiki/List_of_address_prefixes
9628// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
9629
9630module.exports = {
9631 bitcoin: {
9632 messagePrefix: '\x18Bitcoin Signed Message:\n',
9633 bip32: {
9634 public: 0x0488b21e,
9635 private: 0x0488ade4
9636 },
9637 pubKeyHash: 0x00,
9638 scriptHash: 0x05,
9639 wif: 0x80
9640 },
9641 testnet: {
9642 messagePrefix: '\x18Bitcoin Signed Message:\n',
9643 bip32: {
9644 public: 0x043587cf,
9645 private: 0x04358394
9646 },
9647 pubKeyHash: 0x6f,
9648 scriptHash: 0xc4,
9649 wif: 0xef
9650 },
9651 litecoin: {
9652 messagePrefix: '\x19Litecoin Signed Message:\n',
9653 bip32: {
9654 public: 0x019da462,
9655 private: 0x019d9cfe
9656 },
9657 pubKeyHash: 0x30,
9658 scriptHash: 0x32,
9659 wif: 0xb0
9660 }
9661}
9662
9663},{}],52:[function(require,module,exports){
9664var Buffer = require('safe-buffer').Buffer
9665var bip66 = require('bip66')
9666var pushdata = require('pushdata-bitcoin')
9667var typeforce = require('typeforce')
9668var types = require('./types')
9669var scriptNumber = require('./script_number')
9670
9671var OPS = require('bitcoin-ops')
9672var REVERSE_OPS = require('bitcoin-ops/map')
9673var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
9674
9675function isOPInt (value) {
9676 return types.Number(value) &&
9677 ((value === OPS.OP_0) ||
9678 (value >= OPS.OP_1 && value <= OPS.OP_16) ||
9679 (value === OPS.OP_1NEGATE))
9680}
9681
9682function isPushOnlyChunk (value) {
9683 return types.Buffer(value) || isOPInt(value)
9684}
9685
9686function isPushOnly (value) {
9687 return types.Array(value) && value.every(isPushOnlyChunk)
9688}
9689
9690function compile (chunks) {
9691 // TODO: remove me
9692 if (Buffer.isBuffer(chunks)) return chunks
9693
9694 typeforce(types.Array, chunks)
9695
9696 var bufferSize = chunks.reduce(function (accum, chunk) {
9697 // data chunk
9698 if (Buffer.isBuffer(chunk)) {
9699 // adhere to BIP62.3, minimal push policy
9700 if (chunk.length === 1 && (chunk[0] === 0x81 || (chunk[0] >= 1 && chunk[0] <= 16))) {
9701 return accum + 1
9702 }
9703
9704 return accum + pushdata.encodingLength(chunk.length) + chunk.length
9705 }
9706
9707 // opcode
9708 return accum + 1
9709 }, 0.0)
9710
9711 var buffer = Buffer.allocUnsafe(bufferSize)
9712 var offset = 0
9713
9714 chunks.forEach(function (chunk) {
9715 // data chunk
9716 if (Buffer.isBuffer(chunk)) {
9717 // adhere to BIP62.3, minimal push policy
9718 if (chunk.length === 1 && chunk[0] >= 1 && chunk[0] <= 16) {
9719 var opcode = OP_INT_BASE + chunk[0]
9720 buffer.writeUInt8(opcode, offset)
9721 offset += 1
9722 return
9723 }
9724
9725 if (chunk.length === 1 && chunk[0] === 0x81) {
9726 buffer.writeUInt8(OPS.OP_1NEGATE, offset)
9727 offset += 1
9728 return
9729 }
9730
9731 offset += pushdata.encode(buffer, chunk.length, offset)
9732
9733 chunk.copy(buffer, offset)
9734 offset += chunk.length
9735
9736 // opcode
9737 } else {
9738 buffer.writeUInt8(chunk, offset)
9739 offset += 1
9740 }
9741 })
9742
9743 if (offset !== buffer.length) throw new Error('Could not decode chunks')
9744 return buffer
9745}
9746
9747function decompile (buffer) {
9748 // TODO: remove me
9749 if (types.Array(buffer)) return buffer
9750
9751 typeforce(types.Buffer, buffer)
9752
9753 var chunks = []
9754 var i = 0
9755
9756 while (i < buffer.length) {
9757 var opcode = buffer[i]
9758
9759 // data chunk
9760 if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) {
9761 var d = pushdata.decode(buffer, i)
9762
9763 // did reading a pushDataInt fail? empty script
9764 if (d === null) return []
9765 i += d.size
9766
9767 // attempt to read too much data? empty script
9768 if (i + d.number > buffer.length) return []
9769
9770 var data = buffer.slice(i, i + d.number)
9771 i += d.number
9772
9773 chunks.push(data)
9774
9775 // opcode
9776 } else {
9777 chunks.push(opcode)
9778
9779 i += 1
9780 }
9781 }
9782
9783 return chunks
9784}
9785
9786function toASM (chunks) {
9787 if (Buffer.isBuffer(chunks)) {
9788 chunks = decompile(chunks)
9789 }
9790
9791 return chunks.map(function (chunk) {
9792 // data?
9793 if (Buffer.isBuffer(chunk)) return chunk.toString('hex')
9794
9795 // opcode!
9796 return REVERSE_OPS[chunk]
9797 }).join(' ')
9798}
9799
9800function fromASM (asm) {
9801 typeforce(types.String, asm)
9802
9803 return compile(asm.split(' ').map(function (chunkStr) {
9804 // opcode?
9805 if (OPS[chunkStr] !== undefined) return OPS[chunkStr]
9806 typeforce(types.Hex, chunkStr)
9807
9808 // data!
9809 return Buffer.from(chunkStr, 'hex')
9810 }))
9811}
9812
9813function toStack (chunks) {
9814 chunks = decompile(chunks)
9815 typeforce(isPushOnly, chunks)
9816
9817 return chunks.map(function (op) {
9818 if (Buffer.isBuffer(op)) return op
9819 if (op === OPS.OP_0) return Buffer.allocUnsafe(0)
9820
9821 return scriptNumber.encode(op - OP_INT_BASE)
9822 })
9823}
9824
9825function isCanonicalPubKey (buffer) {
9826 if (!Buffer.isBuffer(buffer)) return false
9827 if (buffer.length < 33) return false
9828
9829 switch (buffer[0]) {
9830 case 0x02:
9831 case 0x03:
9832 return buffer.length === 33
9833 case 0x04:
9834 return buffer.length === 65
9835 }
9836
9837 return false
9838}
9839
9840function isDefinedHashType (hashType) {
9841 var hashTypeMod = hashType & ~0x80
9842
9843// return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE
9844 return hashTypeMod > 0x00 && hashTypeMod < 0x04
9845}
9846
9847function isCanonicalSignature (buffer) {
9848 if (!Buffer.isBuffer(buffer)) return false
9849 if (!isDefinedHashType(buffer[buffer.length - 1])) return false
9850
9851 return bip66.check(buffer.slice(0, -1))
9852}
9853
9854module.exports = {
9855 compile: compile,
9856 decompile: decompile,
9857 fromASM: fromASM,
9858 toASM: toASM,
9859 toStack: toStack,
9860
9861 number: require('./script_number'),
9862
9863 isCanonicalPubKey: isCanonicalPubKey,
9864 isCanonicalSignature: isCanonicalSignature,
9865 isPushOnly: isPushOnly,
9866 isDefinedHashType: isDefinedHashType
9867}
9868
9869var templates = require('./templates')
9870for (var key in templates) {
9871 module.exports[key] = templates[key]
9872}
9873
9874},{"./script_number":53,"./templates":54,"./types":78,"bip66":39,"bitcoin-ops":40,"bitcoin-ops/map":41,"pushdata-bitcoin":95,"safe-buffer":98,"typeforce":109}],53:[function(require,module,exports){
9875var Buffer = require('safe-buffer').Buffer
9876
9877function decode (buffer, maxLength, minimal) {
9878 maxLength = maxLength || 4
9879 minimal = minimal === undefined ? true : minimal
9880
9881 var length = buffer.length
9882 if (length === 0) return 0
9883 if (length > maxLength) throw new TypeError('Script number overflow')
9884 if (minimal) {
9885 if ((buffer[length - 1] & 0x7f) === 0) {
9886 if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number')
9887 }
9888 }
9889
9890 // 40-bit
9891 if (length === 5) {
9892 var a = buffer.readUInt32LE(0)
9893 var b = buffer.readUInt8(4)
9894
9895 if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a)
9896 return (b * 0x100000000) + a
9897 }
9898
9899 var result = 0
9900
9901 // 32-bit / 24-bit / 16-bit / 8-bit
9902 for (var i = 0; i < length; ++i) {
9903 result |= buffer[i] << (8 * i)
9904 }
9905
9906 if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1))))
9907 return result
9908}
9909
9910function scriptNumSize (i) {
9911 return i > 0x7fffffff ? 5
9912 : i > 0x7fffff ? 4
9913 : i > 0x7fff ? 3
9914 : i > 0x7f ? 2
9915 : i > 0x00 ? 1
9916 : 0
9917}
9918
9919function encode (number) {
9920 var value = Math.abs(number)
9921 var size = scriptNumSize(value)
9922 var buffer = Buffer.allocUnsafe(size)
9923 var negative = number < 0
9924
9925 for (var i = 0; i < size; ++i) {
9926 buffer.writeUInt8(value & 0xff, i)
9927 value >>= 8
9928 }
9929
9930 if (buffer[size - 1] & 0x80) {
9931 buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1)
9932 } else if (negative) {
9933 buffer[size - 1] |= 0x80
9934 }
9935
9936 return buffer
9937}
9938
9939module.exports = {
9940 decode: decode,
9941 encode: encode
9942}
9943
9944},{"safe-buffer":98}],54:[function(require,module,exports){
9945var decompile = require('../script').decompile
9946var multisig = require('./multisig')
9947var nullData = require('./nulldata')
9948var pubKey = require('./pubkey')
9949var pubKeyHash = require('./pubkeyhash')
9950var scriptHash = require('./scripthash')
9951var witnessPubKeyHash = require('./witnesspubkeyhash')
9952var witnessScriptHash = require('./witnessscripthash')
9953var witnessCommitment = require('./witnesscommitment')
9954
9955var types = {
9956 MULTISIG: 'multisig',
9957 NONSTANDARD: 'nonstandard',
9958 NULLDATA: 'nulldata',
9959 P2PK: 'pubkey',
9960 P2PKH: 'pubkeyhash',
9961 P2SH: 'scripthash',
9962 P2WPKH: 'witnesspubkeyhash',
9963 P2WSH: 'witnessscripthash',
9964 WITNESS_COMMITMENT: 'witnesscommitment'
9965}
9966
9967function classifyOutput (script) {
9968 if (witnessPubKeyHash.output.check(script)) return types.P2WPKH
9969 if (witnessScriptHash.output.check(script)) return types.P2WSH
9970 if (pubKeyHash.output.check(script)) return types.P2PKH
9971 if (scriptHash.output.check(script)) return types.P2SH
9972
9973 // XXX: optimization, below functions .decompile before use
9974 var chunks = decompile(script)
9975 if (multisig.output.check(chunks)) return types.MULTISIG
9976 if (pubKey.output.check(chunks)) return types.P2PK
9977 if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT
9978 if (nullData.output.check(chunks)) return types.NULLDATA
9979
9980 return types.NONSTANDARD
9981}
9982
9983function classifyInput (script, allowIncomplete) {
9984 // XXX: optimization, below functions .decompile before use
9985 var chunks = decompile(script)
9986
9987 if (pubKeyHash.input.check(chunks)) return types.P2PKH
9988 if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH
9989 if (multisig.input.check(chunks, allowIncomplete)) return types.MULTISIG
9990 if (pubKey.input.check(chunks)) return types.P2PK
9991
9992 return types.NONSTANDARD
9993}
9994
9995function classifyWitness (script, allowIncomplete) {
9996 // XXX: optimization, below functions .decompile before use
9997 var chunks = decompile(script)
9998
9999 if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH
10000 if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH
10001
10002 return types.NONSTANDARD
10003}
10004
10005module.exports = {
10006 classifyInput: classifyInput,
10007 classifyOutput: classifyOutput,
10008 classifyWitness: classifyWitness,
10009 multisig: multisig,
10010 nullData: nullData,
10011 pubKey: pubKey,
10012 pubKeyHash: pubKeyHash,
10013 scriptHash: scriptHash,
10014 witnessPubKeyHash: witnessPubKeyHash,
10015 witnessScriptHash: witnessScriptHash,
10016 witnessCommitment: witnessCommitment,
10017 types: types
10018}
10019
10020},{"../script":52,"./multisig":55,"./nulldata":58,"./pubkey":59,"./pubkeyhash":62,"./scripthash":65,"./witnesscommitment":68,"./witnesspubkeyhash":70,"./witnessscripthash":73}],55:[function(require,module,exports){
10021module.exports = {
10022 input: require('./input'),
10023 output: require('./output')
10024}
10025
10026},{"./input":56,"./output":57}],56:[function(require,module,exports){
10027// OP_0 [signatures ...]
10028
10029var Buffer = require('safe-buffer').Buffer
10030var bscript = require('../../script')
10031var typeforce = require('typeforce')
10032var OPS = require('bitcoin-ops')
10033
10034function partialSignature (value) {
10035 return value === OPS.OP_0 || bscript.isCanonicalSignature(value)
10036}
10037
10038function check (script, allowIncomplete) {
10039 var chunks = bscript.decompile(script)
10040 if (chunks.length < 2) return false
10041 if (chunks[0] !== OPS.OP_0) return false
10042
10043 if (allowIncomplete) {
10044 return chunks.slice(1).every(partialSignature)
10045 }
10046
10047 return chunks.slice(1).every(bscript.isCanonicalSignature)
10048}
10049check.toJSON = function () { return 'multisig input' }
10050
10051var EMPTY_BUFFER = Buffer.allocUnsafe(0)
10052
10053function encodeStack (signatures, scriptPubKey) {
10054 typeforce([partialSignature], signatures)
10055
10056 if (scriptPubKey) {
10057 var scriptData = bscript.multisig.output.decode(scriptPubKey)
10058
10059 if (signatures.length < scriptData.m) {
10060 throw new TypeError('Not enough signatures provided')
10061 }
10062
10063 if (signatures.length > scriptData.pubKeys.length) {
10064 throw new TypeError('Too many signatures provided')
10065 }
10066 }
10067
10068 return [].concat(EMPTY_BUFFER, signatures)
10069}
10070
10071function encode (signatures, scriptPubKey) {
10072 return bscript.compile(encodeStack(signatures, scriptPubKey))
10073}
10074
10075function decodeStack (stack, allowIncomplete) {
10076 typeforce(check, stack, allowIncomplete)
10077 return stack.slice(1)
10078}
10079
10080function decode (buffer, allowIncomplete) {
10081 var stack = bscript.decompile(buffer)
10082 return decodeStack(stack, allowIncomplete)
10083}
10084
10085module.exports = {
10086 check: check,
10087 decode: decode,
10088 decodeStack: decodeStack,
10089 encode: encode,
10090 encodeStack: encodeStack
10091}
10092
10093},{"../../script":52,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],57:[function(require,module,exports){
10094// m [pubKeys ...] n OP_CHECKMULTISIG
10095
10096var bscript = require('../../script')
10097var types = require('../../types')
10098var typeforce = require('typeforce')
10099var OPS = require('bitcoin-ops')
10100var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
10101
10102function check (script, allowIncomplete) {
10103 var chunks = bscript.decompile(script)
10104
10105 if (chunks.length < 4) return false
10106 if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) return false
10107 if (!types.Number(chunks[0])) return false
10108 if (!types.Number(chunks[chunks.length - 2])) return false
10109 var m = chunks[0] - OP_INT_BASE
10110 var n = chunks[chunks.length - 2] - OP_INT_BASE
10111
10112 if (m <= 0) return false
10113 if (n > 16) return false
10114 if (m > n) return false
10115 if (n !== chunks.length - 3) return false
10116 if (allowIncomplete) return true
10117
10118 var keys = chunks.slice(1, -2)
10119 return keys.every(bscript.isCanonicalPubKey)
10120}
10121check.toJSON = function () { return 'multi-sig output' }
10122
10123function encode (m, pubKeys) {
10124 typeforce({
10125 m: types.Number,
10126 pubKeys: [bscript.isCanonicalPubKey]
10127 }, {
10128 m: m,
10129 pubKeys: pubKeys
10130 })
10131
10132 var n = pubKeys.length
10133 if (n < m) throw new TypeError('Not enough pubKeys provided')
10134
10135 return bscript.compile([].concat(
10136 OP_INT_BASE + m,
10137 pubKeys,
10138 OP_INT_BASE + n,
10139 OPS.OP_CHECKMULTISIG
10140 ))
10141}
10142
10143function decode (buffer, allowIncomplete) {
10144 var chunks = bscript.decompile(buffer)
10145 typeforce(check, chunks, allowIncomplete)
10146
10147 return {
10148 m: chunks[0] - OP_INT_BASE,
10149 pubKeys: chunks.slice(1, -2)
10150 }
10151}
10152
10153module.exports = {
10154 check: check,
10155 decode: decode,
10156 encode: encode
10157}
10158
10159},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],58:[function(require,module,exports){
10160// OP_RETURN {data}
10161
10162var bscript = require('../script')
10163var types = require('../types')
10164var typeforce = require('typeforce')
10165var OPS = require('bitcoin-ops')
10166
10167function check (script) {
10168 var buffer = bscript.compile(script)
10169
10170 return buffer.length > 1 &&
10171 buffer[0] === OPS.OP_RETURN
10172}
10173check.toJSON = function () { return 'null data output' }
10174
10175function encode (data) {
10176 typeforce(types.Buffer, data)
10177
10178 return bscript.compile([OPS.OP_RETURN, data])
10179}
10180
10181function decode (buffer) {
10182 typeforce(check, buffer)
10183
10184 return buffer.slice(2)
10185}
10186
10187module.exports = {
10188 output: {
10189 check: check,
10190 decode: decode,
10191 encode: encode
10192 }
10193}
10194
10195},{"../script":52,"../types":78,"bitcoin-ops":40,"typeforce":109}],59:[function(require,module,exports){
10196arguments[4][55][0].apply(exports,arguments)
10197},{"./input":60,"./output":61,"dup":55}],60:[function(require,module,exports){
10198// {signature}
10199
10200var bscript = require('../../script')
10201var types = require('../../types')
10202var typeforce = require('typeforce')
10203
10204function check (script) {
10205 var chunks = bscript.decompile(script)
10206
10207 return chunks.length === 1 &&
10208 bscript.isCanonicalSignature(chunks[0])
10209}
10210check.toJSON = function () { return 'pubKey input' }
10211
10212function encodeStack (signature) {
10213 typeforce(types.Buffer, signature)
10214 return [signature]
10215}
10216
10217function encode (signature) {
10218 return bscript.compile(encodeStack(signature))
10219}
10220
10221function decodeStack (stack) {
10222 typeforce(check, stack)
10223 return stack[0]
10224}
10225
10226function decode (buffer) {
10227 var stack = bscript.decompile(buffer)
10228 return decodeStack(stack)
10229}
10230
10231module.exports = {
10232 check: check,
10233 decode: decode,
10234 decodeStack: decodeStack,
10235 encode: encode,
10236 encodeStack: encodeStack
10237}
10238
10239},{"../../script":52,"../../types":78,"typeforce":109}],61:[function(require,module,exports){
10240// {pubKey} OP_CHECKSIG
10241
10242var bscript = require('../../script')
10243var typeforce = require('typeforce')
10244var OPS = require('bitcoin-ops')
10245
10246function check (script) {
10247 var chunks = bscript.decompile(script)
10248
10249 return chunks.length === 2 &&
10250 bscript.isCanonicalPubKey(chunks[0]) &&
10251 chunks[1] === OPS.OP_CHECKSIG
10252}
10253check.toJSON = function () { return 'pubKey output' }
10254
10255function encode (pubKey) {
10256 typeforce(bscript.isCanonicalPubKey, pubKey)
10257
10258 return bscript.compile([pubKey, OPS.OP_CHECKSIG])
10259}
10260
10261function decode (buffer) {
10262 var chunks = bscript.decompile(buffer)
10263 typeforce(check, chunks)
10264
10265 return chunks[0]
10266}
10267
10268module.exports = {
10269 check: check,
10270 decode: decode,
10271 encode: encode
10272}
10273
10274},{"../../script":52,"bitcoin-ops":40,"typeforce":109}],62:[function(require,module,exports){
10275arguments[4][55][0].apply(exports,arguments)
10276},{"./input":63,"./output":64,"dup":55}],63:[function(require,module,exports){
10277// {signature} {pubKey}
10278
10279var bscript = require('../../script')
10280var types = require('../../types')
10281var typeforce = require('typeforce')
10282
10283function check (script) {
10284 var chunks = bscript.decompile(script)
10285
10286 return chunks.length === 2 &&
10287 bscript.isCanonicalSignature(chunks[0]) &&
10288 bscript.isCanonicalPubKey(chunks[1])
10289}
10290check.toJSON = function () { return 'pubKeyHash input' }
10291
10292function encodeStack (signature, pubKey) {
10293 typeforce({
10294 signature: types.Buffer, pubKey: types.Buffer
10295 }, {
10296 signature: signature, pubKey: pubKey
10297 })
10298
10299 return [signature, pubKey]
10300}
10301
10302function encode (signature, pubKey) {
10303 return bscript.compile(encodeStack(signature, pubKey))
10304}
10305
10306function decodeStack (stack) {
10307 typeforce(check, stack)
10308
10309 return {
10310 signature: stack[0],
10311 pubKey: stack[1]
10312 }
10313}
10314
10315function decode (buffer) {
10316 var stack = bscript.decompile(buffer)
10317 return decodeStack(stack)
10318}
10319
10320module.exports = {
10321 check: check,
10322 decode: decode,
10323 decodeStack: decodeStack,
10324 encode: encode,
10325 encodeStack: encodeStack
10326}
10327
10328},{"../../script":52,"../../types":78,"typeforce":109}],64:[function(require,module,exports){
10329// OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
10330
10331var bscript = require('../../script')
10332var types = require('../../types')
10333var typeforce = require('typeforce')
10334var OPS = require('bitcoin-ops')
10335
10336function check (script) {
10337 var buffer = bscript.compile(script)
10338
10339 return buffer.length === 25 &&
10340 buffer[0] === OPS.OP_DUP &&
10341 buffer[1] === OPS.OP_HASH160 &&
10342 buffer[2] === 0x14 &&
10343 buffer[23] === OPS.OP_EQUALVERIFY &&
10344 buffer[24] === OPS.OP_CHECKSIG
10345}
10346check.toJSON = function () { return 'pubKeyHash output' }
10347
10348function encode (pubKeyHash) {
10349 typeforce(types.Hash160bit, pubKeyHash)
10350
10351 return bscript.compile([
10352 OPS.OP_DUP,
10353 OPS.OP_HASH160,
10354 pubKeyHash,
10355 OPS.OP_EQUALVERIFY,
10356 OPS.OP_CHECKSIG
10357 ])
10358}
10359
10360function decode (buffer) {
10361 typeforce(check, buffer)
10362
10363 return buffer.slice(3, 23)
10364}
10365
10366module.exports = {
10367 check: check,
10368 decode: decode,
10369 encode: encode
10370}
10371
10372},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],65:[function(require,module,exports){
10373arguments[4][55][0].apply(exports,arguments)
10374},{"./input":66,"./output":67,"dup":55}],66:[function(require,module,exports){
10375// <scriptSig> {serialized scriptPubKey script}
10376
10377var Buffer = require('safe-buffer').Buffer
10378var bscript = require('../../script')
10379var typeforce = require('typeforce')
10380
10381function check (script, allowIncomplete) {
10382 var chunks = bscript.decompile(script)
10383 if (chunks.length < 1) return false
10384
10385 var lastChunk = chunks[chunks.length - 1]
10386 if (!Buffer.isBuffer(lastChunk)) return false
10387
10388 var scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1)))
10389 var redeemScriptChunks = bscript.decompile(lastChunk)
10390
10391 // is redeemScript a valid script?
10392 if (redeemScriptChunks.length === 0) return false
10393
10394 // is redeemScriptSig push only?
10395 if (!bscript.isPushOnly(scriptSigChunks)) return false
10396
10397 var inputType = bscript.classifyInput(scriptSigChunks, allowIncomplete)
10398 var outputType = bscript.classifyOutput(redeemScriptChunks)
10399 if (chunks.length === 1) {
10400 return outputType === bscript.types.P2WSH || outputType === bscript.types.P2WPKH
10401 }
10402 return inputType === outputType
10403}
10404check.toJSON = function () { return 'scriptHash input' }
10405
10406function encodeStack (redeemScriptStack, redeemScript) {
10407 var serializedScriptPubKey = bscript.compile(redeemScript)
10408
10409 return [].concat(redeemScriptStack, serializedScriptPubKey)
10410}
10411
10412function encode (redeemScriptSig, redeemScript) {
10413 var redeemScriptStack = bscript.decompile(redeemScriptSig)
10414
10415 return bscript.compile(encodeStack(redeemScriptStack, redeemScript))
10416}
10417
10418function decodeStack (stack) {
10419 typeforce(check, stack)
10420
10421 return {
10422 redeemScriptStack: stack.slice(0, -1),
10423 redeemScript: stack[stack.length - 1]
10424 }
10425}
10426
10427function decode (buffer) {
10428 var stack = bscript.decompile(buffer)
10429 var result = decodeStack(stack)
10430 result.redeemScriptSig = bscript.compile(result.redeemScriptStack)
10431 delete result.redeemScriptStack
10432 return result
10433}
10434
10435module.exports = {
10436 check: check,
10437 decode: decode,
10438 decodeStack: decodeStack,
10439 encode: encode,
10440 encodeStack: encodeStack
10441}
10442
10443},{"../../script":52,"safe-buffer":98,"typeforce":109}],67:[function(require,module,exports){
10444// OP_HASH160 {scriptHash} OP_EQUAL
10445
10446var bscript = require('../../script')
10447var types = require('../../types')
10448var typeforce = require('typeforce')
10449var OPS = require('bitcoin-ops')
10450
10451function check (script) {
10452 var buffer = bscript.compile(script)
10453
10454 return buffer.length === 23 &&
10455 buffer[0] === OPS.OP_HASH160 &&
10456 buffer[1] === 0x14 &&
10457 buffer[22] === OPS.OP_EQUAL
10458}
10459check.toJSON = function () { return 'scriptHash output' }
10460
10461function encode (scriptHash) {
10462 typeforce(types.Hash160bit, scriptHash)
10463
10464 return bscript.compile([OPS.OP_HASH160, scriptHash, OPS.OP_EQUAL])
10465}
10466
10467function decode (buffer) {
10468 typeforce(check, buffer)
10469
10470 return buffer.slice(2, 22)
10471}
10472
10473module.exports = {
10474 check: check,
10475 decode: decode,
10476 encode: encode
10477}
10478
10479},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],68:[function(require,module,exports){
10480module.exports = {
10481 output: require('./output')
10482}
10483
10484},{"./output":69}],69:[function(require,module,exports){
10485// OP_RETURN {aa21a9ed} {commitment}
10486
10487var Buffer = require('safe-buffer').Buffer
10488var bscript = require('../../script')
10489var types = require('../../types')
10490var typeforce = require('typeforce')
10491var OPS = require('bitcoin-ops')
10492
10493var HEADER = Buffer.from('aa21a9ed', 'hex')
10494
10495function check (script) {
10496 var buffer = bscript.compile(script)
10497
10498 return buffer.length > 37 &&
10499 buffer[0] === OPS.OP_RETURN &&
10500 buffer[1] === 0x24 &&
10501 buffer.slice(2, 6).equals(HEADER)
10502}
10503
10504check.toJSON = function () { return 'Witness commitment output' }
10505
10506function encode (commitment) {
10507 typeforce(types.Hash256bit, commitment)
10508
10509 var buffer = Buffer.allocUnsafe(36)
10510 HEADER.copy(buffer, 0)
10511 commitment.copy(buffer, 4)
10512
10513 return bscript.compile([OPS.OP_RETURN, buffer])
10514}
10515
10516function decode (buffer) {
10517 typeforce(check, buffer)
10518
10519 return bscript.decompile(buffer)[1].slice(4, 36)
10520}
10521
10522module.exports = {
10523 check: check,
10524 decode: decode,
10525 encode: encode
10526}
10527
10528},{"../../script":52,"../../types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],70:[function(require,module,exports){
10529arguments[4][55][0].apply(exports,arguments)
10530},{"./input":71,"./output":72,"dup":55}],71:[function(require,module,exports){
10531// {signature} {pubKey}
10532
10533var pkh = require('../pubkeyhash/input')
10534
10535module.exports = {
10536 check: pkh.check,
10537 decodeStack: pkh.decodeStack,
10538 encodeStack: pkh.encodeStack
10539}
10540
10541},{"../pubkeyhash/input":63}],72:[function(require,module,exports){
10542// OP_0 {pubKeyHash}
10543
10544var bscript = require('../../script')
10545var types = require('../../types')
10546var typeforce = require('typeforce')
10547var OPS = require('bitcoin-ops')
10548
10549function check (script) {
10550 var buffer = bscript.compile(script)
10551
10552 return buffer.length === 22 &&
10553 buffer[0] === OPS.OP_0 &&
10554 buffer[1] === 0x14
10555}
10556check.toJSON = function () { return 'Witness pubKeyHash output' }
10557
10558function encode (pubKeyHash) {
10559 typeforce(types.Hash160bit, pubKeyHash)
10560
10561 return bscript.compile([OPS.OP_0, pubKeyHash])
10562}
10563
10564function decode (buffer) {
10565 typeforce(check, buffer)
10566
10567 return buffer.slice(2)
10568}
10569
10570module.exports = {
10571 check: check,
10572 decode: decode,
10573 encode: encode
10574}
10575
10576},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],73:[function(require,module,exports){
10577arguments[4][55][0].apply(exports,arguments)
10578},{"./input":74,"./output":75,"dup":55}],74:[function(require,module,exports){
10579// {signature} {pubKey}
10580
10581var p2sh = require('../scripthash/input')
10582
10583module.exports = {
10584 check: p2sh.check,
10585 decodeStack: p2sh.decodeStack,
10586 encodeStack: p2sh.encodeStack
10587}
10588
10589},{"../scripthash/input":66}],75:[function(require,module,exports){
10590// OP_0 {scriptHash}
10591
10592var bscript = require('../../script')
10593var types = require('../../types')
10594var typeforce = require('typeforce')
10595var OPS = require('bitcoin-ops')
10596
10597function check (script) {
10598 var buffer = bscript.compile(script)
10599
10600 return buffer.length === 34 &&
10601 buffer[0] === OPS.OP_0 &&
10602 buffer[1] === 0x20
10603}
10604check.toJSON = function () { return 'Witness scriptHash output' }
10605
10606function encode (scriptHash) {
10607 typeforce(types.Hash256bit, scriptHash)
10608
10609 return bscript.compile([OPS.OP_0, scriptHash])
10610}
10611
10612function decode (buffer) {
10613 typeforce(check, buffer)
10614
10615 return buffer.slice(2)
10616}
10617
10618module.exports = {
10619 check: check,
10620 decode: decode,
10621 encode: encode
10622}
10623
10624},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],76:[function(require,module,exports){
10625var Buffer = require('safe-buffer').Buffer
10626var bcrypto = require('./crypto')
10627var bscript = require('./script')
10628var bufferutils = require('./bufferutils')
10629var opcodes = require('bitcoin-ops')
10630var typeforce = require('typeforce')
10631var types = require('./types')
10632var varuint = require('varuint-bitcoin')
10633
10634function varSliceSize (someScript) {
10635 var length = someScript.length
10636
10637 return varuint.encodingLength(length) + length
10638}
10639
10640function vectorSize (someVector) {
10641 var length = someVector.length
10642
10643 return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) {
10644 return sum + varSliceSize(witness)
10645 }, 0)
10646}
10647
10648function Transaction () {
10649 this.version = 1
10650 this.locktime = 0
10651 this.ins = []
10652 this.outs = []
10653}
10654
10655Transaction.DEFAULT_SEQUENCE = 0xffffffff
10656Transaction.SIGHASH_ALL = 0x01
10657Transaction.SIGHASH_NONE = 0x02
10658Transaction.SIGHASH_SINGLE = 0x03
10659Transaction.SIGHASH_ANYONECANPAY = 0x80
10660Transaction.ADVANCED_TRANSACTION_MARKER = 0x00
10661Transaction.ADVANCED_TRANSACTION_FLAG = 0x01
10662
10663var EMPTY_SCRIPT = Buffer.allocUnsafe(0)
10664var EMPTY_WITNESS = []
10665var ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
10666var ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex')
10667var VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex')
10668var BLANK_OUTPUT = {
10669 script: EMPTY_SCRIPT,
10670 valueBuffer: VALUE_UINT64_MAX
10671}
10672
10673Transaction.fromBuffer = function (buffer, __noStrict) {
10674 var offset = 0
10675 function readSlice (n) {
10676 offset += n
10677 return buffer.slice(offset - n, offset)
10678 }
10679
10680 function readUInt32 () {
10681 var i = buffer.readUInt32LE(offset)
10682 offset += 4
10683 return i
10684 }
10685
10686 function readInt32 () {
10687 var i = buffer.readInt32LE(offset)
10688 offset += 4
10689 return i
10690 }
10691
10692 function readUInt64 () {
10693 var i = bufferutils.readUInt64LE(buffer, offset)
10694 offset += 8
10695 return i
10696 }
10697
10698 function readVarInt () {
10699 var vi = varuint.decode(buffer, offset)
10700 offset += varuint.decode.bytes
10701 return vi
10702 }
10703
10704 function readVarSlice () {
10705 return readSlice(readVarInt())
10706 }
10707
10708 function readVector () {
10709 var count = readVarInt()
10710 var vector = []
10711 for (var i = 0; i < count; i++) vector.push(readVarSlice())
10712 return vector
10713 }
10714
10715 var tx = new Transaction()
10716 tx.version = readInt32()
10717
10718 var marker = buffer.readUInt8(offset)
10719 var flag = buffer.readUInt8(offset + 1)
10720
10721 var hasWitnesses = false
10722 if (marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
10723 flag === Transaction.ADVANCED_TRANSACTION_FLAG) {
10724 offset += 2
10725 hasWitnesses = true
10726 }
10727
10728 var vinLen = readVarInt()
10729 for (var i = 0; i < vinLen; ++i) {
10730 tx.ins.push({
10731 hash: readSlice(32),
10732 index: readUInt32(),
10733 script: readVarSlice(),
10734 sequence: readUInt32(),
10735 witness: EMPTY_WITNESS
10736 })
10737 }
10738
10739 var voutLen = readVarInt()
10740 for (i = 0; i < voutLen; ++i) {
10741 tx.outs.push({
10742 value: readUInt64(),
10743 script: readVarSlice()
10744 })
10745 }
10746
10747 if (hasWitnesses) {
10748 for (i = 0; i < vinLen; ++i) {
10749 tx.ins[i].witness = readVector()
10750 }
10751
10752 // was this pointless?
10753 if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
10754 }
10755
10756 tx.locktime = readUInt32()
10757
10758 if (__noStrict) return tx
10759 if (offset !== buffer.length) throw new Error('Transaction has unexpected data')
10760
10761 return tx
10762}
10763
10764Transaction.fromHex = function (hex) {
10765 return Transaction.fromBuffer(Buffer.from(hex, 'hex'))
10766}
10767
10768Transaction.isCoinbaseHash = function (buffer) {
10769 typeforce(types.Hash256bit, buffer)
10770 for (var i = 0; i < 32; ++i) {
10771 if (buffer[i] !== 0) return false
10772 }
10773 return true
10774}
10775
10776Transaction.prototype.isCoinbase = function () {
10777 return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
10778}
10779
10780Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) {
10781 typeforce(types.tuple(
10782 types.Hash256bit,
10783 types.UInt32,
10784 types.maybe(types.UInt32),
10785 types.maybe(types.Buffer)
10786 ), arguments)
10787
10788 if (types.Null(sequence)) {
10789 sequence = Transaction.DEFAULT_SEQUENCE
10790 }
10791
10792 // Add the input and return the input's index
10793 return (this.ins.push({
10794 hash: hash,
10795 index: index,
10796 script: scriptSig || EMPTY_SCRIPT,
10797 sequence: sequence,
10798 witness: EMPTY_WITNESS
10799 }) - 1)
10800}
10801
10802Transaction.prototype.addOutput = function (scriptPubKey, value) {
10803 typeforce(types.tuple(types.Buffer, types.Satoshi), arguments)
10804
10805 // Add the output and return the output's index
10806 return (this.outs.push({
10807 script: scriptPubKey,
10808 value: value
10809 }) - 1)
10810}
10811
10812Transaction.prototype.hasWitnesses = function () {
10813 return this.ins.some(function (x) {
10814 return x.witness.length !== 0
10815 })
10816}
10817
10818Transaction.prototype.weight = function () {
10819 var base = this.__byteLength(false)
10820 var total = this.__byteLength(true)
10821 return base * 3 + total
10822}
10823
10824Transaction.prototype.virtualSize = function () {
10825 return Math.ceil(this.weight() / 4)
10826}
10827
10828Transaction.prototype.byteLength = function () {
10829 return this.__byteLength(true)
10830}
10831
10832Transaction.prototype.__byteLength = function (__allowWitness) {
10833 var hasWitnesses = __allowWitness && this.hasWitnesses()
10834
10835 return (
10836 (hasWitnesses ? 10 : 8) +
10837 varuint.encodingLength(this.ins.length) +
10838 varuint.encodingLength(this.outs.length) +
10839 this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) +
10840 this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) +
10841 (hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0)
10842 )
10843}
10844
10845Transaction.prototype.clone = function () {
10846 var newTx = new Transaction()
10847 newTx.version = this.version
10848 newTx.locktime = this.locktime
10849
10850 newTx.ins = this.ins.map(function (txIn) {
10851 return {
10852 hash: txIn.hash,
10853 index: txIn.index,
10854 script: txIn.script,
10855 sequence: txIn.sequence,
10856 witness: txIn.witness
10857 }
10858 })
10859
10860 newTx.outs = this.outs.map(function (txOut) {
10861 return {
10862 script: txOut.script,
10863 value: txOut.value
10864 }
10865 })
10866
10867 return newTx
10868}
10869
10870/**
10871 * Hash transaction for signing a specific input.
10872 *
10873 * Bitcoin uses a different hash for each signed transaction input.
10874 * This method copies the transaction, makes the necessary changes based on the
10875 * hashType, and then hashes the result.
10876 * This hash can then be used to sign the provided transaction input.
10877 */
10878Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
10879 typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments)
10880
10881 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
10882 if (inIndex >= this.ins.length) return ONE
10883
10884 // ignore OP_CODESEPARATOR
10885 var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) {
10886 return x !== opcodes.OP_CODESEPARATOR
10887 }))
10888
10889 var txTmp = this.clone()
10890
10891 // SIGHASH_NONE: ignore all outputs? (wildcard payee)
10892 if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
10893 txTmp.outs = []
10894
10895 // ignore sequence numbers (except at inIndex)
10896 txTmp.ins.forEach(function (input, i) {
10897 if (i === inIndex) return
10898
10899 input.sequence = 0
10900 })
10901
10902 // SIGHASH_SINGLE: ignore all outputs, except at the same index?
10903 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
10904 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
10905 if (inIndex >= this.outs.length) return ONE
10906
10907 // truncate outputs after
10908 txTmp.outs.length = inIndex + 1
10909
10910 // "blank" outputs before
10911 for (var i = 0; i < inIndex; i++) {
10912 txTmp.outs[i] = BLANK_OUTPUT
10913 }
10914
10915 // ignore sequence numbers (except at inIndex)
10916 txTmp.ins.forEach(function (input, y) {
10917 if (y === inIndex) return
10918
10919 input.sequence = 0
10920 })
10921 }
10922
10923 // SIGHASH_ANYONECANPAY: ignore inputs entirely?
10924 if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
10925 txTmp.ins = [txTmp.ins[inIndex]]
10926 txTmp.ins[0].script = ourScript
10927
10928 // SIGHASH_ALL: only ignore input scripts
10929 } else {
10930 // "blank" others input scripts
10931 txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT })
10932 txTmp.ins[inIndex].script = ourScript
10933 }
10934
10935 // serialize and hash
10936 var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4)
10937 buffer.writeInt32LE(hashType, buffer.length - 4)
10938 txTmp.__toBuffer(buffer, 0, false)
10939
10940 return bcrypto.hash256(buffer)
10941}
10942
10943Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) {
10944 typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments)
10945
10946 var tbuffer, toffset
10947 function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) }
10948 function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) }
10949 function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) }
10950 function writeVarInt (i) {
10951 varuint.encode(i, tbuffer, toffset)
10952 toffset += varuint.encode.bytes
10953 }
10954 function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
10955
10956 var hashOutputs = ZERO
10957 var hashPrevouts = ZERO
10958 var hashSequence = ZERO
10959
10960 if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) {
10961 tbuffer = Buffer.allocUnsafe(36 * this.ins.length)
10962 toffset = 0
10963
10964 this.ins.forEach(function (txIn) {
10965 writeSlice(txIn.hash)
10966 writeUInt32(txIn.index)
10967 })
10968
10969 hashPrevouts = bcrypto.hash256(tbuffer)
10970 }
10971
10972 if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) &&
10973 (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
10974 (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
10975 tbuffer = Buffer.allocUnsafe(4 * this.ins.length)
10976 toffset = 0
10977
10978 this.ins.forEach(function (txIn) {
10979 writeUInt32(txIn.sequence)
10980 })
10981
10982 hashSequence = bcrypto.hash256(tbuffer)
10983 }
10984
10985 if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
10986 (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
10987 var txOutsSize = this.outs.reduce(function (sum, output) {
10988 return sum + 8 + varSliceSize(output.script)
10989 }, 0)
10990
10991 tbuffer = Buffer.allocUnsafe(txOutsSize)
10992 toffset = 0
10993
10994 this.outs.forEach(function (out) {
10995 writeUInt64(out.value)
10996 writeVarSlice(out.script)
10997 })
10998
10999 hashOutputs = bcrypto.hash256(tbuffer)
11000 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) {
11001 var output = this.outs[inIndex]
11002
11003 tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script))
11004 toffset = 0
11005 writeUInt64(output.value)
11006 writeVarSlice(output.script)
11007
11008 hashOutputs = bcrypto.hash256(tbuffer)
11009 }
11010
11011 tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript))
11012 toffset = 0
11013
11014 var input = this.ins[inIndex]
11015 writeUInt32(this.version)
11016 writeSlice(hashPrevouts)
11017 writeSlice(hashSequence)
11018 writeSlice(input.hash)
11019 writeUInt32(input.index)
11020 writeVarSlice(prevOutScript)
11021 writeUInt64(value)
11022 writeUInt32(input.sequence)
11023 writeSlice(hashOutputs)
11024 writeUInt32(this.locktime)
11025 writeUInt32(hashType)
11026 return bcrypto.hash256(tbuffer)
11027}
11028
11029Transaction.prototype.getHash = function () {
11030 return bcrypto.hash256(this.__toBuffer(undefined, undefined, false))
11031}
11032
11033Transaction.prototype.getId = function () {
11034 // transaction hash's are displayed in reverse order
11035 return this.getHash().reverse().toString('hex')
11036}
11037
11038Transaction.prototype.toBuffer = function (buffer, initialOffset) {
11039 return this.__toBuffer(buffer, initialOffset, true)
11040}
11041
11042Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) {
11043 if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness))
11044
11045 var offset = initialOffset || 0
11046 function writeSlice (slice) { offset += slice.copy(buffer, offset) }
11047 function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) }
11048 function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) }
11049 function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) }
11050 function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) }
11051 function writeVarInt (i) {
11052 varuint.encode(i, buffer, offset)
11053 offset += varuint.encode.bytes
11054 }
11055 function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
11056 function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) }
11057
11058 writeInt32(this.version)
11059
11060 var hasWitnesses = __allowWitness && this.hasWitnesses()
11061
11062 if (hasWitnesses) {
11063 writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER)
11064 writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG)
11065 }
11066
11067 writeVarInt(this.ins.length)
11068
11069 this.ins.forEach(function (txIn) {
11070 writeSlice(txIn.hash)
11071 writeUInt32(txIn.index)
11072 writeVarSlice(txIn.script)
11073 writeUInt32(txIn.sequence)
11074 })
11075
11076 writeVarInt(this.outs.length)
11077 this.outs.forEach(function (txOut) {
11078 if (!txOut.valueBuffer) {
11079 writeUInt64(txOut.value)
11080 } else {
11081 writeSlice(txOut.valueBuffer)
11082 }
11083
11084 writeVarSlice(txOut.script)
11085 })
11086
11087 if (hasWitnesses) {
11088 this.ins.forEach(function (input) {
11089 writeVector(input.witness)
11090 })
11091 }
11092
11093 writeUInt32(this.locktime)
11094
11095 // avoid slicing unless necessary
11096 if (initialOffset !== undefined) return buffer.slice(initialOffset, offset)
11097 return buffer
11098}
11099
11100Transaction.prototype.toHex = function () {
11101 return this.toBuffer().toString('hex')
11102}
11103
11104Transaction.prototype.setInputScript = function (index, scriptSig) {
11105 typeforce(types.tuple(types.Number, types.Buffer), arguments)
11106
11107 this.ins[index].script = scriptSig
11108}
11109
11110Transaction.prototype.setWitness = function (index, witness) {
11111 typeforce(types.tuple(types.Number, [types.Buffer]), arguments)
11112
11113 this.ins[index].witness = witness
11114}
11115
11116module.exports = Transaction
11117
11118},{"./bufferutils":44,"./crypto":45,"./script":52,"./types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109,"varuint-bitcoin":111}],77:[function(require,module,exports){
11119var Buffer = require('safe-buffer').Buffer
11120var baddress = require('./address')
11121var bcrypto = require('./crypto')
11122var bscript = require('./script')
11123var networks = require('./networks')
11124var ops = require('bitcoin-ops')
11125var typeforce = require('typeforce')
11126var types = require('./types')
11127var scriptTypes = bscript.types
11128var SIGNABLE = [bscript.types.P2PKH, bscript.types.P2PK, bscript.types.MULTISIG]
11129var P2SH = SIGNABLE.concat([bscript.types.P2WPKH, bscript.types.P2WSH])
11130
11131var ECPair = require('./ecpair')
11132var ECSignature = require('./ecsignature')
11133var Transaction = require('./transaction')
11134
11135function extractChunks (type, chunks, script) {
11136 var pubKeys = []
11137 var signatures = []
11138 switch (type) {
11139 case scriptTypes.P2PKH:
11140 // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)')
11141 pubKeys = chunks.slice(1)
11142 signatures = chunks.slice(0, 1)
11143 break
11144
11145 case scriptTypes.P2PK:
11146 pubKeys[0] = script ? bscript.pubKey.output.decode(script) : undefined
11147 signatures = chunks.slice(0, 1)
11148 break
11149
11150 case scriptTypes.MULTISIG:
11151 if (script) {
11152 var multisig = bscript.multisig.output.decode(script)
11153 pubKeys = multisig.pubKeys
11154 }
11155
11156 signatures = chunks.slice(1).map(function (chunk) {
11157 return chunk.length === 0 ? undefined : chunk
11158 })
11159 break
11160 }
11161
11162 return {
11163 pubKeys: pubKeys,
11164 signatures: signatures
11165 }
11166}
11167function expandInput (scriptSig, witnessStack) {
11168 if (scriptSig.length === 0 && witnessStack.length === 0) return {}
11169
11170 var prevOutScript
11171 var prevOutType
11172 var scriptType
11173 var script
11174 var redeemScript
11175 var witnessScript
11176 var witnessScriptType
11177 var redeemScriptType
11178 var witness = false
11179 var p2wsh = false
11180 var p2sh = false
11181 var witnessProgram
11182 var chunks
11183
11184 var scriptSigChunks = bscript.decompile(scriptSig)
11185 var sigType = bscript.classifyInput(scriptSigChunks, true)
11186 if (sigType === scriptTypes.P2SH) {
11187 p2sh = true
11188 redeemScript = scriptSigChunks[scriptSigChunks.length - 1]
11189 redeemScriptType = bscript.classifyOutput(redeemScript)
11190 prevOutScript = bscript.scriptHash.output.encode(bcrypto.hash160(redeemScript))
11191 prevOutType = scriptTypes.P2SH
11192 script = redeemScript
11193 }
11194
11195 var classifyWitness = bscript.classifyWitness(witnessStack)
11196 if (classifyWitness === scriptTypes.P2WSH) {
11197 witnessScript = witnessStack[witnessStack.length - 1]
11198 witnessScriptType = bscript.classifyOutput(witnessScript)
11199 p2wsh = true
11200 if (scriptSig.length === 0) {
11201 prevOutScript = bscript.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
11202 prevOutType = scriptTypes.P2WSH
11203 if (typeof redeemScript !== 'undefined') {
11204 throw new Error('Redeem script given when unnecessary')
11205 }
11206 // bare witness
11207 } else {
11208 if (!redeemScript) {
11209 throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty')
11210 }
11211 witnessProgram = bscript.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
11212 if (!redeemScript.equals(witnessProgram)) {
11213 throw new Error('Redeem script didn\'t match witnessScript')
11214 }
11215 }
11216
11217 if (SIGNABLE.indexOf(bscript.classifyOutput(witnessScript)) === -1) {
11218 throw new Error('unsupported witness script')
11219 }
11220 script = witnessScript
11221 scriptType = witnessScriptType
11222 chunks = witnessStack.slice(0, -1)
11223 } else if (classifyWitness === scriptTypes.P2WPKH) {
11224 var key = witnessStack[witnessStack.length - 1]
11225 var keyHash = bcrypto.hash160(key)
11226 if (scriptSig.length === 0) {
11227 prevOutScript = bscript.witnessPubKeyHash.output.encode(keyHash)
11228 prevOutType = scriptTypes.P2WPKH
11229 if (typeof redeemScript !== 'undefined') {
11230 throw new Error('Redeem script given when unnecessary')
11231 }
11232 } else {
11233 if (!redeemScript) {
11234 throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty')
11235 }
11236 witnessProgram = bscript.witnessPubKeyHash.output.encode(keyHash)
11237 if (!redeemScript.equals(witnessProgram)) {
11238 throw new Error('Redeem script did not have the right witness program')
11239 }
11240 }
11241
11242 scriptType = scriptTypes.P2PKH
11243 chunks = witnessStack
11244 } else if (redeemScript) {
11245 if (P2SH.indexOf(redeemScriptType) === -1) {
11246 throw new Error('Bad redeemscript!')
11247 }
11248
11249 script = redeemScript
11250 scriptType = redeemScriptType
11251 chunks = scriptSigChunks.slice(0, -1)
11252 } else {
11253 prevOutType = scriptType = bscript.classifyInput(scriptSig)
11254 chunks = scriptSigChunks
11255 }
11256
11257 var expanded = extractChunks(scriptType, chunks, script)
11258
11259 var result = {
11260 pubKeys: expanded.pubKeys,
11261 signatures: expanded.signatures,
11262 prevOutScript: prevOutScript,
11263 prevOutType: prevOutType,
11264 signType: scriptType,
11265 signScript: script,
11266 witness: Boolean(witness)
11267 }
11268
11269 if (p2sh) {
11270 result.redeemScript = redeemScript
11271 result.redeemScriptType = redeemScriptType
11272 }
11273
11274 if (p2wsh) {
11275 result.witnessScript = witnessScript
11276 result.witnessScriptType = witnessScriptType
11277 }
11278
11279 return result
11280}
11281
11282// could be done in expandInput, but requires the original Transaction for hashForSignature
11283function fixMultisigOrder (input, transaction, vin) {
11284 if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return
11285 if (input.pubKeys.length === input.signatures.length) return
11286
11287 var unmatched = input.signatures.concat()
11288
11289 input.signatures = input.pubKeys.map(function (pubKey) {
11290 var keyPair = ECPair.fromPublicKeyBuffer(pubKey)
11291 var match
11292
11293 // check for a signature
11294 unmatched.some(function (signature, i) {
11295 // skip if undefined || OP_0
11296 if (!signature) return false
11297
11298 // TODO: avoid O(n) hashForSignature
11299 var parsed = ECSignature.parseScriptSignature(signature)
11300 var hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType)
11301
11302 // skip if signature does not match pubKey
11303 if (!keyPair.verify(hash, parsed.signature)) return false
11304
11305 // remove matched signature from unmatched
11306 unmatched[i] = undefined
11307 match = signature
11308
11309 return true
11310 })
11311
11312 return match
11313 })
11314}
11315
11316function expandOutput (script, scriptType, ourPubKey) {
11317 typeforce(types.Buffer, script)
11318
11319 var scriptChunks = bscript.decompile(script)
11320 if (!scriptType) {
11321 scriptType = bscript.classifyOutput(script)
11322 }
11323
11324 var pubKeys = []
11325
11326 switch (scriptType) {
11327 // does our hash160(pubKey) match the output scripts?
11328 case scriptTypes.P2PKH:
11329 if (!ourPubKey) break
11330
11331 var pkh1 = scriptChunks[2]
11332 var pkh2 = bcrypto.hash160(ourPubKey)
11333 if (pkh1.equals(pkh2)) pubKeys = [ourPubKey]
11334 break
11335
11336 // does our hash160(pubKey) match the output scripts?
11337 case scriptTypes.P2WPKH:
11338 if (!ourPubKey) break
11339
11340 var wpkh1 = scriptChunks[1]
11341 var wpkh2 = bcrypto.hash160(ourPubKey)
11342 if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey]
11343 break
11344
11345 case scriptTypes.P2PK:
11346 pubKeys = scriptChunks.slice(0, 1)
11347 break
11348
11349 case scriptTypes.MULTISIG:
11350 pubKeys = scriptChunks.slice(1, -2)
11351 break
11352
11353 default: return { scriptType: scriptType }
11354 }
11355
11356 return {
11357 pubKeys: pubKeys,
11358 scriptType: scriptType,
11359 signatures: pubKeys.map(function () { return undefined })
11360 }
11361}
11362
11363function checkP2shInput (input, redeemScriptHash) {
11364 if (input.prevOutType) {
11365 if (input.prevOutType !== scriptTypes.P2SH) throw new Error('PrevOutScript must be P2SH')
11366
11367 var prevOutScriptScriptHash = bscript.decompile(input.prevOutScript)[1]
11368 if (!prevOutScriptScriptHash.equals(redeemScriptHash)) throw new Error('Inconsistent hash160(RedeemScript)')
11369 }
11370}
11371
11372function checkP2WSHInput (input, witnessScriptHash) {
11373 if (input.prevOutType) {
11374 if (input.prevOutType !== scriptTypes.P2WSH) throw new Error('PrevOutScript must be P2WSH')
11375
11376 var scriptHash = bscript.decompile(input.prevOutScript)[1]
11377 if (!scriptHash.equals(witnessScriptHash)) throw new Error('Inconsistent sha25(WitnessScript)')
11378 }
11379}
11380
11381function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) {
11382 var expanded
11383 var prevOutType
11384 var prevOutScript
11385
11386 var p2sh = false
11387 var p2shType
11388 var redeemScriptHash
11389
11390 var witness = false
11391 var p2wsh = false
11392 var witnessType
11393 var witnessScriptHash
11394
11395 var signType
11396 var signScript
11397
11398 if (redeemScript && witnessScript) {
11399 redeemScriptHash = bcrypto.hash160(redeemScript)
11400 witnessScriptHash = bcrypto.sha256(witnessScript)
11401 checkP2shInput(input, redeemScriptHash)
11402
11403 if (!redeemScript.equals(bscript.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script')
11404
11405 expanded = expandOutput(witnessScript, undefined, kpPubKey)
11406 if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
11407 prevOutType = bscript.types.P2SH
11408 prevOutScript = bscript.scriptHash.output.encode(redeemScriptHash)
11409 p2sh = witness = p2wsh = true
11410 p2shType = bscript.types.P2WSH
11411 signType = witnessType = expanded.scriptType
11412 signScript = witnessScript
11413 } else if (redeemScript) {
11414 redeemScriptHash = bcrypto.hash160(redeemScript)
11415 checkP2shInput(input, redeemScriptHash)
11416
11417 expanded = expandOutput(redeemScript, undefined, kpPubKey)
11418 if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bscript.toASM(redeemScript) + '"')
11419
11420 prevOutType = bscript.types.P2SH
11421 prevOutScript = bscript.scriptHash.output.encode(redeemScriptHash)
11422 p2sh = true
11423 signType = p2shType = expanded.scriptType
11424 signScript = redeemScript
11425 witness = signType === bscript.types.P2WPKH
11426 } else if (witnessScript) {
11427 witnessScriptHash = bcrypto.sha256(witnessScript)
11428 checkP2WSHInput(input, witnessScriptHash)
11429
11430 expanded = expandOutput(witnessScript, undefined, kpPubKey)
11431 if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
11432
11433 prevOutType = bscript.types.P2WSH
11434 prevOutScript = bscript.witnessScriptHash.output.encode(witnessScriptHash)
11435 witness = p2wsh = true
11436 signType = witnessType = expanded.scriptType
11437 signScript = witnessScript
11438 } else if (input.prevOutType) {
11439 // embedded scripts are not possible without a redeemScript
11440 if (input.prevOutType === scriptTypes.P2SH ||
11441 input.prevOutType === scriptTypes.P2WSH) {
11442 throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript')
11443 }
11444
11445 prevOutType = input.prevOutType
11446 prevOutScript = input.prevOutScript
11447 expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey)
11448 if (!expanded.pubKeys) return
11449
11450 witness = (input.prevOutType === scriptTypes.P2WPKH)
11451 signType = prevOutType
11452 signScript = prevOutScript
11453 } else {
11454 prevOutScript = bscript.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey))
11455 expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey)
11456 prevOutType = scriptTypes.P2PKH
11457 witness = false
11458 signType = prevOutType
11459 signScript = prevOutScript
11460 }
11461
11462 if (witness && !types.Satoshi(witnessValue)) {
11463 throw new Error('Input was witness but not given witness value')
11464 }
11465
11466 if (signType === scriptTypes.P2WPKH) {
11467 signScript = bscript.pubKeyHash.output.encode(bscript.witnessPubKeyHash.output.decode(signScript))
11468 }
11469
11470 if (p2sh) {
11471 input.redeemScript = redeemScript
11472 input.redeemScriptType = p2shType
11473 }
11474
11475 if (p2wsh) {
11476 input.witnessScript = witnessScript
11477 input.witnessScriptType = witnessType
11478 }
11479
11480 input.pubKeys = expanded.pubKeys
11481 input.signatures = expanded.signatures
11482 input.signScript = signScript
11483 input.signType = signType
11484 input.prevOutScript = prevOutScript
11485 input.prevOutType = prevOutType
11486 input.witness = witness
11487}
11488
11489function buildStack (type, signatures, pubKeys, allowIncomplete) {
11490 if (type === scriptTypes.P2PKH) {
11491 if (signatures.length === 1 && Buffer.isBuffer(signatures[0]) && pubKeys.length === 1) return bscript.pubKeyHash.input.encodeStack(signatures[0], pubKeys[0])
11492 } else if (type === scriptTypes.P2PK) {
11493 if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return bscript.pubKey.input.encodeStack(signatures[0])
11494 } else if (type === scriptTypes.MULTISIG) {
11495 if (signatures.length > 0) {
11496 signatures = signatures.map(function (signature) {
11497 return signature || ops.OP_0
11498 })
11499 if (!allowIncomplete) {
11500 // remove blank signatures
11501 signatures = signatures.filter(function (x) { return x !== ops.OP_0 })
11502 }
11503
11504 return bscript.multisig.input.encodeStack(signatures /* see if it's necessary first */)
11505 }
11506 } else {
11507 throw new Error('Not yet supported')
11508 }
11509
11510 if (!allowIncomplete) throw new Error('Not enough signatures provided')
11511
11512 return []
11513}
11514
11515function buildInput (input, allowIncomplete) {
11516 var scriptType = input.prevOutType
11517 var sig = []
11518 var witness = []
11519 if (SIGNABLE.indexOf(scriptType) !== -1) {
11520 sig = buildStack(scriptType, input.signatures, input.pubKeys, allowIncomplete)
11521 }
11522
11523 var p2sh = false
11524 if (scriptType === bscript.types.P2SH) {
11525 // We can remove this error later when we have a guarantee prepareInput
11526 // rejects unsignable scripts - it MUST be signable at this point.
11527 if (P2SH.indexOf(input.redeemScriptType) === -1) {
11528 throw new Error('Impossible to sign this type')
11529 }
11530 p2sh = true
11531 if (SIGNABLE.indexOf(input.redeemScriptType) !== -1) {
11532 sig = buildStack(input.redeemScriptType, input.signatures, input.pubKeys, allowIncomplete)
11533 }
11534 // If it wasn't SIGNABLE, it's witness, defer to that
11535 scriptType = input.redeemScriptType
11536 }
11537
11538 if (scriptType === bscript.types.P2WPKH) {
11539 // P2WPKH is a special case of P2PKH
11540 witness = buildStack(bscript.types.P2PKH, input.signatures, input.pubKeys, allowIncomplete)
11541 } else if (scriptType === bscript.types.P2WSH) {
11542 // We can remove this check later
11543 if (SIGNABLE.indexOf(input.witnessScriptType) !== -1) {
11544 witness = buildStack(input.witnessScriptType, input.signatures, input.pubKeys, allowIncomplete)
11545 witness.push(input.witnessScript)
11546 } else {
11547 // We can remove this error later when we have a guarantee prepareInput
11548 // rejects unsignble scripts - it MUST be signable at this point.
11549 throw new Error()
11550 }
11551
11552 scriptType = input.witnessScriptType
11553 }
11554
11555 // append redeemScript if necessary
11556 if (p2sh) {
11557 sig.push(input.redeemScript)
11558 }
11559
11560 return {
11561 type: scriptType,
11562 script: bscript.compile(sig),
11563 witness: witness
11564 }
11565}
11566
11567function TransactionBuilder (network, maximumFeeRate) {
11568 this.prevTxMap = {}
11569 this.network = network || networks.bitcoin
11570
11571 // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth)
11572 this.maximumFeeRate = maximumFeeRate || 1000
11573
11574 this.inputs = []
11575 this.tx = new Transaction()
11576}
11577
11578TransactionBuilder.prototype.setLockTime = function (locktime) {
11579 typeforce(types.UInt32, locktime)
11580
11581 // if any signatures exist, throw
11582 if (this.inputs.some(function (input) {
11583 if (!input.signatures) return false
11584
11585 return input.signatures.some(function (s) { return s })
11586 })) {
11587 throw new Error('No, this would invalidate signatures')
11588 }
11589
11590 this.tx.locktime = locktime
11591}
11592
11593TransactionBuilder.prototype.setVersion = function (version) {
11594 typeforce(types.UInt32, version)
11595
11596 // XXX: this might eventually become more complex depending on what the versions represent
11597 this.tx.version = version
11598}
11599
11600TransactionBuilder.fromTransaction = function (transaction, network) {
11601 var txb = new TransactionBuilder(network)
11602
11603 // Copy transaction fields
11604 txb.setVersion(transaction.version)
11605 txb.setLockTime(transaction.locktime)
11606
11607 // Copy outputs (done first to avoid signature invalidation)
11608 transaction.outs.forEach(function (txOut) {
11609 txb.addOutput(txOut.script, txOut.value)
11610 })
11611
11612 // Copy inputs
11613 transaction.ins.forEach(function (txIn) {
11614 txb.__addInputUnsafe(txIn.hash, txIn.index, {
11615 sequence: txIn.sequence,
11616 script: txIn.script,
11617 witness: txIn.witness
11618 })
11619 })
11620
11621 // fix some things not possible through the public API
11622 txb.inputs.forEach(function (input, i) {
11623 fixMultisigOrder(input, transaction, i)
11624 })
11625
11626 return txb
11627}
11628
11629TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) {
11630 if (!this.__canModifyInputs()) {
11631 throw new Error('No, this would invalidate signatures')
11632 }
11633
11634 var value
11635
11636 // is it a hex string?
11637 if (typeof txHash === 'string') {
11638 // transaction hashs's are displayed in reverse order, un-reverse it
11639 txHash = Buffer.from(txHash, 'hex').reverse()
11640
11641 // is it a Transaction object?
11642 } else if (txHash instanceof Transaction) {
11643 var txOut = txHash.outs[vout]
11644 prevOutScript = txOut.script
11645 value = txOut.value
11646
11647 txHash = txHash.getHash()
11648 }
11649
11650 return this.__addInputUnsafe(txHash, vout, {
11651 sequence: sequence,
11652 prevOutScript: prevOutScript,
11653 value: value
11654 })
11655}
11656
11657TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) {
11658 if (Transaction.isCoinbaseHash(txHash)) {
11659 throw new Error('coinbase inputs not supported')
11660 }
11661
11662 var prevTxOut = txHash.toString('hex') + ':' + vout
11663 if (this.prevTxMap[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut)
11664
11665 var input = {}
11666
11667 // derive what we can from the scriptSig
11668 if (options.script !== undefined) {
11669 input = expandInput(options.script, options.witness || [])
11670 }
11671
11672 // if an input value was given, retain it
11673 if (options.value !== undefined) {
11674 input.value = options.value
11675 }
11676
11677 // derive what we can from the previous transactions output script
11678 if (!input.prevOutScript && options.prevOutScript) {
11679 var prevOutType
11680
11681 if (!input.pubKeys && !input.signatures) {
11682 var expanded = expandOutput(options.prevOutScript)
11683
11684 if (expanded.pubKeys) {
11685 input.pubKeys = expanded.pubKeys
11686 input.signatures = expanded.signatures
11687 }
11688
11689 prevOutType = expanded.scriptType
11690 }
11691
11692 input.prevOutScript = options.prevOutScript
11693 input.prevOutType = prevOutType || bscript.classifyOutput(options.prevOutScript)
11694 }
11695
11696 var vin = this.tx.addInput(txHash, vout, options.sequence, options.scriptSig)
11697 this.inputs[vin] = input
11698 this.prevTxMap[prevTxOut] = vin
11699
11700 return vin
11701}
11702
11703TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) {
11704 if (!this.__canModifyOutputs()) {
11705 throw new Error('No, this would invalidate signatures')
11706 }
11707
11708 // Attempt to get a script if it's a base58 address string
11709 if (typeof scriptPubKey === 'string') {
11710 scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network)
11711 }
11712
11713 return this.tx.addOutput(scriptPubKey, value)
11714}
11715
11716TransactionBuilder.prototype.build = function () {
11717 return this.__build(false)
11718}
11719TransactionBuilder.prototype.buildIncomplete = function () {
11720 return this.__build(true)
11721}
11722
11723TransactionBuilder.prototype.__build = function (allowIncomplete) {
11724 if (!allowIncomplete) {
11725 if (!this.tx.ins.length) throw new Error('Transaction has no inputs')
11726 if (!this.tx.outs.length) throw new Error('Transaction has no outputs')
11727 }
11728
11729 var tx = this.tx.clone()
11730 // Create script signatures from inputs
11731 this.inputs.forEach(function (input, i) {
11732 var scriptType = input.witnessScriptType || input.redeemScriptType || input.prevOutType
11733 if (!scriptType && !allowIncomplete) throw new Error('Transaction is not complete')
11734 var result = buildInput(input, allowIncomplete)
11735
11736 // skip if no result
11737 if (!allowIncomplete) {
11738 if (SIGNABLE.indexOf(result.type) === -1 && result.type !== bscript.types.P2WPKH) {
11739 throw new Error(result.type + ' not supported')
11740 }
11741 }
11742
11743 tx.setInputScript(i, result.script)
11744 tx.setWitness(i, result.witness)
11745 })
11746
11747 if (!allowIncomplete) {
11748 // do not rely on this, its merely a last resort
11749 if (this.__overMaximumFees(tx.byteLength())) {
11750 throw new Error('Transaction has absurd fees')
11751 }
11752 }
11753
11754 return tx
11755}
11756
11757function canSign (input) {
11758 return input.prevOutScript !== undefined &&
11759 input.signScript !== undefined &&
11760 input.pubKeys !== undefined &&
11761 input.signatures !== undefined &&
11762 input.signatures.length === input.pubKeys.length &&
11763 input.pubKeys.length > 0 &&
11764 input.witness !== undefined
11765}
11766
11767TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) {
11768 if (keyPair.network !== this.network) throw new Error('Inconsistent network')
11769 if (!this.inputs[vin]) throw new Error('No input at index: ' + vin)
11770 hashType = hashType || Transaction.SIGHASH_ALL
11771
11772 var input = this.inputs[vin]
11773
11774 // if redeemScript was previously provided, enforce consistency
11775 if (input.redeemScript !== undefined &&
11776 redeemScript &&
11777 !input.redeemScript.equals(redeemScript)) {
11778 throw new Error('Inconsistent redeemScript')
11779 }
11780
11781 var kpPubKey = keyPair.getPublicKeyBuffer()
11782 if (!canSign(input)) {
11783 prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript)
11784 if (!canSign(input)) throw Error(input.prevOutType + ' not supported')
11785 }
11786
11787 // ready to sign
11788 var signatureHash
11789 if (input.witness) {
11790 signatureHash = this.tx.hashForWitnessV0(vin, input.signScript, witnessValue, hashType)
11791 } else {
11792 signatureHash = this.tx.hashForSignature(vin, input.signScript, hashType)
11793 }
11794 // enforce in order signing of public keys
11795 var signed = input.pubKeys.some(function (pubKey, i) {
11796 if (!kpPubKey.equals(pubKey)) return false
11797 if (input.signatures[i]) throw new Error('Signature already exists')
11798
11799 input.signatures[i] = keyPair.sign(signatureHash).toScriptSignature(hashType)
11800 return true
11801 })
11802
11803 if (!signed) throw new Error('Key pair cannot sign for this input')
11804}
11805
11806function signatureHashType (buffer) {
11807 return buffer.readUInt8(buffer.length - 1)
11808}
11809
11810TransactionBuilder.prototype.__canModifyInputs = function () {
11811 return this.inputs.every(function (input) {
11812 // any signatures?
11813 if (input.signatures === undefined) return true
11814
11815 return input.signatures.every(function (signature) {
11816 if (!signature) return true
11817 var hashType = signatureHashType(signature)
11818
11819 // if SIGHASH_ANYONECANPAY is set, signatures would not
11820 // be invalidated by more inputs
11821 return hashType & Transaction.SIGHASH_ANYONECANPAY
11822 })
11823 })
11824}
11825
11826TransactionBuilder.prototype.__canModifyOutputs = function () {
11827 var nInputs = this.tx.ins.length
11828 var nOutputs = this.tx.outs.length
11829
11830 return this.inputs.every(function (input) {
11831 if (input.signatures === undefined) return true
11832
11833 return input.signatures.every(function (signature) {
11834 if (!signature) return true
11835 var hashType = signatureHashType(signature)
11836
11837 var hashTypeMod = hashType & 0x1f
11838 if (hashTypeMod === Transaction.SIGHASH_NONE) return true
11839 if (hashTypeMod === Transaction.SIGHASH_SINGLE) {
11840 // if SIGHASH_SINGLE is set, and nInputs > nOutputs
11841 // some signatures would be invalidated by the addition
11842 // of more outputs
11843 return nInputs <= nOutputs
11844 }
11845 })
11846 })
11847}
11848
11849TransactionBuilder.prototype.__overMaximumFees = function (bytes) {
11850 // not all inputs will have .value defined
11851 var incoming = this.inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0)
11852
11853 // but all outputs do, and if we have any input value
11854 // we can immediately determine if the outputs are too small
11855 var outgoing = this.tx.outs.reduce(function (a, x) { return a + x.value }, 0)
11856 var fee = incoming - outgoing
11857 var feeRate = fee / bytes
11858
11859 return feeRate > this.maximumFeeRate
11860}
11861
11862module.exports = TransactionBuilder
11863
11864},{"./address":42,"./crypto":45,"./ecpair":47,"./ecsignature":48,"./networks":51,"./script":52,"./transaction":76,"./types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],78:[function(require,module,exports){
11865var typeforce = require('typeforce')
11866
11867var UINT31_MAX = Math.pow(2, 31) - 1
11868function UInt31 (value) {
11869 return typeforce.UInt32(value) && value <= UINT31_MAX
11870}
11871
11872function BIP32Path (value) {
11873 return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/)
11874}
11875BIP32Path.toJSON = function () { return 'BIP32 derivation path' }
11876
11877var SATOSHI_MAX = 21 * 1e14
11878function Satoshi (value) {
11879 return typeforce.UInt53(value) && value <= SATOSHI_MAX
11880}
11881
11882// external dependent types
11883var BigInt = typeforce.quacksLike('BigInteger')
11884var ECPoint = typeforce.quacksLike('Point')
11885
11886// exposed, external API
11887var ECSignature = typeforce.compile({ r: BigInt, s: BigInt })
11888var Network = typeforce.compile({
11889 messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String),
11890 bip32: {
11891 public: typeforce.UInt32,
11892 private: typeforce.UInt32
11893 },
11894 pubKeyHash: typeforce.UInt8,
11895 scriptHash: typeforce.UInt8,
11896 wif: typeforce.UInt8
11897})
11898
11899// extend typeforce types with ours
11900var types = {
11901 BigInt: BigInt,
11902 BIP32Path: BIP32Path,
11903 Buffer256bit: typeforce.BufferN(32),
11904 ECPoint: ECPoint,
11905 ECSignature: ECSignature,
11906 Hash160bit: typeforce.BufferN(20),
11907 Hash256bit: typeforce.BufferN(32),
11908 Network: Network,
11909 Satoshi: Satoshi,
11910 UInt31: UInt31
11911}
11912
11913for (var typeName in typeforce) {
11914 types[typeName] = typeforce[typeName]
11915}
11916
11917module.exports = types
11918
11919},{"typeforce":109}],79:[function(require,module,exports){
11920var basex = require('base-x')
11921var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
11922
11923module.exports = basex(ALPHABET)
11924
11925},{"base-x":34}],80:[function(require,module,exports){
11926(function (Buffer){
11927'use strict'
11928
11929var base58 = require('bs58')
11930var createHash = require('create-hash')
11931
11932// SHA256(SHA256(buffer))
11933function sha256x2 (buffer) {
11934 var tmp = createHash('sha256').update(buffer).digest()
11935 return createHash('sha256').update(tmp).digest()
11936}
11937
11938// Encode a buffer as a base58-check encoded string
11939function encode (payload) {
11940 var checksum = sha256x2(payload)
11941
11942 return base58.encode(Buffer.concat([
11943 payload,
11944 checksum
11945 ], payload.length + 4))
11946}
11947
11948function decodeRaw (buffer) {
11949 var payload = buffer.slice(0, -4)
11950 var checksum = buffer.slice(-4)
11951 var newChecksum = sha256x2(payload)
11952
11953 if (checksum[0] ^ newChecksum[0] |
11954 checksum[1] ^ newChecksum[1] |
11955 checksum[2] ^ newChecksum[2] |
11956 checksum[3] ^ newChecksum[3]) return
11957
11958 return payload
11959}
11960
11961// Decode a base58-check encoded string to a buffer, no result if checksum is wrong
11962function decodeUnsafe (string) {
11963 var buffer = base58.decodeUnsafe(string)
11964 if (!buffer) return
11965
11966 return decodeRaw(buffer)
11967}
11968
11969function decode (string) {
11970 var buffer = base58.decode(string)
11971 var payload = decodeRaw(buffer)
11972 if (!payload) throw new Error('Invalid checksum')
11973 return payload
11974}
11975
11976module.exports = {
11977 encode: encode,
11978 decode: decode,
11979 decodeUnsafe: decodeUnsafe
11980}
11981
11982}).call(this,require("buffer").Buffer)
11983},{"bs58":79,"buffer":4,"create-hash":82}],81:[function(require,module,exports){
11984var Buffer = require('safe-buffer').Buffer
11985var Transform = require('stream').Transform
11986var StringDecoder = require('string_decoder').StringDecoder
11987var inherits = require('inherits')
11988
11989function CipherBase (hashMode) {
11990 Transform.call(this)
11991 this.hashMode = typeof hashMode === 'string'
11992 if (this.hashMode) {
11993 this[hashMode] = this._finalOrDigest
11994 } else {
11995 this.final = this._finalOrDigest
11996 }
11997 if (this._final) {
11998 this.__final = this._final
11999 this._final = null
12000 }
12001 this._decoder = null
12002 this._encoding = null
12003}
12004inherits(CipherBase, Transform)
12005
12006CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
12007 if (typeof data === 'string') {
12008 data = Buffer.from(data, inputEnc)
12009 }
12010
12011 var outData = this._update(data)
12012 if (this.hashMode) return this
12013
12014 if (outputEnc) {
12015 outData = this._toString(outData, outputEnc)
12016 }
12017
12018 return outData
12019}
12020
12021CipherBase.prototype.setAutoPadding = function () {}
12022CipherBase.prototype.getAuthTag = function () {
12023 throw new Error('trying to get auth tag in unsupported state')
12024}
12025
12026CipherBase.prototype.setAuthTag = function () {
12027 throw new Error('trying to set auth tag in unsupported state')
12028}
12029
12030CipherBase.prototype.setAAD = function () {
12031 throw new Error('trying to set aad in unsupported state')
12032}
12033
12034CipherBase.prototype._transform = function (data, _, next) {
12035 var err
12036 try {
12037 if (this.hashMode) {
12038 this._update(data)
12039 } else {
12040 this.push(this._update(data))
12041 }
12042 } catch (e) {
12043 err = e
12044 } finally {
12045 next(err)
12046 }
12047}
12048CipherBase.prototype._flush = function (done) {
12049 var err
12050 try {
12051 this.push(this.__final())
12052 } catch (e) {
12053 err = e
12054 }
12055
12056 done(err)
12057}
12058CipherBase.prototype._finalOrDigest = function (outputEnc) {
12059 var outData = this.__final() || Buffer.alloc(0)
12060 if (outputEnc) {
12061 outData = this._toString(outData, outputEnc, true)
12062 }
12063 return outData
12064}
12065
12066CipherBase.prototype._toString = function (value, enc, fin) {
12067 if (!this._decoder) {
12068 this._decoder = new StringDecoder(enc)
12069 this._encoding = enc
12070 }
12071
12072 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
12073
12074 var out = this._decoder.write(value)
12075 if (fin) {
12076 out += this._decoder.end()
12077 }
12078
12079 return out
12080}
12081
12082module.exports = CipherBase
12083
12084},{"inherits":93,"safe-buffer":98,"stream":27,"string_decoder":28}],82:[function(require,module,exports){
12085(function (Buffer){
12086'use strict'
12087var inherits = require('inherits')
12088var md5 = require('./md5')
12089var RIPEMD160 = require('ripemd160')
12090var sha = require('sha.js')
12091
12092var Base = require('cipher-base')
12093
12094function HashNoConstructor (hash) {
12095 Base.call(this, 'digest')
12096
12097 this._hash = hash
12098 this.buffers = []
12099}
12100
12101inherits(HashNoConstructor, Base)
12102
12103HashNoConstructor.prototype._update = function (data) {
12104 this.buffers.push(data)
12105}
12106
12107HashNoConstructor.prototype._final = function () {
12108 var buf = Buffer.concat(this.buffers)
12109 var r = this._hash(buf)
12110 this.buffers = null
12111
12112 return r
12113}
12114
12115function Hash (hash) {
12116 Base.call(this, 'digest')
12117
12118 this._hash = hash
12119}
12120
12121inherits(Hash, Base)
12122
12123Hash.prototype._update = function (data) {
12124 this._hash.update(data)
12125}
12126
12127Hash.prototype._final = function () {
12128 return this._hash.digest()
12129}
12130
12131module.exports = function createHash (alg) {
12132 alg = alg.toLowerCase()
12133 if (alg === 'md5') return new HashNoConstructor(md5)
12134 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
12135
12136 return new Hash(sha(alg))
12137}
12138
12139}).call(this,require("buffer").Buffer)
12140},{"./md5":84,"buffer":4,"cipher-base":81,"inherits":93,"ripemd160":97,"sha.js":100}],83:[function(require,module,exports){
12141(function (Buffer){
12142'use strict'
12143var intSize = 4
12144var zeroBuffer = new Buffer(intSize)
12145zeroBuffer.fill(0)
12146
12147var charSize = 8
12148var hashSize = 16
12149
12150function toArray (buf) {
12151 if ((buf.length % intSize) !== 0) {
12152 var len = buf.length + (intSize - (buf.length % intSize))
12153 buf = Buffer.concat([buf, zeroBuffer], len)
12154 }
12155
12156 var arr = new Array(buf.length >>> 2)
12157 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
12158 arr[j] = buf.readInt32LE(i)
12159 }
12160
12161 return arr
12162}
12163
12164module.exports = function hash (buf, fn) {
12165 var arr = fn(toArray(buf), buf.length * charSize)
12166 buf = new Buffer(hashSize)
12167 for (var i = 0; i < arr.length; i++) {
12168 buf.writeInt32LE(arr[i], i << 2, true)
12169 }
12170 return buf
12171}
12172
12173}).call(this,require("buffer").Buffer)
12174},{"buffer":4}],84:[function(require,module,exports){
12175'use strict'
12176/*
12177 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
12178 * Digest Algorithm, as defined in RFC 1321.
12179 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
12180 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
12181 * Distributed under the BSD License
12182 * See http://pajhome.org.uk/crypt/md5 for more info.
12183 */
12184
12185var makeHash = require('./make-hash')
12186
12187/*
12188 * Calculate the MD5 of an array of little-endian words, and a bit length
12189 */
12190function core_md5 (x, len) {
12191 /* append padding */
12192 x[len >> 5] |= 0x80 << ((len) % 32)
12193 x[(((len + 64) >>> 9) << 4) + 14] = len
12194
12195 var a = 1732584193
12196 var b = -271733879
12197 var c = -1732584194
12198 var d = 271733878
12199
12200 for (var i = 0; i < x.length; i += 16) {
12201 var olda = a
12202 var oldb = b
12203 var oldc = c
12204 var oldd = d
12205
12206 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
12207 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
12208 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
12209 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
12210 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
12211 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
12212 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
12213 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
12214 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
12215 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
12216 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
12217 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
12218 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
12219 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
12220 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
12221 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
12222
12223 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
12224 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
12225 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
12226 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
12227 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
12228 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
12229 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
12230 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
12231 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
12232 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
12233 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
12234 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
12235 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
12236 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
12237 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
12238 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
12239
12240 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
12241 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
12242 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
12243 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
12244 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
12245 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
12246 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
12247 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
12248 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
12249 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
12250 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
12251 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
12252 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
12253 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
12254 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
12255 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
12256
12257 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
12258 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
12259 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
12260 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
12261 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
12262 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
12263 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
12264 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
12265 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
12266 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
12267 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
12268 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
12269 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
12270 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
12271 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
12272 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
12273
12274 a = safe_add(a, olda)
12275 b = safe_add(b, oldb)
12276 c = safe_add(c, oldc)
12277 d = safe_add(d, oldd)
12278 }
12279
12280 return [a, b, c, d]
12281}
12282
12283/*
12284 * These functions implement the four basic operations the algorithm uses.
12285 */
12286function md5_cmn (q, a, b, x, s, t) {
12287 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
12288}
12289
12290function md5_ff (a, b, c, d, x, s, t) {
12291 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
12292}
12293
12294function md5_gg (a, b, c, d, x, s, t) {
12295 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
12296}
12297
12298function md5_hh (a, b, c, d, x, s, t) {
12299 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
12300}
12301
12302function md5_ii (a, b, c, d, x, s, t) {
12303 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
12304}
12305
12306/*
12307 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
12308 * to work around bugs in some JS interpreters.
12309 */
12310function safe_add (x, y) {
12311 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
12312 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
12313 return (msw << 16) | (lsw & 0xFFFF)
12314}
12315
12316/*
12317 * Bitwise rotate a 32-bit number to the left.
12318 */
12319function bit_rol (num, cnt) {
12320 return (num << cnt) | (num >>> (32 - cnt))
12321}
12322
12323module.exports = function md5 (buf) {
12324 return makeHash(buf, core_md5)
12325}
12326
12327},{"./make-hash":83}],85:[function(require,module,exports){
12328'use strict'
12329var inherits = require('inherits')
12330var Legacy = require('./legacy')
12331var Base = require('cipher-base')
12332var Buffer = require('safe-buffer').Buffer
12333var md5 = require('create-hash/md5')
12334var RIPEMD160 = require('ripemd160')
12335
12336var sha = require('sha.js')
12337
12338var ZEROS = Buffer.alloc(128)
12339
12340function Hmac (alg, key) {
12341 Base.call(this, 'digest')
12342 if (typeof key === 'string') {
12343 key = Buffer.from(key)
12344 }
12345
12346 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
12347
12348 this._alg = alg
12349 this._key = key
12350 if (key.length > blocksize) {
12351 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12352 key = hash.update(key).digest()
12353 } else if (key.length < blocksize) {
12354 key = Buffer.concat([key, ZEROS], blocksize)
12355 }
12356
12357 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12358 var opad = this._opad = Buffer.allocUnsafe(blocksize)
12359
12360 for (var i = 0; i < blocksize; i++) {
12361 ipad[i] = key[i] ^ 0x36
12362 opad[i] = key[i] ^ 0x5C
12363 }
12364 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12365 this._hash.update(ipad)
12366}
12367
12368inherits(Hmac, Base)
12369
12370Hmac.prototype._update = function (data) {
12371 this._hash.update(data)
12372}
12373
12374Hmac.prototype._final = function () {
12375 var h = this._hash.digest()
12376 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
12377 return hash.update(this._opad).update(h).digest()
12378}
12379
12380module.exports = function createHmac (alg, key) {
12381 alg = alg.toLowerCase()
12382 if (alg === 'rmd160' || alg === 'ripemd160') {
12383 return new Hmac('rmd160', key)
12384 }
12385 if (alg === 'md5') {
12386 return new Legacy(md5, key)
12387 }
12388 return new Hmac(alg, key)
12389}
12390
12391},{"./legacy":86,"cipher-base":81,"create-hash/md5":84,"inherits":93,"ripemd160":97,"safe-buffer":98,"sha.js":100}],86:[function(require,module,exports){
12392'use strict'
12393var inherits = require('inherits')
12394var Buffer = require('safe-buffer').Buffer
12395
12396var Base = require('cipher-base')
12397
12398var ZEROS = Buffer.alloc(128)
12399var blocksize = 64
12400
12401function Hmac (alg, key) {
12402 Base.call(this, 'digest')
12403 if (typeof key === 'string') {
12404 key = Buffer.from(key)
12405 }
12406
12407 this._alg = alg
12408 this._key = key
12409
12410 if (key.length > blocksize) {
12411 key = alg(key)
12412 } else if (key.length < blocksize) {
12413 key = Buffer.concat([key, ZEROS], blocksize)
12414 }
12415
12416 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12417 var opad = this._opad = Buffer.allocUnsafe(blocksize)
12418
12419 for (var i = 0; i < blocksize; i++) {
12420 ipad[i] = key[i] ^ 0x36
12421 opad[i] = key[i] ^ 0x5C
12422 }
12423
12424 this._hash = [ipad]
12425}
12426
12427inherits(Hmac, Base)
12428
12429Hmac.prototype._update = function (data) {
12430 this._hash.push(data)
12431}
12432
12433Hmac.prototype._final = function () {
12434 var h = this._alg(Buffer.concat(this._hash))
12435 return this._alg(Buffer.concat([this._opad, h]))
12436}
12437module.exports = Hmac
12438
12439},{"cipher-base":81,"inherits":93,"safe-buffer":98}],87:[function(require,module,exports){
12440var assert = require('assert')
12441var BigInteger = require('bigi')
12442
12443var Point = require('./point')
12444
12445function Curve (p, a, b, Gx, Gy, n, h) {
12446 this.p = p
12447 this.a = a
12448 this.b = b
12449 this.G = Point.fromAffine(this, Gx, Gy)
12450 this.n = n
12451 this.h = h
12452
12453 this.infinity = new Point(this, null, null, BigInteger.ZERO)
12454
12455 // result caching
12456 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
12457
12458 // determine size of p in bytes
12459 this.pLength = Math.floor((this.p.bitLength() + 7) / 8)
12460}
12461
12462Curve.prototype.pointFromX = function (isOdd, x) {
12463 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
12464 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves
12465
12466 var y = beta
12467 if (beta.isEven() ^ !isOdd) {
12468 y = this.p.subtract(y) // -y % p
12469 }
12470
12471 return Point.fromAffine(this, x, y)
12472}
12473
12474Curve.prototype.isInfinity = function (Q) {
12475 if (Q === this.infinity) return true
12476
12477 return Q.z.signum() === 0 && Q.y.signum() !== 0
12478}
12479
12480Curve.prototype.isOnCurve = function (Q) {
12481 if (this.isInfinity(Q)) return true
12482
12483 var x = Q.affineX
12484 var y = Q.affineY
12485 var a = this.a
12486 var b = this.b
12487 var p = this.p
12488
12489 // Check that xQ and yQ are integers in the interval [0, p - 1]
12490 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
12491 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
12492
12493 // and check that y^2 = x^3 + ax + b (mod p)
12494 var lhs = y.square().mod(p)
12495 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
12496 return lhs.equals(rhs)
12497}
12498
12499/**
12500 * Validate an elliptic curve point.
12501 *
12502 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
12503 */
12504Curve.prototype.validate = function (Q) {
12505 // Check Q != O
12506 assert(!this.isInfinity(Q), 'Point is at infinity')
12507 assert(this.isOnCurve(Q), 'Point is not on the curve')
12508
12509 // Check nQ = O (where Q is a scalar multiple of G)
12510 var nQ = Q.multiply(this.n)
12511 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
12512
12513 return true
12514}
12515
12516module.exports = Curve
12517
12518},{"./point":91,"assert":1,"bigi":37}],88:[function(require,module,exports){
12519module.exports={
12520 "secp128r1": {
12521 "p": "fffffffdffffffffffffffffffffffff",
12522 "a": "fffffffdfffffffffffffffffffffffc",
12523 "b": "e87579c11079f43dd824993c2cee5ed3",
12524 "n": "fffffffe0000000075a30d1b9038a115",
12525 "h": "01",
12526 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
12527 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
12528 },
12529 "secp160k1": {
12530 "p": "fffffffffffffffffffffffffffffffeffffac73",
12531 "a": "00",
12532 "b": "07",
12533 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
12534 "h": "01",
12535 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
12536 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
12537 },
12538 "secp160r1": {
12539 "p": "ffffffffffffffffffffffffffffffff7fffffff",
12540 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
12541 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
12542 "n": "0100000000000000000001f4c8f927aed3ca752257",
12543 "h": "01",
12544 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
12545 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
12546 },
12547 "secp192k1": {
12548 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
12549 "a": "00",
12550 "b": "03",
12551 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
12552 "h": "01",
12553 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
12554 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
12555 },
12556 "secp192r1": {
12557 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
12558 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
12559 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
12560 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
12561 "h": "01",
12562 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
12563 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
12564 },
12565 "secp256k1": {
12566 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
12567 "a": "00",
12568 "b": "07",
12569 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
12570 "h": "01",
12571 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
12572 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
12573 },
12574 "secp256r1": {
12575 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
12576 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
12577 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
12578 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
12579 "h": "01",
12580 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
12581 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
12582 }
12583}
12584
12585},{}],89:[function(require,module,exports){
12586var Point = require('./point')
12587var Curve = require('./curve')
12588
12589var getCurveByName = require('./names')
12590
12591module.exports = {
12592 Curve: Curve,
12593 Point: Point,
12594 getCurveByName: getCurveByName
12595}
12596
12597},{"./curve":87,"./names":90,"./point":91}],90:[function(require,module,exports){
12598var BigInteger = require('bigi')
12599
12600var curves = require('./curves.json')
12601var Curve = require('./curve')
12602
12603function getCurveByName (name) {
12604 var curve = curves[name]
12605 if (!curve) return null
12606
12607 var p = new BigInteger(curve.p, 16)
12608 var a = new BigInteger(curve.a, 16)
12609 var b = new BigInteger(curve.b, 16)
12610 var n = new BigInteger(curve.n, 16)
12611 var h = new BigInteger(curve.h, 16)
12612 var Gx = new BigInteger(curve.Gx, 16)
12613 var Gy = new BigInteger(curve.Gy, 16)
12614
12615 return new Curve(p, a, b, Gx, Gy, n, h)
12616}
12617
12618module.exports = getCurveByName
12619
12620},{"./curve":87,"./curves.json":88,"bigi":37}],91:[function(require,module,exports){
12621(function (Buffer){
12622var assert = require('assert')
12623var BigInteger = require('bigi')
12624
12625var THREE = BigInteger.valueOf(3)
12626
12627function Point (curve, x, y, z) {
12628 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
12629
12630 this.curve = curve
12631 this.x = x
12632 this.y = y
12633 this.z = z
12634 this._zInv = null
12635
12636 this.compressed = true
12637}
12638
12639Object.defineProperty(Point.prototype, 'zInv', {
12640 get: function () {
12641 if (this._zInv === null) {
12642 this._zInv = this.z.modInverse(this.curve.p)
12643 }
12644
12645 return this._zInv
12646 }
12647})
12648
12649Object.defineProperty(Point.prototype, 'affineX', {
12650 get: function () {
12651 return this.x.multiply(this.zInv).mod(this.curve.p)
12652 }
12653})
12654
12655Object.defineProperty(Point.prototype, 'affineY', {
12656 get: function () {
12657 return this.y.multiply(this.zInv).mod(this.curve.p)
12658 }
12659})
12660
12661Point.fromAffine = function (curve, x, y) {
12662 return new Point(curve, x, y, BigInteger.ONE)
12663}
12664
12665Point.prototype.equals = function (other) {
12666 if (other === this) return true
12667 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
12668 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
12669
12670 // u = Y2 * Z1 - Y1 * Z2
12671 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
12672
12673 if (u.signum() !== 0) return false
12674
12675 // v = X2 * Z1 - X1 * Z2
12676 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
12677
12678 return v.signum() === 0
12679}
12680
12681Point.prototype.negate = function () {
12682 var y = this.curve.p.subtract(this.y)
12683
12684 return new Point(this.curve, this.x, y, this.z)
12685}
12686
12687Point.prototype.add = function (b) {
12688 if (this.curve.isInfinity(this)) return b
12689 if (this.curve.isInfinity(b)) return this
12690
12691 var x1 = this.x
12692 var y1 = this.y
12693 var x2 = b.x
12694 var y2 = b.y
12695
12696 // u = Y2 * Z1 - Y1 * Z2
12697 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
12698 // v = X2 * Z1 - X1 * Z2
12699 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
12700
12701 if (v.signum() === 0) {
12702 if (u.signum() === 0) {
12703 return this.twice() // this == b, so double
12704 }
12705
12706 return this.curve.infinity // this = -b, so infinity
12707 }
12708
12709 var v2 = v.square()
12710 var v3 = v2.multiply(v)
12711 var x1v2 = x1.multiply(v2)
12712 var zu2 = u.square().multiply(this.z)
12713
12714 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
12715 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
12716 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
12717 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)
12718 // z3 = v^3 * z1 * z2
12719 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
12720
12721 return new Point(this.curve, x3, y3, z3)
12722}
12723
12724Point.prototype.twice = function () {
12725 if (this.curve.isInfinity(this)) return this
12726 if (this.y.signum() === 0) return this.curve.infinity
12727
12728 var x1 = this.x
12729 var y1 = this.y
12730
12731 var y1z1 = y1.multiply(this.z).mod(this.curve.p)
12732 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
12733 var a = this.curve.a
12734
12735 // w = 3 * x1^2 + a * z1^2
12736 var w = x1.square().multiply(THREE)
12737
12738 if (a.signum() !== 0) {
12739 w = w.add(this.z.square().multiply(a))
12740 }
12741
12742 w = w.mod(this.curve.p)
12743 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
12744 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
12745 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
12746 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
12747 // z3 = 8 * (y1 * z1)^3
12748 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
12749
12750 return new Point(this.curve, x3, y3, z3)
12751}
12752
12753// Simple NAF (Non-Adjacent Form) multiplication algorithm
12754// TODO: modularize the multiplication algorithm
12755Point.prototype.multiply = function (k) {
12756 if (this.curve.isInfinity(this)) return this
12757 if (k.signum() === 0) return this.curve.infinity
12758
12759 var e = k
12760 var h = e.multiply(THREE)
12761
12762 var neg = this.negate()
12763 var R = this
12764
12765 for (var i = h.bitLength() - 2; i > 0; --i) {
12766 var hBit = h.testBit(i)
12767 var eBit = e.testBit(i)
12768
12769 R = R.twice()
12770
12771 if (hBit !== eBit) {
12772 R = R.add(hBit ? this : neg)
12773 }
12774 }
12775
12776 return R
12777}
12778
12779// Compute this*j + x*k (simultaneous multiplication)
12780Point.prototype.multiplyTwo = function (j, x, k) {
12781 var i = Math.max(j.bitLength(), k.bitLength()) - 1
12782 var R = this.curve.infinity
12783 var both = this.add(x)
12784
12785 while (i >= 0) {
12786 var jBit = j.testBit(i)
12787 var kBit = k.testBit(i)
12788
12789 R = R.twice()
12790
12791 if (jBit) {
12792 if (kBit) {
12793 R = R.add(both)
12794 } else {
12795 R = R.add(this)
12796 }
12797 } else if (kBit) {
12798 R = R.add(x)
12799 }
12800 --i
12801 }
12802
12803 return R
12804}
12805
12806Point.prototype.getEncoded = function (compressed) {
12807 if (compressed == null) compressed = this.compressed
12808 if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00'
12809
12810 var x = this.affineX
12811 var y = this.affineY
12812 var byteLength = this.curve.pLength
12813 var buffer
12814
12815 // 0x02/0x03 | X
12816 if (compressed) {
12817 buffer = new Buffer(1 + byteLength)
12818 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
12819
12820 // 0x04 | X | Y
12821 } else {
12822 buffer = new Buffer(1 + byteLength + byteLength)
12823 buffer.writeUInt8(0x04, 0)
12824
12825 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
12826 }
12827
12828 x.toBuffer(byteLength).copy(buffer, 1)
12829
12830 return buffer
12831}
12832
12833Point.decodeFrom = function (curve, buffer) {
12834 var type = buffer.readUInt8(0)
12835 var compressed = (type !== 4)
12836
12837 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
12838 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength))
12839
12840 var Q
12841 if (compressed) {
12842 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
12843 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
12844
12845 var isOdd = (type === 0x03)
12846 Q = curve.pointFromX(isOdd, x)
12847 } else {
12848 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
12849
12850 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
12851 Q = Point.fromAffine(curve, x, y)
12852 }
12853
12854 Q.compressed = compressed
12855 return Q
12856}
12857
12858Point.prototype.toString = function () {
12859 if (this.curve.isInfinity(this)) return '(INFINITY)'
12860
12861 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
12862}
12863
12864module.exports = Point
12865
12866}).call(this,require("buffer").Buffer)
12867},{"assert":1,"bigi":37,"buffer":4}],92:[function(require,module,exports){
12868(function (Buffer){
12869'use strict'
12870var Transform = require('stream').Transform
12871var inherits = require('inherits')
12872
12873function HashBase (blockSize) {
12874 Transform.call(this)
12875
12876 this._block = new Buffer(blockSize)
12877 this._blockSize = blockSize
12878 this._blockOffset = 0
12879 this._length = [0, 0, 0, 0]
12880
12881 this._finalized = false
12882}
12883
12884inherits(HashBase, Transform)
12885
12886HashBase.prototype._transform = function (chunk, encoding, callback) {
12887 var error = null
12888 try {
12889 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
12890 this.update(chunk)
12891 } catch (err) {
12892 error = err
12893 }
12894
12895 callback(error)
12896}
12897
12898HashBase.prototype._flush = function (callback) {
12899 var error = null
12900 try {
12901 this.push(this._digest())
12902 } catch (err) {
12903 error = err
12904 }
12905
12906 callback(error)
12907}
12908
12909HashBase.prototype.update = function (data, encoding) {
12910 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
12911 if (this._finalized) throw new Error('Digest already called')
12912 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
12913
12914 // consume data
12915 var block = this._block
12916 var offset = 0
12917 while (this._blockOffset + data.length - offset >= this._blockSize) {
12918 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
12919 this._update()
12920 this._blockOffset = 0
12921 }
12922 while (offset < data.length) block[this._blockOffset++] = data[offset++]
12923
12924 // update length
12925 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
12926 this._length[j] += carry
12927 carry = (this._length[j] / 0x0100000000) | 0
12928 if (carry > 0) this._length[j] -= 0x0100000000 * carry
12929 }
12930
12931 return this
12932}
12933
12934HashBase.prototype._update = function (data) {
12935 throw new Error('_update is not implemented')
12936}
12937
12938HashBase.prototype.digest = function (encoding) {
12939 if (this._finalized) throw new Error('Digest already called')
12940 this._finalized = true
12941
12942 var digest = this._digest()
12943 if (encoding !== undefined) digest = digest.toString(encoding)
12944 return digest
12945}
12946
12947HashBase.prototype._digest = function () {
12948 throw new Error('_digest is not implemented')
12949}
12950
12951module.exports = HashBase
12952
12953}).call(this,require("buffer").Buffer)
12954},{"buffer":4,"inherits":93,"stream":27}],93:[function(require,module,exports){
12955arguments[4][8][0].apply(exports,arguments)
12956},{"dup":8}],94:[function(require,module,exports){
12957(function (Buffer){
12958// constant-space merkle root calculation algorithm
12959module.exports = function fastRoot (values, digestFn) {
12960 if (!Array.isArray(values)) throw TypeError('Expected values Array')
12961 if (typeof digestFn !== 'function') throw TypeError('Expected digest Function')
12962
12963 var length = values.length
12964 var results = values.concat()
12965
12966 while (length > 1) {
12967 var j = 0
12968
12969 for (var i = 0; i < length; i += 2, ++j) {
12970 var left = results[i]
12971 var right = i + 1 === length ? left : results[i + 1]
12972 var data = Buffer.concat([left, right])
12973
12974 results[j] = digestFn(data)
12975 }
12976
12977 length = j
12978 }
12979
12980 return results[0]
12981}
12982
12983}).call(this,require("buffer").Buffer)
12984},{"buffer":4}],95:[function(require,module,exports){
12985var OPS = require('bitcoin-ops')
12986
12987function encodingLength (i) {
12988 return i < OPS.OP_PUSHDATA1 ? 1
12989 : i <= 0xff ? 2
12990 : i <= 0xffff ? 3
12991 : 5
12992}
12993
12994function encode (buffer, number, offset) {
12995 var size = encodingLength(number)
12996
12997 // ~6 bit
12998 if (size === 1) {
12999 buffer.writeUInt8(number, offset)
13000
13001 // 8 bit
13002 } else if (size === 2) {
13003 buffer.writeUInt8(OPS.OP_PUSHDATA1, offset)
13004 buffer.writeUInt8(number, offset + 1)
13005
13006 // 16 bit
13007 } else if (size === 3) {
13008 buffer.writeUInt8(OPS.OP_PUSHDATA2, offset)
13009 buffer.writeUInt16LE(number, offset + 1)
13010
13011 // 32 bit
13012 } else {
13013 buffer.writeUInt8(OPS.OP_PUSHDATA4, offset)
13014 buffer.writeUInt32LE(number, offset + 1)
13015 }
13016
13017 return size
13018}
13019
13020function decode (buffer, offset) {
13021 var opcode = buffer.readUInt8(offset)
13022 var number, size
13023
13024 // ~6 bit
13025 if (opcode < OPS.OP_PUSHDATA1) {
13026 number = opcode
13027 size = 1
13028
13029 // 8 bit
13030 } else if (opcode === OPS.OP_PUSHDATA1) {
13031 if (offset + 2 > buffer.length) return null
13032 number = buffer.readUInt8(offset + 1)
13033 size = 2
13034
13035 // 16 bit
13036 } else if (opcode === OPS.OP_PUSHDATA2) {
13037 if (offset + 3 > buffer.length) return null
13038 number = buffer.readUInt16LE(offset + 1)
13039 size = 3
13040
13041 // 32 bit
13042 } else {
13043 if (offset + 5 > buffer.length) return null
13044 if (opcode !== OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode')
13045
13046 number = buffer.readUInt32LE(offset + 1)
13047 size = 5
13048 }
13049
13050 return {
13051 opcode: opcode,
13052 number: number,
13053 size: size
13054 }
13055}
13056
13057module.exports = {
13058 encodingLength: encodingLength,
13059 encode: encode,
13060 decode: decode
13061}
13062
13063},{"bitcoin-ops":40}],96:[function(require,module,exports){
13064(function (process,global){
13065'use strict'
13066
13067function oldBrowser () {
13068 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
13069}
13070
13071var Buffer = require('safe-buffer').Buffer
13072var crypto = global.crypto || global.msCrypto
13073
13074if (crypto && crypto.getRandomValues) {
13075 module.exports = randomBytes
13076} else {
13077 module.exports = oldBrowser
13078}
13079
13080function randomBytes (size, cb) {
13081 // phantomjs needs to throw
13082 if (size > 65536) throw new Error('requested too many random bytes')
13083 // in case browserify isn't using the Uint8Array version
13084 var rawBytes = new global.Uint8Array(size)
13085
13086 // This will not work in older browsers.
13087 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
13088 if (size > 0) { // getRandomValues fails on IE if size == 0
13089 crypto.getRandomValues(rawBytes)
13090 }
13091
13092 // XXX: phantomjs doesn't like a buffer being passed here
13093 var bytes = Buffer.from(rawBytes.buffer)
13094
13095 if (typeof cb === 'function') {
13096 return process.nextTick(function () {
13097 cb(null, bytes)
13098 })
13099 }
13100
13101 return bytes
13102}
13103
13104}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13105},{"_process":12,"safe-buffer":98}],97:[function(require,module,exports){
13106(function (Buffer){
13107'use strict'
13108var inherits = require('inherits')
13109var HashBase = require('hash-base')
13110
13111function RIPEMD160 () {
13112 HashBase.call(this, 64)
13113
13114 // state
13115 this._a = 0x67452301
13116 this._b = 0xefcdab89
13117 this._c = 0x98badcfe
13118 this._d = 0x10325476
13119 this._e = 0xc3d2e1f0
13120}
13121
13122inherits(RIPEMD160, HashBase)
13123
13124RIPEMD160.prototype._update = function () {
13125 var m = new Array(16)
13126 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
13127
13128 var al = this._a
13129 var bl = this._b
13130 var cl = this._c
13131 var dl = this._d
13132 var el = this._e
13133
13134 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
13135 // K = 0x00000000
13136 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
13137 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
13138 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
13139 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
13140 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
13141 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
13142 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
13143 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
13144 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
13145 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
13146 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
13147 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
13148 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
13149 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
13150 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
13151 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
13152 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
13153
13154 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
13155 // K = 0x5a827999
13156 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
13157 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
13158 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
13159 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
13160 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
13161 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
13162 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
13163 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
13164 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
13165 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
13166 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
13167 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
13168 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
13169 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
13170 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
13171 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
13172 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
13173
13174 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
13175 // K = 0x6ed9eba1
13176 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
13177 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
13178 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
13179 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
13180 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
13181 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
13182 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
13183 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
13184 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
13185 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
13186 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
13187 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
13188 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
13189 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
13190 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
13191 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
13192 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
13193
13194 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
13195 // K = 0x8f1bbcdc
13196 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
13197 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
13198 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
13199 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
13200 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
13201 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
13202 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
13203 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
13204 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
13205 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
13206 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
13207 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
13208 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
13209 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
13210 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
13211 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
13212 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
13213
13214 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
13215 // K = 0xa953fd4e
13216 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
13217 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
13218 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
13219 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
13220 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
13221 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
13222 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
13223 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
13224 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
13225 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
13226 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
13227 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
13228 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
13229 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
13230 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
13231 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
13232 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
13233
13234 var ar = this._a
13235 var br = this._b
13236 var cr = this._c
13237 var dr = this._d
13238 var er = this._e
13239
13240 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
13241 // K' = 0x50a28be6
13242 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
13243 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
13244 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
13245 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
13246 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
13247 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
13248 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
13249 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
13250 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
13251 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
13252 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
13253 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
13254 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
13255 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
13256 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
13257 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
13258 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
13259
13260 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
13261 // K' = 0x5c4dd124
13262 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
13263 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
13264 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
13265 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
13266 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
13267 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
13268 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
13269 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
13270 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
13271 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
13272 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
13273 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
13274 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
13275 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
13276 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
13277 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
13278 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
13279
13280 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
13281 // K' = 0x6d703ef3
13282 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
13283 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
13284 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
13285 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
13286 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
13287 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
13288 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
13289 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
13290 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
13291 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
13292 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
13293 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
13294 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
13295 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
13296 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
13297 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
13298 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
13299
13300 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
13301 // K' = 0x7a6d76e9
13302 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
13303 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
13304 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
13305 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
13306 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
13307 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
13308 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
13309 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
13310 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
13311 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
13312 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
13313 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
13314 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
13315 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
13316 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
13317 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
13318 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
13319
13320 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
13321 // K' = 0x00000000
13322 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
13323 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
13324 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
13325 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
13326 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
13327 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
13328 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
13329 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
13330 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
13331 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
13332 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
13333 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
13334 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
13335 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
13336 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
13337 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
13338 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
13339
13340 // change state
13341 var t = (this._b + cl + dr) | 0
13342 this._b = (this._c + dl + er) | 0
13343 this._c = (this._d + el + ar) | 0
13344 this._d = (this._e + al + br) | 0
13345 this._e = (this._a + bl + cr) | 0
13346 this._a = t
13347}
13348
13349RIPEMD160.prototype._digest = function () {
13350 // create padding and handle blocks
13351 this._block[this._blockOffset++] = 0x80
13352 if (this._blockOffset > 56) {
13353 this._block.fill(0, this._blockOffset, 64)
13354 this._update()
13355 this._blockOffset = 0
13356 }
13357
13358 this._block.fill(0, this._blockOffset, 56)
13359 this._block.writeUInt32LE(this._length[0], 56)
13360 this._block.writeUInt32LE(this._length[1], 60)
13361 this._update()
13362
13363 // produce result
13364 var buffer = new Buffer(20)
13365 buffer.writeInt32LE(this._a, 0)
13366 buffer.writeInt32LE(this._b, 4)
13367 buffer.writeInt32LE(this._c, 8)
13368 buffer.writeInt32LE(this._d, 12)
13369 buffer.writeInt32LE(this._e, 16)
13370 return buffer
13371}
13372
13373function rotl (x, n) {
13374 return (x << n) | (x >>> (32 - n))
13375}
13376
13377function fn1 (a, b, c, d, e, m, k, s) {
13378 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
13379}
13380
13381function fn2 (a, b, c, d, e, m, k, s) {
13382 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
13383}
13384
13385function fn3 (a, b, c, d, e, m, k, s) {
13386 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
13387}
13388
13389function fn4 (a, b, c, d, e, m, k, s) {
13390 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
13391}
13392
13393function fn5 (a, b, c, d, e, m, k, s) {
13394 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
13395}
13396
13397module.exports = RIPEMD160
13398
13399}).call(this,require("buffer").Buffer)
13400},{"buffer":4,"hash-base":92,"inherits":93}],98:[function(require,module,exports){
13401arguments[4][26][0].apply(exports,arguments)
13402},{"buffer":4,"dup":26}],99:[function(require,module,exports){
13403(function (Buffer){
13404// prototype class for hash functions
13405function Hash (blockSize, finalSize) {
13406 this._block = new Buffer(blockSize)
13407 this._finalSize = finalSize
13408 this._blockSize = blockSize
13409 this._len = 0
13410 this._s = 0
13411}
13412
13413Hash.prototype.update = function (data, enc) {
13414 if (typeof data === 'string') {
13415 enc = enc || 'utf8'
13416 data = new Buffer(data, enc)
13417 }
13418
13419 var l = this._len += data.length
13420 var s = this._s || 0
13421 var f = 0
13422 var buffer = this._block
13423
13424 while (s < l) {
13425 var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
13426 var ch = (t - f)
13427
13428 for (var i = 0; i < ch; i++) {
13429 buffer[(s % this._blockSize) + i] = data[i + f]
13430 }
13431
13432 s += ch
13433 f += ch
13434
13435 if ((s % this._blockSize) === 0) {
13436 this._update(buffer)
13437 }
13438 }
13439 this._s = s
13440
13441 return this
13442}
13443
13444Hash.prototype.digest = function (enc) {
13445 // Suppose the length of the message M, in bits, is l
13446 var l = this._len * 8
13447
13448 // Append the bit 1 to the end of the message
13449 this._block[this._len % this._blockSize] = 0x80
13450
13451 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
13452 this._block.fill(0, this._len % this._blockSize + 1)
13453
13454 if (l % (this._blockSize * 8) >= this._finalSize * 8) {
13455 this._update(this._block)
13456 this._block.fill(0)
13457 }
13458
13459 // to this append the block which is equal to the number l written in binary
13460 // TODO: handle case where l is > Math.pow(2, 29)
13461 this._block.writeInt32BE(l, this._blockSize - 4)
13462
13463 var hash = this._update(this._block) || this._hash()
13464
13465 return enc ? hash.toString(enc) : hash
13466}
13467
13468Hash.prototype._update = function () {
13469 throw new Error('_update must be implemented by subclass')
13470}
13471
13472module.exports = Hash
13473
13474}).call(this,require("buffer").Buffer)
13475},{"buffer":4}],100:[function(require,module,exports){
13476var exports = module.exports = function SHA (algorithm) {
13477 algorithm = algorithm.toLowerCase()
13478
13479 var Algorithm = exports[algorithm]
13480 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
13481
13482 return new Algorithm()
13483}
13484
13485exports.sha = require('./sha')
13486exports.sha1 = require('./sha1')
13487exports.sha224 = require('./sha224')
13488exports.sha256 = require('./sha256')
13489exports.sha384 = require('./sha384')
13490exports.sha512 = require('./sha512')
13491
13492},{"./sha":101,"./sha1":102,"./sha224":103,"./sha256":104,"./sha384":105,"./sha512":106}],101:[function(require,module,exports){
13493(function (Buffer){
13494/*
13495 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
13496 * in FIPS PUB 180-1
13497 * This source code is derived from sha1.js of the same repository.
13498 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
13499 * operation was added.
13500 */
13501
13502var inherits = require('inherits')
13503var Hash = require('./hash')
13504
13505var K = [
13506 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13507]
13508
13509var W = new Array(80)
13510
13511function Sha () {
13512 this.init()
13513 this._w = W
13514
13515 Hash.call(this, 64, 56)
13516}
13517
13518inherits(Sha, Hash)
13519
13520Sha.prototype.init = function () {
13521 this._a = 0x67452301
13522 this._b = 0xefcdab89
13523 this._c = 0x98badcfe
13524 this._d = 0x10325476
13525 this._e = 0xc3d2e1f0
13526
13527 return this
13528}
13529
13530function rotl5 (num) {
13531 return (num << 5) | (num >>> 27)
13532}
13533
13534function rotl30 (num) {
13535 return (num << 30) | (num >>> 2)
13536}
13537
13538function ft (s, b, c, d) {
13539 if (s === 0) return (b & c) | ((~b) & d)
13540 if (s === 2) return (b & c) | (b & d) | (c & d)
13541 return b ^ c ^ d
13542}
13543
13544Sha.prototype._update = function (M) {
13545 var W = this._w
13546
13547 var a = this._a | 0
13548 var b = this._b | 0
13549 var c = this._c | 0
13550 var d = this._d | 0
13551 var e = this._e | 0
13552
13553 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
13554 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
13555
13556 for (var j = 0; j < 80; ++j) {
13557 var s = ~~(j / 20)
13558 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
13559
13560 e = d
13561 d = c
13562 c = rotl30(b)
13563 b = a
13564 a = t
13565 }
13566
13567 this._a = (a + this._a) | 0
13568 this._b = (b + this._b) | 0
13569 this._c = (c + this._c) | 0
13570 this._d = (d + this._d) | 0
13571 this._e = (e + this._e) | 0
13572}
13573
13574Sha.prototype._hash = function () {
13575 var H = new Buffer(20)
13576
13577 H.writeInt32BE(this._a | 0, 0)
13578 H.writeInt32BE(this._b | 0, 4)
13579 H.writeInt32BE(this._c | 0, 8)
13580 H.writeInt32BE(this._d | 0, 12)
13581 H.writeInt32BE(this._e | 0, 16)
13582
13583 return H
13584}
13585
13586module.exports = Sha
13587
13588}).call(this,require("buffer").Buffer)
13589},{"./hash":99,"buffer":4,"inherits":93}],102:[function(require,module,exports){
13590(function (Buffer){
13591/*
13592 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
13593 * in FIPS PUB 180-1
13594 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
13595 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
13596 * Distributed under the BSD License
13597 * See http://pajhome.org.uk/crypt/md5 for details.
13598 */
13599
13600var inherits = require('inherits')
13601var Hash = require('./hash')
13602
13603var K = [
13604 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13605]
13606
13607var W = new Array(80)
13608
13609function Sha1 () {
13610 this.init()
13611 this._w = W
13612
13613 Hash.call(this, 64, 56)
13614}
13615
13616inherits(Sha1, Hash)
13617
13618Sha1.prototype.init = function () {
13619 this._a = 0x67452301
13620 this._b = 0xefcdab89
13621 this._c = 0x98badcfe
13622 this._d = 0x10325476
13623 this._e = 0xc3d2e1f0
13624
13625 return this
13626}
13627
13628function rotl1 (num) {
13629 return (num << 1) | (num >>> 31)
13630}
13631
13632function rotl5 (num) {
13633 return (num << 5) | (num >>> 27)
13634}
13635
13636function rotl30 (num) {
13637 return (num << 30) | (num >>> 2)
13638}
13639
13640function ft (s, b, c, d) {
13641 if (s === 0) return (b & c) | ((~b) & d)
13642 if (s === 2) return (b & c) | (b & d) | (c & d)
13643 return b ^ c ^ d
13644}
13645
13646Sha1.prototype._update = function (M) {
13647 var W = this._w
13648
13649 var a = this._a | 0
13650 var b = this._b | 0
13651 var c = this._c | 0
13652 var d = this._d | 0
13653 var e = this._e | 0
13654
13655 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
13656 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
13657
13658 for (var j = 0; j < 80; ++j) {
13659 var s = ~~(j / 20)
13660 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
13661
13662 e = d
13663 d = c
13664 c = rotl30(b)
13665 b = a
13666 a = t
13667 }
13668
13669 this._a = (a + this._a) | 0
13670 this._b = (b + this._b) | 0
13671 this._c = (c + this._c) | 0
13672 this._d = (d + this._d) | 0
13673 this._e = (e + this._e) | 0
13674}
13675
13676Sha1.prototype._hash = function () {
13677 var H = new Buffer(20)
13678
13679 H.writeInt32BE(this._a | 0, 0)
13680 H.writeInt32BE(this._b | 0, 4)
13681 H.writeInt32BE(this._c | 0, 8)
13682 H.writeInt32BE(this._d | 0, 12)
13683 H.writeInt32BE(this._e | 0, 16)
13684
13685 return H
13686}
13687
13688module.exports = Sha1
13689
13690}).call(this,require("buffer").Buffer)
13691},{"./hash":99,"buffer":4,"inherits":93}],103:[function(require,module,exports){
13692(function (Buffer){
13693/**
13694 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
13695 * in FIPS 180-2
13696 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
13697 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
13698 *
13699 */
13700
13701var inherits = require('inherits')
13702var Sha256 = require('./sha256')
13703var Hash = require('./hash')
13704
13705var W = new Array(64)
13706
13707function Sha224 () {
13708 this.init()
13709
13710 this._w = W // new Array(64)
13711
13712 Hash.call(this, 64, 56)
13713}
13714
13715inherits(Sha224, Sha256)
13716
13717Sha224.prototype.init = function () {
13718 this._a = 0xc1059ed8
13719 this._b = 0x367cd507
13720 this._c = 0x3070dd17
13721 this._d = 0xf70e5939
13722 this._e = 0xffc00b31
13723 this._f = 0x68581511
13724 this._g = 0x64f98fa7
13725 this._h = 0xbefa4fa4
13726
13727 return this
13728}
13729
13730Sha224.prototype._hash = function () {
13731 var H = new Buffer(28)
13732
13733 H.writeInt32BE(this._a, 0)
13734 H.writeInt32BE(this._b, 4)
13735 H.writeInt32BE(this._c, 8)
13736 H.writeInt32BE(this._d, 12)
13737 H.writeInt32BE(this._e, 16)
13738 H.writeInt32BE(this._f, 20)
13739 H.writeInt32BE(this._g, 24)
13740
13741 return H
13742}
13743
13744module.exports = Sha224
13745
13746}).call(this,require("buffer").Buffer)
13747},{"./hash":99,"./sha256":104,"buffer":4,"inherits":93}],104:[function(require,module,exports){
13748(function (Buffer){
13749/**
13750 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
13751 * in FIPS 180-2
13752 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
13753 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
13754 *
13755 */
13756
13757var inherits = require('inherits')
13758var Hash = require('./hash')
13759
13760var K = [
13761 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
13762 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
13763 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
13764 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
13765 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
13766 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
13767 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
13768 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
13769 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
13770 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
13771 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
13772 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
13773 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
13774 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
13775 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
13776 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
13777]
13778
13779var W = new Array(64)
13780
13781function Sha256 () {
13782 this.init()
13783
13784 this._w = W // new Array(64)
13785
13786 Hash.call(this, 64, 56)
13787}
13788
13789inherits(Sha256, Hash)
13790
13791Sha256.prototype.init = function () {
13792 this._a = 0x6a09e667
13793 this._b = 0xbb67ae85
13794 this._c = 0x3c6ef372
13795 this._d = 0xa54ff53a
13796 this._e = 0x510e527f
13797 this._f = 0x9b05688c
13798 this._g = 0x1f83d9ab
13799 this._h = 0x5be0cd19
13800
13801 return this
13802}
13803
13804function ch (x, y, z) {
13805 return z ^ (x & (y ^ z))
13806}
13807
13808function maj (x, y, z) {
13809 return (x & y) | (z & (x | y))
13810}
13811
13812function sigma0 (x) {
13813 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
13814}
13815
13816function sigma1 (x) {
13817 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
13818}
13819
13820function gamma0 (x) {
13821 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
13822}
13823
13824function gamma1 (x) {
13825 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
13826}
13827
13828Sha256.prototype._update = function (M) {
13829 var W = this._w
13830
13831 var a = this._a | 0
13832 var b = this._b | 0
13833 var c = this._c | 0
13834 var d = this._d | 0
13835 var e = this._e | 0
13836 var f = this._f | 0
13837 var g = this._g | 0
13838 var h = this._h | 0
13839
13840 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
13841 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
13842
13843 for (var j = 0; j < 64; ++j) {
13844 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
13845 var T2 = (sigma0(a) + maj(a, b, c)) | 0
13846
13847 h = g
13848 g = f
13849 f = e
13850 e = (d + T1) | 0
13851 d = c
13852 c = b
13853 b = a
13854 a = (T1 + T2) | 0
13855 }
13856
13857 this._a = (a + this._a) | 0
13858 this._b = (b + this._b) | 0
13859 this._c = (c + this._c) | 0
13860 this._d = (d + this._d) | 0
13861 this._e = (e + this._e) | 0
13862 this._f = (f + this._f) | 0
13863 this._g = (g + this._g) | 0
13864 this._h = (h + this._h) | 0
13865}
13866
13867Sha256.prototype._hash = function () {
13868 var H = new Buffer(32)
13869
13870 H.writeInt32BE(this._a, 0)
13871 H.writeInt32BE(this._b, 4)
13872 H.writeInt32BE(this._c, 8)
13873 H.writeInt32BE(this._d, 12)
13874 H.writeInt32BE(this._e, 16)
13875 H.writeInt32BE(this._f, 20)
13876 H.writeInt32BE(this._g, 24)
13877 H.writeInt32BE(this._h, 28)
13878
13879 return H
13880}
13881
13882module.exports = Sha256
13883
13884}).call(this,require("buffer").Buffer)
13885},{"./hash":99,"buffer":4,"inherits":93}],105:[function(require,module,exports){
13886(function (Buffer){
13887var inherits = require('inherits')
13888var SHA512 = require('./sha512')
13889var Hash = require('./hash')
13890
13891var W = new Array(160)
13892
13893function Sha384 () {
13894 this.init()
13895 this._w = W
13896
13897 Hash.call(this, 128, 112)
13898}
13899
13900inherits(Sha384, SHA512)
13901
13902Sha384.prototype.init = function () {
13903 this._ah = 0xcbbb9d5d
13904 this._bh = 0x629a292a
13905 this._ch = 0x9159015a
13906 this._dh = 0x152fecd8
13907 this._eh = 0x67332667
13908 this._fh = 0x8eb44a87
13909 this._gh = 0xdb0c2e0d
13910 this._hh = 0x47b5481d
13911
13912 this._al = 0xc1059ed8
13913 this._bl = 0x367cd507
13914 this._cl = 0x3070dd17
13915 this._dl = 0xf70e5939
13916 this._el = 0xffc00b31
13917 this._fl = 0x68581511
13918 this._gl = 0x64f98fa7
13919 this._hl = 0xbefa4fa4
13920
13921 return this
13922}
13923
13924Sha384.prototype._hash = function () {
13925 var H = new Buffer(48)
13926
13927 function writeInt64BE (h, l, offset) {
13928 H.writeInt32BE(h, offset)
13929 H.writeInt32BE(l, offset + 4)
13930 }
13931
13932 writeInt64BE(this._ah, this._al, 0)
13933 writeInt64BE(this._bh, this._bl, 8)
13934 writeInt64BE(this._ch, this._cl, 16)
13935 writeInt64BE(this._dh, this._dl, 24)
13936 writeInt64BE(this._eh, this._el, 32)
13937 writeInt64BE(this._fh, this._fl, 40)
13938
13939 return H
13940}
13941
13942module.exports = Sha384
13943
13944}).call(this,require("buffer").Buffer)
13945},{"./hash":99,"./sha512":106,"buffer":4,"inherits":93}],106:[function(require,module,exports){
13946(function (Buffer){
13947var inherits = require('inherits')
13948var Hash = require('./hash')
13949
13950var K = [
13951 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
13952 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
13953 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
13954 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
13955 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
13956 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
13957 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
13958 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
13959 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
13960 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
13961 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
13962 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
13963 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
13964 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
13965 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
13966 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
13967 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
13968 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
13969 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
13970 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
13971 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
13972 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
13973 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
13974 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
13975 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
13976 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
13977 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
13978 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
13979 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
13980 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
13981 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
13982 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
13983 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
13984 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
13985 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
13986 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
13987 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
13988 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
13989 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
13990 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
13991]
13992
13993var W = new Array(160)
13994
13995function Sha512 () {
13996 this.init()
13997 this._w = W
13998
13999 Hash.call(this, 128, 112)
14000}
14001
14002inherits(Sha512, Hash)
14003
14004Sha512.prototype.init = function () {
14005 this._ah = 0x6a09e667
14006 this._bh = 0xbb67ae85
14007 this._ch = 0x3c6ef372
14008 this._dh = 0xa54ff53a
14009 this._eh = 0x510e527f
14010 this._fh = 0x9b05688c
14011 this._gh = 0x1f83d9ab
14012 this._hh = 0x5be0cd19
14013
14014 this._al = 0xf3bcc908
14015 this._bl = 0x84caa73b
14016 this._cl = 0xfe94f82b
14017 this._dl = 0x5f1d36f1
14018 this._el = 0xade682d1
14019 this._fl = 0x2b3e6c1f
14020 this._gl = 0xfb41bd6b
14021 this._hl = 0x137e2179
14022
14023 return this
14024}
14025
14026function Ch (x, y, z) {
14027 return z ^ (x & (y ^ z))
14028}
14029
14030function maj (x, y, z) {
14031 return (x & y) | (z & (x | y))
14032}
14033
14034function sigma0 (x, xl) {
14035 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
14036}
14037
14038function sigma1 (x, xl) {
14039 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
14040}
14041
14042function Gamma0 (x, xl) {
14043 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
14044}
14045
14046function Gamma0l (x, xl) {
14047 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
14048}
14049
14050function Gamma1 (x, xl) {
14051 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
14052}
14053
14054function Gamma1l (x, xl) {
14055 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
14056}
14057
14058function getCarry (a, b) {
14059 return (a >>> 0) < (b >>> 0) ? 1 : 0
14060}
14061
14062Sha512.prototype._update = function (M) {
14063 var W = this._w
14064
14065 var ah = this._ah | 0
14066 var bh = this._bh | 0
14067 var ch = this._ch | 0
14068 var dh = this._dh | 0
14069 var eh = this._eh | 0
14070 var fh = this._fh | 0
14071 var gh = this._gh | 0
14072 var hh = this._hh | 0
14073
14074 var al = this._al | 0
14075 var bl = this._bl | 0
14076 var cl = this._cl | 0
14077 var dl = this._dl | 0
14078 var el = this._el | 0
14079 var fl = this._fl | 0
14080 var gl = this._gl | 0
14081 var hl = this._hl | 0
14082
14083 for (var i = 0; i < 32; i += 2) {
14084 W[i] = M.readInt32BE(i * 4)
14085 W[i + 1] = M.readInt32BE(i * 4 + 4)
14086 }
14087 for (; i < 160; i += 2) {
14088 var xh = W[i - 15 * 2]
14089 var xl = W[i - 15 * 2 + 1]
14090 var gamma0 = Gamma0(xh, xl)
14091 var gamma0l = Gamma0l(xl, xh)
14092
14093 xh = W[i - 2 * 2]
14094 xl = W[i - 2 * 2 + 1]
14095 var gamma1 = Gamma1(xh, xl)
14096 var gamma1l = Gamma1l(xl, xh)
14097
14098 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
14099 var Wi7h = W[i - 7 * 2]
14100 var Wi7l = W[i - 7 * 2 + 1]
14101
14102 var Wi16h = W[i - 16 * 2]
14103 var Wi16l = W[i - 16 * 2 + 1]
14104
14105 var Wil = (gamma0l + Wi7l) | 0
14106 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
14107 Wil = (Wil + gamma1l) | 0
14108 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
14109 Wil = (Wil + Wi16l) | 0
14110 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
14111
14112 W[i] = Wih
14113 W[i + 1] = Wil
14114 }
14115
14116 for (var j = 0; j < 160; j += 2) {
14117 Wih = W[j]
14118 Wil = W[j + 1]
14119
14120 var majh = maj(ah, bh, ch)
14121 var majl = maj(al, bl, cl)
14122
14123 var sigma0h = sigma0(ah, al)
14124 var sigma0l = sigma0(al, ah)
14125 var sigma1h = sigma1(eh, el)
14126 var sigma1l = sigma1(el, eh)
14127
14128 // t1 = h + sigma1 + ch + K[j] + W[j]
14129 var Kih = K[j]
14130 var Kil = K[j + 1]
14131
14132 var chh = Ch(eh, fh, gh)
14133 var chl = Ch(el, fl, gl)
14134
14135 var t1l = (hl + sigma1l) | 0
14136 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
14137 t1l = (t1l + chl) | 0
14138 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
14139 t1l = (t1l + Kil) | 0
14140 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
14141 t1l = (t1l + Wil) | 0
14142 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
14143
14144 // t2 = sigma0 + maj
14145 var t2l = (sigma0l + majl) | 0
14146 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
14147
14148 hh = gh
14149 hl = gl
14150 gh = fh
14151 gl = fl
14152 fh = eh
14153 fl = el
14154 el = (dl + t1l) | 0
14155 eh = (dh + t1h + getCarry(el, dl)) | 0
14156 dh = ch
14157 dl = cl
14158 ch = bh
14159 cl = bl
14160 bh = ah
14161 bl = al
14162 al = (t1l + t2l) | 0
14163 ah = (t1h + t2h + getCarry(al, t1l)) | 0
14164 }
14165
14166 this._al = (this._al + al) | 0
14167 this._bl = (this._bl + bl) | 0
14168 this._cl = (this._cl + cl) | 0
14169 this._dl = (this._dl + dl) | 0
14170 this._el = (this._el + el) | 0
14171 this._fl = (this._fl + fl) | 0
14172 this._gl = (this._gl + gl) | 0
14173 this._hl = (this._hl + hl) | 0
14174
14175 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
14176 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
14177 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
14178 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
14179 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
14180 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
14181 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
14182 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
14183}
14184
14185Sha512.prototype._hash = function () {
14186 var H = new Buffer(64)
14187
14188 function writeInt64BE (h, l, offset) {
14189 H.writeInt32BE(h, offset)
14190 H.writeInt32BE(l, offset + 4)
14191 }
14192
14193 writeInt64BE(this._ah, this._al, 0)
14194 writeInt64BE(this._bh, this._bl, 8)
14195 writeInt64BE(this._ch, this._cl, 16)
14196 writeInt64BE(this._dh, this._dl, 24)
14197 writeInt64BE(this._eh, this._el, 32)
14198 writeInt64BE(this._fh, this._fl, 40)
14199 writeInt64BE(this._gh, this._gl, 48)
14200 writeInt64BE(this._hh, this._hl, 56)
14201
14202 return H
14203}
14204
14205module.exports = Sha512
14206
14207}).call(this,require("buffer").Buffer)
14208},{"./hash":99,"buffer":4,"inherits":93}],107:[function(require,module,exports){
14209var inherits = require('inherits')
14210var native = require('./native')
14211
14212function TfTypeError (type, value, valueTypeName) {
14213 this.__error = Error.call(this)
14214 this.__type = type
14215 this.__value = value
14216 this.__valueTypeName = valueTypeName
14217
14218 var message
14219 Object.defineProperty(this, 'message', {
14220 enumerable: true,
14221 get: function () {
14222 if (message) return message
14223
14224 valueTypeName = valueTypeName || getValueTypeName(value)
14225 message = tfErrorString(type, value, valueTypeName)
14226
14227 return message
14228 }
14229 })
14230}
14231
14232function TfPropertyTypeError (type, property, label, value, error, valueTypeName) {
14233 this.__error = error || Error.call(this)
14234 this.__label = label
14235 this.__property = property
14236 this.__type = type
14237 this.__value = value
14238 this.__valueTypeName = valueTypeName
14239
14240 var message
14241 Object.defineProperty(this, 'message', {
14242 enumerable: true,
14243 get: function () {
14244 if (message) return message
14245 if (type) {
14246 valueTypeName = valueTypeName || getValueTypeName(value)
14247 message = tfPropertyErrorString(type, label, property, value, valueTypeName)
14248 } else {
14249 message = 'Unexpected property "' + property + '"'
14250 }
14251
14252 return message
14253 }
14254 })
14255}
14256
14257// inherit from Error, assign stack
14258[TfTypeError, TfPropertyTypeError].forEach(function (tfErrorType) {
14259 inherits(tfErrorType, Error)
14260 Object.defineProperty(tfErrorType, 'stack', {
14261 get: function () { return this.__error.stack }
14262 })
14263})
14264
14265function tfCustomError (expected, actual) {
14266 return new TfTypeError(expected, {}, actual)
14267}
14268
14269function tfSubError (e, property, label) {
14270 // sub child?
14271 if (e instanceof TfPropertyTypeError) {
14272 property = property + '.' + e.__property
14273 label = e.__label
14274
14275 return new TfPropertyTypeError(
14276 e.__type, property, label, e.__value, e.__error, e.__valueTypeName
14277 )
14278 }
14279
14280 // child?
14281 if (e instanceof TfTypeError) {
14282 return new TfPropertyTypeError(
14283 e.__type, property, label, e.__value, e.__error, e.__valueTypeName
14284 )
14285 }
14286
14287 return e
14288}
14289
14290function getTypeName (fn) {
14291 return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1]
14292}
14293
14294function getValueTypeName (value) {
14295 return native.Nil(value) ? '' : getTypeName(value.constructor)
14296}
14297
14298function getValue (value) {
14299 if (native.Function(value)) return ''
14300 if (native.String(value)) return JSON.stringify(value)
14301 if (value && native.Object(value)) return ''
14302 return value
14303}
14304
14305function tfJSON (type) {
14306 if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type)
14307 if (native.Array(type)) return 'Array'
14308 if (type && native.Object(type)) return 'Object'
14309
14310 return type !== undefined ? type : ''
14311}
14312
14313function tfErrorString (type, value, valueTypeName) {
14314 var valueJson = getValue(value)
14315
14316 return 'Expected ' + tfJSON(type) + ', got' +
14317 (valueTypeName !== '' ? ' ' + valueTypeName : '') +
14318 (valueJson !== '' ? ' ' + valueJson : '')
14319}
14320
14321function tfPropertyErrorString (type, label, name, value, valueTypeName) {
14322 var description = '" of type '
14323 if (label === 'key') description = '" with key type '
14324
14325 return tfErrorString('property "' + tfJSON(name) + description + tfJSON(type), value, valueTypeName)
14326}
14327
14328module.exports = {
14329 TfTypeError: TfTypeError,
14330 TfPropertyTypeError: TfPropertyTypeError,
14331 tfCustomError: tfCustomError,
14332 tfSubError: tfSubError,
14333 tfJSON: tfJSON,
14334 getValueTypeName: getValueTypeName
14335}
14336
14337},{"./native":110,"inherits":93}],108:[function(require,module,exports){
14338(function (Buffer){
14339var NATIVE = require('./native')
14340var ERRORS = require('./errors')
14341
14342function _Buffer (value) {
14343 return Buffer.isBuffer(value)
14344}
14345
14346function Hex (value) {
14347 return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value)
14348}
14349
14350function _LengthN (type, length) {
14351 var name = type.toJSON()
14352
14353 function Length (value) {
14354 if (!type(value)) return false
14355 if (value.length === length) return true
14356
14357 throw ERRORS.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')')
14358 }
14359 Length.toJSON = function () { return name }
14360
14361 return Length
14362}
14363
14364var _ArrayN = _LengthN.bind(null, NATIVE.Array)
14365var _BufferN = _LengthN.bind(null, _Buffer)
14366var _HexN = _LengthN.bind(null, Hex)
14367
14368var UINT53_MAX = Math.pow(2, 53) - 1
14369
14370function Finite (value) {
14371 return typeof value === 'number' && isFinite(value)
14372}
14373function Int8 (value) { return ((value << 24) >> 24) === value }
14374function Int16 (value) { return ((value << 16) >> 16) === value }
14375function Int32 (value) { return (value | 0) === value }
14376function UInt8 (value) { return (value & 0xff) === value }
14377function UInt16 (value) { return (value & 0xffff) === value }
14378function UInt32 (value) { return (value >>> 0) === value }
14379function UInt53 (value) {
14380 return typeof value === 'number' &&
14381 value >= 0 &&
14382 value <= UINT53_MAX &&
14383 Math.floor(value) === value
14384}
14385
14386var types = {
14387 ArrayN: _ArrayN,
14388 Buffer: _Buffer,
14389 BufferN: _BufferN,
14390 Finite: Finite,
14391 Hex: Hex,
14392 HexN: _HexN,
14393 Int8: Int8,
14394 Int16: Int16,
14395 Int32: Int32,
14396 UInt8: UInt8,
14397 UInt16: UInt16,
14398 UInt32: UInt32,
14399 UInt53: UInt53
14400}
14401
14402for (var typeName in types) {
14403 types[typeName].toJSON = function (t) {
14404 return t
14405 }.bind(null, typeName)
14406}
14407
14408module.exports = types
14409
14410}).call(this,{"isBuffer":require("../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
14411},{"../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js":9,"./errors":107,"./native":110}],109:[function(require,module,exports){
14412var ERRORS = require('./errors')
14413var NATIVE = require('./native')
14414
14415// short-hand
14416var tfJSON = ERRORS.tfJSON
14417var TfTypeError = ERRORS.TfTypeError
14418var TfPropertyTypeError = ERRORS.TfPropertyTypeError
14419var tfSubError = ERRORS.tfSubError
14420var getValueTypeName = ERRORS.getValueTypeName
14421
14422var TYPES = {
14423 arrayOf: function arrayOf (type) {
14424 type = compile(type)
14425
14426 function _arrayOf (array, strict) {
14427 if (!NATIVE.Array(array)) return false
14428
14429 return array.every(function (value, i) {
14430 try {
14431 return typeforce(type, value, strict)
14432 } catch (e) {
14433 throw tfSubError(e, i)
14434 }
14435 })
14436 }
14437 _arrayOf.toJSON = function () { return '[' + tfJSON(type) + ']' }
14438
14439 return _arrayOf
14440 },
14441
14442 maybe: function maybe (type) {
14443 type = compile(type)
14444
14445 function _maybe (value, strict) {
14446 return NATIVE.Nil(value) || type(value, strict, maybe)
14447 }
14448 _maybe.toJSON = function () { return '?' + tfJSON(type) }
14449
14450 return _maybe
14451 },
14452
14453 map: function map (propertyType, propertyKeyType) {
14454 propertyType = compile(propertyType)
14455 if (propertyKeyType) propertyKeyType = compile(propertyKeyType)
14456
14457 function _map (value, strict) {
14458 if (!NATIVE.Object(value, strict)) return false
14459 if (NATIVE.Nil(value, strict)) return false
14460
14461 for (var propertyName in value) {
14462 try {
14463 if (propertyKeyType) {
14464 typeforce(propertyKeyType, propertyName, strict)
14465 }
14466 } catch (e) {
14467 throw tfSubError(e, propertyName, 'key')
14468 }
14469
14470 try {
14471 var propertyValue = value[propertyName]
14472 typeforce(propertyType, propertyValue, strict)
14473 } catch (e) {
14474 throw tfSubError(e, propertyName)
14475 }
14476 }
14477
14478 return true
14479 }
14480
14481 if (propertyKeyType) {
14482 _map.toJSON = function () {
14483 return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}'
14484 }
14485 } else {
14486 _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }
14487 }
14488
14489 return _map
14490 },
14491
14492 object: function object (uncompiled) {
14493 var type = {}
14494
14495 for (var typePropertyName in uncompiled) {
14496 type[typePropertyName] = compile(uncompiled[typePropertyName])
14497 }
14498
14499 function _object (value, strict) {
14500 if (!NATIVE.Object(value)) return false
14501 if (NATIVE.Nil(value)) return false
14502
14503 var propertyName
14504
14505 try {
14506 for (propertyName in type) {
14507 var propertyType = type[propertyName]
14508 var propertyValue = value[propertyName]
14509
14510 typeforce(propertyType, propertyValue, strict)
14511 }
14512 } catch (e) {
14513 throw tfSubError(e, propertyName)
14514 }
14515
14516 if (strict) {
14517 for (propertyName in value) {
14518 if (type[propertyName]) continue
14519
14520 throw new TfPropertyTypeError(undefined, propertyName)
14521 }
14522 }
14523
14524 return true
14525 }
14526 _object.toJSON = function () { return tfJSON(type) }
14527
14528 return _object
14529 },
14530
14531 oneOf: function oneOf () {
14532 var types = [].slice.call(arguments).map(compile)
14533
14534 function _oneOf (value, strict) {
14535 return types.some(function (type) {
14536 try {
14537 return typeforce(type, value, strict)
14538 } catch (e) {
14539 return false
14540 }
14541 })
14542 }
14543 _oneOf.toJSON = function () { return types.map(tfJSON).join('|') }
14544
14545 return _oneOf
14546 },
14547
14548 quacksLike: function quacksLike (type) {
14549 function _quacksLike (value) {
14550 return type === getValueTypeName(value)
14551 }
14552 _quacksLike.toJSON = function () { return type }
14553
14554 return _quacksLike
14555 },
14556
14557 tuple: function tuple () {
14558 var types = [].slice.call(arguments).map(compile)
14559
14560 function _tuple (values, strict) {
14561 return types.every(function (type, i) {
14562 try {
14563 return typeforce(type, values[i], strict)
14564 } catch (e) {
14565 throw tfSubError(e, i)
14566 }
14567 }) && (!strict || values.length === arguments.length)
14568 }
14569 _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }
14570
14571 return _tuple
14572 },
14573
14574 value: function value (expected) {
14575 function _value (actual) {
14576 return actual === expected
14577 }
14578 _value.toJSON = function () { return expected }
14579
14580 return _value
14581 }
14582}
14583
14584function compile (type) {
14585 if (NATIVE.String(type)) {
14586 if (type[0] === '?') return TYPES.maybe(compile(type.slice(1)))
14587
14588 return NATIVE[type] || TYPES.quacksLike(type)
14589 } else if (type && NATIVE.Object(type)) {
14590 if (NATIVE.Array(type)) return TYPES.arrayOf(compile(type[0]))
14591
14592 return TYPES.object(type)
14593 } else if (NATIVE.Function(type)) {
14594 return type
14595 }
14596
14597 return TYPES.value(type)
14598}
14599
14600function typeforce (type, value, strict, surrogate) {
14601 if (NATIVE.Function(type)) {
14602 if (type(value, strict)) return true
14603
14604 throw new TfTypeError(surrogate || type, value)
14605 }
14606
14607 // JIT
14608 return typeforce(compile(type), value, strict)
14609}
14610
14611// assign types to typeforce function
14612for (var typeName in NATIVE) {
14613 typeforce[typeName] = NATIVE[typeName]
14614}
14615
14616for (typeName in TYPES) {
14617 typeforce[typeName] = TYPES[typeName]
14618}
14619
14620var EXTRA = require('./extra')
14621for (typeName in EXTRA) {
14622 typeforce[typeName] = EXTRA[typeName]
14623}
14624
14625// async wrapper
14626function __async (type, value, strict, callback) {
14627 // default to falsy strict if using shorthand overload
14628 if (typeof strict === 'function') return __async(type, value, false, strict)
14629
14630 try {
14631 typeforce(type, value, strict)
14632 } catch (e) {
14633 return callback(e)
14634 }
14635
14636 callback()
14637}
14638
14639typeforce.async = __async
14640typeforce.compile = compile
14641typeforce.TfTypeError = TfTypeError
14642typeforce.TfPropertyTypeError = TfPropertyTypeError
14643
14644module.exports = typeforce
14645
14646},{"./errors":107,"./extra":108,"./native":110}],110:[function(require,module,exports){
14647var types = {
14648 Array: function (value) { return value !== null && value !== undefined && value.constructor === Array },
14649 Boolean: function (value) { return typeof value === 'boolean' },
14650 Function: function (value) { return typeof value === 'function' },
14651 Nil: function (value) { return value === undefined || value === null },
14652 Number: function (value) { return typeof value === 'number' },
14653 Object: function (value) { return typeof value === 'object' },
14654 String: function (value) { return typeof value === 'string' },
14655 '': function () { return true }
14656}
14657
14658// TODO: deprecate
14659types.Null = types.Nil
14660
14661for (var typeName in types) {
14662 types[typeName].toJSON = function (t) {
14663 return t
14664 }.bind(null, typeName)
14665}
14666
14667module.exports = types
14668
14669},{}],111:[function(require,module,exports){
14670(function (Buffer){
14671'use strict'
14672
14673// Number.MAX_SAFE_INTEGER
14674var MAX_SAFE_INTEGER = 9007199254740991
14675
14676function checkUInt53 (n) {
14677 if (n < 0 || n > MAX_SAFE_INTEGER || n % 1 !== 0) throw new RangeError('value out of range')
14678}
14679
14680function encode (number, buffer, offset) {
14681 checkUInt53(number)
14682
14683 if (!buffer) buffer = new Buffer(encodingLength(number))
14684 if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance')
14685 if (!offset) offset = 0
14686
14687 // 8 bit
14688 if (number < 0xfd) {
14689 buffer.writeUInt8(number, offset)
14690 encode.bytes = 1
14691
14692 // 16 bit
14693 } else if (number <= 0xffff) {
14694 buffer.writeUInt8(0xfd, offset)
14695 buffer.writeUInt16LE(number, offset + 1)
14696 encode.bytes = 3
14697
14698 // 32 bit
14699 } else if (number <= 0xffffffff) {
14700 buffer.writeUInt8(0xfe, offset)
14701 buffer.writeUInt32LE(number, offset + 1)
14702 encode.bytes = 5
14703
14704 // 64 bit
14705 } else {
14706 buffer.writeUInt8(0xff, offset)
14707 buffer.writeUInt32LE(number >>> 0, offset + 1)
14708 buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5)
14709 encode.bytes = 9
14710 }
14711
14712 return buffer
14713}
14714
14715function decode (buffer, offset) {
14716 if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance')
14717 if (!offset) offset = 0
14718
14719 var first = buffer.readUInt8(offset)
14720
14721 // 8 bit
14722 if (first < 0xfd) {
14723 decode.bytes = 1
14724 return first
14725
14726 // 16 bit
14727 } else if (first === 0xfd) {
14728 decode.bytes = 3
14729 return buffer.readUInt16LE(offset + 1)
14730
14731 // 32 bit
14732 } else if (first === 0xfe) {
14733 decode.bytes = 5
14734 return buffer.readUInt32LE(offset + 1)
14735
14736 // 64 bit
14737 } else {
14738 decode.bytes = 9
14739 var lo = buffer.readUInt32LE(offset + 1)
14740 var hi = buffer.readUInt32LE(offset + 5)
14741 var number = hi * 0x0100000000 + lo
14742 checkUInt53(number)
14743
14744 return number
14745 }
14746}
14747
14748function encodingLength (number) {
14749 checkUInt53(number)
14750
14751 return (
14752 number < 0xfd ? 1
14753 : number <= 0xffff ? 3
14754 : number <= 0xffffffff ? 5
14755 : 9
14756 )
14757}
14758
14759module.exports = { encode: encode, decode: decode, encodingLength: encodingLength }
14760
14761}).call(this,require("buffer").Buffer)
14762},{"buffer":4}],112:[function(require,module,exports){
14763(function (Buffer){
14764var bs58check = require('bs58check')
14765
14766function decodeRaw (buffer, version) {
14767 // check version only if defined
14768 if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version')
14769
14770 // uncompressed
14771 if (buffer.length === 33) {
14772 return {
14773 version: buffer[0],
14774 privateKey: buffer.slice(1, 33),
14775 compressed: false
14776 }
14777 }
14778
14779 // invalid length
14780 if (buffer.length !== 34) throw new Error('Invalid WIF length')
14781
14782 // invalid compression flag
14783 if (buffer[33] !== 0x01) throw new Error('Invalid compression flag')
14784
14785 return {
14786 version: buffer[0],
14787 privateKey: buffer.slice(1, 33),
14788 compressed: true
14789 }
14790}
14791
14792function encodeRaw (version, privateKey, compressed) {
14793 var result = new Buffer(compressed ? 34 : 33)
14794
14795 result.writeUInt8(version, 0)
14796 privateKey.copy(result, 1)
14797
14798 if (compressed) {
14799 result[33] = 0x01
14800 }
14801
14802 return result
14803}
14804
14805function decode (string, version) {
14806 return decodeRaw(bs58check.decode(string), version)
14807}
14808
14809function encode (version, privateKey, compressed) {
14810 if (typeof version === 'number') return bs58check.encode(encodeRaw(version, privateKey, compressed))
14811
14812 return bs58check.encode(
14813 encodeRaw(
14814 version.version,
14815 version.privateKey,
14816 version.compressed
14817 )
14818 )
14819}
14820
14821module.exports = {
14822 decode: decode,
14823 decodeRaw: decodeRaw,
14824 encode: encode,
14825 encodeRaw: encodeRaw
14826}
14827
14828}).call(this,require("buffer").Buffer)
14829},{"bs58check":80,"buffer":4}]},{},[33])(33)
14830}); \ No newline at end of file
diff --git a/src/js/bitcoinjs-extensions.js b/src/js/bitcoinjs-extensions.js
index 631af7e..ac2123c 100644
--- a/src/js/bitcoinjs-extensions.js
+++ b/src/js/bitcoinjs-extensions.js
@@ -1,5 +1,5 @@
1bitcoin.networks.shadow = { 1bitcoinjs.bitcoin.networks.shadow = {
2 magicPrefix: '\x19ShadowCash Signed Message:\n', 2 messagePrefix: "unused",
3 bip32: { 3 bip32: {
4 public: 0xEE80286A, 4 public: 0xEE80286A,
5 private: 0xEE8031E8 5 private: 0xEE8031E8
@@ -7,13 +7,10 @@ bitcoin.networks.shadow = {
7 pubKeyHash: 0x3f, 7 pubKeyHash: 0x3f,
8 scriptHash: 0x7d, 8 scriptHash: 0x7d,
9 wif: 0xbf, 9 wif: 0xbf,
10 dustThreshold: 0,
11 feePerKb: 1000,
12 estimateFee: function() { return "unused in this app" },
13}; 10};
14 11
15bitcoin.networks.shadowtn = { 12bitcoinjs.bitcoin.networks.shadowtn = {
16 magicPrefix: '\x19ShadowCash Signed Message:\n', 13 messagePrefix: "unused",
17 bip32: { 14 bip32: {
18 public: 0x76C0FDFB, 15 public: 0x76C0FDFB,
19 private: 0x76C1077A 16 private: 0x76C1077A
@@ -21,21 +18,21 @@ bitcoin.networks.shadowtn = {
21 pubKeyHash: 0x7f, 18 pubKeyHash: 0x7f,
22 scriptHash: 0xc4, 19 scriptHash: 0xc4,
23 wif: 0xff, 20 wif: 0xff,
24 dustThreshold: 0,
25 feePerKb: 1000,
26 estimateFee: function() { return "unused in this app" },
27}; 21};
28 22
29bitcoin.networks.clam = { 23bitcoinjs.bitcoin.networks.clam = {
24 messagePrefix: "unused",
30 bip32: { 25 bip32: {
31 public: 0xa8c26d64, 26 public: 0xa8c26d64,
32 private: 0xa8c17826 27 private: 0xa8c17826
33 }, 28 },
34 pubKeyHash: 0x89, 29 pubKeyHash: 0x89,
30 scriptHash: 0x00, // TODO set this correctly
35 wif: 0x85, 31 wif: 0x85,
36}; 32};
37 33
38bitcoin.networks.crown = { 34bitcoin.networks.crown = {
35 messagePrefix: "unused",
39 bip32: { 36 bip32: {
40 public: 0x0488b21e, 37 public: 0x0488b21e,
41 private: 0x0488ade4 38 private: 0x0488ade4
@@ -46,6 +43,7 @@ bitcoin.networks.crown = {
46}; 43};
47 44
48bitcoin.networks.dash = { 45bitcoin.networks.dash = {
46 messagePrefix: "unused",
49 bip32: { 47 bip32: {
50 public: 0x0488b21e, 48 public: 0x0488b21e,
51 private: 0x0488ade4 49 private: 0x0488ade4
@@ -55,7 +53,8 @@ bitcoin.networks.dash = {
55 wif: 0xcc, 53 wif: 0xcc,
56}; 54};
57 55
58bitcoin.networks.dashtn = { 56bitcoinjs.bitcoin.networks.dashtn = {
57 messagePrefix: "unused",
59 bip32: { 58 bip32: {
60 public: 0x043587cf, 59 public: 0x043587cf,
61 private: 0x04358394 60 private: 0x04358394
@@ -65,7 +64,8 @@ bitcoin.networks.dashtn = {
65 wif: 0xef, 64 wif: 0xef,
66}; 65};
67 66
68bitcoin.networks.game = { 67bitcoinjs.bitcoin.networks.game = {
68 messagePrefix: "unused",
69 bip32: { 69 bip32: {
70 public: 0x0488b21e, 70 public: 0x0488b21e,
71 private: 0x0488ade4 71 private: 0x0488ade4
@@ -75,27 +75,30 @@ bitcoin.networks.game = {
75 wif: 0xa6, 75 wif: 0xa6,
76}; 76};
77 77
78bitcoin.networks.namecoin = { 78bitcoinjs.bitcoin.networks.namecoin = {
79 messagePrefix: "unused",
79 bip32: { 80 bip32: {
80 public: 0x0488b21e, 81 public: 0x0488b21e,
81 private: 0x0488ade4 82 private: 0x0488ade4
82 }, 83 },
83 pubKeyHash: 0x34, 84 pubKeyHash: 0x34,
84 //scriptHash: 0x10, 85 scriptHash: 0x00, // TODO set this correctly
85 wif: 0x80, 86 wif: 0x80,
86}; 87};
87 88
88bitcoin.networks.peercoin = { 89bitcoinjs.bitcoin.networks.peercoin = {
90 messagePrefix: "unused",
89 bip32: { 91 bip32: {
90 public: 0x0488b21e, 92 public: 0x0488b21e,
91 private: 0x0488ade4 93 private: 0x0488ade4
92 }, 94 },
93 pubKeyHash: 0x37, 95 pubKeyHash: 0x37,
94 //scriptHash: 0x10, 96 scriptHash: 0x00, // TODO set this correctly
95 wif: 0xb7, 97 wif: 0xb7,
96}; 98};
97 99
98bitcoin.networks.slimcoin = { 100bitcoinjs.bitcoin.networks.slimcoin = {
101 messagePrefix: "unused",
99 bip32: { 102 bip32: {
100 public: 0xef6adf10, 103 public: 0xef6adf10,
101 private: 0xef69ea80 104 private: 0xef69ea80
@@ -105,7 +108,8 @@ bitcoin.networks.slimcoin = {
105 wif: 0x46, 108 wif: 0x46,
106}; 109};
107 110
108bitcoin.networks.slimcointn = { 111bitcoinjs.bitcoin.networks.slimcointn = {
112 messagePrefix: "unused",
109 bip32: { 113 bip32: {
110 public: 0x043587CF, 114 public: 0x043587CF,
111 private: 0x04358394 115 private: 0x04358394
@@ -115,3 +119,68 @@ bitcoin.networks.slimcointn = {
115 wif: 0x57, 119 wif: 0x57,
116}; 120};
117 121
122bitcoinjs.bitcoin.networks.dogecoin = {
123 messagePrefix: '\x19Dogecoin Signed Message:\n',
124 bip32: {
125 public: 0x02facafd,
126 private: 0x02fac398
127 },
128 pubKeyHash: 0x1e,
129 scriptHash: 0x16,
130 wif: 0x9e,
131},
132
133bitcoinjs.bitcoin.networks.viacoin = {
134 messagePrefix: '\x18Viacoin Signed Message:\n',
135 bip32: {
136 public: 0x0488b21e,
137 private: 0x0488ade4
138 },
139 pubKeyHash: 0x47,
140 scriptHash: 0x21,
141 wif: 0xc7,
142},
143
144bitcoinjs.bitcoin.networks.viacointestnet = {
145 messagePrefix: '\x18Viacoin Signed Message:\n',
146 bip32: {
147 public: 0x043587cf,
148 private: 0x04358394
149 },
150 pubKeyHash: 0x7f,
151 scriptHash: 0xc4,
152 wif: 0xff,
153},
154
155bitcoinjs.bitcoin.networks.gamerscoin = {
156 messagePrefix: '\x19Gamerscoin Signed Message:\n',
157 bip32: {
158 public: 0x019da462,
159 private: 0x019d9cfe
160 },
161 pubKeyHash: 0x26,
162 scriptHash: 0x05,
163 wif: 0xA6,
164},
165
166bitcoinjs.bitcoin.networks.jumbucks = {
167 messagePrefix: '\x19Jumbucks Signed Message:\n',
168 bip32: {
169 public: 0x037a689a,
170 private: 0x037a6460
171 },
172 pubKeyHash: 0x2b,
173 scriptHash: 0x05,
174 wif: 0xab,
175},
176
177bitcoinjs.bitcoin.networks.zetacoin = {
178 messagePrefix: '\x18Zetacoin Signed Message:\n',
179 bip32: {
180 public: 0x0488b21e,
181 private: 0x0488ade4
182 },
183 pubKeyHash: 0x50,
184 scriptHash: 0x09,
185 wif: 0xe0,
186}
diff --git a/src/js/index.js b/src/js/index.js
index 1e88b70..9b8432a 100644
--- a/src/js/index.js
+++ b/src/js/index.js
@@ -6,7 +6,7 @@
6 var seed = null; 6 var seed = null;
7 var bip32RootKey = null; 7 var bip32RootKey = null;
8 var bip32ExtendedKey = null; 8 var bip32ExtendedKey = null;
9 var network = bitcoin.networks.bitcoin; 9 var network = bitcoinjs.bitcoin.networks.bitcoin;
10 var addressRowTemplate = $("#address-row-template"); 10 var addressRowTemplate = $("#address-row-template");
11 11
12 var showIndex = true; 12 var showIndex = true;
@@ -338,11 +338,11 @@
338 338
339 function calcBip32RootKeyFromSeed(phrase, passphrase) { 339 function calcBip32RootKeyFromSeed(phrase, passphrase) {
340 seed = mnemonic.toSeed(phrase, passphrase); 340 seed = mnemonic.toSeed(phrase, passphrase);
341 bip32RootKey = bitcoin.HDNode.fromSeedHex(seed, network); 341 bip32RootKey = bitcoinjs.bitcoin.HDNode.fromSeedHex(seed, network);
342 } 342 }
343 343
344 function calcBip32RootKeyFromBase58(rootKeyBase58) { 344 function calcBip32RootKeyFromBase58(rootKeyBase58) {
345 bip32RootKey = bitcoin.HDNode.fromBase58(rootKeyBase58, network); 345 bip32RootKey = bitcoinjs.bitcoin.HDNode.fromBase58(rootKeyBase58, network);
346 } 346 }
347 347
348 function calcBip32ExtendedKey(path) { 348 function calcBip32ExtendedKey(path) {
@@ -360,7 +360,7 @@
360 continue; 360 continue;
361 } 361 }
362 var hardened = bit[bit.length-1] == "'"; 362 var hardened = bit[bit.length-1] == "'";
363 var isPriv = "privKey" in extendedKey; 363 var isPriv = !(extendedKey.isNeutered());
364 var invalidDerivationPath = hardened && !isPriv; 364 var invalidDerivationPath = hardened && !isPriv;
365 if (invalidDerivationPath) { 365 if (invalidDerivationPath) {
366 extendedKey = null; 366 extendedKey = null;
@@ -416,7 +416,7 @@
416 416
417 function validateRootKey(rootKeyBase58) { 417 function validateRootKey(rootKeyBase58) {
418 try { 418 try {
419 bitcoin.HDNode.fromBase58(rootKeyBase58); 419 bitcoinjs.bitcoin.HDNode.fromBase58(rootKeyBase58);
420 } 420 }
421 catch (e) { 421 catch (e) {
422 return "Invalid root key"; 422 return "Invalid root key";
@@ -490,7 +490,7 @@
490 } 490 }
491 // Check no hardened derivation path when using xpub keys 491 // Check no hardened derivation path when using xpub keys
492 var hardened = path.indexOf("'") > -1; 492 var hardened = path.indexOf("'") > -1;
493 var isXpubkey = !("privKey" in bip32RootKey); 493 var isXpubkey = bip32RootKey.isNeutered();
494 if (hardened && isXpubkey) { 494 if (hardened && isXpubkey) {
495 return "Hardened derivation path is invalid with xpub key"; 495 return "Hardened derivation path is invalid with xpub key";
496 } 496 }
@@ -509,7 +509,7 @@
509 // Calculate the account extended keys 509 // Calculate the account extended keys
510 var accountExtendedKey = calcBip32ExtendedKey(path); 510 var accountExtendedKey = calcBip32ExtendedKey(path);
511 var accountXprv = accountExtendedKey.toBase58(); 511 var accountXprv = accountExtendedKey.toBase58();
512 var accountXpub = accountExtendedKey.toBase58(false); 512 var accountXpub = accountExtendedKey.neutered().toBase58();
513 // Display the extended keys 513 // Display the extended keys
514 DOM.bip44accountXprv.val(accountXprv); 514 DOM.bip44accountXprv.val(accountXprv);
515 DOM.bip44accountXpub.val(accountXpub); 515 DOM.bip44accountXpub.val(accountXpub);
@@ -521,12 +521,12 @@
521 var rootKey = bip32RootKey.toBase58(); 521 var rootKey = bip32RootKey.toBase58();
522 DOM.rootKey.val(rootKey); 522 DOM.rootKey.val(rootKey);
523 var xprvkeyB58 = "NA"; 523 var xprvkeyB58 = "NA";
524 if (bip32ExtendedKey.privKey) { 524 if (!bip32ExtendedKey.isNeutered()) {
525 xprvkeyB58 = bip32ExtendedKey.toBase58(); 525 xprvkeyB58 = bip32ExtendedKey.toBase58();
526 } 526 }
527 var extendedPrivKey = xprvkeyB58; 527 var extendedPrivKey = xprvkeyB58;
528 DOM.extendedPrivKey.val(extendedPrivKey); 528 DOM.extendedPrivKey.val(extendedPrivKey);
529 var extendedPubKey = bip32ExtendedKey.toBase58(false); 529 var extendedPubKey = bip32ExtendedKey.neutered().toBase58();
530 DOM.extendedPubKey.val(extendedPubKey); 530 DOM.extendedPubKey.val(extendedPubKey);
531 // Display the addresses and privkeys 531 // Display the addresses and privkeys
532 clearAddressesList(); 532 clearAddressesList();
@@ -567,7 +567,7 @@
567 if (!self.shouldGenerate) { 567 if (!self.shouldGenerate) {
568 return; 568 return;
569 } 569 }
570 var key = ""; 570 var key = "NA";
571 if (useHardenedAddresses) { 571 if (useHardenedAddresses) {
572 key = bip32ExtendedKey.deriveHardened(index); 572 key = bip32ExtendedKey.deriveHardened(index);
573 } 573 }
@@ -576,17 +576,17 @@
576 } 576 }
577 var address = key.getAddress().toString(); 577 var address = key.getAddress().toString();
578 var privkey = "NA"; 578 var privkey = "NA";
579 if (key.privKey) { 579 if (!key.isNeutered()) {
580 privkey = key.privKey.toWIF(network); 580 privkey = key.keyPair.toWIF(network);
581 } 581 }
582 var pubkey = key.pubKey.toHex(); 582 var pubkey = key.getPublicKeyBuffer().toString('hex');
583 var indexText = getDerivationPath() + "/" + index; 583 var indexText = getDerivationPath() + "/" + index;
584 if (useHardenedAddresses) { 584 if (useHardenedAddresses) {
585 indexText = indexText + "'"; 585 indexText = indexText + "'";
586 } 586 }
587 // Ethereum values are different 587 // Ethereum values are different
588 if (networks[DOM.network.val()].name == "ETH - Ethereum") { 588 if (networks[DOM.network.val()].name == "ETH - Ethereum") {
589 var privKeyBuffer = key.privKey.d.toBuffer(); 589 var privKeyBuffer = key.keyPair.d.toBuffer();
590 privkey = privKeyBuffer.toString('hex'); 590 privkey = privKeyBuffer.toString('hex');
591 var addressBuffer = ethUtil.privateToAddress(privKeyBuffer); 591 var addressBuffer = ethUtil.privateToAddress(privKeyBuffer);
592 var hexAddress = addressBuffer.toString('hex'); 592 var hexAddress = addressBuffer.toString('hex');
@@ -1059,21 +1059,21 @@
1059 { 1059 {
1060 name: "BTC - Bitcoin", 1060 name: "BTC - Bitcoin",
1061 onSelect: function() { 1061 onSelect: function() {
1062 network = bitcoin.networks.bitcoin; 1062 network = bitcoinjs.bitcoin.networks.bitcoin;
1063 DOM.bip44coin.val(0); 1063 DOM.bip44coin.val(0);
1064 }, 1064 },
1065 }, 1065 },
1066 { 1066 {
1067 name: "BTC - Bitcoin Testnet", 1067 name: "BTC - Bitcoin Testnet",
1068 onSelect: function() { 1068 onSelect: function() {
1069 network = bitcoin.networks.testnet; 1069 network = bitcoinjs.bitcoin.networks.testnet;
1070 DOM.bip44coin.val(1); 1070 DOM.bip44coin.val(1);
1071 }, 1071 },
1072 }, 1072 },
1073 { 1073 {
1074 name: "CLAM - Clams", 1074 name: "CLAM - Clams",
1075 onSelect: function() { 1075 onSelect: function() {
1076 network = bitcoin.networks.clam; 1076 network = bitcoinjs.bitcoin.networks.clam;
1077 DOM.bip44coin.val(23); 1077 DOM.bip44coin.val(23);
1078 }, 1078 },
1079 }, 1079 },
@@ -1087,14 +1087,14 @@
1087 { 1087 {
1088 name: "DASH - Dash", 1088 name: "DASH - Dash",
1089 onSelect: function() { 1089 onSelect: function() {
1090 network = bitcoin.networks.dash; 1090 network = bitcoinjs.bitcoin.networks.dash;
1091 DOM.bip44coin.val(5); 1091 DOM.bip44coin.val(5);
1092 }, 1092 },
1093 }, 1093 },
1094 { 1094 {
1095 name: "DASH - Dash Testnet", 1095 name: "DASH - Dash Testnet",
1096 onSelect: function() { 1096 onSelect: function() {
1097 network = bitcoin.networks.dashtn; 1097 network = bitcoinjs.bitcoin.networks.dashtn;
1098 DOM.bip44coin.val(1); 1098 DOM.bip44coin.val(1);
1099 }, 1099 },
1100 }, 1100 },
@@ -1108,84 +1108,84 @@
1108 { 1108 {
1109 name: "ETH - Ethereum", 1109 name: "ETH - Ethereum",
1110 onSelect: function() { 1110 onSelect: function() {
1111 network = bitcoin.networks.bitcoin; 1111 network = bitcoinjs.bitcoin.networks.bitcoin;
1112 DOM.bip44coin.val(60); 1112 DOM.bip44coin.val(60);
1113 }, 1113 },
1114 }, 1114 },
1115 { 1115 {
1116 name: "GAME - GameCredits", 1116 name: "GAME - GameCredits",
1117 onSelect: function() { 1117 onSelect: function() {
1118 network = bitcoin.networks.game; 1118 network = bitcoinjs.bitcoin.networks.game;
1119 DOM.bip44coin.val(101); 1119 DOM.bip44coin.val(101);
1120 }, 1120 },
1121 }, 1121 },
1122 { 1122 {
1123 name: "JBS - Jumbucks", 1123 name: "JBS - Jumbucks",
1124 onSelect: function() { 1124 onSelect: function() {
1125 network = bitcoin.networks.jumbucks; 1125 network = bitcoinjs.bitcoin.networks.jumbucks;
1126 DOM.bip44coin.val(26); 1126 DOM.bip44coin.val(26);
1127 }, 1127 },
1128 }, 1128 },
1129 { 1129 {
1130 name: "LTC - Litecoin", 1130 name: "LTC - Litecoin",
1131 onSelect: function() { 1131 onSelect: function() {
1132 network = bitcoin.networks.litecoin; 1132 network = bitcoinjs.bitcoin.networks.litecoin;
1133 DOM.bip44coin.val(2); 1133 DOM.bip44coin.val(2);
1134 }, 1134 },
1135 }, 1135 },
1136 { 1136 {
1137 name: "NMC - Namecoin", 1137 name: "NMC - Namecoin",
1138 onSelect: function() { 1138 onSelect: function() {
1139 network = bitcoin.networks.namecoin; 1139 network = bitcoinjs.bitcoin.networks.namecoin;
1140 DOM.bip44coin.val(7); 1140 DOM.bip44coin.val(7);
1141 }, 1141 },
1142 }, 1142 },
1143 { 1143 {
1144 name: "PPC - Peercoin", 1144 name: "PPC - Peercoin",
1145 onSelect: function() { 1145 onSelect: function() {
1146 network = bitcoin.networks.peercoin; 1146 network = bitcoinjs.bitcoin.networks.peercoin;
1147 DOM.bip44coin.val(6); 1147 DOM.bip44coin.val(6);
1148 }, 1148 },
1149 }, 1149 },
1150 { 1150 {
1151 name: "SDC - ShadowCash", 1151 name: "SDC - ShadowCash",
1152 onSelect: function() { 1152 onSelect: function() {
1153 network = bitcoin.networks.shadow; 1153 network = bitcoinjs.bitcoin.networks.shadow;
1154 DOM.bip44coin.val(35); 1154 DOM.bip44coin.val(35);
1155 }, 1155 },
1156 }, 1156 },
1157 { 1157 {
1158 name: "SDC - ShadowCash Testnet", 1158 name: "SDC - ShadowCash Testnet",
1159 onSelect: function() { 1159 onSelect: function() {
1160 network = bitcoin.networks.shadowtn; 1160 network = bitcoinjs.bitcoin.networks.shadowtn;
1161 DOM.bip44coin.val(1); 1161 DOM.bip44coin.val(1);
1162 }, 1162 },
1163 }, 1163 },
1164 { 1164 {
1165 name: "SLM - Slimcoin", 1165 name: "SLM - Slimcoin",
1166 onSelect: function() { 1166 onSelect: function() {
1167 network = bitcoin.networks.slimcoin; 1167 network = bitcoinjs.bitcoin.networks.slimcoin;
1168 DOM.bip44coin.val(63); 1168 DOM.bip44coin.val(63);
1169 }, 1169 },
1170 }, 1170 },
1171 { 1171 {
1172 name: "SLM - Slimcoin Testnet", 1172 name: "SLM - Slimcoin Testnet",
1173 onSelect: function() { 1173 onSelect: function() {
1174 network = bitcoin.networks.slimcointn; 1174 network = bitcoinjs.bitcoin.networks.slimcointn;
1175 DOM.bip44coin.val(111); 1175 DOM.bip44coin.val(111);
1176 }, 1176 },
1177 }, 1177 },
1178 { 1178 {
1179 name: "VIA - Viacoin", 1179 name: "VIA - Viacoin",
1180 onSelect: function() { 1180 onSelect: function() {
1181 network = bitcoin.networks.viacoin; 1181 network = bitcoinjs.bitcoin.networks.viacoin;
1182 DOM.bip44coin.val(14); 1182 DOM.bip44coin.val(14);
1183 }, 1183 },
1184 }, 1184 },
1185 { 1185 {
1186 name: "VIA - Viacoin Testnet", 1186 name: "VIA - Viacoin Testnet",
1187 onSelect: function() { 1187 onSelect: function() {
1188 network = bitcoin.networks.viacointestnet; 1188 network = bitcoinjs.bitcoin.networks.viacointestnet;
1189 DOM.bip44coin.val(1); 1189 DOM.bip44coin.val(1);
1190 }, 1190 },
1191 }, 1191 },