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
3 function BigInteger(a
, b
, c
) {
4 if (!(this instanceof BigInteger
))
5 return new BigInteger(a
, b
, c
)
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
)
14 var proto
= BigInteger
.prototype
16 // duck-typed isBigInteger
17 proto
.__bigi
= require('../package.json').version
18 BigInteger
.isBigInteger = function (obj
, check_ver
) {
19 return obj
&& obj
.__bigi
&& (!check_ver
|| obj
.__bigi
=== proto
.__bigi
)
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.
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)
33 function am1(i
, x
, w
, j
, c
, n
) {
35 var v
= x
* this[i
++] + w
[j
] + c
36 c
= Math
.floor(v
/ 0x4000000)
37 w
[j
++] = v
& 0x3ffffff
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)
44 function am2(i
, x
, w
, j
, c
, n
) {
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
57 // Alternately, set max digit bits to 28 since some
58 // browsers slow down when dealing with 32-bit numbers.
59 function am3(i
, x
, w
, j
, c
, n
) {
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
74 BigInteger
.prototype.am
= am1
77 BigInteger
.prototype.DB
= dbits
78 BigInteger
.prototype.DM
= ((1 << dbits
) - 1)
79 var DV
= BigInteger
.prototype.DV
= (1 << dbits
)
82 BigInteger
.prototype.FV
= Math
.pow(2, BI_FP
)
83 BigInteger
.prototype.F1
= BI_FP
- dbits
84 BigInteger
.prototype.F2
= 2 * dbits
- BI_FP
87 var BI_RM
= "0123456789abcdefghijklmnopqrstuvwxyz"
88 var BI_RC
= new Array()
90 rr
= "0".charCodeAt(0)
91 for (vv
= 0; vv
<= 9; ++vv
) BI_RC
[rr
++] = vv
92 rr
= "a".charCodeAt(0)
93 for (vv
= 10; vv
< 36; ++vv
) BI_RC
[rr
++] = vv
94 rr
= "A".charCodeAt(0)
95 for (vv
= 10; vv
< 36; ++vv
) BI_RC
[rr
++] = vv
97 function int2char(n
) {
98 return BI_RM
.charAt(n
)
101 function intAt(s
, i
) {
102 var c
= BI_RC
[s
.charCodeAt(i
)]
103 return (c
== null) ? -1 : c
106 // (protected) copy this to r
107 function bnpCopyTo(r
) {
108 for (var i
= this.t
- 1; i
>= 0; --i
) r
[i
] = this[i
]
113 // (protected) set from integer value x, -DV <= x < DV
114 function bnpFromInt(x
) {
116 this.s
= (x
< 0) ? -1 : 0
117 if (x
> 0) this[0] = x
118 else if (x
< -1) this[0] = x
+ DV
122 // return bigint initialized to value
124 var r
= new BigInteger()
129 // (protected) set from string and radix
130 function bnpFromString(s
, b
) {
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
150 var x
= (k
== 8) ? s
[i
] & 0xff : intAt(s
, i
)
152 if (s
.charAt(i
) == "-") mi
= true
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
))
162 self
[self
.t
- 1] |= x
<< sh
164 if (sh
>= self
.DB
) sh
-= self
.DB
166 if (k
== 8 && (s
[0] & 0x80) != 0) {
168 if (sh
> 0) self
[self
.t
- 1] |= ((1 << (self
.DB
- sh
)) - 1) << sh
171 if (mi
) BigInteger
.ZERO
.subTo(self
, self
)
174 // (protected) clamp off excess high words
175 function bnpClamp() {
176 var c
= this.s
& this.DM
177 while (this.t
> 0 && this[this.t
- 1] == c
)--this.t
180 // (public) return string representation in given radix
181 function bnToString(b
) {
183 if (self
.s
< 0) return "-" + self
.negate()
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,
196 var p
= self
.DB
- (i
* self
.DB
) % k
198 if (p
< self
.DB
&& (d
= self
[i
] >> p
) > 0) {
204 d
= (self
[i
] & ((1 << p
) - 1)) << (k
- p
)
205 d
|= self
[--i
] >> (p
+= self
.DB
- k
)
207 d
= (self
[i
] >> (p
-= k
)) & km
214 if (m
) r
+= int2char(d
)
221 function bnNegate() {
222 var r
= new BigInteger()
223 BigInteger
.ZERO
.subTo(this, r
)
229 return (this.s
< 0) ? this.negate() : this
232 // (public) return + if this > a, - if this < a, 0 if equal
233 function bnCompareTo(a
) {
238 if (r
!= 0) return (this.s
< 0) ? -r : r
240 if ((r
= this[i
] - a
[i
]) != 0) return r
244 // returns bit length of the integer x
248 if ((t
= x
>>> 16) != 0) {
252 if ((t
= x
>> 8) != 0) {
256 if ((t
= x
>> 4) != 0) {
260 if ((t
= x
>> 2) != 0) {
264 if ((t
= x
>> 1) != 0) {
271 // (public) return the number of bits in "this"
272 function bnBitLength() {
273 if (this.t
<= 0) return 0
274 return this.DB
* (this.t
- 1) + nbits(this[this.t
- 1] ^ (this.s
& this.DM
))
277 // (public) return the number of bytes in "this"
278 function bnByteLength() {
279 return this.bitLength() >> 3
282 // (protected) r = this << n*DB
283 function bnpDLShiftTo(n
, r
) {
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
291 // (protected) r = this >> n*DB
292 function 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)
298 // (protected) r = this << n
299 function bnpLShiftTo(n
, r
) {
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
,
307 for (i
= self
.t
- 1; i
>= 0; --i
) {
308 r
[i
+ ds
+ 1] = (self
[i
] >> cbs
) | c
309 c
= (self
[i
] & bm
) << bs
311 for (i
= ds
- 1; i
>= 0; --i
) r
[i
] = 0
313 r
.t
= self
.t
+ ds
+ 1
318 // (protected) r = this >> n
319 function bnpRShiftTo(n
, r
) {
322 var ds
= Math
.floor(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
335 if (bs
> 0) r
[self
.t
- ds
- 1] |= (self
.s
& bm
) << cbs
340 // (protected) r = this - a
341 function bnpSubTo(a
, r
) {
345 m
= Math
.min(a
.t
, self
.t
)
368 r
.s
= (c
< 0) ? -1 : 0
369 if (c
< -1) r
[i
++] = self
.DV
+ c
370 else if (c
> 0) r
[i
++] = c
375 // (protected) r = this * a, r != this,a (HAC 14.12)
376 // "this" should be the larger one if appropriate.
377 function bnpMultiplyTo(a
, r
) {
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
)
386 if (this.s
!= a
.s
) BigInteger
.ZERO
.subTo(r
, r
)
389 // (protected) r = this^2, r != this (HAC 14.16)
390 function bnpSquareTo(r
) {
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
) {
401 if (r
.t
> 0) r
[r
.t
- 1] += x
.am(i
, x
[i
], r
, 2 * i
, 0, 1)
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.
408 function bnpDivRemTo(m
, q
, r
) {
411 if (pm
.t
<= 0) return
414 if (q
!= null) q
.fromInt(0)
415 if (r
!= null) self
.copyTo(r
)
418 if (r
== null) r
= new BigInteger()
419 var y
= new BigInteger(),
422 var nsh
= self
.DB
- nbits(pm
[pm
.t
- 1]); // normalize modulus
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
,
439 t
= (q
== null) ? new BigInteger() : q
441 if (r
.compareTo(t
) >= 0) {
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
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
454 while (r
[i
] < --qd
) r
.subTo(t
, r
)
459 if (ts
!= ms
) BigInteger
.ZERO
.subTo(q
, q
)
463 if (nsh
> 0) r
.rShiftTo(nsh
, r
); // Denormalize remainder
464 if (ts
< 0) BigInteger
.ZERO
.subTo(r
, r
)
467 // (public) this mod a
469 var r
= new BigInteger()
471 .divRemTo(a
, null, r
)
472 if (this.s
< 0 && r
.compareTo(BigInteger
.ZERO
) > 0) a
.subTo(r
, r
)
476 // Modular reduction using "classic" algorithm
477 function Classic(m
) {
481 function cConvert(x
) {
482 if (x
.s
< 0 || x
.compareTo(this.m
) >= 0) return x
.mod(this.m
)
486 function cRevert(x
) {
490 function cReduce(x
) {
491 x
.divRemTo(this.m
, null, x
)
494 function cMulTo(x
, y
, r
) {
499 function cSqrTo(x
, r
) {
504 Classic
.prototype.convert
= cConvert
505 Classic
.prototype.revert
= cRevert
506 Classic
.prototype.reduce
= cReduce
507 Classic
.prototype.mulTo
= cMulTo
508 Classic
.prototype.sqrTo
= cSqrTo
510 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
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.
520 function bnpInvDigit() {
521 if (this.t
< 1) return 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
535 // Montgomery reduction
536 function Montgomery(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
546 function montConvert(x
) {
547 var r
= new BigInteger()
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
)
556 function montRevert(x
) {
557 var r
= new BigInteger()
563 // x = x/R mod m (HAC 14.32)
564 function montReduce(x
) {
565 while (x
.t
<= this.mt2
) // pad x so am has enough room later
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
573 x
[j
] += this.m
.am(0, u0
, x
, i
, 0, this.m
.t
)
575 while (x
[j
] >= x
.DV
) {
581 x
.drShiftTo(this.m
.t
, x
)
582 if (x
.compareTo(this.m
) >= 0) x
.subTo(this.m
, x
)
585 // r = "x^2/R mod m"; x != r
586 function montSqrTo(x
, r
) {
591 // r = "xy/R mod m"; x,y != r
592 function montMulTo(x
, y
, r
) {
597 Montgomery
.prototype.convert
= montConvert
598 Montgomery
.prototype.revert
= montRevert
599 Montgomery
.prototype.reduce
= montReduce
600 Montgomery
.prototype.mulTo
= montMulTo
601 Montgomery
.prototype.sqrTo
= montSqrTo
603 // (protected) true iff this is even
604 function bnpIsEven() {
605 return ((this.t
> 0) ? (this[0] & 1) : this.s
) == 0
608 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
609 function bnpExp(e
, z
) {
610 if (e
> 0xffffffff || e
< 1) return BigInteger
.ONE
611 var r
= new BigInteger(),
612 r2
= new BigInteger(),
618 if ((e
& (1 << i
)) > 0) z
.mulTo(r2
, g
, r
)
628 // (public) this^e % m, 0 <= e < 2^32
629 function bnModPowInt(e
, m
) {
631 if (e
< 256 || m
.isEven()) z
= new Classic(m
)
632 else z
= new Montgomery(m
)
633 return this.exp(e
, z
)
637 proto
.copyTo
= bnpCopyTo
638 proto
.fromInt
= bnpFromInt
639 proto
.fromString
= bnpFromString
640 proto
.clamp
= bnpClamp
641 proto
.dlShiftTo
= bnpDLShiftTo
642 proto
.drShiftTo
= bnpDRShiftTo
643 proto
.lShiftTo
= bnpLShiftTo
644 proto
.rShiftTo
= bnpRShiftTo
645 proto
.subTo
= bnpSubTo
646 proto
.multiplyTo
= bnpMultiplyTo
647 proto
.squareTo
= bnpSquareTo
648 proto
.divRemTo
= bnpDivRemTo
649 proto
.invDigit
= bnpInvDigit
650 proto
.isEven
= bnpIsEven
654 proto
.toString
= bnToString
655 proto
.negate
= bnNegate
657 proto
.compareTo
= bnCompareTo
658 proto
.bitLength
= bnBitLength
659 proto
.byteLength
= bnByteLength
661 proto
.modPowInt
= bnModPowInt
665 var r
= new BigInteger()
670 // (public) return value as integer
671 function bnIntValue() {
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]
681 // (public) return value as byte
682 function bnByteValue() {
683 return (this.t
== 0) ? this.s : (this[0] << 24) >> 24
686 // (public) return value as short (assumes DB>=16)
687 function bnShortValue() {
688 return (this.t
== 0) ? this.s : (this[0] << 16) >> 16
691 // (protected) return x s.t. r^x < DV
692 function bnpChunkSize(r
) {
693 return Math
.floor(Math
.LN2
* this.DB
/ Math
.log(r
))
696 // (public) 0 if this == 0, 1 if this > 0
697 function bnSigNum() {
698 if (this.s
< 0) return -1
699 else if (this.t
<= 0 || (this.t
== 1 && this[0] <= 0)) return 0
703 // (protected) convert to radix string
704 function 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
)
710 y
= new BigInteger(),
711 z
= new BigInteger(),
713 this.divRemTo(d
, y
, z
)
714 while (y
.signum() > 0) {
715 r
= (a
+ z
.intValue())
724 // (protected) convert from radix string
725 function bnpFromRadix(s
, b
) {
728 if (b
== null) b
= 10
729 var cs
= self
.chunkSize(b
)
730 var d
= Math
.pow(b
, cs
),
734 for (var i
= 0; i
< s
.length
; ++i
) {
737 if (s
.charAt(i
) == "-" && self
.signum() == 0) mi
= true
743 self
.dAddOffset(w
, 0)
749 self
.dMultiply(Math
.pow(b
, j
))
750 self
.dAddOffset(w
, 0)
752 if (mi
) BigInteger
.ZERO
.subTo(self
, self
)
755 // (protected) alternate constructor
756 function bnpFromNumber(a
, b
, c
) {
758 if ("number" == typeof b
) {
759 // new BigInteger(int,int,RNG)
760 if (a
< 2) self
.fromInt(1)
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
)
772 // new BigInteger(int,RNG)
775 x
.length
= (a
>> 3) + 1
777 if (t
> 0) x
[0] &= ((1 << t
) - 1)
779 self
.fromString(x
, 256)
783 // (public) convert to bigendian byte array
784 function bnToByteArray() {
789 var p
= self
.DB
- (i
* self
.DB
) % 8,
792 if (p
< self
.DB
&& (d
= self
[i
] >> p
) != (self
.s
& self
.DM
) >> p
)
793 r
[k
++] = d
| (self
.s
<< (self
.DB
- p
))
796 d
= (self
[i
] & ((1 << p
) - 1)) << (8 - p
)
797 d
|= self
[--i
] >> (p
+= self
.DB
- 8)
799 d
= (self
[i
] >> (p
-= 8)) & 0xff
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
813 function bnEquals(a
) {
814 return (this.compareTo(a
) == 0)
818 return (this.compareTo(a
) < 0) ? this : a
822 return (this.compareTo(a
) > 0) ? this : a
825 // (protected) r = this op a (bitwise)
826 function bnpBitwiseTo(a
, op
, r
) {
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
])
832 for (i
= m
; i
< self
.t
; ++i
) r
[i
] = op(self
[i
], f
)
836 for (i
= m
; i
< a
.t
; ++i
) r
[i
] = op(f
, a
[i
])
839 r
.s
= op(self
.s
, a
.s
)
844 function op_and(x
, y
) {
849 var r
= new BigInteger()
850 this.bitwiseTo(a
, op_and
, r
)
855 function op_or(x
, y
) {
860 var r
= new BigInteger()
861 this.bitwiseTo(a
, op_or
, r
)
866 function op_xor(x
, y
) {
871 var r
= new BigInteger()
872 this.bitwiseTo(a
, op_xor
, r
)
876 // (public) this & ~a
877 function op_andnot(x
, y
) {
881 function bnAndNot(a
) {
882 var r
= new BigInteger()
883 this.bitwiseTo(a
, op_andnot
, r
)
889 var r
= new BigInteger()
890 for (var i
= 0; i
< this.t
; ++i
) r
[i
] = this.DM
& ~this[i
]
896 // (public) this << n
897 function bnShiftLeft(n
) {
898 var r
= new BigInteger()
899 if (n
< 0) this.rShiftTo(-n
, r
)
900 else this.lShiftTo(n
, r
)
904 // (public) this >> n
905 function bnShiftRight(n
) {
906 var r
= new BigInteger()
907 if (n
< 0) this.lShiftTo(-n
, r
)
908 else this.rShiftTo(n
, r
)
912 // return index of lowest 1-bit in x, x < 2^31
914 if (x
== 0) return -1
916 if ((x
& 0xffff) == 0) {
920 if ((x
& 0xff) == 0) {
924 if ((x
& 0xf) == 0) {
936 // (public) returns index of lowest 1-bit (or -1 if none)
937 function 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
944 // return number of 1 bits in x
954 // (public) return number of set bits
955 function bnBitCount() {
958 for (var i
= 0; i
< this.t
; ++i
) r
+= cbit(this[i
] ^ x
)
962 // (public) true iff nth bit is set
963 function 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)
969 // (protected) this op (1<<n)
970 function bnpChangeBit(n
, op
) {
971 var r
= BigInteger
.ONE
.shiftLeft(n
)
972 this.bitwiseTo(r
, op
, r
)
976 // (public) this | (1<<n)
977 function bnSetBit(n
) {
978 return this.changeBit(n
, op_or
)
981 // (public) this & ~(1<<n)
982 function bnClearBit(n
) {
983 return this.changeBit(n
, op_andnot
)
986 // (public) this ^ (1<<n)
987 function bnFlipBit(n
) {
988 return this.changeBit(n
, op_xor
)
991 // (protected) r = this + a
992 function bnpAddTo(a
, r
) {
997 m
= Math
.min(a
.t
, self
.t
)
1000 r
[i
++] = c
& self
.DM
1005 while (i
< self
.t
) {
1007 r
[i
++] = c
& self
.DM
1015 r
[i
++] = c
& self
.DM
1020 r
.s
= (c
< 0) ? -1 : 0
1021 if (c
> 0) r
[i
++] = c
1022 else if (c
< -1) r
[i
++] = self
.DV
+ c
1027 // (public) this + a
1029 var r
= new BigInteger()
1034 // (public) this - a
1035 function bnSubtract(a
) {
1036 var r
= new BigInteger()
1041 // (public) this * a
1042 function bnMultiply(a
) {
1043 var r
= new BigInteger()
1044 this.multiplyTo(a
, r
)
1049 function bnSquare() {
1050 var r
= new BigInteger()
1055 // (public) this / a
1056 function bnDivide(a
) {
1057 var r
= new BigInteger()
1058 this.divRemTo(a
, r
, null)
1062 // (public) this % a
1063 function bnRemainder(a
) {
1064 var r
= new BigInteger()
1065 this.divRemTo(a
, null, r
)
1069 // (public) [this/a,this%a]
1070 function bnDivideAndRemainder(a
) {
1071 var q
= new BigInteger(),
1072 r
= new BigInteger()
1073 this.divRemTo(a
, q
, r
)
1074 return new Array(q
, r
)
1077 // (protected) this *= n, this >= 0, 1 < n < DV
1078 function bnpDMultiply(n
) {
1079 this[this.t
] = this.am(0, n
- 1, this, 0, 0, this.t
)
1084 // (protected) this += n << w words, this >= 0
1085 function bnpDAddOffset(n
, w
) {
1087 while (this.t
<= w
) this[this.t
++] = 0
1089 while (this[w
] >= this.DV
) {
1091 if (++w
>= this.t
) this[this.t
++] = 0
1097 function NullExp() {}
1103 function nMulTo(x
, y
, r
) {
1107 function nSqrTo(x
, r
) {
1111 NullExp
.prototype.convert
= nNop
1112 NullExp
.prototype.revert
= nNop
1113 NullExp
.prototype.mulTo
= nMulTo
1114 NullExp
.prototype.sqrTo
= nSqrTo
1118 return this.exp(e
, new NullExp())
1121 // (protected) r = lower n words of "this * a", a.t <= n
1122 // "this" should be the larger one if appropriate.
1123 function bnpMultiplyLowerTo(a
, n
, r
) {
1124 var i
= Math
.min(this.t
+ a
.t
, n
)
1125 r
.s
= 0; // assumes a,this >= 0
1127 while (i
> 0) r
[--i
] = 0
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
)
1134 // (protected) r = "this * a" without lower n words, n > 0
1135 // "this" should be the larger one if appropriate.
1136 function bnpMultiplyUpperTo(a
, n
, r
) {
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
)
1147 // Barrett modular reduction
1148 function Barrett(m
) {
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
)
1157 function 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
1161 var r
= new BigInteger()
1168 function barrettRevert(x
) {
1172 // x = x mod m (HAC 14.42)
1173 function barrettReduce(x
) {
1175 x
.drShiftTo(self
.m
.t
- 1, self
.r2
)
1176 if (x
.t
> self
.m
.t
+ 1) {
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)
1184 while (x
.compareTo(self
.m
) >= 0) x
.subTo(self
.m
, x
)
1187 // r = x^2 mod m; x != r
1188 function barrettSqrTo(x
, r
) {
1193 // r = x*y mod m; x,y != r
1194 function barrettMulTo(x
, y
, r
) {
1199 Barrett
.prototype.convert
= barrettConvert
1200 Barrett
.prototype.revert
= barrettRevert
1201 Barrett
.prototype.reduce
= barrettReduce
1202 Barrett
.prototype.mulTo
= barrettMulTo
1203 Barrett
.prototype.sqrTo
= barrettSqrTo
1205 // (public) this^e % m (HAC 14.85)
1206 function bnModPow(e
, m
) {
1207 var i
= e
.bitLength(),
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
1218 else if (m
.isEven())
1221 z
= new Montgomery(m
)
1224 var g
= new Array(),
1228 g
[1] = z
.convert(this)
1230 var g2
= new BigInteger()
1233 g
[n
] = new BigInteger()
1234 z
.mulTo(g2
, g
[n
- 2], g
[n
])
1241 r2
= new BigInteger(),
1245 if (i
>= k1
) w
= (e
[j
] >> (i
- k1
)) & km
1247 w
= (e
[j
] & ((1 << (i
+ 1)) - 1)) << (k1
- i
)
1248 if (j
> 0) w
|= e
[j
- 1] >> (this.DB
+ i
- k1
)
1252 while ((w
& 1) == 0) {
1260 if (is1
) { // ret == 1, don't bother squaring or multiplying it
1269 if (n
> 0) z
.sqrTo(r
, r2
)
1275 z
.mulTo(r2
, g
[w
], r
)
1278 while (j
>= 0 && (e
[j
] & (1 << i
)) == 0) {
1292 // (public) gcd(this,a) (HAC 14.54)
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) {
1301 var i
= x
.getLowestSetBit(),
1302 g
= y
.getLowestSetBit()
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) {
1320 if (g
> 0) y
.lShiftTo(g
, y
)
1324 // (protected) this % n, n < 2^26
1325 function bnpModInt(n
) {
1326 if (n
<= 0) return 0
1327 var d
= this.DV
% n
,
1328 r
= (this.s
< 0) ? n
- 1 : 0
1330 if (d
== 0) r
= this[0] % n
1332 for (var i
= this.t
- 1; i
>= 0; --i
) r
= (d
* r
+ this[i
]) % n
1336 // (public) 1/this % m (HAC 14.61)
1337 function bnModInverse(m
) {
1339 if ((this.isEven() && ac
) || m
.signum() == 0) return BigInteger
.ZERO
1346 while (u
.signum() != 0) {
1347 while (u
.isEven()) {
1350 if (!a
.isEven() || !b
.isEven()) {
1355 } else if (!b
.isEven()) b
.subTo(m
, b
)
1358 while (v
.isEven()) {
1361 if (!c
.isEven() || !d
.isEven()) {
1366 } else if (!d
.isEven()) d
.subTo(m
, d
)
1369 if (u
.compareTo(v
) >= 0) {
1371 if (ac
) a
.subTo(c
, a
)
1375 if (ac
) c
.subTo(a
, c
)
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
)
1383 if (d
.signum() < 0) return d
.add(m
)
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
1401 var lplim
= (1 << 26) / lowprimes
[lowprimes
.length
- 1]
1403 // (public) test primality with certainty >= 1-.5^t
1404 function 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
1411 if (x
.isEven()) return false
1413 while (i
< lowprimes
.length
) {
1414 var m
= lowprimes
[i
],
1416 while (j
< lowprimes
.length
&& m
< lplim
) m
*= lowprimes
[j
++]
1418 while (i
< j
) if (m
% lowprimes
[i
++] == 0) return false
1420 return x
.millerRabin(t
)
1423 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
1424 function 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
)
1430 if (t
> lowprimes
.length
) t
= lowprimes
.length
1431 var a
= new BigInteger(null)
1433 for (var i
= 0; i
< t
; ++i
) {
1435 j
= lowprimes
[Math
.floor(Math
.random() * lowprimes
.length
)]
1436 if (bases
.indexOf(j
) == -1) break
1440 var y
= a
.modPow(r
, this)
1441 if (y
.compareTo(BigInteger
.ONE
) != 0 && y
.compareTo(n1
) != 0) {
1443 while (j
++ < k
&& y
.compareTo(n1
) != 0) {
1444 y
= y
.modPowInt(2, this)
1445 if (y
.compareTo(BigInteger
.ONE
) == 0) return false
1447 if (y
.compareTo(n1
) != 0) return false
1454 proto
.chunkSize
= bnpChunkSize
1455 proto
.toRadix
= bnpToRadix
1456 proto
.fromRadix
= bnpFromRadix
1457 proto
.fromNumber
= bnpFromNumber
1458 proto
.bitwiseTo
= bnpBitwiseTo
1459 proto
.changeBit
= bnpChangeBit
1460 proto
.addTo
= bnpAddTo
1461 proto
.dMultiply
= bnpDMultiply
1462 proto
.dAddOffset
= bnpDAddOffset
1463 proto
.multiplyLowerTo
= bnpMultiplyLowerTo
1464 proto
.multiplyUpperTo
= bnpMultiplyUpperTo
1465 proto
.modInt
= bnpModInt
1466 proto
.millerRabin
= bnpMillerRabin
1469 proto
.clone
= bnClone
1470 proto
.intValue
= bnIntValue
1471 proto
.byteValue
= bnByteValue
1472 proto
.shortValue
= bnShortValue
1473 proto
.signum
= bnSigNum
1474 proto
.toByteArray
= bnToByteArray
1475 proto
.equals
= bnEquals
1481 proto
.andNot
= bnAndNot
1483 proto
.shiftLeft
= bnShiftLeft
1484 proto
.shiftRight
= bnShiftRight
1485 proto
.getLowestSetBit
= bnGetLowestSetBit
1486 proto
.bitCount
= bnBitCount
1487 proto
.testBit
= bnTestBit
1488 proto
.setBit
= bnSetBit
1489 proto
.clearBit
= bnClearBit
1490 proto
.flipBit
= bnFlipBit
1492 proto
.subtract
= bnSubtract
1493 proto
.multiply
= bnMultiply
1494 proto
.divide
= bnDivide
1495 proto
.remainder
= bnRemainder
1496 proto
.divideAndRemainder
= bnDivideAndRemainder
1497 proto
.modPow
= bnModPow
1498 proto
.modInverse
= bnModInverse
1501 proto
.isProbablePrime
= bnIsProbablePrime
1503 // JSBN-specific extension
1504 proto
.square
= bnSquare
1507 BigInteger
.ZERO
= nbv(0)
1508 BigInteger
.ONE
= nbv(1)
1509 BigInteger
.valueOf
= nbv
1511 module
.exports
= BigInteger
1513 },{"../package.json":4}],2:[function(require
,module
,exports
){
1515 // FIXME: Kind of a weird way to throw exceptions, consider removing
1516 var assert
= require('assert')
1517 var BigInteger
= require('./bigi')
1520 * Turns a byte array into a big integer.
1522 * This function will interpret a byte array as a big integer in big
1525 BigInteger
.fromByteArrayUnsigned = function(byteArray
) {
1526 // BigInteger expects a DER integer conformant byte array
1527 if (byteArray
[0] & 0x80) {
1528 return new BigInteger([0].concat(byteArray
))
1531 return new BigInteger(byteArray
)
1535 * Returns a byte array representation of the big integer.
1537 * This returns the absolute of the contained value in big endian
1538 * form. A value of zero results in an empty array.
1540 BigInteger
.prototype.toByteArrayUnsigned = function() {
1541 var byteArray
= this.toByteArray()
1542 return byteArray
[0] === 0 ? byteArray
.slice(1) : byteArray
1545 BigInteger
.fromDERInteger = function(byteArray
) {
1546 return new BigInteger(byteArray
)
1550 * Converts BigInteger to a DER integer representation.
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.
1570 * -62300 => 0xff0ca4
1572 BigInteger
.prototype.toDERInteger
= BigInteger
.prototype.toByteArray
1574 BigInteger
.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
)
1579 return new BigInteger([0].concat(byteArray
))
1582 return new BigInteger(buffer
)
1585 BigInteger
.fromHex = function(hex
) {
1586 if (hex
=== '') return BigInteger
.ZERO
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)
1593 BigInteger
.prototype.toBuffer = function(size
) {
1594 var byteArray
= this.toByteArrayUnsigned()
1597 var padding
= size
- byteArray
.length
1598 while (zeros
.length
< padding
) zeros
.push(0)
1600 return new Buffer(zeros
.concat(byteArray
))
1603 BigInteger
.prototype.toHex = function(size
) {
1604 return this.toBuffer(size
).toString('hex')
1607 }).call(this,require("buffer").Buffer
)
1608 },{"./bigi":1,"assert":5,"buffer":7}],3:[function(require
,module
,exports
){
1609 var BigInteger
= require('./bigi')
1612 require('./convert')
1614 module
.exports
= BigInteger
1615 },{"./bigi":1,"./convert":2}],4:[function(require
,module
,exports
){
1619 "description": "Big integers.",
1637 "devDependencies": {
1640 "coveralls": "^2.10.0",
1641 "istanbul": "^0.2.11"
1644 "url": "https://github.com/cryptocoinjs/bigi",
1647 "main": "./lib/index.js",
1649 "test": "_mocha -- test/*.js",
1650 "jshint": "jshint --config jshint.json lib/*.js ; true",
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"
1657 "files": "test/*.js",
1663 "safari/6.0..latest",
1664 "iphone/6.0..latest",
1665 "android-browser/4.2..latest"
1669 "url": "https://github.com/cryptocoinjs/bigi/issues"
1671 "homepage": "https://github.com/cryptocoinjs/bigi",
1672 "_id": "bigi@1.4.0",
1674 "shasum": "90ac1aeac0a531216463bdb58f42c1e05c8407ac",
1675 "tarball": "http://registry.npmjs.org/bigi/-/bigi-1.4.0.tgz"
1677 "_from": "bigi@^1.4.0",
1678 "_npmVersion": "1.4.3",
1681 "email": "jprichardson@gmail.com"
1686 "email": "jprichardson@gmail.com"
1689 "name": "midnightlightning",
1690 "email": "boydb@midnightdesign.ws"
1693 "name": "sidazhang",
1694 "email": "sidazhang89@gmail.com"
1698 "email": "npm@shesek.info"
1702 "_shasum": "90ac1aeac0a531216463bdb58f42c1e05c8407ac",
1703 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.0.tgz"
1706 },{}],5:[function(require
,module
,exports
){
1707 // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
1709 // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
1711 // Originally from narwhal.js (http://narwhaljs.org)
1712 // Copyright (c) 2009 Thomas Robinson <280north.com>
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:
1721 // The above copyright notice and this permission notice shall be included in
1722 // all copies or substantial portions of the Software.
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.
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
1734 var util
= require('util/');
1736 var pSlice
= Array
.prototype.slice
;
1737 var hasOwn
= Object
.prototype.hasOwnProperty
;
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.
1743 var assert
= module
.exports
= ok
;
1745 // 2. The AssertionError is defined in assert.
1746 // new assert.AssertionError({ message: message,
1748 // expected: expected })
1750 assert
.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;
1759 this.message
= getMessage(this);
1760 this.generatedMessage
= true;
1762 var stackStartFunction
= options
.stackStartFunction
|| fail
;
1764 if (Error
.captureStackTrace
) {
1765 Error
.captureStackTrace(this, stackStartFunction
);
1768 // non v8 browsers so we can have a stacktrace
1769 var err
= new Error();
1771 var out
= err
.stack
;
1773 // try to strip useless frames
1774 var fn_name
= stackStartFunction
.name
;
1775 var idx
= out
.indexOf('\n' + fn_name
);
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);
1788 // assert.AssertionError instanceof Error
1789 util
.inherits(assert
.AssertionError
, Error
);
1791 function replacer(key
, value
) {
1792 if (util
.isUndefined(value
)) {
1795 if (util
.isNumber(value
) && !isFinite(value
)) {
1796 return value
.toString();
1798 if (util
.isFunction(value
) || util
.isRegExp(value
)) {
1799 return value
.toString();
1804 function truncate(s
, n
) {
1805 if (util
.isString(s
)) {
1806 return s
.length
< n
? s : s
.slice(0, n
);
1812 function getMessage(self
) {
1813 return truncate(JSON
.stringify(self
.actual
, replacer
), 128) + ' ' +
1814 self
.operator
+ ' ' +
1815 truncate(JSON
.stringify(self
.expected
, replacer
), 128);
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
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.
1829 function fail(actual
, expected
, message
, operator
, stackStartFunction
) {
1830 throw new assert
.AssertionError({
1835 stackStartFunction: stackStartFunction
1839 // EXTENSION! allows for well behaved errors defined elsewhere.
1842 // 4. Pure assertion tests whether a value is truthy, as determined
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);.
1849 function ok(value
, message
) {
1850 if (!value
) fail(value
, true, message
, '==', assert
.ok
);
1854 // 5. The equality assertion tests shallow, coercive equality with
1856 // assert.equal(actual, expected, message_opt);
1858 assert
.equal
= function equal(actual
, expected
, message
) {
1859 if (actual
!= expected
) fail(actual
, expected
, message
, '==', assert
.equal
);
1862 // 6. The non-equality assertion tests for whether two objects are not equal
1863 // with != assert.notEqual(actual, expected, message_opt);
1865 assert
.notEqual
= function notEqual(actual
, expected
, message
) {
1866 if (actual
== expected
) {
1867 fail(actual
, expected
, message
, '!=', assert
.notEqual
);
1871 // 7. The equivalence assertion tests a deep equality relation.
1872 // assert.deepEqual(actual, expected, message_opt);
1874 assert
.deepEqual
= function deepEqual(actual
, expected
, message
) {
1875 if (!_deepEqual(actual
, expected
)) {
1876 fail(actual
, expected
, message
, 'deepEqual', assert
.deepEqual
);
1880 function _deepEqual(actual
, expected
) {
1881 // 7.1. All identical values are equivalent, as determined by ===.
1882 if (actual
=== expected
) {
1885 } else if (util
.isBuffer(actual
) && util
.isBuffer(expected
)) {
1886 if (actual
.length
!= expected
.length
) return false;
1888 for (var i
= 0; i
< actual
.length
; i
++) {
1889 if (actual
[i
] !== expected
[i
]) return false;
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();
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
;
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
;
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.
1921 return objEquiv(actual
, expected
);
1925 function isArguments(object
) {
1926 return Object
.prototype.toString
.call(object
) == '[object Arguments]';
1929 function objEquiv(a
, b
) {
1930 if (util
.isNullOrUndefined(a
) || util
.isNullOrUndefined(b
))
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
)) {
1938 var aIsArgs
= isArguments(a
),
1939 bIsArgs
= isArguments(b
);
1940 if ((aIsArgs
&& !bIsArgs
) || (!aIsArgs
&& bIsArgs
))
1945 return _deepEqual(a
, b
);
1947 var ka
= objectKeys(a
),
1950 // having the same number of owned properties (keys incorporates
1952 if (ka
.length
!= kb
.length
)
1954 //the same set of keys (although not necessarily the same order),
1958 for (i
= ka
.length
- 1; i
>= 0; i
--) {
1962 //equivalent values for every corresponding key, and
1963 //~~~possibly expensive deep test
1964 for (i
= ka
.length
- 1; i
>= 0; i
--) {
1966 if (!_deepEqual(a
[key
], b
[key
])) return false;
1971 // 8. The non-equivalence assertion tests for any deep inequality.
1972 // assert.notDeepEqual(actual, expected, message_opt);
1974 assert
.notDeepEqual
= function notDeepEqual(actual
, expected
, message
) {
1975 if (_deepEqual(actual
, expected
)) {
1976 fail(actual
, expected
, message
, 'notDeepEqual', assert
.notDeepEqual
);
1980 // 9. The strict equality assertion tests strict equality, as determined by ===.
1981 // assert.strictEqual(actual, expected, message_opt);
1983 assert
.strictEqual
= function strictEqual(actual
, expected
, message
) {
1984 if (actual
!== expected
) {
1985 fail(actual
, expected
, message
, '===', assert
.strictEqual
);
1989 // 10. The strict non-equality assertion tests for strict inequality, as
1990 // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
1992 assert
.notStrictEqual
= function notStrictEqual(actual
, expected
, message
) {
1993 if (actual
=== expected
) {
1994 fail(actual
, expected
, message
, '!==', assert
.notStrictEqual
);
1998 function expectedException(actual
, expected
) {
1999 if (!actual
|| !expected
) {
2003 if (Object
.prototype.toString
.call(expected
) == '[object RegExp]') {
2004 return expected
.test(actual
);
2005 } else if (actual
instanceof expected
) {
2007 } else if (expected
.call({}, actual
) === true) {
2014 function _throws(shouldThrow
, block
, expected
, message
) {
2017 if (util
.isString(expected
)) {
2028 message
= (expected
&& expected
.name
? ' (' + expected
.name
+ ').' : '.') +
2029 (message
? ' ' + message : '.');
2031 if (shouldThrow
&& !actual
) {
2032 fail(actual
, expected
, 'Missing expected exception' + message
);
2035 if (!shouldThrow
&& expectedException(actual
, expected
)) {
2036 fail(actual
, expected
, 'Got unwanted exception' + message
);
2039 if ((shouldThrow
&& actual
&& expected
&&
2040 !expectedException(actual
, expected
)) || (!shouldThrow
&& actual
)) {
2045 // 11. Expected to throw an error:
2046 // assert.throws(block, Error_opt, message_opt);
2048 assert
.throws = function(block
, /*optional*/error
, /*optional*/message
) {
2049 _throws
.apply(this, [true].concat(pSlice
.call(arguments
)));
2052 // EXTENSION! This is annoying to write outside this module.
2053 assert
.doesNotThrow = function(block
, /*optional*/message
) {
2054 _throws
.apply(this, [false].concat(pSlice
.call(arguments
)));
2057 assert
.ifError = function(err
) { if (err
) {throw err
;}};
2059 var objectKeys
= Object
.keys
|| function (obj
) {
2061 for (var key
in obj
) {
2062 if (hasOwn
.call(obj
, key
)) keys
.push(key
);
2067 },{"util/":29}],6:[function(require
,module
,exports
){
2069 },{}],7:[function(require
,module
,exports
){
2071 * The buffer module from node.js, for the browser.
2073 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2077 var base64
= require('base64-js')
2078 var ieee754
= require('ieee754')
2079 var isArray
= require('is-array')
2081 exports
.Buffer
= Buffer
2082 exports
.SlowBuffer
= SlowBuffer
2083 exports
.INSPECT_MAX_BYTES
= 50
2084 Buffer
.poolSize
= 8192 // not used by this implementation
2089 * If `Buffer.TYPED_ARRAY_SUPPORT`:
2090 * === true Use Uint8Array implementation (fastest)
2091 * === false Use Object implementation (most compatible, even IE6)
2093 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
2094 * Opera 11.6+, iOS 4.2+.
2096 * Due to various browser bugs, sometimes the Object implementation will be used even
2097 * when the browser supports typed arrays.
2101 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
2102 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
2104 * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
2107 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
2109 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
2110 * incorrect length in some situations.
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.
2115 Buffer
.TYPED_ARRAY_SUPPORT
= (function () {
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`
2130 function kMaxLength () {
2131 return Buffer
.TYPED_ARRAY_SUPPORT
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
2145 * By augmenting the instances, we can avoid modifying the `Uint8Array`
2148 function 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
)
2156 this.parent
= undefined
2159 if (typeof arg
=== 'number') {
2160 return fromNumber(this, arg
)
2163 // Slightly less common case.
2164 if (typeof arg
=== 'string') {
2165 return fromString(this, arg
, arguments
.length
> 1 ? arguments
[1] : 'utf8')
2169 return fromObject(this, arg
)
2172 function 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
++) {
2182 function fromString (that
, string
, encoding
) {
2183 if (typeof encoding
!== 'string' || encoding
=== '') encoding
= 'utf8'
2185 // Assumption: byteLength() return value is always < kMaxLength.
2186 var length
= byteLength(string
, encoding
) | 0
2187 that
= allocate(that
, length
)
2189 that
.write(string
, encoding
)
2193 function fromObject (that
, object
) {
2194 if (Buffer
.isBuffer(object
)) return fromBuffer(that
, object
)
2196 if (isArray(object
)) return fromArray(that
, object
)
2198 if (object
== null) {
2199 throw new TypeError('must start with number, buffer, array or string')
2202 if (typeof ArrayBuffer
!== 'undefined') {
2203 if (object
.buffer
instanceof ArrayBuffer
) {
2204 return fromTypedArray(that
, object
)
2206 if (object
instanceof ArrayBuffer
) {
2207 return fromArrayBuffer(that
, object
)
2211 if (object
.length
) return fromArrayLike(that
, object
)
2213 return fromJsonObject(that
, object
)
2216 function fromBuffer (that
, buffer
) {
2217 var length
= checked(buffer
.length
) | 0
2218 that
= allocate(that
, length
)
2219 buffer
.copy(that
, 0, 0, length
)
2223 function 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
2232 // Duplicate of fromArray() to keep fromArray() monomorphic.
2233 function 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
2245 function fromArrayBuffer (that
, array
) {
2246 if (Buffer
.TYPED_ARRAY_SUPPORT
) {
2247 // Return an augmented `Uint8Array` instance, for best performance
2249 that
= Buffer
._augment(new Uint8Array(array
))
2251 // Fallback: Return an object instance of the Buffer class
2252 that
= fromTypedArray(that
, new Uint8Array(array
))
2257 function 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
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.
2268 function fromJsonObject (that
, object
) {
2272 if (object
.type
=== 'Buffer' && isArray(object
.data
)) {
2274 length
= checked(array
.length
) | 0
2276 that
= allocate(that
, length
)
2278 for (var i
= 0; i
< length
; i
+= 1) {
2279 that
[i
] = array
[i
] & 255
2284 function 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
))
2289 // Fallback: Return an object instance of the Buffer class
2290 that
.length
= length
2291 that
._isBuffer
= true
2294 var fromPool
= length
!== 0 && length
<= Buffer
.poolSize
>>> 1
2295 if (fromPool
) that
.parent
= rootParent
2300 function 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')
2310 function SlowBuffer (subject
, encoding
) {
2311 if (!(this instanceof SlowBuffer
)) return new SlowBuffer(subject
, encoding
)
2313 var buf
= new Buffer(subject
, encoding
)
2318 Buffer
.isBuffer
= function isBuffer (b
) {
2319 return !!(b
!= null && b
._isBuffer
)
2322 Buffer
.compare
= function compare (a
, b
) {
2323 if (!Buffer
.isBuffer(a
) || !Buffer
.isBuffer(b
)) {
2324 throw new TypeError('Arguments must be Buffers')
2327 if (a
=== b
) return 0
2333 var len
= Math
.min(x
, y
)
2335 if (a
[i
] !== b
[i
]) break
2345 if (x
< y
) return -1
2350 Buffer
.isEncoding
= function isEncoding (encoding
) {
2351 switch (String(encoding
).toLowerCase()) {
2369 Buffer
.concat
= function concat (list
, length
) {
2370 if (!isArray(list
)) throw new TypeError('list argument must be an Array of Buffers.')
2372 if (list
.length
=== 0) {
2373 return new Buffer(0)
2377 if (length
=== undefined) {
2379 for (i
= 0; i
< list
.length
; i
++) {
2380 length
+= list
[i
].length
2384 var buf
= new Buffer(length
)
2386 for (i
= 0; i
< list
.length
; i
++) {
2394 function byteLength (string
, encoding
) {
2395 if (typeof string
!== 'string') string
= '' + string
2397 var len
= string
.length
2398 if (len
=== 0) return 0
2400 // Use a for loop to avoid recursion
2401 var loweredCase
= false
2412 return utf8ToBytes(string
).length
2421 return base64ToBytes(string
).length
2423 if (loweredCase
) return utf8ToBytes(string
).length
// assume utf8
2424 encoding
= ('' + encoding
).toLowerCase()
2429 Buffer
.byteLength
= byteLength
2431 // pre-set for values that may exist in the future
2432 Buffer
.prototype.length
= undefined
2433 Buffer
.prototype.parent
= undefined
2435 function slowToString (encoding
, start
, end
) {
2436 var loweredCase
= false
2439 end
= end
=== undefined || end
=== Infinity
? this.length : end
| 0
2441 if (!encoding
) encoding
= 'utf8'
2442 if (start
< 0) start
= 0
2443 if (end
> this.length
) end
= this.length
2444 if (end
<= start
) return ''
2449 return hexSlice(this, start
, end
)
2453 return utf8Slice(this, start
, end
)
2456 return asciiSlice(this, start
, end
)
2459 return binarySlice(this, start
, end
)
2462 return base64Slice(this, start
, end
)
2468 return utf16leSlice(this, start
, end
)
2471 if (loweredCase
) throw new TypeError('Unknown encoding: ' + encoding
)
2472 encoding
= (encoding
+ '').toLowerCase()
2478 Buffer
.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
)
2485 Buffer
.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
2491 Buffer
.prototype.inspect
= function inspect () {
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
+= ' ... '
2498 return '<Buffer ' + str
+ '>'
2501 Buffer
.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
)
2507 Buffer
.prototype.indexOf
= function indexOf (val
, byteOffset
) {
2508 if (byteOffset
> 0x7fffffff) byteOffset
= 0x7fffffff
2509 else if (byteOffset
< -0x80000000) byteOffset
= -0x80000000
2512 if (this.length
=== 0) return -1
2513 if (byteOffset
>= this.length
) return -1
2515 // Negative offsets start from the end of the buffer
2516 if (byteOffset
< 0) byteOffset
= Math
.max(this.length
+ byteOffset
, 0)
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
)
2522 if (Buffer
.isBuffer(val
)) {
2523 return arrayIndexOf(this, val
, byteOffset
)
2525 if (typeof val
=== 'number') {
2526 if (Buffer
.TYPED_ARRAY_SUPPORT
&& Uint8Array
.prototype.indexOf
=== 'function') {
2527 return Uint8Array
.prototype.indexOf
.call(this, val
, byteOffset
)
2529 return arrayIndexOf(this, [ val
], byteOffset
)
2532 function arrayIndexOf (arr
, val
, byteOffset
) {
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
2545 throw new TypeError('val must be string, number or Buffer')
2548 // `get` is deprecated
2549 Buffer
.prototype.get = function get (offset
) {
2550 console
.log('.get() is deprecated. Access using array indexes instead.')
2551 return this.readUInt8(offset
)
2554 // `set` is deprecated
2555 Buffer
.prototype.set = function set (v
, offset
) {
2556 console
.log('.set() is deprecated. Access using array indexes instead.')
2557 return this.writeUInt8(v
, offset
)
2560 function hexWrite (buf
, string
, offset
, length
) {
2561 offset
= Number(offset
) || 0
2562 var remaining
= buf
.length
- offset
2566 length
= Number(length
)
2567 if (length
> remaining
) {
2572 // must be an even number of digits
2573 var strLen
= string
.length
2574 if (strLen
% 2 !== 0) throw new Error('Invalid hex string')
2576 if (length
> strLen
/ 2) {
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
2587 function utf8Write (buf
, string
, offset
, length
) {
2588 return blitBuffer(utf8ToBytes(string
, buf
.length
- offset
), buf
, offset
, length
)
2591 function asciiWrite (buf
, string
, offset
, length
) {
2592 return blitBuffer(asciiToBytes(string
), buf
, offset
, length
)
2595 function binaryWrite (buf
, string
, offset
, length
) {
2596 return asciiWrite(buf
, string
, offset
, length
)
2599 function base64Write (buf
, string
, offset
, length
) {
2600 return blitBuffer(base64ToBytes(string
), buf
, offset
, length
)
2603 function ucs2Write (buf
, string
, offset
, length
) {
2604 return blitBuffer(utf16leToBytes(string
, buf
.length
- offset
), buf
, offset
, length
)
2607 Buffer
.prototype.write
= function write (string
, offset
, length
, encoding
) {
2608 // Buffer#write(string)
2609 if (offset
=== undefined) {
2611 length
= this.length
2613 // Buffer#write(string, encoding)
2614 } else if (length
=== undefined && typeof offset
=== 'string') {
2616 length
= this.length
2618 // Buffer#write(string, offset[, length][, encoding])
2619 } else if (isFinite(offset
)) {
2621 if (isFinite(length
)) {
2623 if (encoding
=== undefined) encoding
= 'utf8'
2628 // legacy write(string, encoding, offset, length) - remove in v0.13
2636 var remaining
= this.length
- offset
2637 if (length
=== undefined || length
> remaining
) length
= remaining
2639 if ((string
.length
> 0 && (length
< 0 || offset
< 0)) || offset
> this.length
) {
2640 throw new RangeError('attempt to write outside buffer bounds')
2643 if (!encoding
) encoding
= 'utf8'
2645 var loweredCase
= false
2649 return hexWrite(this, string
, offset
, length
)
2653 return utf8Write(this, string
, offset
, length
)
2656 return asciiWrite(this, string
, offset
, length
)
2659 return binaryWrite(this, string
, offset
, length
)
2662 // Warning: maxLength not taken into account in base64Write
2663 return base64Write(this, string
, offset
, length
)
2669 return ucs2Write(this, string
, offset
, length
)
2672 if (loweredCase
) throw new TypeError('Unknown encoding: ' + encoding
)
2673 encoding
= ('' + encoding
).toLowerCase()
2679 Buffer
.prototype.toJSON
= function toJSON () {
2682 data: Array
.prototype.slice
.call(this._arr
|| this, 0)
2686 function base64Slice (buf
, start
, end
) {
2687 if (start
=== 0 && end
=== buf
.length
) {
2688 return base64
.fromByteArray(buf
)
2690 return base64
.fromByteArray(buf
.slice(start
, end
))
2694 function utf8Slice (buf
, start
, end
) {
2695 end
= Math
.min(buf
.length
, end
)
2700 var bytesPerSequence
2706 for (; i
< end
; i
+= bytesPerSequence
) {
2710 if (firstByte
> 0xEF) {
2711 bytesPerSequence
= 4
2712 } else if (firstByte
> 0xDF) {
2713 bytesPerSequence
= 3
2714 } else if (firstByte
> 0xBF) {
2715 bytesPerSequence
= 2
2717 bytesPerSequence
= 1
2720 if (i
+ bytesPerSequence
<= end
) {
2721 switch (bytesPerSequence
) {
2723 if (firstByte
< 0x80) {
2724 codePoint
= firstByte
2728 secondByte
= buf
[i
+ 1]
2729 if ((secondByte
& 0xC0) === 0x80) {
2730 tempCodePoint
= (firstByte
& 0x1F) << 0x6 | (secondByte
& 0x3F)
2731 if (tempCodePoint
> 0x7F) {
2732 codePoint
= tempCodePoint
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
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
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
2772 return String
.fromCharCode
.apply(String
, res
)
2775 function asciiSlice (buf
, start
, end
) {
2777 end
= Math
.min(buf
.length
, end
)
2779 for (var i
= start
; i
< end
; i
++) {
2780 ret
+= String
.fromCharCode(buf
[i
] & 0x7F)
2785 function binarySlice (buf
, start
, end
) {
2787 end
= Math
.min(buf
.length
, end
)
2789 for (var i
= start
; i
< end
; i
++) {
2790 ret
+= String
.fromCharCode(buf
[i
])
2795 function hexSlice (buf
, start
, end
) {
2796 var len
= buf
.length
2798 if (!start
|| start
< 0) start
= 0
2799 if (!end
|| end
< 0 || end
> len
) end
= len
2802 for (var i
= start
; i
< end
; i
++) {
2803 out
+= toHex(buf
[i
])
2808 function utf16leSlice (buf
, start
, end
) {
2809 var bytes
= buf
.slice(start
, end
)
2811 for (var i
= 0; i
< bytes
.length
; i
+= 2) {
2812 res
+= String
.fromCharCode(bytes
[i
] + bytes
[i
+ 1] * 256)
2817 Buffer
.prototype.slice
= function slice (start
, end
) {
2818 var len
= this.length
2820 end
= end
=== undefined ? len : ~~end
2824 if (start
< 0) start
= 0
2825 } else if (start
> len
) {
2831 if (end
< 0) end
= 0
2832 } else if (end
> len
) {
2836 if (end
< start
) end
= start
2839 if (Buffer
.TYPED_ARRAY_SUPPORT
) {
2840 newBuf
= Buffer
._augment(this.subarray(start
, end
))
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
]
2849 if (newBuf
.length
) newBuf
.parent
= this.parent
|| this
2855 * Need to make sure that buffer isn't trying to write out of bounds.
2857 function 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')
2862 Buffer
.prototype.readUIntLE
= function readUIntLE (offset
, byteLength
, noAssert
) {
2864 byteLength
= byteLength
| 0
2865 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
2867 var val
= this[offset
]
2870 while (++i
< byteLength
&& (mul
*= 0x100)) {
2871 val
+= this[offset
+ i
] * mul
2877 Buffer
.prototype.readUIntBE
= function readUIntBE (offset
, byteLength
, noAssert
) {
2879 byteLength
= byteLength
| 0
2881 checkOffset(offset
, byteLength
, this.length
)
2884 var val
= this[offset
+ --byteLength
]
2886 while (byteLength
> 0 && (mul
*= 0x100)) {
2887 val
+= this[offset
+ --byteLength
] * mul
2893 Buffer
.prototype.readUInt8
= function readUInt8 (offset
, noAssert
) {
2894 if (!noAssert
) checkOffset(offset
, 1, this.length
)
2898 Buffer
.prototype.readUInt16LE
= function readUInt16LE (offset
, noAssert
) {
2899 if (!noAssert
) checkOffset(offset
, 2, this.length
)
2900 return this[offset
] | (this[offset
+ 1] << 8)
2903 Buffer
.prototype.readUInt16BE
= function readUInt16BE (offset
, noAssert
) {
2904 if (!noAssert
) checkOffset(offset
, 2, this.length
)
2905 return (this[offset
] << 8) | this[offset
+ 1]
2908 Buffer
.prototype.readUInt32LE
= function readUInt32LE (offset
, noAssert
) {
2909 if (!noAssert
) checkOffset(offset
, 4, this.length
)
2911 return ((this[offset
]) |
2912 (this[offset
+ 1] << 8) |
2913 (this[offset
+ 2] << 16)) +
2914 (this[offset
+ 3] * 0x1000000)
2917 Buffer
.prototype.readUInt32BE
= function readUInt32BE (offset
, noAssert
) {
2918 if (!noAssert
) checkOffset(offset
, 4, this.length
)
2920 return (this[offset
] * 0x1000000) +
2921 ((this[offset
+ 1] << 16) |
2922 (this[offset
+ 2] << 8) |
2926 Buffer
.prototype.readIntLE
= function readIntLE (offset
, byteLength
, noAssert
) {
2928 byteLength
= byteLength
| 0
2929 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
2931 var val
= this[offset
]
2934 while (++i
< byteLength
&& (mul
*= 0x100)) {
2935 val
+= this[offset
+ i
] * mul
2939 if (val
>= mul
) val
-= Math
.pow(2, 8 * byteLength
)
2944 Buffer
.prototype.readIntBE
= function readIntBE (offset
, byteLength
, noAssert
) {
2946 byteLength
= byteLength
| 0
2947 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
2951 var val
= this[offset
+ --i
]
2952 while (i
> 0 && (mul
*= 0x100)) {
2953 val
+= this[offset
+ --i
] * mul
2957 if (val
>= mul
) val
-= Math
.pow(2, 8 * byteLength
)
2962 Buffer
.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)
2968 Buffer
.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
2974 Buffer
.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
2980 Buffer
.prototype.readInt32LE
= function readInt32LE (offset
, noAssert
) {
2981 if (!noAssert
) checkOffset(offset
, 4, this.length
)
2983 return (this[offset
]) |
2984 (this[offset
+ 1] << 8) |
2985 (this[offset
+ 2] << 16) |
2986 (this[offset
+ 3] << 24)
2989 Buffer
.prototype.readInt32BE
= function readInt32BE (offset
, noAssert
) {
2990 if (!noAssert
) checkOffset(offset
, 4, this.length
)
2992 return (this[offset
] << 24) |
2993 (this[offset
+ 1] << 16) |
2994 (this[offset
+ 2] << 8) |
2998 Buffer
.prototype.readFloatLE
= function readFloatLE (offset
, noAssert
) {
2999 if (!noAssert
) checkOffset(offset
, 4, this.length
)
3000 return ieee754
.read(this, offset
, true, 23, 4)
3003 Buffer
.prototype.readFloatBE
= function readFloatBE (offset
, noAssert
) {
3004 if (!noAssert
) checkOffset(offset
, 4, this.length
)
3005 return ieee754
.read(this, offset
, false, 23, 4)
3008 Buffer
.prototype.readDoubleLE
= function readDoubleLE (offset
, noAssert
) {
3009 if (!noAssert
) checkOffset(offset
, 8, this.length
)
3010 return ieee754
.read(this, offset
, true, 52, 8)
3013 Buffer
.prototype.readDoubleBE
= function readDoubleBE (offset
, noAssert
) {
3014 if (!noAssert
) checkOffset(offset
, 8, this.length
)
3015 return ieee754
.read(this, offset
, false, 52, 8)
3018 function 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')
3024 Buffer
.prototype.writeUIntLE
= function writeUIntLE (value
, offset
, byteLength
, noAssert
) {
3027 byteLength
= byteLength
| 0
3028 if (!noAssert
) checkInt(this, value
, offset
, byteLength
, Math
.pow(2, 8 * byteLength
), 0)
3032 this[offset
] = value
& 0xFF
3033 while (++i
< byteLength
&& (mul
*= 0x100)) {
3034 this[offset
+ i
] = (value
/ mul
) & 0xFF
3037 return offset
+ byteLength
3040 Buffer
.prototype.writeUIntBE
= function writeUIntBE (value
, offset
, byteLength
, noAssert
) {
3043 byteLength
= byteLength
| 0
3044 if (!noAssert
) checkInt(this, value
, offset
, byteLength
, Math
.pow(2, 8 * byteLength
), 0)
3046 var i
= byteLength
- 1
3048 this[offset
+ i
] = value
& 0xFF
3049 while (--i
>= 0 && (mul
*= 0x100)) {
3050 this[offset
+ i
] = (value
/ mul
) & 0xFF
3053 return offset
+ byteLength
3056 Buffer
.prototype.writeUInt8
= function writeUInt8 (value
, offset
, noAssert
) {
3059 if (!noAssert
) checkInt(this, value
, offset
, 1, 0xff, 0)
3060 if (!Buffer
.TYPED_ARRAY_SUPPORT
) value
= Math
.floor(value
)
3061 this[offset
] = value
3065 function 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
3073 Buffer
.prototype.writeUInt16LE
= function writeUInt16LE (value
, offset
, noAssert
) {
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)
3081 objectWriteUInt16(this, value
, offset
, true)
3086 Buffer
.prototype.writeUInt16BE
= function writeUInt16BE (value
, offset
, noAssert
) {
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
3094 objectWriteUInt16(this, value
, offset
, false)
3099 function 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
3106 Buffer
.prototype.writeUInt32LE
= function writeUInt32LE (value
, offset
, noAssert
) {
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
3116 objectWriteUInt32(this, value
, offset
, true)
3121 Buffer
.prototype.writeUInt32BE
= function writeUInt32BE (value
, offset
, noAssert
) {
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
3131 objectWriteUInt32(this, value
, offset
, false)
3136 Buffer
.prototype.writeIntLE
= function writeIntLE (value
, offset
, byteLength
, noAssert
) {
3140 var limit
= Math
.pow(2, 8 * byteLength
- 1)
3142 checkInt(this, value
, offset
, byteLength
, limit
- 1, -limit
)
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
3153 return offset
+ byteLength
3156 Buffer
.prototype.writeIntBE
= function writeIntBE (value
, offset
, byteLength
, noAssert
) {
3160 var limit
= Math
.pow(2, 8 * byteLength
- 1)
3162 checkInt(this, value
, offset
, byteLength
, limit
- 1, -limit
)
3165 var i
= byteLength
- 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
3173 return offset
+ byteLength
3176 Buffer
.prototype.writeInt8
= function writeInt8 (value
, offset
, noAssert
) {
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
3186 Buffer
.prototype.writeInt16LE
= function writeInt16LE (value
, offset
, noAssert
) {
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)
3194 objectWriteUInt16(this, value
, offset
, true)
3199 Buffer
.prototype.writeInt16BE
= function writeInt16BE (value
, offset
, noAssert
) {
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
3207 objectWriteUInt16(this, value
, offset
, false)
3212 Buffer
.prototype.writeInt32LE
= function writeInt32LE (value
, offset
, noAssert
) {
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)
3222 objectWriteUInt32(this, value
, offset
, true)
3227 Buffer
.prototype.writeInt32BE
= function writeInt32BE (value
, offset
, noAssert
) {
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
3238 objectWriteUInt32(this, value
, offset
, false)
3243 function 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')
3249 function writeFloat (buf
, value
, offset
, littleEndian
, noAssert
) {
3251 checkIEEE754(buf
, value
, offset
, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3253 ieee754
.write(buf
, value
, offset
, littleEndian
, 23, 4)
3257 Buffer
.prototype.writeFloatLE
= function writeFloatLE (value
, offset
, noAssert
) {
3258 return writeFloat(this, value
, offset
, true, noAssert
)
3261 Buffer
.prototype.writeFloatBE
= function writeFloatBE (value
, offset
, noAssert
) {
3262 return writeFloat(this, value
, offset
, false, noAssert
)
3265 function writeDouble (buf
, value
, offset
, littleEndian
, noAssert
) {
3267 checkIEEE754(buf
, value
, offset
, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3269 ieee754
.write(buf
, value
, offset
, littleEndian
, 52, 8)
3273 Buffer
.prototype.writeDoubleLE
= function writeDoubleLE (value
, offset
, noAssert
) {
3274 return writeDouble(this, value
, offset
, true, noAssert
)
3277 Buffer
.prototype.writeDoubleBE
= function writeDoubleBE (value
, offset
, noAssert
) {
3278 return writeDouble(this, value
, offset
, false, noAssert
)
3281 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3282 Buffer
.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
3289 // Copy 0 bytes; we're done
3290 if (end
=== start
) return 0
3291 if (target
.length
=== 0 || this.length
=== 0) return 0
3293 // Fatal error conditions
3294 if (targetStart
< 0) {
3295 throw new RangeError('targetStart out of bounds')
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')
3301 if (end
> this.length
) end
= this.length
3302 if (target
.length
- targetStart
< end
- start
) {
3303 end
= target
.length
- targetStart
+ start
3306 var len
= end
- start
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
]
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
]
3320 target
._set(this.subarray(start
, start
+ len
), targetStart
)
3326 // fill(value, start=0, end=buffer.length)
3327 Buffer
.prototype.fill
= function fill (value
, start
, end
) {
3328 if (!value
) value
= 0
3329 if (!start
) start
= 0
3330 if (!end
) end
= this.length
3332 if (end
< start
) throw new RangeError('end < start')
3334 // Fill 0 bytes; we're done
3335 if (end
=== start
) return
3336 if (this.length
=== 0) return
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')
3342 if (typeof value
=== 'number') {
3343 for (i
= start
; i
< end
; i
++) {
3347 var bytes
= utf8ToBytes(value
.toString())
3348 var len
= bytes
.length
3349 for (i
= start
; i
< end
; i
++) {
3350 this[i
] = bytes
[i
% len
]
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.
3361 Buffer
.prototype.toArrayBuffer
= function toArrayBuffer () {
3362 if (typeof Uint8Array
!== 'undefined') {
3363 if (Buffer
.TYPED_ARRAY_SUPPORT
) {
3364 return (new Buffer(this)).buffer
3366 var buf
= new Uint8Array(this.length
)
3367 for (var i
= 0, len
= buf
.length
; i
< len
; i
+= 1) {
3373 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
3380 var BP
= Buffer
.prototype
3383 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
3385 Buffer
._augment
= function _augment (arr
) {
3386 arr
.constructor = Buffer
3387 arr
._isBuffer
= true
3389 // save reference to original Uint8Array set method before overwriting
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
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
3442 arr
.inspect
= BP
.inspect
3443 arr
.toArrayBuffer
= BP
.toArrayBuffer
3448 var INVALID_BASE64_RE
= /[^+\/0-9A-Za-z-_]/g
3450 function 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) {
3462 function stringtrim (str
) {
3463 if (str
.trim
) return str
.trim()
3464 return str
.replace(/^\s+|\s+$/g, '')
3467 function toHex (n
) {
3468 if (n
< 16) return '0' + n
.toString(16)
3469 return n
.toString(16)
3472 function utf8ToBytes (string
, units
) {
3473 units
= units
|| Infinity
3475 var length
= string
.length
3476 var leadSurrogate
= null
3479 for (var i
= 0; i
< length
; i
++) {
3480 codePoint
= string
.charCodeAt(i
)
3482 // is surrogate component
3483 if (codePoint
> 0xD7FF && codePoint
< 0xE000) {
3484 // last char was a lead
3485 if (!leadSurrogate
) {
3487 if (codePoint
> 0xDBFF) {
3489 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
3492 } else if (i
+ 1 === length
) {
3494 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
3499 leadSurrogate
= codePoint
3505 if (codePoint
< 0xDC00) {
3506 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
3507 leadSurrogate
= codePoint
3511 // valid surrogate pair
3512 codePoint
= leadSurrogate
- 0xD800 << 10 | codePoint
- 0xDC00 | 0x10000
3514 } else if (leadSurrogate
) {
3515 // valid bmp char, but last char was a lead
3516 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
3519 leadSurrogate
= null
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
3528 codePoint
>> 0x6 | 0xC0,
3529 codePoint
& 0x3F | 0x80
3531 } else if (codePoint
< 0x10000) {
3532 if ((units
-= 3) < 0) break
3534 codePoint
>> 0xC | 0xE0,
3535 codePoint
>> 0x6 & 0x3F | 0x80,
3536 codePoint
& 0x3F | 0x80
3538 } else if (codePoint
< 0x110000) {
3539 if ((units
-= 4) < 0) break
3541 codePoint
>> 0x12 | 0xF0,
3542 codePoint
>> 0xC & 0x3F | 0x80,
3543 codePoint
>> 0x6 & 0x3F | 0x80,
3544 codePoint
& 0x3F | 0x80
3547 throw new Error('Invalid code point')
3554 function asciiToBytes (str
) {
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)
3563 function utf16leToBytes (str
, units
) {
3566 for (var i
= 0; i
< str
.length
; i
++) {
3567 if ((units
-= 2) < 0) break
3569 c
= str
.charCodeAt(i
)
3579 function base64ToBytes (str
) {
3580 return base64
.toByteArray(base64clean(str
))
3583 function 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
]
3591 },{"base64-js":8,"ieee754":9,"is-array":10}],8:[function(require
,module
,exports
){
3592 var lookup
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3594 ;(function (exports
) {
3597 var Arr
= (typeof Uint8Array
!== 'undefined')
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)
3609 function decode (elt
) {
3610 var code
= elt
.charCodeAt(0)
3611 if (code
=== PLUS
||
3612 code
=== PLUS_URL_SAFE
)
3614 if (code
=== SLASH
||
3615 code
=== SLASH_URL_SAFE
)
3618 return -1 //no match
3619 if (code
< NUMBER
+ 10)
3620 return code
- NUMBER
+ 26 + 26
3621 if (code
< UPPER
+ 26)
3623 if (code
< LOWER
+ 26)
3624 return code
- LOWER
+ 26
3627 function b64ToByteArray (b64
) {
3628 var i
, j
, l
, tmp
, placeHolders
, arr
3630 if (b64
.length
% 4 > 0) {
3631 throw new Error('Invalid string. Length must be a multiple of 4')
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
3642 // base64 is 4/3 + up to two characters of the original data
3643 arr
= new Arr(b64
.length
* 3 / 4 - placeHolders
)
3645 // if there are placeholders, only get up to the last complete 4 chars
3646 l
= placeHolders
> 0 ? b64
.length
- 4 : b64
.length
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)
3661 if (placeHolders
=== 2) {
3662 tmp
= (decode(b64
.charAt(i
)) << 2) | (decode(b64
.charAt(i
+ 1)) >> 4)
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)
3673 function uint8ToBase64 (uint8
) {
3675 extraBytes
= uint8
.length
% 3, // if we have 1 byte left, pad 2 bytes
3679 function encode (num
) {
3680 return lookup
.charAt(num
)
3683 function tripletToBase64 (num
) {
3684 return encode(num
>> 18 & 0x3F) + encode(num
>> 12 & 0x3F) + encode(num
>> 6 & 0x3F) + encode(num
& 0x3F)
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
)
3693 // pad the end with zeros, but make sure to not forget the extra bytes
3694 switch (extraBytes
) {
3696 temp
= uint8
[uint8
.length
- 1]
3697 output
+= encode(temp
>> 2)
3698 output
+= encode((temp
<< 4) & 0x3F)
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)
3713 exports
.toByteArray
= b64ToByteArray
3714 exports
.fromByteArray
= uint8ToBase64
3715 }(typeof exports
=== 'undefined' ? (this.base64js
= {}) : exports
))
3717 },{}],9:[function(require
,module
,exports
){
3718 exports
.read = function (buffer
, offset
, isLE
, mLen
, nBytes
) {
3720 var eLen
= nBytes
* 8 - mLen
- 1
3721 var eMax
= (1 << eLen
) - 1
3722 var eBias
= eMax
>> 1
3724 var i
= isLE
? (nBytes
- 1) : 0
3725 var d
= isLE
? -1 : 1
3726 var s
= buffer
[offset
+ i
]
3730 e
= s
& ((1 << (-nBits
)) - 1)
3733 for (; nBits
> 0; e
= e
* 256 + buffer
[offset
+ i
], i
+= d
, nBits
-= 8) {}
3735 m
= e
& ((1 << (-nBits
)) - 1)
3738 for (; nBits
> 0; m
= m
* 256 + buffer
[offset
+ i
], i
+= d
, nBits
-= 8) {}
3742 } else if (e
=== eMax
) {
3743 return m
? NaN : ((s
? -1 : 1) * Infinity
)
3745 m
= m
+ Math
.pow(2, mLen
)
3748 return (s
? -1 : 1) * m
* Math
.pow(2, e
- mLen
)
3751 exports
.write = function (buffer
, value
, offset
, isLE
, mLen
, nBytes
) {
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
3761 value
= Math
.abs(value
)
3763 if (isNaN(value
) || value
=== Infinity
) {
3764 m
= isNaN(value
) ? 1 : 0
3767 e
= Math
.floor(Math
.log(value
) / Math
.LN2
)
3768 if (value
* (c
= Math
.pow(2, -e
)) < 1) {
3772 if (e
+ eBias
>= 1) {
3775 value
+= rt
* Math
.pow(2, 1 - eBias
)
3777 if (value
* c
>= 2) {
3782 if (e
+ eBias
>= eMax
) {
3785 } else if (e
+ eBias
>= 1) {
3786 m
= (value
* c
- 1) * Math
.pow(2, mLen
)
3789 m
= value
* Math
.pow(2, eBias
- 1) * Math
.pow(2, mLen
)
3794 for (; mLen
>= 8; buffer
[offset
+ i
] = m
& 0xff, i
+= d
, m
/= 256, mLen
-= 8) {}
3798 for (; eLen
> 0; buffer
[offset
+ i
] = e
& 0xff, i
+= d
, e
/= 256, eLen
-= 8) {}
3800 buffer
[offset
+ i
- d
] |= s
* 128
3803 },{}],10:[function(require
,module
,exports
){
3809 var isArray
= Array
.isArray
;
3815 var str
= Object
.prototype.toString
;
3818 * Whether or not the given `val`
3825 * isArray(arguments);
3830 * @param {mixed} val
3834 module
.exports
= isArray
|| function (val
) {
3835 return !! val
&& '[object Array]' == str
.call(val
);
3838 },{}],11:[function(require
,module
,exports
){
3839 // Copyright Joyent, Inc. and other Node contributors.
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:
3849 // The above copyright notice and this permission notice shall be included
3850 // in all copies or substantial portions of the Software.
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.
3860 function EventEmitter() {
3861 this._events
= this._events
|| {};
3862 this._maxListeners
= this._maxListeners
|| undefined;
3864 module
.exports
= EventEmitter
;
3866 // Backwards-compat with node 0.10.x
3867 EventEmitter
.EventEmitter
= EventEmitter
;
3869 EventEmitter
.prototype._events
= undefined;
3870 EventEmitter
.prototype._maxListeners
= undefined;
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.
3874 EventEmitter
.defaultMaxListeners
= 10;
3876 // Obviously not all Emitters should be limited to 10. This function allows
3877 // that to be increased. Set to zero for unlimited.
3878 EventEmitter
.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
;
3885 EventEmitter
.prototype.emit = function(type
) {
3886 var er
, handler
, len
, args
, i
, listeners
;
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
)) {
3896 if (er
instanceof Error
) {
3897 throw er
; // Unhandled 'error' event
3899 throw TypeError('Uncaught, unspecified "error" event.');
3903 handler
= this._events
[type
];
3905 if (isUndefined(handler
))
3908 if (isFunction(handler
)) {
3909 switch (arguments
.length
) {
3915 handler
.call(this, arguments
[1]);
3918 handler
.call(this, arguments
[1], arguments
[2]);
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
);
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
];
3934 listeners
= handler
.slice();
3935 len
= listeners
.length
;
3936 for (i
= 0; i
< len
; i
++)
3937 listeners
[i
].apply(this, args
);
3943 EventEmitter
.prototype.addListener = function(type
, listener
) {
3946 if (!isFunction(listener
))
3947 throw TypeError('listener must be a function');
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
);
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
);
3966 // Adding the second element, need to change to array.
3967 this._events
[type
] = [this._events
[type
], listener
];
3969 // Check for listener leak
3970 if (isObject(this._events
[type
]) && !this._events
[type
].warned
) {
3972 if (!isUndefined(this._maxListeners
)) {
3973 m
= this._maxListeners
;
3975 m
= EventEmitter
.defaultMaxListeners
;
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
3994 EventEmitter
.prototype.on
= EventEmitter
.prototype.addListener
;
3996 EventEmitter
.prototype.once = function(type
, listener
) {
3997 if (!isFunction(listener
))
3998 throw TypeError('listener must be a function');
4003 this.removeListener(type
, g
);
4007 listener
.apply(this, arguments
);
4011 g
.listener
= listener
;
4017 // emits a 'removeListener' event iff the listener was removed
4018 EventEmitter
.prototype.removeListener = function(type
, listener
) {
4019 var list
, position
, length
, i
;
4021 if (!isFunction(listener
))
4022 throw TypeError('listener must be a function');
4024 if (!this._events
|| !this._events
[type
])
4027 list
= this._events
[type
];
4028 length
= list
.length
;
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
);
4037 } else if (isObject(list
)) {
4038 for (i
= length
; i
-- > 0;) {
4039 if (list
[i
] === listener
||
4040 (list
[i
].listener
&& list
[i
].listener
=== listener
)) {
4049 if (list
.length
=== 1) {
4051 delete this._events
[type
];
4053 list
.splice(position
, 1);
4056 if (this._events
.removeListener
)
4057 this.emit('removeListener', type
, listener
);
4063 EventEmitter
.prototype.removeAllListeners = function(type
) {
4069 // not listening for removeListener, no need to emit
4070 if (!this._events
.removeListener
) {
4071 if (arguments
.length
=== 0)
4073 else if (this._events
[type
])
4074 delete this._events
[type
];
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
);
4084 this.removeAllListeners('removeListener');
4089 listeners
= this._events
[type
];
4091 if (isFunction(listeners
)) {
4092 this.removeListener(type
, listeners
);
4095 while (listeners
.length
)
4096 this.removeListener(type
, listeners
[listeners
.length
- 1]);
4098 delete this._events
[type
];
4103 EventEmitter
.prototype.listeners = function(type
) {
4105 if (!this._events
|| !this._events
[type
])
4107 else if (isFunction(this._events
[type
]))
4108 ret
= [this._events
[type
]];
4110 ret
= this._events
[type
].slice();
4114 EventEmitter
.listenerCount = function(emitter
, type
) {
4116 if (!emitter
._events
|| !emitter
._events
[type
])
4118 else if (isFunction(emitter
._events
[type
]))
4121 ret
= emitter
._events
[type
].length
;
4125 function isFunction(arg
) {
4126 return typeof arg
=== 'function';
4129 function isNumber(arg
) {
4130 return typeof arg
=== 'number';
4133 function isObject(arg
) {
4134 return typeof arg
=== 'object' && arg
!== null;
4137 function isUndefined(arg
) {
4138 return arg
=== void 0;
4141 },{}],12:[function(require
,module
,exports
){
4142 if (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, {
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
4166 },{}],13:[function(require
,module
,exports
){
4167 module
.exports
= Array
.isArray
|| function (arr
) {
4168 return Object
.prototype.toString
.call(arr
) == '[object Array]';
4171 },{}],14:[function(require
,module
,exports
){
4172 // shim for using process in browser
4174 var process
= module
.exports
= {};
4176 var draining
= false;
4178 var queueIndex
= -1;
4180 function cleanUpNextTick() {
4182 if (currentQueue
.length
) {
4183 queue
= currentQueue
.concat(queue
);
4192 function drainQueue() {
4196 var timeout
= setTimeout(cleanUpNextTick
);
4199 var len
= queue
.length
;
4201 currentQueue
= queue
;
4203 while (++queueIndex
< len
) {
4204 currentQueue
[queueIndex
].run();
4209 currentQueue
= null;
4211 clearTimeout(timeout
);
4214 process
.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
];
4221 queue
.push(new Item(fun
, args
));
4222 if (queue
.length
=== 1 && !draining
) {
4223 setTimeout(drainQueue
, 0);
4227 // v8 likes predictible objects
4228 function Item(fun
, array
) {
4232 Item
.prototype.run = function () {
4233 this.fun
.apply(null, this.array
);
4235 process
.title
= 'browser';
4236 process
.browser
= true;
4239 process
.version
= ''; // empty string to avoid regexp issues
4240 process
.versions
= {};
4245 process
.addListener
= noop
;
4246 process
.once
= noop
;
4248 process
.removeListener
= noop
;
4249 process
.removeAllListeners
= noop
;
4250 process
.emit
= noop
;
4252 process
.binding = function (name
) {
4253 throw new Error('process.binding is not supported');
4257 process
.cwd = function () { return '/' };
4258 process
.chdir = function (dir
) {
4259 throw new Error('process.chdir is not supported');
4261 process
.umask = function() { return 0; };
4263 },{}],15:[function(require
,module
,exports
){
4264 module
.exports
= require("./lib/_stream_duplex.js")
4266 },{"./lib/_stream_duplex.js":16}],16:[function(require
,module
,exports
){
4267 (function (process
){
4268 // Copyright Joyent, Inc. and other Node contributors.
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:
4278 // The above copyright notice and this permission notice shall be included
4279 // in all copies or substantial portions of the Software.
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.
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
4294 module
.exports
= Duplex
;
4297 var objectKeys
= Object
.keys
|| function (obj
) {
4299 for (var key
in obj
) keys
.push(key
);
4306 var util
= require('core-util-is');
4307 util
.inherits
= require('inherits');
4310 var Readable = require('./_stream_readable');
4311 var Writable = require('./_stream_writable');
4313 util.inherits(Duplex, Readable);
4315 forEach(objectKeys(Writable.prototype), function(method) {
4316 if (!Duplex.prototype[method])
4317 Duplex.prototype[method] = Writable.prototype[method];
4320 function Duplex(options) {
4321 if (!(this instanceof Duplex))
4322 return new Duplex(options);
4324 Readable.call(this, options);
4325 Writable.call(this, options);
4327 if (options && options.readable === false)
4328 this.readable = false;
4330 if (options && options.writable === false)
4331 this.writable = false;
4333 this.allowHalfOpen = true;
4334 if (options && options.allowHalfOpen === false)
4335 this.allowHalfOpen = false;
4337 this.once('end', onend);
4340 // the no-half-open enforcer
4342 // if we allow half-open state, or if the writable side ended,
4344 if (this.allowHalfOpen || this._writableState.ended)
4347 // no more data can be written.
4348 // But allow more writes to happen in this tick.
4349 process.nextTick(this.end.bind(this));
4352 function forEach (xs, f) {
4353 for (var i = 0, l = xs.length; i < l; i++) {
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.
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:
4370 // The above copyright notice and this permission notice shall be included
4371 // in all copies or substantial portions of the Software.
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.
4381 // a passthrough stream.
4382 // basically just the most minimal sort of Transform stream.
4383 // Every written chunk gets output as-is.
4385 module.exports = PassThrough;
4387 var Transform = require('./_stream_transform');
4390 var util
= require('core-util-is');
4391 util
.inherits
= require('inherits');
4394 util.inherits(PassThrough, Transform);
4396 function PassThrough(options) {
4397 if (!(this instanceof PassThrough))
4398 return new PassThrough(options);
4400 Transform.call(this, options);
4403 PassThrough.prototype._transform = function(chunk, encoding, cb) {
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.
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:
4419 // The above copyright notice and this permission notice shall be included
4420 // in all copies or substantial portions of the Software.
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.
4430 module.exports = Readable;
4433 var isArray
= require('isarray');
4438 var Buffer
= require('buffer').Buffer
;
4441 Readable.ReadableState = ReadableState;
4443 var EE = require('events').EventEmitter;
4446 if (!EE
.listenerCount
) EE
.listenerCount = function(emitter
, type
) {
4447 return emitter
.listeners(type
).length
;
4451 var Stream = require('stream');
4454 var util
= require('core-util-is');
4455 util
.inherits
= require('inherits');
4462 var debug
= require('util');
4463 if (debug
&& debug
.debuglog
) {
4464 debug
= debug
.debuglog('stream');
4466 debug = function () {};
4471 util.inherits(Readable, Stream);
4473 function ReadableState(options, stream) {
4474 var Duplex = require('./_stream_duplex');
4476 options = options || {};
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;
4485 this.highWaterMark = ~~this.highWaterMark;
4490 this.pipesCount = 0;
4491 this.flowing = null;
4493 this.endEmitted = false;
4494 this.reading = false;
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.
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;
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;
4513 if (stream instanceof Duplex)
4514 this.objectMode = this.objectMode || !!options.readableObjectMode;
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';
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;
4525 // the number of writers that are awaiting a drain event in .pipe()s
4526 this.awaitDrain = 0;
4528 // if true, a maybeReadMore has been scheduled
4529 this.readingMore = false;
4531 this.decoder = null;
4532 this.encoding = null;
4533 if (options.encoding) {
4535 StringDecoder = require('string_decoder/').StringDecoder;
4536 this.decoder = new StringDecoder(options.encoding);
4537 this.encoding = options.encoding;
4541 function Readable(options) {
4542 var Duplex = require('./_stream_duplex');
4544 if (!(this instanceof Readable))
4545 return new Readable(options);
4547 this._readableState = new ReadableState(options, this);
4550 this.readable = true;
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.
4559 Readable.prototype.push = function(chunk, encoding) {
4560 var state = this._readableState;
4562 if (util.isString(chunk) && !state.objectMode) {
4563 encoding = encoding || state.defaultEncoding;
4564 if (encoding !== state.encoding) {
4565 chunk = new Buffer(chunk, encoding);
4570 return readableAddChunk(this, state, chunk, encoding, false);
4573 // Unshift should *always* be something directly out of read()
4574 Readable.prototype.unshift = function(chunk) {
4575 var state = this._readableState;
4576 return readableAddChunk(this, state, chunk, '', true);
4579 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
4580 var er = chunkInvalid(state, chunk);
4582 stream.emit('error', er);
4583 } else if (util.isNullOrUndefined(chunk)) {
4584 state.reading = false;
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);
4595 if (state.decoder && !addToFront && !encoding)
4596 chunk = state.decoder.write(chunk);
4599 state.reading = false;
4601 // if we want the data now, just emit it.
4602 if (state.flowing && state.length === 0 && !state.sync) {
4603 stream.emit('data', chunk);
4606 // update the buffer info.
4607 state.length += state.objectMode ? 1 : chunk.length;
4609 state.buffer.unshift(chunk);
4611 state.buffer.push(chunk);
4613 if (state.needReadable)
4614 emitReadable(stream);
4617 maybeReadMore(stream, state);
4619 } else if (!addToFront) {
4620 state.reading = false;
4623 return needMoreData(state);
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.
4635 function needMoreData(state) {
4636 return !state.ended &&
4637 (state.needReadable ||
4638 state.length < state.highWaterMark ||
4639 state.length === 0);
4642 // backwards compatibility.
4643 Readable.prototype.setEncoding = function(enc) {
4645 StringDecoder = require('string_decoder/').StringDecoder;
4646 this._readableState.decoder = new StringDecoder(enc);
4647 this._readableState.encoding = enc;
4651 // Don't raise the hwm > 128MB
4652 var MAX_HWM = 0x800000;
4653 function roundUpToNextPowerOf2(n) {
4657 // Get the next highest power of 2
4659 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
4665 function howMuchToRead(n, state) {
4666 if (state.length === 0 && state.ended)
4669 if (state.objectMode)
4670 return n === 0 ? 0 : 1;
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;
4677 return state.length;
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
4687 if (n > state.highWaterMark)
4688 state.highWaterMark = roundUpToNextPowerOf2(n);
4690 // don't have that much. return null, unless we've ended.
4691 if (n > state.length) {
4693 state.needReadable = true;
4696 return state.length;
4702 // you can override either this method, or the async _read(n) below.
4703 Readable.prototype.read = function(n) {
4705 var state = this._readableState;
4708 if (!util.isNumber(n) || n > 0)
4709 state.emittedReadable = false;
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.
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)
4725 n = howMuchToRead(n, state);
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)
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.
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.
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
4754 // 3. Actually pull the requested chunks out of the buffer and return.
4756 // if we need a readable event, then we need to do some reading.
4757 var doRead = state.needReadable;
4758 debug('need readable', doRead);
4760 // if we currently have less than the highWaterMark, then also read some
4761 if (state.length === 0 || state.length - n < state.highWaterMark) {
4763 debug('length less than watermark', doRead);
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) {
4770 debug('reading or ended', doRead);
4775 state.reading = 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);
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);
4792 ret = fromList(n, state);
4796 if (util.isNull(ret)) {
4797 state.needReadable = true;
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;
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)
4812 if (!util.isNull(ret))
4813 this.emit('data', ret);
4818 function chunkInvalid(state, chunk) {
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');
4830 function 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;
4840 // emit 'readable' now to make sure it gets picked up.
4841 emitReadable(stream);
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.
4847 function emitReadable(stream) {
4848 var state = stream._readableState;
4849 state.needReadable = false;
4850 if (!state.emittedReadable) {
4851 debug('emitReadable', state.flowing);
4852 state.emittedReadable = true;
4854 process.nextTick(function() {
4855 emitReadable_(stream);
4858 emitReadable_(stream);
4862 function emitReadable_(stream) {
4863 debug('emit readable');
4864 stream.emit('readable');
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.
4875 function maybeReadMore(stream, state) {
4876 if (!state.readingMore) {
4877 state.readingMore = true;
4878 process.nextTick(function() {
4879 maybeReadMore_(stream, state);
4884 function 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');
4890 if (len === state.length)
4891 // didn't get any data, stop spinning.
4896 state.readingMore = false;
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.
4903 Readable.prototype._read = function(n) {
4904 this.emit('error', new Error('not implemented'));
4907 Readable.prototype.pipe = function(dest, pipeOpts) {
4909 var state = this._readableState;
4911 switch (state.pipesCount) {
4916 state.pipes = [state.pipes, dest];
4919 state.pipes.push(dest);
4922 state.pipesCount += 1;
4923 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
4925 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
4926 dest !== process.stdout &&
4927 dest !== process.stderr;
4929 var endFn = doEnd ? onend : cleanup;
4930 if (state.endEmitted)
4931 process.nextTick(endFn);
4933 src.once('end', endFn);
4935 dest.on('unpipe', onunpipe);
4936 function onunpipe(readable) {
4938 if (readable === src) {
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
4952 var ondrain = pipeOnDrain(src);
4953 dest.on('drain', ondrain);
4955 function 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);
4967 // if the reader is waiting for a drain event from this
4968 // specific writer, then it would cause it to never start
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))
4977 src.on('data', ondata);
4978 function ondata(chunk) {
4980 var ret = dest.write(chunk);
4981 if (false === ret) {
4982 debug('false write response, pause',
4983 src._readableState.awaitDrain);
4984 src._readableState.awaitDrain++;
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);
4994 dest.removeListener('error', onerror);
4995 if (EE.listenerCount(dest, 'error') === 0)
4996 dest.emit('error', er);
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);
5005 dest._events.error = [onerror, dest._events.error];
5009 // Both close and finish should trigger unpipe, but only once.
5010 function onclose() {
5011 dest.removeListener('finish', onfinish);
5014 dest.once('close', onclose);
5015 function onfinish() {
5017 dest.removeListener('close', onclose);
5020 dest.once('finish', onfinish);
5027 // tell the dest that it's being piped to
5028 dest.emit('pipe', src);
5030 // start the flow if it hasn't been started already.
5031 if (!state.flowing) {
5032 debug('pipe resume');
5039 function pipeOnDrain(src) {
5041 var state = src._readableState;
5042 debug('pipeOnDrain', state.awaitDrain);
5043 if (state.awaitDrain)
5045 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
5046 state.flowing = true;
5053 Readable.prototype.unpipe = function(dest) {
5054 var state = this._readableState;
5056 // if we're not piping anywhere, then do nothing.
5057 if (state.pipesCount === 0)
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)
5071 state.pipesCount = 0;
5072 state.flowing = false;
5074 dest.emit('unpipe', this);
5078 // slow case. multiple pipe destinations.
5082 var dests = state.pipes;
5083 var len = state.pipesCount;
5085 state.pipesCount = 0;
5086 state.flowing = false;
5088 for (var i = 0; i < len; i++)
5089 dests[i].emit('unpipe', this);
5093 // try to find the right one.
5094 var i = indexOf(state.pipes, dest);
5098 state.pipes.splice(i, 1);
5099 state.pipesCount -= 1;
5100 if (state.pipesCount === 1)
5101 state.pipes = state.pipes[0];
5103 dest.emit('unpipe', this);
5108 // set up data events if they are asked for
5109 // Ensure readable listeners eventually get something
5110 Readable.prototype.on = function(ev, fn) {
5111 var res = Stream.prototype.on.call(this, ev, fn);
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) {
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) {
5127 process.nextTick(function() {
5128 debug('readable nexttick read 0');
5131 } else if (state.length) {
5132 emitReadable(this, state);
5139 Readable.prototype.addListener = Readable.prototype.on;
5141 // pause() and resume() are remnants of the legacy readable stream API
5142 // If the user uses them, then switch into old mode.
5143 Readable.prototype.resume = function() {
5144 var state = this._readableState;
5145 if (!state.flowing) {
5147 state.flowing = true;
5148 if (!state.reading) {
5149 debug('resume read 0');
5152 resume(this, state);
5157 function resume(stream, state) {
5158 if (!state.resumeScheduled) {
5159 state.resumeScheduled = true;
5160 process.nextTick(function() {
5161 resume_(stream, state);
5166 function resume_(stream, state) {
5167 state.resumeScheduled = false;
5168 stream.emit('resume');
5170 if (state.flowing && !state.reading)
5174 Readable.prototype.pause = function() {
5175 debug('call pause flowing=%j', this._readableState.flowing);
5176 if (false !== this._readableState.flowing) {
5178 this._readableState.flowing = false;
5184 function flow(stream) {
5185 var state = stream._readableState;
5186 debug('flow', state.flowing);
5187 if (state.flowing) {
5189 var chunk = stream.read();
5190 } while (null !== chunk && state.flowing);
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.
5197 Readable.prototype.wrap = function(stream) {
5198 var state = this._readableState;
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)
5213 stream.on('data', function(chunk) {
5214 debug('wrapped data');
5216 chunk = state.decoder.write(chunk);
5217 if (!chunk || !state.objectMode && !chunk.length)
5220 var ret = self.push(chunk);
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);
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));
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);
5258 // exposed for testing purposes only.
5259 Readable._fromList = fromList;
5261 // Pluck off n bytes from an array of buffers.
5262 // Length is the combined lengths of all the buffers in the list.
5263 function fromList(n, state) {
5264 var list = state.buffer;
5265 var length = state.length;
5266 var stringMode = !!state.decoder;
5267 var objectMode = !!state.objectMode;
5270 // nothing in the list, definitely empty.
5271 if (list.length === 0)
5276 else if (objectMode)
5278 else if (!n || n >= length) {
5279 // read it all, truncate the array.
5281 ret = list.join('');
5283 ret = Buffer.concat(list, length);
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.
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
5298 // we have enough to cover it, but it spans past the first buffer.
5302 ret = new Buffer(n);
5305 for (var i = 0, l = list.length; i < l && c < n; i++) {
5307 var cpy = Math.min(n - c, buf.length);
5310 ret += buf.slice(0, cpy);
5312 buf.copy(ret, c, 0, cpy);
5314 if (cpy < buf.length)
5315 list[0] = buf.slice(cpy);
5327 function endReadable(stream) {
5328 var state = stream._readableState;
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');
5335 if (!state.endEmitted) {
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;
5348 function forEach (xs, f) {
5349 for (var i = 0, l = xs.length; i < l; i++) {
5354 function indexOf (xs, x) {
5355 for (var i = 0, l = xs.length; i < l; i++) {
5356 if (xs[i] === x) return i;
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.
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:
5373 // The above copyright notice and this permission notice shall be included
5374 // in all copies or substantial portions of the Software.
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.
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.)
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.
5396 // Here's how this works:
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.
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.
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.
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.
5427 module.exports = Transform;
5429 var Duplex = require('./_stream_duplex');
5432 var util
= require('core-util-is');
5433 util
.inherits
= require('inherits');
5436 util.inherits(Transform, Duplex);
5439 function TransformState(options, stream) {
5440 this.afterTransform = function(er, data) {
5441 return afterTransform(stream, er, data);
5444 this.needTransform = false;
5445 this.transforming = false;
5446 this.writecb = null;
5447 this.writechunk = null;
5450 function afterTransform(stream, er, data) {
5451 var ts = stream._transformState;
5452 ts.transforming = false;
5454 var cb = ts.writecb;
5457 return stream.emit('error', new Error('no writecb in Transform class'));
5459 ts.writechunk = null;
5462 if (!util.isNullOrUndefined(data))
5468 var rs = stream._readableState;
5470 if (rs.needReadable || rs.length < rs.highWaterMark) {
5471 stream._read(rs.highWaterMark);
5476 function Transform(options) {
5477 if (!(this instanceof Transform))
5478 return new Transform(options);
5480 Duplex.call(this, options);
5482 this._transformState = new TransformState(options, this);
5484 // when the writable side finishes, then flush out anything remaining.
5487 // start out asking for a readable event once data is transformed.
5488 this._readableState.needReadable = true;
5490 // we have implemented the _read method, and done the other things
5491 // that Readable wants before the first _read call, so unset the
5493 this._readableState.sync = false;
5495 this.once('prefinish', function() {
5496 if (util.isFunction(this._flush))
5497 this._flush(function(er) {
5505 Transform.prototype.push = function(chunk, encoding) {
5506 this._transformState.needTransform = false;
5507 return Duplex.prototype.push.call(this, chunk, encoding);
5510 // This is the part where you do stuff!
5511 // override this function in implementation classes.
5512 // 'chunk' is an input chunk.
5514 // Call `push(newChunk)` to pass along transformed output
5515 // to the readable side. You may call 'push' zero or more times.
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.
5520 Transform.prototype._transform = function(chunk, encoding, cb) {
5521 throw new Error('not implemented');
5524 Transform.prototype._write = function(chunk, encoding, cb) {
5525 var ts = this._transformState;
5527 ts.writechunk = chunk;
5528 ts.writeencoding = encoding;
5529 if (!ts.transforming) {
5530 var rs = this._readableState;
5531 if (ts.needTransform ||
5533 rs.length < rs.highWaterMark)
5534 this._read(rs.highWaterMark);
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.
5541 Transform.prototype._read = function(n) {
5542 var ts = this._transformState;
5544 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
5545 ts.transforming = true;
5546 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
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;
5555 function done(stream, er) {
5557 return stream.emit('error', er);
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;
5565 throw new Error('calling transform done when ws.length != 0');
5567 if (ts.transforming)
5568 throw new Error('calling transform done when still transforming');
5570 return stream.push(null);
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.
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:
5585 // The above copyright notice and this permission notice shall be included
5586 // in all copies or substantial portions of the Software.
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.
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.
5600 module.exports = Writable;
5603 var Buffer
= require('buffer').Buffer
;
5606 Writable.WritableState = WritableState;
5610 var util
= require('core-util-is');
5611 util
.inherits
= require('inherits');
5614 var Stream = require('stream');
5616 util.inherits(Writable, Stream);
5618 function WriteReq(chunk, encoding, cb) {
5620 this.encoding = encoding;
5624 function WritableState(options, stream) {
5625 var Duplex = require('./_stream_duplex');
5627 options = options || {};
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;
5636 // object stream flag to indicate whether or not this stream
5637 // contains buffers or objects.
5638 this.objectMode = !!options.objectMode;
5640 if (stream instanceof Duplex)
5641 this.objectMode = this.objectMode || !!options.writableObjectMode;
5644 this.highWaterMark = ~~this.highWaterMark;
5646 this.needDrain = false;
5647 // at the start of calling end()
5648 this.ending = false;
5649 // when end() has been called, and returned
5651 // when 'finish' is emitted
5652 this.finished = false;
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;
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';
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
5670 // a flag to see when we're in the middle of a write.
5671 this.writing = false;
5673 // when true all writes will be buffered until .uncork() call
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.
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;
5687 // the callback that's passed to _write(chunk,cb)
5688 this.onwrite = function(er) {
5689 onwrite(stream, er);
5692 // the callback that the user supplies to write(chunk,encoding,cb)
5693 this.writecb = null;
5695 // the amount that is being written when _write is called.
5700 // number of pending user-supplied write callbacks
5701 // this must be 0 before 'finish' can be emitted
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;
5708 // True if the error was already emitted and should not be thrown again
5709 this.errorEmitted = false;
5712 function Writable(options) {
5713 var Duplex = require('./_stream_duplex');
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);
5720 this._writableState = new WritableState(options, this);
5723 this.writable = true;
5728 // Otherwise people can pipe Writable streams, which is just wrong.
5729 Writable.prototype.pipe = function() {
5730 this.emit('error', new Error('Cannot pipe. Not readable.'));
5734 function 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() {
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.
5748 function validChunk(stream, state, chunk, cb) {
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() {
5764 Writable.prototype.write = function(chunk, encoding, cb) {
5765 var state = this._writableState;
5768 if (util.isFunction(encoding)) {
5773 if (util.isBuffer(chunk))
5774 encoding = 'buffer';
5776 encoding = state.defaultEncoding;
5778 if (!util.isFunction(cb))
5782 writeAfterEnd(this, state, cb);
5783 else if (validChunk(this, state, chunk, cb)) {
5785 ret = writeOrBuffer(this, state, chunk, encoding, cb);
5791 Writable.prototype.cork = function() {
5792 var state = this._writableState;
5797 Writable.prototype.uncork = function() {
5798 var state = this._writableState;
5803 if (!state.writing &&
5806 !state.bufferProcessing &&
5807 state.buffer.length)
5808 clearBuffer(this, state);
5812 function decodeChunk(state, chunk, encoding) {
5813 if (!state.objectMode &&
5814 state.decodeStrings !== false &&
5815 util.isString(chunk)) {
5816 chunk = new Buffer(chunk, encoding);
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.
5824 function 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;
5830 state.length += len;
5832 var ret = state.length < state.highWaterMark;
5833 // we must ensure that previous needDrain will not be reset to false.
5835 state.needDrain = true;
5837 if (state.writing || state.corked)
5838 state.buffer.push(new WriteReq(chunk, encoding, cb));
5840 doWrite(stream, state, false, len, chunk, encoding, cb);
5845 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
5846 state.writelen = len;
5848 state.writing = true;
5851 stream._writev(chunk, state.onwrite);
5853 stream._write(chunk, encoding, state.onwrite);
5857 function onwriteError(stream, state, sync, er, cb) {
5859 process.nextTick(function() {
5868 stream._writableState.errorEmitted = true;
5869 stream.emit('error', er);
5872 function onwriteStateUpdate(state) {
5873 state.writing = false;
5874 state.writecb = null;
5875 state.length -= state.writelen;
5879 function onwrite(stream, er) {
5880 var state = stream._writableState;
5881 var sync = state.sync;
5882 var cb = state.writecb;
5884 onwriteStateUpdate(state);
5887 onwriteError(stream, state, sync, er, cb);
5889 // Check if we're actually ready to finish, but don't emit yet
5890 var finished = needFinish(stream, state);
5894 !state.bufferProcessing &&
5895 state.buffer.length) {
5896 clearBuffer(stream, state);
5900 process.nextTick(function() {
5901 afterWrite(stream, state, finished, cb);
5904 afterWrite(stream, state, finished, cb);
5909 function afterWrite(stream, state, finished, cb) {
5911 onwriteDrain(stream, state);
5914 finishMaybe(stream, state);
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.
5920 function onwriteDrain(stream, state) {
5921 if (state.length === 0 && state.needDrain) {
5922 state.needDrain = false;
5923 stream.emit('drain');
5928 // if there's something in the buffer waiting, then process it
5929 function clearBuffer(stream, state) {
5930 state.bufferProcessing = true;
5932 if (stream._writev && state.buffer.length > 1) {
5933 // Fast case, write everything using _writev()
5935 for (var c = 0; c < state.buffer.length; c++)
5936 cbs.push(state.buffer[c].callback);
5938 // count the one we are adding, as well.
5939 // TODO(isaacs) clean this up
5941 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
5942 for (var i = 0; i < cbs.length; i++) {
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;
5959 doWrite(stream, state, false, len, chunk, encoding, cb);
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) {
5971 if (c < state.buffer.length)
5972 state.buffer = state.buffer.slice(c);
5974 state.buffer.length = 0;
5977 state.bufferProcessing = false;
5980 Writable.prototype._write = function(chunk, encoding, cb) {
5981 cb(new Error('not implemented'));
5985 Writable.prototype._writev = null;
5987 Writable.prototype.end = function(chunk, encoding, cb) {
5988 var state = this._writableState;
5990 if (util.isFunction(chunk)) {
5994 } else if (util.isFunction(encoding)) {
5999 if (!util.isNullOrUndefined(chunk))
6000 this.write(chunk, encoding);
6002 // .end() fully uncorks
6008 // ignore unnecessary end() calls.
6009 if (!state.ending && !state.finished)
6010 endWritable(this, state, cb);
6014 function needFinish(stream, state) {
6015 return (state.ending &&
6016 state.length === 0 &&
6021 function prefinish(stream, state) {
6022 if (!state.prefinished) {
6023 state.prefinished = true;
6024 stream.emit('prefinish');
6028 function finishMaybe(stream, state) {
6029 var need = needFinish(stream, state);
6031 if (state.pendingcb === 0) {
6032 prefinish(stream, state);
6033 state.finished = true;
6034 stream.emit('finish');
6036 prefinish(stream, state);
6041 function endWritable(stream, state, cb) {
6042 state.ending = true;
6043 finishMaybe(stream, state);
6046 process.nextTick(cb);
6048 stream.once('finish', cb);
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){
6056 // Copyright Joyent, Inc. and other Node contributors.
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:
6066 // The above copyright notice and this permission notice shall be included
6067 // in all copies or substantial portions of the Software.
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.
6077 // NOTE: These type checking functions intentionally don't use `instanceof`
6078 // because it is fragile and can be easily faked with `Object.create()`.
6079 function isArray(ar) {
6080 return Array.isArray(ar);
6082 exports.isArray = isArray;
6084 function isBoolean(arg) {
6085 return typeof arg === 'boolean';
6087 exports.isBoolean = isBoolean;
6089 function isNull(arg) {
6090 return arg === null;
6092 exports.isNull = isNull;
6094 function isNullOrUndefined(arg) {
6097 exports.isNullOrUndefined = isNullOrUndefined;
6099 function isNumber(arg) {
6100 return typeof arg === 'number';
6102 exports.isNumber = isNumber;
6104 function isString(arg) {
6105 return typeof arg === 'string';
6107 exports.isString = isString;
6109 function isSymbol(arg) {
6110 return typeof arg === 'symbol';
6112 exports.isSymbol = isSymbol;
6114 function isUndefined(arg) {
6115 return arg === void 0;
6117 exports.isUndefined = isUndefined;
6119 function isRegExp(re) {
6120 return isObject(re) && objectToString(re) === '[object RegExp]';
6122 exports.isRegExp = isRegExp;
6124 function isObject(arg) {
6125 return typeof arg === 'object' && arg !== null;
6127 exports.isObject = isObject;
6129 function isDate(d) {
6130 return isObject(d) && objectToString(d) === '[object Date]';
6132 exports.isDate = isDate;
6134 function isError(e) {
6135 return isObject(e) &&
6136 (objectToString(e) === '[object Error]' || e instanceof Error);
6138 exports.isError = isError;
6140 function isFunction(arg) {
6141 return typeof arg === 'function';
6143 exports.isFunction = isFunction;
6145 function 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';
6153 exports.isPrimitive = isPrimitive;
6155 function isBuffer(arg) {
6156 return Buffer.isBuffer(arg);
6158 exports.isBuffer = isBuffer;
6160 function objectToString(o) {
6161 return Object.prototype.toString.call(o);
6163 }).call(this,require("buffer").Buffer)
6164 },{"buffer":7}],22:[function(require,module,exports){
6165 module.exports = require("./lib/_stream_passthrough.js")
6167 },{"./lib/_stream_passthrough.js":17}],23:[function(require,module,exports){
6168 exports = module.exports = require('./lib/_stream_readable.js');
6169 exports.Stream = require('stream');
6170 exports.Readable = exports;
6171 exports.Writable = require('./lib/_stream_writable.js');
6172 exports.Duplex = require('./lib/_stream_duplex.js');
6173 exports.Transform = require('./lib/_stream_transform.js');
6174 exports.PassThrough = require('./lib/_stream_passthrough.js');
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){
6177 module.exports = require("./lib/_stream_transform.js")
6179 },{"./lib/_stream_transform.js":19}],25:[function(require,module,exports){
6180 module.exports = require("./lib/_stream_writable.js")
6182 },{"./lib/_stream_writable.js":20}],26:[function(require,module,exports){
6183 // Copyright Joyent, Inc. and other Node contributors.
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:
6193 // The above copyright notice and this permission notice shall be included
6194 // in all copies or substantial portions of the Software.
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.
6204 module.exports = Stream;
6206 var EE = require('events').EventEmitter;
6207 var inherits = require('inherits');
6209 inherits(Stream, EE);
6210 Stream.Readable = require('readable-stream/readable.js');
6211 Stream.Writable = require('readable-stream/writable.js');
6212 Stream.Duplex = require('readable-stream/duplex.js');
6213 Stream.Transform = require('readable-stream/transform.js');
6214 Stream.PassThrough = require('readable-stream/passthrough.js');
6216 // Backwards-compat with node 0.4.x
6217 Stream.Stream = Stream;
6221 // old-style streams. Note that the pipe method (the only relevant
6222 // part of this class) is overridden in the Readable class.
6228 Stream.prototype.pipe = function(dest, options) {
6231 function ondata(chunk) {
6232 if (dest.writable) {
6233 if (false === dest.write(chunk) && source.pause) {
6239 source.on('data', ondata);
6241 function ondrain() {
6242 if (source.readable && source.resume) {
6247 dest.on('drain', ondrain);
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);
6256 var didOnEnd = false;
6258 if (didOnEnd) return;
6265 function onclose() {
6266 if (didOnEnd) return;
6269 if (typeof dest.destroy === 'function') dest.destroy();
6272 // don't leave dangling pipes when there are errors.
6273 function onerror(er) {
6275 if (EE.listenerCount(this, 'error') === 0) {
6276 throw er; // Unhandled stream error in pipe.
6280 source.on('error', onerror);
6281 dest.on('error', onerror);
6283 // remove all the event listeners that were added.
6284 function cleanup() {
6285 source.removeListener('data', ondata);
6286 dest.removeListener('drain', ondrain);
6288 source.removeListener('end', onend);
6289 source.removeListener('close', onclose);
6291 source.removeListener('error', onerror);
6292 dest.removeListener('error', onerror);
6294 source.removeListener('end', cleanup);
6295 source.removeListener('close', cleanup);
6297 dest.removeListener('close', cleanup);
6300 source.on('end', cleanup);
6301 source.on('close', cleanup);
6303 dest.on('close', cleanup);
6305 dest.emit('pipe', source);
6307 // Allow for unix-like usage: A.pipe(B).pipe(C)
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.
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:
6322 // The above copyright notice and this permission notice shall be included
6323 // in all copies or substantial portions of the Software.
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.
6333 var Buffer = require('buffer').Buffer;
6335 var 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;
6344 function assertEncoding(encoding) {
6345 if (encoding && !isBufferEncoding(encoding)) {
6346 throw new Error('Unknown encoding: ' + encoding);
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.
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.
6358 var StringDecoder = exports.StringDecoder = function(encoding) {
6359 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
6360 assertEncoding(encoding);
6361 switch (this.encoding) {
6363 // CESU-8 represents each of Surrogate Pair by 3-bytes
6364 this.surrogateSize = 3;
6368 // UTF-16 represents each of Surrogate Pair by 2-bytes
6369 this.surrogateSize = 2;
6370 this.detectIncompleteChar = utf16DetectIncompleteChar;
6373 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
6374 this.surrogateSize = 3;
6375 this.detectIncompleteChar = base64DetectIncompleteChar;
6378 this.write = passThroughWrite;
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;
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.
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/ .
6401 StringDecoder.prototype.write = function(buffer) {
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 :
6410 // add the new bytes to the char buffer
6411 buffer.copy(this.charBuffer, this.charReceived, 0, available);
6412 this.charReceived += available;
6414 if (this.charReceived < this.charLength) {
6415 // still not enough chars in this buffer? wait for more ...
6419 // remove bytes belonging to the current character from the buffer
6420 buffer = buffer.slice(available, buffer.length);
6422 // get the character that was split
6423 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
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;
6432 this.charReceived = this.charLength = 0;
6434 // if there are no more bytes in this buffer, just emit our char
6435 if (buffer.length === 0) {
6441 // determine and set charLength / charReceived
6442 this.detectIncompleteChar(buffer);
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;
6451 charStr += buffer.toString(this.encoding, 0, end);
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);
6465 // or just emit the charStr
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.
6473 StringDecoder.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;
6477 // Figure out if one of the last i bytes of our buffer announces an
6479 for (; i > 0; i--) {
6480 var c = buffer[buffer.length - i];
6482 // See http://en.wikipedia.org/wiki/UTF-8#Description
6485 if (i == 1 && c >> 5 == 0x06) {
6486 this.charLength = 2;
6491 if (i <= 2 && c >> 4 == 0x0E) {
6492 this.charLength = 3;
6497 if (i <= 3 && c >> 3 == 0x1E) {
6498 this.charLength = 4;
6502 this.charReceived = i;
6505 StringDecoder.prototype.end = function(buffer) {
6507 if (buffer && buffer.length)
6508 res = this.write(buffer);
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);
6520 function passThroughWrite(buffer) {
6521 return buffer.toString(this.encoding);
6524 function utf16DetectIncompleteChar(buffer) {
6525 this.charReceived = buffer.length % 2;
6526 this.charLength = this.charReceived ? 2 : 0;
6529 function base64DetectIncompleteChar(buffer) {
6530 this.charReceived = buffer.length % 3;
6531 this.charLength = this.charReceived ? 3 : 0;
6534 },{"buffer":7}],28:[function(require,module,exports){
6535 module.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';
6541 },{}],29:[function(require,module,exports){
6542 (function (process,global){
6543 // Copyright Joyent, Inc. and other Node contributors.
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:
6553 // The above copyright notice and this permission notice shall be included
6554 // in all copies or substantial portions of the Software.
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.
6564 var formatRegExp = /%[sdj%]/g;
6565 exports.format = function(f) {
6568 for (var i = 0; i < arguments.length; i++) {
6569 objects.push(inspect(arguments[i]));
6571 return objects.join(' ');
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;
6581 case '%s': return String(args[i++]);
6582 case '%d': return Number(args[i++]);
6585 return JSON.stringify(args[i++]);
6587 return '[Circular]';
6593 for (var x = args[i]; i < len; x = args[++i]) {
6594 if (isNull(x) || !isObject(x)) {
6597 str += ' ' + inspect(x);
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.
6607 exports.deprecate = function(fn, msg) {
6608 // Allow for deprecating things in the process of starting up.
6609 if (isUndefined(global.process)) {
6611 return exports.deprecate(fn, msg).apply(this, arguments);
6615 if (process.noDeprecation === true) {
6620 function deprecated() {
6622 if (process.throwDeprecation) {
6623 throw new Error(msg);
6624 } else if (process.traceDeprecation) {
6631 return fn.apply(this, arguments);
6640 exports.debuglog = function(set) {
6641 if (isUndefined(debugEnviron))
6642 debugEnviron = process.env.NODE_DEBUG || '';
6643 set = set.toUpperCase();
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);
6652 debugs[set] = function() {};
6660 * Echos the value of a value. Trys to print the value out
6661 * in the best way possible given the different types.
6663 * @param {Object} obj The object to print out.
6664 * @param {Object} opts Optional options object that alters the output.
6666 /* legacy: obj, showHidden, depth, colors*/
6667 function inspect(obj
, opts
) {
6671 stylize: stylizeNoColor
6674 if (arguments
.length
>= 3) ctx
.depth
= arguments
[2];
6675 if (arguments
.length
>= 4) ctx
.colors
= arguments
[3];
6676 if (isBoolean(opts
)) {
6678 ctx
.showHidden
= opts
;
6680 // got an "options" object
6681 exports
._extend(ctx
, opts
);
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
);
6691 exports
.inspect
= inspect
;
6694 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
6698 'underline' : [4, 24],
6699 'inverse' : [7, 27],
6706 'magenta' : [35, 39],
6711 // Don't use 'blue' not visible on cmd.exe
6715 'boolean': 'yellow',
6716 'undefined': 'grey',
6720 // "name": intentionally not styling
6725 function stylizeWithColor(str
, styleType
) {
6726 var style
= inspect
.styles
[styleType
];
6729 return '\u001b[' + inspect
.colors
[style
][0] + 'm' + str
+
6730 '\u001b[' + inspect
.colors
[style
][1] + 'm';
6737 function stylizeNoColor(str
, styleType
) {
6742 function arrayToHash(array
) {
6745 array
.forEach(function(val
, idx
) {
6753 function 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
&&
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
);
6770 // Primitive types cannot have properties
6771 var primitive
= formatPrimitive(ctx
, value
);
6776 // Look up the keys of the object.
6777 var keys
= Object
.keys(value
);
6778 var visibleKeys
= arrayToHash(keys
);
6780 if (ctx
.showHidden
) {
6781 keys
= Object
.getOwnPropertyNames(value
);
6784 // IE doesn't make error fields non-enumerable
6785 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
6787 && (keys
.indexOf('message') >= 0 || keys
.indexOf('description') >= 0)) {
6788 return formatError(value
);
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');
6797 if (isRegExp(value
)) {
6798 return ctx
.stylize(RegExp
.prototype.toString
.call(value
), 'regexp');
6800 if (isDate(value
)) {
6801 return ctx
.stylize(Date
.prototype.toString
.call(value
), 'date');
6803 if (isError(value
)) {
6804 return formatError(value
);
6808 var base
= '', array
= false, braces
= ['{', '}'];
6810 // Make Array say that they are Array
6811 if (isArray(value
)) {
6813 braces
= ['[', ']'];
6816 // Make functions say that they are functions
6817 if (isFunction(value
)) {
6818 var n
= value
.name
? ': ' + value
.name : '';
6819 base
= ' [Function' + n
+ ']';
6822 // Make RegExps say that they are RegExps
6823 if (isRegExp(value
)) {
6824 base
= ' ' + RegExp
.prototype.toString
.call(value
);
6827 // Make dates with properties first say the date
6828 if (isDate(value
)) {
6829 base
= ' ' + Date
.prototype.toUTCString
.call(value
);
6832 // Make error with message first say the error
6833 if (isError(value
)) {
6834 base
= ' ' + formatError(value
);
6837 if (keys
.length
=== 0 && (!array
|| value
.length
== 0)) {
6838 return braces
[0] + base
+ braces
[1];
6841 if (recurseTimes
< 0) {
6842 if (isRegExp(value
)) {
6843 return ctx
.stylize(RegExp
.prototype.toString
.call(value
), 'regexp');
6845 return ctx
.stylize('[Object]', 'special');
6849 ctx
.seen
.push(value
);
6853 output
= formatArray(ctx
, value
, recurseTimes
, visibleKeys
, keys
);
6855 output
= keys
.map(function(key
) {
6856 return formatProperty(ctx
, value
, recurseTimes
, visibleKeys
, key
, array
);
6862 return reduceToSingleString(output
, base
, braces
);
6866 function 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');
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.
6881 return ctx
.stylize('null', 'null');
6885 function formatError(value
) {
6886 return '[' + Error
.prototype.toString
.call(value
) + ']';
6890 function formatArray(ctx
, value
, recurseTimes
, visibleKeys
, keys
) {
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
,
6900 keys
.forEach(function(key
) {
6901 if (!key
.match(/^\d+$/)) {
6902 output
.push(formatProperty(ctx
, value
, recurseTimes
, visibleKeys
,
6910 function formatProperty(ctx
, value
, recurseTimes
, visibleKeys
, key
, array
) {
6911 var name
, str
, desc
;
6912 desc
= Object
.getOwnPropertyDescriptor(value
, key
) || { value: value
[key
] };
6915 str
= ctx
.stylize('[Getter/Setter]', 'special');
6917 str
= ctx
.stylize('[Getter]', 'special');
6921 str
= ctx
.stylize('[Setter]', 'special');
6924 if (!hasOwnProperty(visibleKeys
, key
)) {
6925 name
= '[' + key
+ ']';
6928 if (ctx
.seen
.indexOf(desc
.value
) < 0) {
6929 if (isNull(recurseTimes
)) {
6930 str
= formatValue(ctx
, desc
.value
, null);
6932 str
= formatValue(ctx
, desc
.value
, recurseTimes
- 1);
6934 if (str
.indexOf('\n') > -1) {
6936 str
= str
.split('\n').map(function(line
) {
6938 }).join('\n').substr(2);
6940 str
= '\n' + str
.split('\n').map(function(line
) {
6946 str
= ctx
.stylize('[Circular]', 'special');
6949 if (isUndefined(name
)) {
6950 if (array
&& key
.match(/^\d+$/)) {
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');
6958 name
= name
.replace(/'/g, "\\'")
6959 .replace(/\\"/g
, '"')
6960 .replace(/(^"|"$)/g, "'");
6961 name
= ctx
.stylize(name
, 'string');
6965 return name
+ ': ' + str
;
6969 function reduceToSingleString(output
, base
, braces
) {
6970 var numLinesEst
= 0;
6971 var length
= output
.reduce(function(prev
, cur
) {
6973 if (cur
.indexOf('\n') >= 0) numLinesEst
++;
6974 return prev
+ cur
.replace(/\u001b\[\d\d?m/g, '').length
+ 1;
6979 (base
=== '' ? '' : base
+ '\n ') +
6981 output
.join(',\n ') +
6986 return braces
[0] + base
+ ' ' + output
.join(', ') + ' ' + braces
[1];
6990 // NOTE: These type checking functions intentionally don't use `instanceof`
6991 // because it is fragile and can be easily faked with `Object.create()`.
6992 function isArray(ar
) {
6993 return Array
.isArray(ar
);
6995 exports
.isArray
= isArray
;
6997 function isBoolean(arg
) {
6998 return typeof arg
=== 'boolean';
7000 exports
.isBoolean
= isBoolean
;
7002 function isNull(arg
) {
7003 return arg
=== null;
7005 exports
.isNull
= isNull
;
7007 function isNullOrUndefined(arg
) {
7010 exports
.isNullOrUndefined
= isNullOrUndefined
;
7012 function isNumber(arg
) {
7013 return typeof arg
=== 'number';
7015 exports
.isNumber
= isNumber
;
7017 function isString(arg
) {
7018 return typeof arg
=== 'string';
7020 exports
.isString
= isString
;
7022 function isSymbol(arg
) {
7023 return typeof arg
=== 'symbol';
7025 exports
.isSymbol
= isSymbol
;
7027 function isUndefined(arg
) {
7028 return arg
=== void 0;
7030 exports
.isUndefined
= isUndefined
;
7032 function isRegExp(re
) {
7033 return isObject(re
) && objectToString(re
) === '[object RegExp]';
7035 exports
.isRegExp
= isRegExp
;
7037 function isObject(arg
) {
7038 return typeof arg
=== 'object' && arg
!== null;
7040 exports
.isObject
= isObject
;
7042 function isDate(d
) {
7043 return isObject(d
) && objectToString(d
) === '[object Date]';
7045 exports
.isDate
= isDate
;
7047 function isError(e
) {
7048 return isObject(e
) &&
7049 (objectToString(e
) === '[object Error]' || e
instanceof Error
);
7051 exports
.isError
= isError
;
7053 function isFunction(arg
) {
7054 return typeof arg
=== 'function';
7056 exports
.isFunction
= isFunction
;
7058 function 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';
7066 exports
.isPrimitive
= isPrimitive
;
7068 exports
.isBuffer
= require('./support/isBuffer');
7070 function objectToString(o
) {
7071 return Object
.prototype.toString
.call(o
);
7076 return n
< 10 ? '0' + n
.toString(10) : n
.toString(10);
7080 var months
= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
7081 'Oct', 'Nov', 'Dec'];
7084 function timestamp() {
7086 var time
= [pad(d
.getHours()),
7087 pad(d
.getMinutes()),
7088 pad(d
.getSeconds())].join(':');
7089 return [d
.getDate(), months
[d
.getMonth()], time
].join(' ');
7093 // log is just a thin wrapper to console.log that prepends a timestamp
7094 exports
.log = function() {
7095 console
.log('%s - %s', timestamp(), exports
.format
.apply(exports
, arguments
));
7100 * Inherit the prototype methods from one constructor into another.
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).
7108 * @param {function} ctor Constructor function which needs to inherit the
7110 * @param {function} superCtor Constructor function to inherit prototype from.
7112 exports
.inherits
= require('inherits');
7114 exports
._extend = function(origin
, add
) {
7115 // Don't do anything if add isn't an object
7116 if (!add
|| !isObject(add
)) return origin
;
7118 var keys
= Object
.keys(add
);
7119 var i
= keys
.length
;
7121 origin
[keys
[i
]] = add
[keys
[i
]];
7126 function hasOwnProperty(obj
, prop
) {
7127 return Object
.prototype.hasOwnProperty
.call(obj
, prop
);
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
7139 var ALPHABET
= '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
7140 var ALPHABET_MAP
= {}
7141 for(var i
= 0; i
< ALPHABET
.length
; i
++) {
7142 ALPHABET_MAP
[ALPHABET
.charAt(i
)] = i
7146 function encode(buffer
) {
7147 if (buffer
.length
=== 0) return ''
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
7153 digits
[0] += buffer
[i
]
7156 for (j
= 0; j
< digits
.length
; ++j
) {
7159 carry
= (digits
[j
] / BASE
) | 0
7164 digits
.push(carry
% BASE
)
7166 carry
= (carry
/ BASE
) | 0
7170 // deal with leading zeros
7171 for (i
= 0; buffer
[i
] === 0 && i
< buffer
.length
- 1; i
++) digits
.push(0)
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
]]
7181 function decode(string
) {
7182 if (string
.length
=== 0) return []
7184 var i
, j
, bytes
= [0]
7185 for (i
= 0; i
< string
.length
; i
++) {
7187 if (!(c
in ALPHABET_MAP
)) throw new Error('Non-base58 character')
7189 for (j
= 0; j
< bytes
.length
; j
++) bytes
[j
] *= BASE
7190 bytes
[0] += ALPHABET_MAP
[c
]
7193 for (j
= 0; j
< bytes
.length
; ++j
) {
7196 carry
= bytes
[j
] >> 8
7201 bytes
.push(carry
& 0xff)
7207 // deal with leading zeros
7208 for (i
= 0; string
[i
] === '1' && i
< string
.length
- 1; i
++) bytes
.push(0)
7210 return bytes
.reverse()
7218 },{}],31:[function(require
,module
,exports
){
7222 var base58
= require('bs58')
7223 var createHash
= require('create-hash')
7225 // SHA256(SHA256(buffer))
7226 function sha256x2 (buffer
) {
7227 buffer
= createHash('sha256').update(buffer
).digest()
7228 return createHash('sha256').update(buffer
).digest()
7231 // Encode a buffer as a base58-check encoded string
7232 function encode (payload
) {
7233 var checksum
= sha256x2(payload
).slice(0, 4)
7235 return base58
.encode(Buffer
.concat([
7241 // Decode a base58-check encoded string to a buffer
7242 function decode (string
) {
7243 var buffer
= new Buffer(base58
.decode(string
))
7245 var payload
= buffer
.slice(0, -4)
7246 var checksum
= buffer
.slice(-4)
7247 var newChecksum
= sha256x2(payload
).slice(0, 4)
7249 for (var i
= 0; i
< newChecksum
.length
; ++i
) {
7250 if (newChecksum
[i
] === checksum
[i
]) continue
7252 throw new Error('Invalid checksum')
7263 }).call(this,require("buffer").Buffer
)
7264 },{"bs58":30,"buffer":7,"create-hash":32}],32:[function(require
,module
,exports
){
7267 var inherits
= require('inherits')
7268 var md5
= require('./md5')
7269 var rmd160
= require('ripemd160')
7270 var sha
= require('sha.js')
7272 var Transform
= require('stream').Transform
7274 function HashNoConstructor(hash
) {
7275 Transform
.call(this)
7281 inherits(HashNoConstructor
, Transform
)
7283 HashNoConstructor
.prototype._transform = function (data
, _
, next
) {
7284 this.buffers
.push(data
)
7289 HashNoConstructor
.prototype._flush = function (next
) {
7290 this.push(this.digest())
7294 HashNoConstructor
.prototype.update = function (data
, enc
) {
7295 if (typeof data
=== 'string') {
7296 data
= new Buffer(data
, enc
)
7299 this.buffers
.push(data
)
7303 HashNoConstructor
.prototype.digest = function (enc
) {
7304 var buf
= Buffer
.concat(this.buffers
)
7305 var r
= this._hash(buf
)
7308 return enc
? r
.toString(enc
) : r
7311 function Hash(hash
) {
7312 Transform
.call(this)
7317 inherits(Hash
, Transform
)
7319 Hash
.prototype._transform = function (data
, enc
, next
) {
7320 if (enc
) data
= new Buffer(data
, enc
)
7322 this._hash
.update(data
)
7327 Hash
.prototype._flush = function (next
) {
7328 this.push(this._hash
.digest())
7334 Hash
.prototype.update = function (data
, enc
) {
7335 if (typeof data
=== 'string') {
7336 data
= new Buffer(data
, enc
)
7339 this._hash
.update(data
)
7343 Hash
.prototype.digest = function (enc
) {
7344 var outData
= this._hash
.digest()
7346 return enc
? outData
.toString(enc
) : outData
7349 module
.exports
= function createHash (alg
) {
7350 if ('md5' === alg
) return new HashNoConstructor(md5
)
7351 if ('rmd160' === alg
) return new HashNoConstructor(rmd160
)
7353 return new Hash(sha(alg
))
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
){
7361 var zeroBuffer
= new Buffer(intSize
); zeroBuffer
.fill(0);
7364 function 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
);
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
));
7378 function 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);
7387 function 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
);
7392 exports
.hash
= hash
;
7393 }).call(this,require("buffer").Buffer
)
7394 },{"buffer":7}],34:[function(require
,module
,exports
){
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.
7405 var helpers
= require('./helpers');
7408 * Calculate the MD5 of an array of little-endian words, and a bit length
7410 function core_md5(x
, len
)
7412 /* append padding */
7413 x
[len
>> 5] |= 0x80 << ((len
) % 32);
7414 x
[(((len
+ 64) >>> 9) << 4) + 14] = len
;
7418 var c
= -1732584194;
7421 for(var i
= 0; i
< x
.length
; i
+= 16)
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);
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);
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);
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);
7496 a
= safe_add(a
, olda
);
7497 b
= safe_add(b
, oldb
);
7498 c
= safe_add(c
, oldc
);
7499 d
= safe_add(d
, oldd
);
7501 return Array(a
, b
, c
, d
);
7506 * These functions implement the four basic operations the algorithm uses.
7508 function md5_cmn(q
, a
, b
, x
, s
, t
)
7510 return safe_add(bit_rol(safe_add(safe_add(a
, q
), safe_add(x
, t
)), s
),b
);
7512 function md5_ff(a
, b
, c
, d
, x
, s
, t
)
7514 return md5_cmn((b
& c
) | ((~b
) & d
), a
, b
, x
, s
, t
);
7516 function md5_gg(a
, b
, c
, d
, x
, s
, t
)
7518 return md5_cmn((b
& d
) | (c
& (~d
)), a
, b
, x
, s
, t
);
7520 function md5_hh(a
, b
, c
, d
, x
, s
, t
)
7522 return md5_cmn(b
^ c
^ d
, a
, b
, x
, s
, t
);
7524 function md5_ii(a
, b
, c
, d
, x
, s
, t
)
7526 return md5_cmn(c
^ (b
| (~d
)), a
, b
, x
, s
, t
);
7530 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
7531 * to work around bugs in some JS interpreters.
7533 function safe_add(x
, y
)
7535 var lsw
= (x
& 0xFFFF) + (y
& 0xFFFF);
7536 var msw
= (x
>> 16) + (y
>> 16) + (lsw
>> 16);
7537 return (msw
<< 16) | (lsw
& 0xFFFF);
7541 * Bitwise rotate a 32-bit number to the left.
7543 function bit_rol(num
, cnt
)
7545 return (num
<< cnt
) | (num
>>> (32 - cnt
));
7548 module
.exports
= function md5(buf
) {
7549 return helpers
.hash(buf
, core_md5
, 16);
7551 },{"./helpers":33}],35:[function(require
,module
,exports
){
7552 arguments
[4][12][0].apply(exports
,arguments
)
7553 },{"dup":12}],36:[function(require
,module
,exports
){
7557 code.google.com/p/crypto-js
7558 (c) 2009-2013 by Jeff Mott. All rights reserved.
7559 code.google.com/p/crypto-js/wiki/License
7562 (c) 2012 by Cédric Mesnil. All rights reserved.
7564 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
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.
7569 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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
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
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
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
7605 var hl
= [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
7606 var hr
= [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
7608 function bytesToWords (bytes
) {
7610 for (var i
= 0, b
= 0; i
< bytes
.length
; i
++, b
+= 8) {
7611 words
[b
>>> 5] |= bytes
[i
] << (24 - b
% 32)
7616 function wordsToBytes (words
) {
7618 for (var b
= 0; b
< words
.length
* 32; b
+= 8) {
7619 bytes
.push((words
[b
>>> 5] >>> (24 - b
% 32)) & 0xFF)
7624 function processBlock (H
, M
, offset
) {
7626 for (var i
= 0; i
< 16; i
++) {
7627 var offset_i
= offset
+ i
7628 var M_offset_i
= M
[offset_i
]
7632 (((M_offset_i
<< 8) | (M_offset_i
>>> 24)) & 0x00ff00ff) |
7633 (((M_offset_i
<< 24) | (M_offset_i
>>> 8)) & 0xff00ff00)
7637 // Working variables
7638 var al
, bl
, cl
, dl
, el
7639 var ar
, br
, cr
, dr
, er
7649 for (i
= 0; i
< 80; i
+= 1) {
7650 t
= (al
+ M
[offset
+ zl
[i
]]) | 0
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]
7671 t
= (ar
+ M
[offset
+ zr
[i
]]) | 0
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]
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
7703 function f1 (x
, y
, z
) {
7704 return ((x
) ^ (y
) ^ (z
))
7707 function f2 (x
, y
, z
) {
7708 return (((x
) & (y
)) | ((~x
) & (z
)))
7711 function f3 (x
, y
, z
) {
7712 return (((x
) | (~(y
))) ^ (z
))
7715 function f4 (x
, y
, z
) {
7716 return (((x
) & (z
)) | ((y
) & (~(z
))))
7719 function f5 (x
, y
, z
) {
7720 return ((x
) ^ ((y
) | (~(z
))))
7723 function rotl (x
, n
) {
7724 return (x
<< n
) | (x
>>> (32 - n
))
7727 function ripemd160 (message
) {
7728 var H
= [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
7730 if (typeof message
=== 'string') {
7731 message
= new Buffer(message
, 'utf8')
7734 var m
= bytesToWords(message
)
7736 var nBitsLeft
= message
.length
* 8
7737 var nBitsTotal
= message
.length
* 8
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)
7746 for (var i
= 0; i
< m
.length
; i
+= 16) {
7747 processBlock(H
, m
, i
)
7751 for (i
= 0; i
< 5; i
++) {
7756 H
[i
] = (((H_i
<< 8) | (H_i
>>> 24)) & 0x00ff00ff) |
7757 (((H_i
<< 24) | (H_i
>>> 8)) & 0xff00ff00)
7760 var digestbytes
= wordsToBytes(H
)
7761 return new Buffer(digestbytes
)
7764 module
.exports
= ripemd160
7766 }).call(this,require("buffer").Buffer
)
7767 },{"buffer":7}],37:[function(require
,module
,exports
){
7769 // prototype class for hash functions
7770 function Hash (blockSize
, finalSize
) {
7771 this._block
= new Buffer(blockSize
)
7772 this._finalSize
= finalSize
7773 this._blockSize
= blockSize
7778 Hash
.prototype.update = function (data
, enc
) {
7779 if (typeof data
=== 'string') {
7781 data
= new Buffer(data
, enc
)
7784 var l
= this._len
+= data
.length
7785 var s
= this._s
|| 0
7787 var buffer
= this._block
7790 var t
= Math
.min(data
.length
, f
+ this._blockSize
- (s
% this._blockSize
))
7793 for (var i
= 0; i
< ch
; i
++) {
7794 buffer
[(s
% this._blockSize
) + i
] = data
[i
+ f
]
7800 if ((s
% this._blockSize
) === 0) {
7801 this._update(buffer
)
7809 Hash
.prototype.digest = function (enc
) {
7810 // Suppose the length of the message M, in bits, is l
7811 var l
= this._len
* 8
7813 // Append the bit 1 to the end of the message
7814 this._block
[this._len
% this._blockSize
] = 0x80
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)
7819 if (l
% (this._blockSize
* 8) >= this._finalSize
* 8) {
7820 this._update(this._block
)
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)
7828 var hash
= this._update(this._block
) || this._hash()
7830 return enc
? hash
.toString(enc
) : hash
7833 Hash
.prototype._update = function () {
7834 throw new Error('_update must be implemented by subclass')
7837 module
.exports
= Hash
7839 }).call(this,require("buffer").Buffer
)
7840 },{"buffer":7}],38:[function(require
,module
,exports
){
7841 var exports
= module
.exports
= function SHA (algorithm
) {
7842 algorithm
= algorithm
.toLowerCase()
7844 var Algorithm
= exports
[algorithm
]
7845 if (!Algorithm
) throw new Error(algorithm
+ ' is not supported (we accept pull requests)')
7847 return new Algorithm()
7850 exports
.sha
= require('./sha')
7851 exports
.sha1
= require('./sha1')
7852 exports
.sha224
= require('./sha224')
7853 exports
.sha256
= require('./sha256')
7854 exports
.sha384
= require('./sha384')
7855 exports
.sha512
= require('./sha512')
7857 },{"./sha":39,"./sha1":40,"./sha224":41,"./sha256":42,"./sha384":43,"./sha512":44}],39:[function(require
,module
,exports
){
7860 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
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.
7867 var inherits
= require('inherits')
7868 var Hash
= require('./hash')
7870 var W
= new Array(80)
7876 Hash
.call(this, 64, 56)
7881 Sha
.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
7892 * Bitwise rotate a 32-bit number to the left.
7894 function rol (num
, cnt
) {
7895 return (num
<< cnt
) | (num
>>> (32 - cnt
))
7898 Sha
.prototype._update = function (M
) {
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) }
7913 function calcW () { return W
[j
- 3] ^ W
[j
- 8] ^ W
[j
- 14] ^ W
[j
- 16] }
7914 function loop (w
, f
) {
7917 var t
= rol(a
, 5) + f
+ e
+ w
+ k
7928 while (j
< 16) loop(M
.readInt32BE(j
* 4), (b
& c
) | ((~b
) & d
))
7929 while (j
< 20) loop(calcW(), (b
& c
) | ((~b
) & d
))
7931 while (j
< 40) loop(calcW(), b
^ c
^ d
)
7933 while (j
< 60) loop(calcW(), (b
& c
) | (b
& d
) | (c
& d
))
7935 while (j
< 80) loop(calcW(), b
^ c
^ d
)
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
7944 Sha
.prototype._hash = function () {
7945 var H
= new Buffer(20)
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)
7956 module
.exports
= Sha
7959 }).call(this,require("buffer").Buffer
)
7960 },{"./hash":37,"buffer":7,"inherits":35}],40:[function(require
,module
,exports
){
7963 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
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.
7971 var inherits
= require('inherits')
7972 var Hash
= require('./hash')
7974 var W
= new Array(80)
7980 Hash
.call(this, 64, 56)
7983 inherits(Sha1
, Hash
)
7985 Sha1
.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
7996 * Bitwise rotate a 32-bit number to the left.
7998 function rol (num
, cnt
) {
7999 return (num
<< cnt
) | (num
>>> (32 - cnt
))
8002 Sha1
.prototype._update = function (M
) {
8013 function calcW () { return rol(W
[j
- 3] ^ W
[j
- 8] ^ W
[j
- 14] ^ W
[j
- 16], 1) }
8014 function loop (w
, f
) {
8017 var t
= rol(a
, 5) + f
+ e
+ w
+ k
8028 while (j
< 16) loop(M
.readInt32BE(j
* 4), (b
& c
) | ((~b
) & d
))
8029 while (j
< 20) loop(calcW(), (b
& c
) | ((~b
) & d
))
8031 while (j
< 40) loop(calcW(), b
^ c
^ d
)
8033 while (j
< 60) loop(calcW(), (b
& c
) | (b
& d
) | (c
& d
))
8035 while (j
< 80) loop(calcW(), b
^ c
^ d
)
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
8044 Sha1
.prototype._hash = function () {
8045 var H
= new Buffer(20)
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)
8056 module
.exports
= Sha1
8058 }).call(this,require("buffer").Buffer
)
8059 },{"./hash":37,"buffer":7,"inherits":35}],41:[function(require
,module
,exports
){
8062 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
8064 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
8065 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
8069 var inherits
= require('inherits')
8070 var Sha256
= require('./sha256')
8071 var Hash
= require('./hash')
8073 var W
= new Array(64)
8075 function Sha224 () {
8078 this._w
= W
// new Array(64)
8080 Hash
.call(this, 64, 56)
8083 inherits(Sha224
, Sha256
)
8085 Sha224
.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
8098 Sha224
.prototype._hash = function () {
8099 var H
= new Buffer(28)
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)
8112 module
.exports
= Sha224
8114 }).call(this,require("buffer").Buffer
)
8115 },{"./hash":37,"./sha256":42,"buffer":7,"inherits":35}],42:[function(require
,module
,exports
){
8118 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
8120 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
8121 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
8125 var inherits
= require('inherits')
8126 var Hash
= require('./hash')
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
8147 var W
= new Array(64)
8149 function Sha256 () {
8152 this._w
= W
// new Array(64)
8154 Hash
.call(this, 64, 56)
8157 inherits(Sha256
, Hash
)
8159 Sha256
.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
8173 return (X
>>> n
) | (X
<< (32 - n
))
8180 function Ch (x
, y
, z
) {
8181 return ((x
& y
) ^ ((~x
) & z
))
8184 function Maj (x
, y
, z
) {
8185 return ((x
& y
) ^ (x
& z
) ^ (y
& z
))
8188 function Sigma0256 (x
) {
8189 return (S(x
, 2) ^ S(x
, 13) ^ S(x
, 22))
8192 function Sigma1256 (x
) {
8193 return (S(x
, 6) ^ S(x
, 11) ^ S(x
, 25))
8196 function Gamma0256 (x
) {
8197 return (S(x
, 7) ^ S(x
, 18) ^ R(x
, 3))
8200 function Gamma1256 (x
) {
8201 return (S(x
, 17) ^ S(x
, 19) ^ R(x
, 10))
8204 Sha256
.prototype._update = function (M
) {
8218 function calcW () { return Gamma1256(W
[j
- 2]) + W
[j
- 7] + Gamma0256(W
[j
- 15]) + W
[j
- 16] }
8222 var T1
= h
+ Sigma1256(e
) + Ch(e
, f
, g
) + K
[j
] + w
8223 var T2
= Sigma0256(a
) + Maj(a
, b
, c
)
8237 while (j
< 16) loop(M
.readInt32BE(j
* 4))
8238 while (j
< 64) loop(calcW())
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
8250 Sha256
.prototype._hash = function () {
8251 var H
= new Buffer(32)
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)
8265 module
.exports
= Sha256
8267 }).call(this,require("buffer").Buffer
)
8268 },{"./hash":37,"buffer":7,"inherits":35}],43:[function(require
,module
,exports
){
8270 var inherits
= require('inherits')
8271 var SHA512
= require('./sha512')
8272 var Hash
= require('./hash')
8274 var W
= new Array(160)
8276 function Sha384 () {
8280 Hash
.call(this, 128, 112)
8283 inherits(Sha384
, SHA512
)
8285 Sha384
.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
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
8307 Sha384
.prototype._hash = function () {
8308 var H
= new Buffer(48)
8310 function writeInt64BE (h
, l
, offset
) {
8311 H
.writeInt32BE(h
, offset
)
8312 H
.writeInt32BE(l
, offset
+ 4)
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)
8325 module
.exports
= Sha384
8327 }).call(this,require("buffer").Buffer
)
8328 },{"./hash":37,"./sha512":44,"buffer":7,"inherits":35}],44:[function(require
,module
,exports
){
8330 var inherits
= require('inherits')
8331 var Hash
= require('./hash')
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
8376 var W
= new Array(160)
8378 function Sha512 () {
8382 Hash
.call(this, 128, 112)
8385 inherits(Sha512
, Hash
)
8387 Sha512
.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
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
8409 function S (X
, Xl
, n
) {
8410 return (X
>>> n
) | (Xl
<< (32 - n
))
8413 function Ch (x
, y
, z
) {
8414 return ((x
& y
) ^ ((~x
) & z
))
8417 function Maj (x
, y
, z
) {
8418 return ((x
& y
) ^ (x
& z
) ^ (y
& z
))
8421 Sha512
.prototype._update = function (M
) {
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
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)
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)
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]
8459 var Wi16
= W
[j
- 16 * 2]
8460 var Wi16l
= W
[j
- 16 * 2 + 1]
8462 Wil
= gamma0l
+ Wi7l
8463 Wi
= gamma0
+ Wi7
+ ((Wil
>>> 0) < (gamma0l
>>> 0) ? 1 : 0)
8465 Wi
= Wi
+ gamma1
+ ((Wil
>>> 0) < (gamma1l
>>> 0) ? 1 : 0)
8467 Wi
= Wi
+ Wi16
+ ((Wil
>>> 0) < (Wi16l
>>> 0) ? 1 : 0)
8474 var maj
= Maj(a
, b
, c
)
8475 var majl
= Maj(al
, bl
, cl
)
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)
8482 // t1 = h + sigma1 + ch + K[i] + W[i]
8486 var ch
= Ch(e
, f
, g
)
8487 var chl
= Ch(el
, fl
, gl
)
8489 var t1l
= hl
+ sigma1l
8490 var t1
= h
+ sigma1h
+ ((t1l
>>> 0) < (hl
>>> 0) ? 1 : 0)
8492 t1
= t1
+ ch
+ ((t1l
>>> 0) < (chl
>>> 0) ? 1 : 0)
8494 t1
= t1
+ Ki
+ ((t1l
>>> 0) < (Kil
>>> 0) ? 1 : 0)
8496 t1
= t1
+ Wi
+ ((t1l
>>> 0) < (Wil
>>> 0) ? 1 : 0)
8498 // t2 = sigma0 + maj
8499 var t2l
= sigma0l
+ majl
8500 var t2
= sigma0h
+ maj
+ ((t2l
>>> 0) < (sigma0l
>>> 0) ? 1 : 0)
8509 e
= (d
+ t1
+ ((el
>>> 0) < (dl
>>> 0) ? 1 : 0)) | 0
8516 al
= (t1l
+ t2l
) | 0
8517 a
= (t1
+ t2
+ ((al
>>> 0) < (t1l
>>> 0) ? 1 : 0)) | 0
8524 Wi
= M
.readInt32BE(j
* 4)
8525 Wil
= M
.readInt32BE(j
* 4 + 4)
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
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
8554 Sha512
.prototype._hash = function () {
8555 var H
= new Buffer(64)
8557 function writeInt64BE (h
, l
, offset
) {
8558 H
.writeInt32BE(h
, offset
)
8559 H
.writeInt32BE(l
, offset
+ 4)
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)
8574 module
.exports
= Sha512
8576 }).call(this,require("buffer").Buffer
)
8577 },{"./hash":37,"buffer":7,"inherits":35}],45:[function(require
,module
,exports
){
8580 var createHash
= require('create-hash/browser');
8581 var inherits
= require('inherits')
8583 var Transform
= require('stream').Transform
8585 var ZEROS
= new Buffer(128)
8588 function Hmac(alg
, key
) {
8589 Transform
.call(this)
8591 if (typeof key
=== 'string') {
8592 key
= new Buffer(key
)
8595 var blocksize
= (alg
=== 'sha512' || alg
=== 'sha384') ? 128 : 64
8600 if (key
.length
> blocksize
) {
8601 key
= createHash(alg
).update(key
).digest()
8603 } else if (key
.length
< blocksize
) {
8604 key
= Buffer
.concat([key
, ZEROS
], blocksize
)
8607 var ipad
= this._ipad
= new Buffer(blocksize
)
8608 var opad
= this._opad
= new Buffer(blocksize
)
8610 for (var i
= 0; i
< blocksize
; i
++) {
8611 ipad
[i
] = key
[i
] ^ 0x36
8612 opad
[i
] = key
[i
] ^ 0x5C
8615 this._hash
= createHash(alg
).update(ipad
)
8618 inherits(Hmac
, Transform
)
8620 Hmac
.prototype.update = function (data
, enc
) {
8621 this._hash
.update(data
, enc
)
8626 Hmac
.prototype._transform = function (data
, _
, next
) {
8627 this._hash
.update(data
)
8632 Hmac
.prototype._flush = function (next
) {
8633 this.push(this.digest())
8638 Hmac
.prototype.digest = function (enc
) {
8639 var h
= this._hash
.digest()
8641 return createHash(this._alg
).update(this._opad
).update(h
).digest(enc
)
8644 module
.exports
= function createHmac(alg
, key
) {
8645 return new Hmac(alg
, key
)
8648 }).call(this,require("buffer").Buffer
)
8649 },{"buffer":7,"create-hash/browser":32,"inherits":46,"stream":26}],46:[function(require
,module
,exports
){
8650 arguments
[4][12][0].apply(exports
,arguments
)
8651 },{"dup":12}],47:[function(require
,module
,exports
){
8652 var assert
= require('assert')
8653 var BigInteger
= require('bigi')
8655 var Point
= require('./point')
8657 function Curve(p
, a
, b
, Gx
, Gy
, n
, h
) {
8661 this.G
= Point
.fromAffine(this, Gx
, Gy
)
8665 this.infinity
= new Point(this, null, null, BigInteger
.ZERO
)
8668 this.pOverFour
= p
.add(BigInteger
.ONE
).shiftRight(2)
8671 Curve
.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
8676 if (beta
.isEven() ^ !isOdd
) {
8677 y
= this.p
.subtract(y
) // -y % p
8680 return Point
.fromAffine(this, x
, y
)
8683 Curve
.prototype.isInfinity = function(Q
) {
8684 if (Q
=== this.infinity
) return true
8686 return Q
.z
.signum() === 0 && Q
.y
.signum() !== 0
8689 Curve
.prototype.isOnCurve = function(Q
) {
8690 if (this.isInfinity(Q
)) return true
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
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
)
8709 * Validate an elliptic curve point.
8711 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
8713 Curve
.prototype.validate = function(Q
) {
8715 assert(!this.isInfinity(Q
), 'Point is at infinity')
8716 assert(this.isOnCurve(Q
), 'Point is not on the curve')
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')
8725 module
.exports
= Curve
8727 },{"./point":51,"assert":5,"bigi":3}],48:[function(require
,module
,exports
){
8730 "p": "fffffffdffffffffffffffffffffffff",
8731 "a": "fffffffdfffffffffffffffffffffffc",
8732 "b": "e87579c11079f43dd824993c2cee5ed3",
8733 "n": "fffffffe0000000075a30d1b9038a115",
8735 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
8736 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
8739 "p": "fffffffffffffffffffffffffffffffeffffac73",
8742 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
8744 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
8745 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
8748 "p": "ffffffffffffffffffffffffffffffff7fffffff",
8749 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
8750 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
8751 "n": "0100000000000000000001f4c8f927aed3ca752257",
8753 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
8754 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
8757 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
8760 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
8762 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
8763 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
8766 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
8767 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
8768 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
8769 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
8771 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
8772 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
8775 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
8778 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
8780 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
8781 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
8784 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
8785 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
8786 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
8787 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
8789 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
8790 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
8794 },{}],49:[function(require
,module
,exports
){
8795 var Point
= require('./point')
8796 var Curve
= require('./curve')
8798 var getCurveByName
= require('./names')
8803 getCurveByName: getCurveByName
8806 },{"./curve":47,"./names":50,"./point":51}],50:[function(require
,module
,exports
){
8807 var BigInteger
= require('bigi')
8809 var curves
= require('./curves')
8810 var Curve
= require('./curve')
8812 function getCurveByName(name
) {
8813 var curve
= curves
[name
]
8814 if (!curve
) return null
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)
8824 return new Curve(p
, a
, b
, Gx
, Gy
, n
, h
)
8827 module
.exports
= getCurveByName
8829 },{"./curve":47,"./curves":48,"bigi":3}],51:[function(require
,module
,exports
){
8831 var assert
= require('assert')
8832 var BigInteger
= require('bigi')
8834 var THREE
= BigInteger
.valueOf(3)
8836 function Point(curve
, x
, y
, z
) {
8837 assert
.notStrictEqual(z
, undefined, 'Missing Z coordinate')
8845 this.compressed
= true
8848 Object
.defineProperty(Point
.prototype, 'zInv', {
8850 if (this._zInv
=== null) {
8851 this._zInv
= this.z
.modInverse(this.curve
.p
)
8858 Object
.defineProperty(Point
.prototype, 'affineX', {
8860 return this.x
.multiply(this.zInv
).mod(this.curve
.p
)
8864 Object
.defineProperty(Point
.prototype, 'affineY', {
8866 return this.y
.multiply(this.zInv
).mod(this.curve
.p
)
8870 Point
.fromAffine = function(curve
, x
, y
) {
8871 return new Point(curve
, x
, y
, BigInteger
.ONE
)
8874 Point
.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)
8879 // u = Y2 * Z1 - Y1 * Z2
8880 var u
= other
.y
.multiply(this.z
).subtract(this.y
.multiply(other
.z
)).mod(this.curve
.p
)
8882 if (u
.signum() !== 0) return false
8884 // v = X2 * Z1 - X1 * Z2
8885 var v
= other
.x
.multiply(this.z
).subtract(this.x
.multiply(other
.z
)).mod(this.curve
.p
)
8887 return v
.signum() === 0
8890 Point
.prototype.negate = function() {
8891 var y
= this.curve
.p
.subtract(this.y
)
8893 return new Point(this.curve
, this.x
, y
, this.z
)
8896 Point
.prototype.add = function(b
) {
8897 if (this.curve
.isInfinity(this)) return b
8898 if (this.curve
.isInfinity(b
)) return this
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
)
8910 if (v
.signum() === 0) {
8911 if (u
.signum() === 0) {
8912 return this.twice() // this == b, so double
8915 return this.curve
.infinity
// this = -b, so infinity
8919 var v3
= v2
.multiply(v
)
8920 var x1v2
= x1
.multiply(v2
)
8921 var zu2
= u
.square().multiply(this.z
)
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
)
8930 return new Point(this.curve
, x3
, y3
, z3
)
8933 Point
.prototype.twice = function() {
8934 if (this.curve
.isInfinity(this)) return this
8935 if (this.y
.signum() === 0) return this.curve
.infinity
8940 var y1z1
= y1
.multiply(this.z
)
8941 var y1sqz1
= y1z1
.multiply(y1
).mod(this.curve
.p
)
8942 var a
= this.curve
.a
8944 // w = 3 * x1^2 + a * z1^2
8945 var w
= x1
.square().multiply(THREE
)
8947 if (a
.signum() !== 0) {
8948 w
= w
.add(this.z
.square().multiply(a
))
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
)
8959 return new Point(this.curve
, x3
, y3
, z3
)
8962 // Simple NAF (Non-Adjacent Form) multiplication algorithm
8963 // TODO: modularize the multiplication algorithm
8964 Point
.prototype.multiply = function(k
) {
8965 if (this.curve
.isInfinity(this)) return this
8966 if (k
.signum() === 0) return this.curve
.infinity
8969 var h
= e
.multiply(THREE
)
8971 var neg
= this.negate()
8974 for (var i
= h
.bitLength() - 2; i
> 0; --i
) {
8977 var hBit
= h
.testBit(i
)
8978 var eBit
= e
.testBit(i
)
8981 R
= R
.add(hBit
? this : neg
)
8988 // Compute this*j + x*k (simultaneous multiplication)
8989 Point
.prototype.multiplyTwo = function(j
, x
, k
) {
8992 if (j
.bitLength() > k
.bitLength())
8993 i
= j
.bitLength() - 1
8995 i
= k
.bitLength() - 1
8997 var R
= this.curve
.infinity
8998 var both
= this.add(x
)
9003 var jBit
= j
.testBit(i
)
9004 var kBit
= k
.testBit(i
)
9025 Point
.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'
9029 var x
= this.affineX
9030 var y
= this.affineY
9034 // Determine size of q in bytes
9035 var byteLength
= Math
.floor((this.curve
.p
.bitLength() + 7) / 8)
9039 buffer
= new Buffer(1 + byteLength
)
9040 buffer
.writeUInt8(y
.isEven() ? 0x02 : 0x03, 0)
9044 buffer
= new Buffer(1 + byteLength
+ byteLength
)
9045 buffer
.writeUInt8(0x04, 0)
9047 y
.toBuffer(byteLength
).copy(buffer
, 1 + byteLength
)
9050 x
.toBuffer(byteLength
).copy(buffer
, 1)
9055 Point
.decodeFrom = function(curve
, buffer
) {
9056 var type
= buffer
.readUInt8(0)
9057 var compressed
= (type
!== 4)
9059 var byteLength
= Math
.floor((curve
.p
.bitLength() + 7) / 8)
9060 var x
= BigInteger
.fromBuffer(buffer
.slice(1, 1 + byteLength
))
9064 assert
.equal(buffer
.length
, byteLength
+ 1, 'Invalid sequence length')
9065 assert(type
=== 0x02 || type
=== 0x03, 'Invalid sequence tag')
9067 var isOdd
= (type
=== 0x03)
9068 Q
= curve
.pointFromX(isOdd
, x
)
9071 assert
.equal(buffer
.length
, 1 + byteLength
+ byteLength
, 'Invalid sequence length')
9073 var y
= BigInteger
.fromBuffer(buffer
.slice(1 + byteLength
))
9074 Q
= Point
.fromAffine(curve
, x
, y
)
9077 Q
.compressed
= compressed
9081 Point
.prototype.toString = function () {
9082 if (this.curve
.isInfinity(this)) return '(INFINITY)'
9084 return '(' + this.affineX
.toString() + ',' + this.affineY
.toString() + ')'
9087 module
.exports
= Point
9089 }).call(this,require("buffer").Buffer
)
9090 },{"assert":5,"bigi":3,"buffer":7}],52:[function(require
,module
,exports
){
9091 (function (process
,global
,Buffer
){
9094 var crypto
= global
.crypto
|| global
.msCrypto
9095 if(crypto
&& crypto
.getRandomValues
) {
9096 module
.exports
= randomBytes
;
9098 module
.exports
= oldBrowser
;
9100 function 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
9106 crypto
.getRandomValues(bytes
);
9107 if (typeof cb
=== 'function') {
9108 return process
.nextTick(function () {
9114 function oldBrowser() {
9116 'secure random number generation not supported by this browser\n'+
9117 'use chrome, FireFox or Internet Explorer 11'
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
){
9126 function getFunctionName(fn
) {
9127 return fn
.name
|| fn
.toString().match(/function (.*?)\s
*\(/)[1];
9130 function getTypeTypeName(type
) {
9131 if (nativeTypes
.Function(type
)) {
9132 type
= type
.toJSON
? type
.toJSON() : getFunctionName(type
);
9134 if (nativeTypes
.Object(type
)) return JSON
.stringify(type
);
9139 function getValueTypeName(value
) {
9140 if (nativeTypes
.Null(value
)) return '';
9142 return getFunctionName(value
.constructor);
9145 function tfErrorString(type
, value
) {
9146 var typeTypeName
= getTypeTypeName(type
);
9147 var valueTypeName
= getValueTypeName(value
);
9149 return 'Expected ' + typeTypeName
+ ', got ' + (valueTypeName
&& valueTypeName
+ ' ') + JSON
.stringify(value
);
9152 function tfPropertyErrorString(type
, name
, value
) {
9153 return tfErrorString('property \"' + name
+ '\" of type ' + getTypeTypeName(type
), value
);
9157 Array: (function (_Array
) {
9158 function Array(_x
) {
9159 return _Array
.apply(this, arguments
);
9162 Array
.toString = function () {
9163 return _Array
.toString();
9167 })(function (value
) {
9168 return value
!== null && value
!== undefined && value
.constructor === Array
;
9170 Boolean: function Boolean(value
) {
9171 return typeof value
=== 'boolean';
9173 Buffer: (function (_Buffer
) {
9174 function Buffer(_x2
) {
9175 return _Buffer
.apply(this, arguments
);
9178 Buffer
.toString = function () {
9179 return _Buffer
.toString();
9183 })(function (value
) {
9184 return Buffer
.isBuffer(value
);
9186 Function: function Function(value
) {
9187 return typeof value
=== 'function';
9189 Null: function Null(value
) {
9190 return value
=== undefined || value
=== null;
9192 Number: function Number(value
) {
9193 return typeof value
=== 'number';
9195 Object: function Object(value
) {
9196 return typeof value
=== 'object';
9198 String: function String(value
) {
9199 return typeof value
=== 'string';
9206 function tJSON(type
) {
9207 return type
&& type
.toJSON
? type
.toJSON() : type
;
9210 function sJSON(type
) {
9211 var json
= tJSON(type
);
9212 return nativeTypes
.Object(json
) ? JSON
.stringify(json
) : json
;
9216 arrayOf: function arrayOf(type
) {
9217 function arrayOf(value
, strict
) {
9219 return nativeTypes
.Array(value
) && value
.every(function (x
) {
9220 return typeforce(type
, x
, strict
);
9226 arrayOf
.toJSON = function () {
9227 return [tJSON(type
)];
9233 maybe: function maybe(type
) {
9234 function maybe(value
, strict
) {
9235 return nativeTypes
.Null(value
) || typeforce(type
, value
, strict
);
9237 maybe
.toJSON = function () {
9238 return '?' + sJSON(type
);
9244 object: function object(type
) {
9245 function object(value
, strict
) {
9246 typeforce(nativeTypes
.Object
, value
, strict
);
9248 var propertyName
, propertyType
, propertyValue
;
9251 for (propertyName
in type
) {
9252 propertyType
= type
[propertyName
];
9253 propertyValue
= value
[propertyName
];
9255 typeforce(propertyType
, propertyValue
, strict
);
9258 throw new TypeError(tfPropertyErrorString(propertyType
, propertyName
, propertyValue
));
9262 for (propertyName
in value
) {
9263 if (type
[propertyName
]) continue;
9265 throw new TypeError('Unexpected property "' + propertyName
+ '"');
9271 object
.toJSON = function () {
9278 oneOf: function oneOf() {
9279 for (var _len
= arguments
.length
, types
= Array(_len
), _key
= 0; _key
< _len
; _key
++) {
9280 types
[_key
] = arguments
[_key
];
9283 function oneOf(value
, strict
) {
9284 return types
.some(function (type
) {
9286 return typeforce(type
, value
, strict
);
9292 oneOf
.toJSON = function () {
9293 return types
.map(sJSON
).join('|');
9299 quacksLike: function quacksLike(type
) {
9300 function quacksLike(value
, strict
) {
9301 return type
=== getValueTypeName(value
);
9303 quacksLike
.toJSON = function () {
9310 tuple: function tuple() {
9311 for (var _len2
= arguments
.length
, types
= Array(_len2
), _key2
= 0; _key2
< _len2
; _key2
++) {
9312 types
[_key2
] = arguments
[_key2
];
9315 function tuple(value
, strict
) {
9316 return types
.every(function (type
, i
) {
9317 return typeforce(type
, value
[i
], strict
);
9320 tuple
.toJSON = function () {
9321 return '(' + types
.map(sJSON
).join(', ') + ')';
9327 value: function value(expected
) {
9328 function value(actual
) {
9329 return actual
=== expected
;
9331 value
.toJSON = function () {
9339 function compile(type
) {
9340 if (nativeTypes
.String(type
)) {
9341 if (type
[0] === '?') return otherTypes
.maybe(compile(type
.slice(1)));
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]));
9349 for (var propertyName
in type
) {
9350 compiled
[propertyName
] = compile(type
[propertyName
]);
9353 return otherTypes
.object(compiled
);
9354 } else if (nativeTypes
.Function(type
)) {
9358 return otherTypes
.value(type
);
9361 function typeforce(_x3
, _x4
, _x5
) {
9364 _function: while (_again
) {
9370 if (nativeTypes
.Function(type
)) {
9371 if (type(value
, strict
)) return true;
9373 throw new TypeError(tfErrorString(type
, value
));
9377 _x3
= compile(type
);
9385 // assign all types to typeforce function
9387 Object
.keys(nativeTypes
).forEach(function (typeName
) {
9388 var nativeType
= nativeTypes
[typeName
];
9389 nativeType
.toJSON = function () {
9393 typeforce
[typeName
] = nativeType
;
9396 for (typeName
in otherTypes
) {
9397 typeforce
[typeName
] = otherTypes
[typeName
];
9400 module
.exports
= typeforce
;
9401 module
.exports
.compile
= compile
;
9402 }).call(this,require("buffer").Buffer
)
9403 },{"buffer":7}],54:[function(require
,module
,exports
){
9405 var assert
= require('assert')
9406 var base58check
= require('bs58check')
9407 var typeForce
= require('typeforce')
9408 var networks
= require('./networks')
9409 var scripts
= require('./scripts')
9411 function findScriptTypeByVersion (version
) {
9412 for (var networkName
in networks
) {
9413 var network
= networks
[networkName
]
9415 if (version
=== network
.pubKeyHash
) return 'pubkeyhash'
9416 if (version
=== network
.scriptHash
) return 'scripthash'
9420 function Address (hash
, version
) {
9421 typeForce('Buffer', hash
)
9423 assert
.strictEqual(hash
.length
, 20, 'Invalid hash length')
9424 assert
.strictEqual(version
& 0xff, version
, 'Invalid version byte')
9427 this.version
= version
9430 Address
.fromBase58Check = function (string
) {
9431 var payload
= base58check
.decode(string
)
9432 var version
= payload
.readUInt8(0)
9433 var hash
= payload
.slice(1)
9435 return new Address(hash
, version
)
9438 Address
.fromOutputScript = function (script
, network
) {
9439 network
= network
|| networks
.bitcoin
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
)
9444 assert(false, script
.toASM() + ' has no matching Address')
9447 Address
.prototype.toBase58Check = function () {
9448 var payload
= new Buffer(21)
9449 payload
.writeUInt8(this.version
, 0)
9450 this.hash
.copy(payload
, 1)
9452 return base58check
.encode(payload
)
9455 Address
.prototype.toOutputScript = function () {
9456 var scriptType
= findScriptTypeByVersion(this.version
)
9458 if (scriptType
=== 'pubkeyhash') return scripts
.pubKeyHashOutput(this.hash
)
9459 if (scriptType
=== 'scripthash') return scripts
.scriptHashOutput(this.hash
)
9461 assert(false, this.toString() + ' has no matching Script')
9464 Address
.prototype.toString
= Address
.prototype.toBase58Check
9466 module
.exports
= Address
9468 }).call(this,require("buffer").Buffer
)
9469 },{"./networks":66,"./scripts":69,"assert":5,"bs58check":31,"buffer":7,"typeforce":53}],55:[function(require
,module
,exports
){
9470 var bs58check
= require('bs58check')
9472 function decode () {
9473 console
.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.')
9475 return bs58check
.decode
.apply(undefined, arguments
)
9478 function encode () {
9479 console
.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.')
9481 return bs58check
.encode
.apply(undefined, arguments
)
9489 },{"bs58check":31}],56:[function(require
,module
,exports
){
9491 var assert
= require('assert')
9492 var bufferutils
= require('./bufferutils')
9493 var crypto
= require('./crypto')
9495 var Transaction
= require('./transaction')
9499 this.prevHash
= null
9500 this.merkleRoot
= null
9506 Block
.fromBuffer = function (buffer
) {
9507 assert(buffer
.length
>= 80, 'Buffer too small (< 80 bytes)')
9510 function readSlice (n
) {
9512 return buffer
.slice(offset
- n
, offset
)
9515 function readUInt32 () {
9516 var i
= buffer
.readUInt32LE(offset
)
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()
9529 if (buffer
.length
=== 80) return block
9531 function readVarInt () {
9532 var vi
= bufferutils
.readVarInt(buffer
, offset
)
9537 // FIXME: poor performance
9538 function readTransaction () {
9539 var tx
= Transaction
.fromBuffer(buffer
.slice(offset
), true)
9541 offset
+= tx
.toBuffer().length
9545 var nTransactions
= readVarInt()
9546 block
.transactions
= []
9548 for (var i
= 0; i
< nTransactions
; ++i
) {
9549 var tx
= readTransaction()
9550 block
.transactions
.push(tx
)
9556 Block
.fromHex = function (hex
) {
9557 return Block
.fromBuffer(new Buffer(hex
, 'hex'))
9560 Block
.prototype.getHash = function () {
9561 return crypto
.hash256(this.toBuffer(true))
9564 Block
.prototype.getId = function () {
9565 return bufferutils
.reverse(this.getHash()).toString('hex')
9568 Block
.prototype.getUTCDate = function () {
9569 var date
= new Date(0) // epoch
9570 date
.setUTCSeconds(this.timestamp
)
9575 Block
.prototype.toBuffer = function (headersOnly
) {
9576 var buffer
= new Buffer(80)
9579 function writeSlice (slice
) {
9580 slice
.copy(buffer
, offset
)
9581 offset
+= slice
.length
9584 function writeUInt32 (i
) {
9585 buffer
.writeUInt32LE(i
, offset
)
9589 writeUInt32(this.version
)
9590 writeSlice(this.prevHash
)
9591 writeSlice(this.merkleRoot
)
9592 writeUInt32(this.timestamp
)
9593 writeUInt32(this.bits
)
9594 writeUInt32(this.nonce
)
9596 if (headersOnly
|| !this.transactions
) return buffer
9598 var txLenBuffer
= bufferutils
.varIntBuffer(this.transactions
.length
)
9599 var txBuffers
= this.transactions
.map(function (tx
) {
9600 return tx
.toBuffer()
9603 return Buffer
.concat([buffer
, txLenBuffer
].concat(txBuffers
))
9606 Block
.prototype.toHex = function (headersOnly
) {
9607 return this.toBuffer(headersOnly
).toString('hex')
9610 module
.exports
= Block
9612 }).call(this,require("buffer").Buffer
)
9613 },{"./bufferutils":57,"./crypto":58,"./transaction":70,"assert":5,"buffer":7}],57:[function(require
,module
,exports
){
9615 var assert
= require('assert')
9616 var opcodes
= require('./opcodes')
9618 // https://github.com/feross/buffer/blob/master/index.js#L1127
9619 function 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')
9626 function pushDataSize (i
) {
9627 return i
< opcodes
.OP_PUSHDATA1
? 1
9633 function readPushDataInt (buffer
, offset
) {
9634 var opcode
= buffer
.readUInt8(offset
)
9638 if (opcode
< opcodes
.OP_PUSHDATA1
) {
9643 } else if (opcode
=== opcodes
.OP_PUSHDATA1
) {
9644 if (offset
+ 2 > buffer
.length
) return null
9645 number
= buffer
.readUInt8(offset
+ 1)
9649 } else if (opcode
=== opcodes
.OP_PUSHDATA2
) {
9650 if (offset
+ 3 > buffer
.length
) return null
9651 number
= buffer
.readUInt16LE(offset
+ 1)
9656 if (offset
+ 5 > buffer
.length
) return null
9657 assert
.equal(opcode
, opcodes
.OP_PUSHDATA4
, 'Unexpected opcode')
9659 number
= buffer
.readUInt32LE(offset
+ 1)
9670 function readUInt64LE (buffer
, offset
) {
9671 var a
= buffer
.readUInt32LE(offset
)
9672 var b
= buffer
.readUInt32LE(offset
+ 4)
9675 verifuint(b
+ a
, 0x001fffffffffffff)
9680 function readVarInt (buffer
, offset
) {
9681 var t
= buffer
.readUInt8(offset
)
9690 } else if (t
< 254) {
9691 number
= buffer
.readUInt16LE(offset
+ 1)
9695 } else if (t
< 255) {
9696 number
= buffer
.readUInt32LE(offset
+ 1)
9701 number
= readUInt64LE(buffer
, offset
+ 1)
9711 function writePushDataInt (buffer
, number
, offset
) {
9712 var size
= pushDataSize(number
)
9716 buffer
.writeUInt8(number
, offset
)
9719 } else if (size
=== 2) {
9720 buffer
.writeUInt8(opcodes
.OP_PUSHDATA1
, offset
)
9721 buffer
.writeUInt8(number
, offset
+ 1)
9724 } else if (size
=== 3) {
9725 buffer
.writeUInt8(opcodes
.OP_PUSHDATA2
, offset
)
9726 buffer
.writeUInt16LE(number
, offset
+ 1)
9730 buffer
.writeUInt8(opcodes
.OP_PUSHDATA4
, offset
)
9731 buffer
.writeUInt32LE(number
, offset
+ 1)
9737 function writeUInt64LE (buffer
, value
, offset
) {
9738 verifuint(value
, 0x001fffffffffffff)
9740 buffer
.writeInt32LE(value
& -1, offset
)
9741 buffer
.writeUInt32LE(Math
.floor(value
/ 0x100000000), offset
+ 4)
9744 function varIntSize (i
) {
9747 : i
< 0x100000000 ? 5
9751 function writeVarInt (buffer
, number
, offset
) {
9752 var size
= varIntSize(number
)
9756 buffer
.writeUInt8(number
, offset
)
9759 } else if (size
=== 3) {
9760 buffer
.writeUInt8(253, offset
)
9761 buffer
.writeUInt16LE(number
, offset
+ 1)
9764 } else if (size
=== 5) {
9765 buffer
.writeUInt8(254, offset
)
9766 buffer
.writeUInt32LE(number
, offset
+ 1)
9770 buffer
.writeUInt8(255, offset
)
9771 writeUInt64LE(buffer
, number
, offset
+ 1)
9777 function varIntBuffer (i
) {
9778 var size
= varIntSize(i
)
9779 var buffer
= new Buffer(size
)
9780 writeVarInt(buffer
, i
, 0)
9785 function reverse (buffer
) {
9786 var buffer2
= new Buffer(buffer
)
9787 Array
.prototype.reverse
.call(buffer2
)
9792 pushDataSize: pushDataSize
,
9793 readPushDataInt: readPushDataInt
,
9794 readUInt64LE: readUInt64LE
,
9795 readVarInt: readVarInt
,
9797 varIntBuffer: varIntBuffer
,
9798 varIntSize: varIntSize
,
9799 writePushDataInt: writePushDataInt
,
9800 writeUInt64LE: writeUInt64LE
,
9801 writeVarInt: writeVarInt
9804 }).call(this,require("buffer").Buffer
)
9805 },{"./opcodes":67,"assert":5,"buffer":7}],58:[function(require
,module
,exports
){
9806 var createHash
= require('create-hash')
9808 function hash160 (buffer
) {
9809 return ripemd160(sha256(buffer
))
9812 function hash256 (buffer
) {
9813 return sha256(sha256(buffer
))
9816 function ripemd160 (buffer
) {
9817 return createHash('rmd160').update(buffer
).digest()
9820 function sha1 (buffer
) {
9821 return createHash('sha1').update(buffer
).digest()
9824 function sha256 (buffer
) {
9825 return createHash('sha256').update(buffer
).digest()
9828 // FIXME: Name not consistent with others
9829 var createHmac
= require('create-hmac')
9831 function 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()
9836 function 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()
9842 ripemd160: ripemd160
,
9847 HmacSHA256: HmacSHA256
,
9848 HmacSHA512: HmacSHA512
9851 },{"create-hash":32,"create-hmac":45}],59:[function(require
,module
,exports
){
9853 var assert
= require('assert')
9854 var createHmac
= require('create-hmac')
9855 var typeForce
= require('typeforce')
9857 var BigInteger
= require('bigi')
9858 var ECSignature
= require('./ecsignature')
9860 var ZERO
= new Buffer([0])
9861 var ONE
= new Buffer([1])
9863 // https://tools.ietf.org/html/rfc6979#section-3.2
9864 function deterministicGenerateK (curve
, hash
, d
, checkSig
) {
9865 typeForce('Buffer', hash
)
9866 typeForce('BigInteger', d
)
9868 // FIXME: remove/uncomment for 2.0.0
9869 // typeForce('Function', checkSig)
9871 if (typeof checkSig
!== 'function') {
9872 console
.warn('deterministicGenerateK requires a checkSig callback in 2.0.0, see #337 for more information')
9874 checkSig = function (k
) {
9877 var e
= BigInteger
.fromBuffer(hash
)
9879 var Q
= G
.multiply(k
)
9881 if (curve
.isInfinity(Q
))
9884 var r
= Q
.affineX
.mod(n
)
9885 if (r
.signum() === 0)
9888 var s
= k
.modInverse(n
).multiply(e
.add(d
.multiply(r
))).mod(n
)
9889 if (s
.signum() === 0)
9897 assert
.equal(hash
.length
, 32, 'Hash must be 256 bit')
9899 var x
= d
.toBuffer(32)
9900 var k
= new Buffer(32)
9901 var v
= new Buffer(32)
9903 // Step A, ignored as hash already provided
9911 k
= createHmac('sha256', k
)
9919 v
= createHmac('sha256', k
).update(v
).digest()
9922 k
= createHmac('sha256', k
)
9930 v
= createHmac('sha256', k
).update(v
).digest()
9932 // Step H1/H2a, ignored as tlen === qlen (256 bit)
9934 v
= createHmac('sha256', k
).update(v
).digest()
9936 var T
= BigInteger
.fromBuffer(v
)
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
)
9945 v
= createHmac('sha256', k
).update(v
).digest()
9947 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
9949 v
= createHmac('sha256', k
).update(v
).digest()
9950 T
= BigInteger
.fromBuffer(v
)
9956 function sign (curve
, hash
, d
) {
9959 var e
= BigInteger
.fromBuffer(hash
)
9963 deterministicGenerateK(curve
, hash
, d
, function (k
) {
9964 var Q
= G
.multiply(k
)
9966 if (curve
.isInfinity(Q
))
9969 r
= Q
.affineX
.mod(n
)
9970 if (r
.signum() === 0)
9973 s
= k
.modInverse(n
).multiply(e
.add(d
.multiply(r
))).mod(n
)
9974 if (s
.signum() === 0)
9980 var N_OVER_TWO
= n
.shiftRight(1)
9982 // enforce low S values, see bip62: 'low s values in signatures'
9983 if (s
.compareTo(N_OVER_TWO
) > 0) {
9987 return new ECSignature(r
, s
)
9990 function verifyRaw (curve
, e
, signature
, Q
) {
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
10002 var c
= s
.modInverse(n
)
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
)
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
)
10013 // 1.4.5 (cont.) Enforce R is not at infinity
10014 if (curve
.isInfinity(R
)) return false
10016 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
10020 function verify (curve
, hash
, signature
, Q
) {
10021 // 1.4.2 H = Hash(M), already done by the user
10023 var e
= BigInteger
.fromBuffer(hash
)
10025 return verifyRaw(curve
, e
, signature
, Q
)
10029 * Recover a public key from a signature.
10031 * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
10032 * Key Recovery Operation".
10034 * http://www.secg.org/download/aid-780/sec1-v2.pdf
10036 function recoverPubKey (curve
, e
, signature
, i
) {
10037 assert
.strictEqual(i
& 3, i
, 'Recovery param is more than two bits')
10042 var r
= signature
.r
10043 var s
= signature
.s
10045 assert(r
.signum() > 0 && r
.compareTo(n
) < 0, 'Invalid r value')
10046 assert(s
.signum() > 0 && s
.compareTo(n
) < 0, 'Invalid s value')
10048 // A set LSB signifies that the y-coordinate is odd
10051 // The more significant bit specifies whether we should use the
10052 // first or second candidate key.
10053 var isSecondKey
= i
>> 1
10055 // 1.1 Let x = r + jn
10056 var x
= isSecondKey
? r
.add(n
) : r
10057 var R
= curve
.pointFromX(isYOdd
, x
)
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')
10063 // Compute -e from e
10064 var eNeg
= e
.negate().mod(n
)
10066 // 1.6.1 Compute Q = r^-1 (sR - eG)
10067 // Q = r^-1 (sR + -eG)
10068 var rInv
= r
.modInverse(n
)
10070 var Q
= R
.multiplyTwo(s
, G
, eNeg
).multiply(rInv
)
10077 * Calculate pubkey extraction parameter.
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
10084 * This function simply tries all four cases and returns the value
10085 * that resulted in a successful pubkey recovery.
10087 function calcPubKeyRecoveryParam (curve
, e
, signature
, Q
) {
10088 for (var i
= 0; i
< 4; i
++) {
10089 var Qprime
= recoverPubKey(curve
, e
, signature
, i
)
10092 if (Qprime
.equals(Q
)) {
10097 throw new Error('Unable to find valid recovery factor')
10101 calcPubKeyRecoveryParam: calcPubKeyRecoveryParam
,
10102 deterministicGenerateK: deterministicGenerateK
,
10103 recoverPubKey: recoverPubKey
,
10106 verifyRaw: verifyRaw
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
){
10112 var assert
= require('assert')
10113 var base58check
= require('bs58check')
10114 var ecdsa
= require('./ecdsa')
10115 var networks
= require('./networks')
10116 var randomBytes
= require('randombytes')
10117 var typeForce
= require('typeforce')
10119 var BigInteger
= require('bigi')
10120 var ECPubKey
= require('./ecpubkey')
10122 var ecurve
= require('ecurve')
10123 var secp256k1
= ecurve
.getCurveByName('secp256k1')
10125 function 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')
10129 var Q
= ECKey
.curve
.G
.multiply(d
)
10132 this.pub
= new ECPubKey(Q
, compressed
)
10136 ECKey
.curve
= secp256k1
10138 // Static constructors
10139 ECKey
.fromWIF = function (string
) {
10140 var payload
= base58check
.decode(string
)
10141 var compressed
= false
10143 // Ignore the version byte
10144 payload
= payload
.slice(1)
10146 if (payload
.length
=== 33) {
10147 assert
.strictEqual(payload
[32], 0x01, 'Invalid compression flag')
10149 // Truncate the compression flag
10150 payload
= payload
.slice(0, -1)
10154 assert
.equal(payload
.length
, 32, 'Invalid WIF payload length')
10156 var d
= BigInteger
.fromBuffer(payload
)
10157 return new ECKey(d
, compressed
)
10160 ECKey
.makeRandom = function (compressed
, rng
) {
10161 rng
= rng
|| randomBytes
10163 var buffer
= rng(32)
10164 typeForce('Buffer', buffer
)
10165 assert
.equal(buffer
.length
, 32, 'Expected 256-bit Buffer from RNG')
10167 var d
= BigInteger
.fromBuffer(buffer
)
10168 d
= d
.mod(ECKey
.curve
.n
)
10170 return new ECKey(d
, compressed
)
10173 // Export functions
10174 ECKey
.prototype.toWIF = function (network
) {
10175 network
= network
|| networks
.bitcoin
10177 var bufferLen
= this.pub
.compressed
? 34 : 33
10178 var buffer
= new Buffer(bufferLen
)
10180 buffer
.writeUInt8(network
.wif
, 0)
10181 this.d
.toBuffer(32).copy(buffer
, 1)
10183 if (this.pub
.compressed
) {
10184 buffer
.writeUInt8(0x01, 33)
10187 return base58check
.encode(buffer
)
10191 ECKey
.prototype.sign = function (hash
) {
10192 return ecdsa
.sign(ECKey
.curve
, hash
, this.d
)
10195 module
.exports
= ECKey
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
){
10200 var crypto
= require('./crypto')
10201 var ecdsa
= require('./ecdsa')
10202 var typeForce
= require('typeforce')
10203 var networks
= require('./networks')
10205 var Address
= require('./address')
10207 var ecurve
= require('ecurve')
10208 var secp256k1
= ecurve
.getCurveByName('secp256k1')
10210 function ECPubKey (Q
, compressed
) {
10211 if (compressed
=== undefined) {
10215 typeForce('Point', Q
)
10216 typeForce('Boolean', compressed
)
10218 this.compressed
= compressed
10223 ECPubKey
.curve
= secp256k1
10225 // Static constructors
10226 ECPubKey
.fromBuffer = function (buffer
) {
10227 var Q
= ecurve
.Point
.decodeFrom(ECPubKey
.curve
, buffer
)
10228 return new ECPubKey(Q
, Q
.compressed
)
10231 ECPubKey
.fromHex = function (hex
) {
10232 return ECPubKey
.fromBuffer(new Buffer(hex
, 'hex'))
10236 ECPubKey
.prototype.getAddress = function (network
) {
10237 network
= network
|| networks
.bitcoin
10239 return new Address(crypto
.hash160(this.toBuffer()), network
.pubKeyHash
)
10242 ECPubKey
.prototype.verify = function (hash
, signature
) {
10243 return ecdsa
.verify(ECPubKey
.curve
, hash
, signature
, this.Q
)
10246 // Export functions
10247 ECPubKey
.prototype.toBuffer = function () {
10248 return this.Q
.getEncoded(this.compressed
)
10251 ECPubKey
.prototype.toHex = function () {
10252 return this.toBuffer().toString('hex')
10255 module
.exports
= ECPubKey
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
){
10260 var assert
= require('assert')
10261 var typeForce
= require('typeforce')
10263 var BigInteger
= require('bigi')
10265 function ECSignature (r
, s
) {
10266 typeForce('BigInteger', r
)
10267 typeForce('BigInteger', s
)
10273 ECSignature
.parseCompact = function (buffer
) {
10274 assert
.equal(buffer
.length
, 65, 'Invalid signature length')
10275 var i
= buffer
.readUInt8(0) - 27
10278 assert
.equal(i
, i
& 7, 'Invalid signature parameter')
10279 var compressed
= !!(i
& 4)
10281 // Recovery param only
10284 var r
= BigInteger
.fromBuffer(buffer
.slice(1, 33))
10285 var s
= BigInteger
.fromBuffer(buffer
.slice(33))
10288 compressed: compressed
,
10290 signature: new ECSignature(r
, s
)
10294 ECSignature
.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')
10299 var rLen
= buffer
.readUInt8(3)
10300 assert(rLen
> 0, 'R length is zero')
10302 var offset
= 4 + rLen
10303 assert
.equal(buffer
.readUInt8(offset
), 0x02, 'Expected a DER integer (2)')
10305 var sLen
= buffer
.readUInt8(offset
+ 1)
10306 assert(sLen
> 0, 'S length is zero')
10308 var rB
= buffer
.slice(4, offset
)
10309 var sB
= buffer
.slice(offset
+ 2)
10312 if (rLen
> 1 && rB
.readUInt8(0) === 0x00) {
10313 assert(rB
.readUInt8(1) & 0x80, 'R value excessively padded')
10316 if (sLen
> 1 && sB
.readUInt8(0) === 0x00) {
10317 assert(sB
.readUInt8(1) & 0x80, 'S value excessively padded')
10320 assert
.equal(offset
, buffer
.length
, 'Invalid DER encoding')
10321 var r
= BigInteger
.fromDERInteger(rB
)
10322 var s
= BigInteger
.fromDERInteger(sB
)
10324 assert(r
.signum() >= 0, 'R value is negative')
10325 assert(s
.signum() >= 0, 'S value is negative')
10327 return new ECSignature(r
, s
)
10330 // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
10331 ECSignature
.parseScriptSignature = function (buffer
) {
10332 var hashType
= buffer
.readUInt8(buffer
.length
- 1)
10333 var hashTypeMod
= hashType
& ~0x80
10335 assert(hashTypeMod
> 0x00 && hashTypeMod
< 0x04, 'Invalid hashType ' + hashType
)
10338 signature: ECSignature
.fromDER(buffer
.slice(0, -1)),
10343 ECSignature
.prototype.toCompact = function (i
, compressed
) {
10350 var buffer
= new Buffer(65)
10351 buffer
.writeUInt8(i
, 0)
10353 this.r
.toBuffer(32).copy(buffer
, 1)
10354 this.s
.toBuffer(32).copy(buffer
, 33)
10359 ECSignature
.prototype.toDER = function () {
10360 var rBa
= this.r
.toDERInteger()
10361 var sBa
= this.s
.toDERInteger()
10366 sequence
.push(0x02, rBa
.length
)
10367 sequence
= sequence
.concat(rBa
)
10370 sequence
.push(0x02, sBa
.length
)
10371 sequence
= sequence
.concat(sBa
)
10374 sequence
.unshift(0x30, sequence
.length
)
10376 return new Buffer(sequence
)
10379 ECSignature
.prototype.toScriptSignature = function (hashType
) {
10380 var hashTypeMod
= hashType
& ~0x80
10381 assert(hashTypeMod
> 0x00 && hashTypeMod
< 0x04, 'Invalid hashType ' + hashType
)
10383 var hashTypeBuffer
= new Buffer(1)
10384 hashTypeBuffer
.writeUInt8(hashType
, 0)
10386 return Buffer
.concat([this.toDER(), hashTypeBuffer
])
10389 module
.exports
= ECSignature
10391 }).call(this,require("buffer").Buffer
)
10392 },{"assert":5,"bigi":3,"buffer":7,"typeforce":53}],63:[function(require
,module
,exports
){
10393 (function (Buffer
){
10394 var assert
= require('assert')
10395 var base58check
= require('bs58check')
10396 var bcrypto
= require('./crypto')
10397 var createHmac
= require('create-hmac')
10398 var typeForce
= require('typeforce')
10399 var networks
= require('./networks')
10401 var BigInteger
= require('bigi')
10402 var ECKey
= require('./eckey')
10403 var ECPubKey
= require('./ecpubkey')
10405 var ecurve
= require('ecurve')
10406 var curve
= ecurve
.getCurveByName('secp256k1')
10408 function findBIP32NetworkByVersion (version
) {
10409 for (var name
in networks
) {
10410 var network
= networks
[name
]
10412 if (version
=== network
.bip32
.private || version
=== network
.bip32
.public) {
10417 assert(false, 'Could not find network for ' + version
.toString(16))
10420 function HDNode (K
, chainCode
, network
) {
10421 network
= network
|| networks
.bitcoin
10423 typeForce('Buffer', chainCode
)
10425 assert
.equal(chainCode
.length
, 32, 'Expected chainCode length of 32, got ' + chainCode
.length
)
10426 assert(network
.bip32
, 'Unknown BIP32 constants for network')
10428 this.chainCode
= chainCode
10431 this.parentFingerprint
= 0x00000000
10432 this.network
= network
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')
10440 this.pubKey
= K
.pub
10441 } else if (K
instanceof ECPubKey
) {
10442 assert(K
.compressed
, 'ECPubKey must be compressed')
10445 this.pubKey
= new ECPubKey(K
, true)
10449 HDNode
.MASTER_SECRET
= new Buffer('Bitcoin seed')
10450 HDNode
.HIGHEST_BIT
= 0x80000000
10453 HDNode
.fromSeedBuffer = function (seed
, network
) {
10454 typeForce('Buffer', seed
)
10456 assert(seed
.length
>= 16, 'Seed should be at least 128 bits')
10457 assert(seed
.length
<= 64, 'Seed should be at most 512 bits')
10459 var I
= createHmac('sha512', HDNode
.MASTER_SECRET
).update(seed
).digest()
10460 var IL
= I
.slice(0, 32)
10461 var IR
= I
.slice(32)
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
)
10467 return new HDNode(pIL
, IR
, network
)
10470 HDNode
.fromSeedHex = function (hex
, network
) {
10471 return HDNode
.fromSeedBuffer(new Buffer(hex
, 'hex'), network
)
10474 HDNode
.fromBase58 = function (string
, network
) {
10475 return HDNode
.fromBuffer(base58check
.decode(string
), network
, true)
10478 // FIXME: remove in 2.x.y
10479 HDNode
.fromBuffer = function (buffer
, network
, __ignoreDeprecation
) {
10480 if (!__ignoreDeprecation
) {
10481 console
.warn('HDNode.fromBuffer() is deprecated for removal in 2.x.y, use fromBase58 instead')
10484 assert
.strictEqual(buffer
.length
, HDNode
.LENGTH
, 'Invalid buffer length')
10486 // 4 byte: version bytes
10487 var version
= buffer
.readUInt32BE(0)
10490 assert(version
=== network
.bip32
.private || version
=== network
.bip32
.public, "Network doesn't match")
10494 network
= findBIP32NetworkByVersion(version
)
10497 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
10498 var depth
= buffer
.readUInt8(4)
10500 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
10501 var parentFingerprint
= buffer
.readUInt32BE(5)
10503 assert
.strictEqual(parentFingerprint
, 0x00000000, 'Invalid parent fingerprint')
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')
10511 // 32 bytes: the chain code
10512 var chainCode
= buffer
.slice(13, 45)
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
)
10522 // 33 bytes: public key data (0x02 + X or 0x03 + X)
10524 data
= buffer
.slice(45, 78)
10525 var Q
= ecurve
.Point
.decodeFrom(curve
, data
)
10526 assert
.equal(Q
.compressed
, true, 'Invalid public key')
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.
10532 hd
= new HDNode(Q
, chainCode
, network
)
10537 hd
.parentFingerprint
= parentFingerprint
10542 // FIXME: remove in 2.x.y
10543 HDNode
.fromHex = function (hex
, network
) {
10544 return HDNode
.fromBuffer(new Buffer(hex
, 'hex'), network
)
10547 HDNode
.prototype.getIdentifier = function () {
10548 return bcrypto
.hash160(this.pubKey
.toBuffer())
10551 HDNode
.prototype.getFingerprint = function () {
10552 return this.getIdentifier().slice(0, 4)
10555 HDNode
.prototype.getAddress = function () {
10556 return this.pubKey
.getAddress(this.network
)
10559 HDNode
.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
10568 HDNode
.prototype.toBase58 = function (isPrivate
) {
10569 return base58check
.encode(this.toBuffer(isPrivate
, true))
10572 // FIXME: remove in 2.x.y
10573 HDNode
.prototype.toBuffer = function (isPrivate
, __ignoreDeprecation
) {
10574 if (isPrivate
=== undefined) {
10575 isPrivate
= !!this.privKey
10577 // FIXME: remove in 2.x.y
10579 console
.warn('isPrivate flag is deprecated, please use the .neutered() method instead')
10582 if (!__ignoreDeprecation
) {
10583 console
.warn('HDNode.toBuffer() is deprecated for removal in 2.x.y, use toBase58 instead')
10587 var version
= isPrivate
? this.network
.bip32
.private : this.network
.bip32
.public
10588 var buffer
= new Buffer(HDNode
.LENGTH
)
10590 // 4 bytes: version bytes
10591 buffer
.writeUInt32BE(version
, 0)
10594 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
10595 buffer
.writeUInt8(this.depth
, 4)
10597 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
10598 buffer
.writeUInt32BE(this.parentFingerprint
, 5)
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)
10604 // 32 bytes: the chain code
10605 this.chainCode
.copy(buffer
, 13)
10607 // 33 bytes: the public key or private key data
10609 // FIXME: remove in 2.x.y
10610 assert(this.privKey
, 'Missing private key')
10612 // 0x00 + k for private keys
10613 buffer
.writeUInt8(0, 45)
10614 this.privKey
.d
.toBuffer(32).copy(buffer
, 46)
10616 // X9.62 encoding for public keys
10617 this.pubKey
.toBuffer().copy(buffer
, 45)
10623 // FIXME: remove in 2.x.y
10624 HDNode
.prototype.toHex = function (isPrivate
) {
10625 return this.toBuffer(isPrivate
).toString('hex')
10628 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
10629 HDNode
.prototype.derive = function (index
) {
10630 var isHardened
= index
>= HDNode
.HIGHEST_BIT
10631 var indexBuffer
= new Buffer(4)
10632 indexBuffer
.writeUInt32BE(index
, 0)
10638 assert(this.privKey
, 'Could not derive hardened child key')
10640 // data = 0x00 || ser256(kpar) || ser32(index)
10641 data
= Buffer
.concat([
10642 this.privKey
.d
.toBuffer(33),
10648 // data = serP(point(kpar)) || ser32(index)
10649 // = serP(Kpar) || ser32(index)
10650 data
= Buffer
.concat([
10651 this.pubKey
.toBuffer(),
10656 var I
= createHmac('sha512', this.chainCode
).update(data
).digest()
10657 var IL
= I
.slice(0, 32)
10658 var IR
= I
.slice(32)
10660 var pIL
= BigInteger
.fromBuffer(IL
)
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)
10667 // Private parent key -> private child key
10669 if (this.privKey
) {
10670 // ki = parse256(IL) + kpar (mod n)
10671 var ki
= pIL
.add(this.privKey
.d
).mod(curve
.n
)
10673 // In case ki == 0, proceed with the next value for i
10674 if (ki
.signum() === 0) {
10675 return this.derive(index
+ 1)
10678 hd
= new HDNode(ki
, IR
, this.network
)
10680 // Public parent key -> public child key
10682 // Ki = point(parse256(IL)) + Kpar
10684 var Ki
= curve
.G
.multiply(pIL
).add(this.pubKey
.Q
)
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)
10691 hd
= new HDNode(Ki
, IR
, this.network
)
10694 hd
.depth
= this.depth
+ 1
10696 hd
.parentFingerprint
= this.getFingerprint().readUInt32BE(0)
10701 HDNode
.prototype.deriveHardened = function (index
) {
10702 // Only derives hardened private keys by default
10703 return this.derive(index
+ HDNode
.HIGHEST_BIT
)
10706 HDNode
.prototype.toString
= HDNode
.prototype.toBase58
10708 module
.exports
= HDNode
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
){
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')
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
){
10735 var bufferutils
= require('./bufferutils')
10736 var crypto
= require('./crypto')
10737 var ecdsa
= require('./ecdsa')
10738 var networks
= require('./networks')
10740 var BigInteger
= require('bigi')
10741 var ECPubKey
= require('./ecpubkey')
10742 var ECSignature
= require('./ecsignature')
10744 var ecurve
= require('ecurve')
10745 var ecparams
= ecurve
.getCurveByName('secp256k1')
10747 function magicHash (message
, network
) {
10748 var magicPrefix
= new Buffer(network
.magicPrefix
)
10749 var messageBuffer
= new Buffer(message
)
10750 var lengthBuffer
= bufferutils
.varIntBuffer(messageBuffer
.length
)
10752 var buffer
= Buffer
.concat([magicPrefix
, lengthBuffer
, messageBuffer
])
10753 return crypto
.hash256(buffer
)
10756 function sign (privKey
, message
, network
) {
10757 network
= network
|| networks
.bitcoin
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
)
10764 return signature
.toCompact(i
, privKey
.pub
.compressed
)
10767 // TODO: network could be implied from address
10768 function verify (address
, signature
, message
, network
) {
10769 if (!Buffer
.isBuffer(signature
)) {
10770 signature
= new Buffer(signature
, 'base64')
10773 network
= network
|| networks
.bitcoin
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
)
10780 var pubKey
= new ECPubKey(Q
, parsed
.compressed
)
10781 return pubKey
.getAddress(network
).toString() === address
.toString()
10785 magicHash: magicHash
,
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
10797 magicPrefix: '\x18Bitcoin Signed Message:\n',
10799 public: 0x0488b21e,
10800 private: 0x0488ade4
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')
10810 magicPrefix: '\x18Bitcoin Signed Message:\n',
10812 public: 0x043587cf,
10813 private: 0x04358394
10818 dustThreshold: 546,
10820 estimateFee: estimateFee('testnet')
10823 magicPrefix: '\x19Litecoin Signed Message:\n',
10825 public: 0x019da462,
10826 private: 0x019d9cfe
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')
10837 magicPrefix: '\x19Dogecoin Signed Message:\n',
10839 public: 0x02facafd,
10840 private: 0x02fac398
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')
10851 magicPrefix: '\x18Viacoin Signed Message:\n',
10853 public: 0x0488b21e,
10854 private: 0x0488ade4
10859 dustThreshold: 560,
10860 dustSoftThreshold: 100000,
10861 feePerKb: 100000, //
10862 estimateFee: estimateFee('viacoin')
10865 magicPrefix: '\x18Viacoin Signed Message:\n',
10867 public: 0x043587cf,
10868 private: 0x04358394
10873 dustThreshold: 560,
10874 dustSoftThreshold: 100000,
10876 estimateFee: estimateFee('viacointestnet')
10879 magicPrefix: '\x19Gamerscoin Signed Message:\n',
10881 public: 0x019da462,
10882 private: 0x019d9cfe
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')
10893 magicPrefix: '\x19Jumbucks Signed Message:\n',
10895 public: 0x037a689a,
10896 private: 0x037a6460
10902 dustSoftThreshold: 10000,
10904 estimateFee: estimateFee('jumbucks')
10907 magicPrefix: '\x18Zetacoin Signed Message:\n',
10909 public: 0x0488b21e,
10910 private: 0x0488ade4
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')
10921 function estimateFee (type
) {
10922 return function (tx
) {
10923 var network
= networks
[type
]
10924 var baseFee
= network
.feePerKb
10925 var byteSize
= tx
.toBuffer().length
10927 var fee
= baseFee
* Math
.ceil(byteSize
/ 1000)
10928 if (network
.dustSoftThreshold
=== undefined) return fee
10930 tx
.outs
.forEach(function (e
) {
10931 if (e
.value
< network
.dustSoftThreshold
) {
10940 module
.exports
= networks
10942 },{}],67:[function(require
,module
,exports
){
10983 OP_TOALTSTACK: 107,
10984 OP_FROMALTSTACK: 108,
11016 OP_EQUALVERIFY: 136,
11041 OP_NUMEQUALVERIFY: 157,
11042 OP_NUMNOTEQUAL: 158,
11044 OP_GREATERTHAN: 160,
11045 OP_LESSTHANOREQUAL: 161,
11046 OP_GREATERTHANOREQUAL: 162,
11058 OP_CODESEPARATOR: 171,
11060 OP_CHECKSIGVERIFY: 173,
11061 OP_CHECKMULTISIG: 174,
11062 OP_CHECKMULTISIGVERIFY: 175,
11076 // template matching params
11077 OP_PUBKEYHASH: 253,
11079 OP_INVALIDOPCODE: 255
11082 },{}],68:[function(require
,module
,exports
){
11083 (function (Buffer
){
11084 var assert
= require('assert')
11085 var bufferutils
= require('./bufferutils')
11086 var crypto
= require('./crypto')
11087 var typeForce
= require('typeforce')
11088 var opcodes
= require('./opcodes')
11090 function Script (buffer
, chunks
) {
11091 typeForce('Buffer', buffer
)
11092 typeForce('Array', chunks
)
11094 this.buffer
= buffer
11095 this.chunks
= chunks
11098 Script
.fromASM = function (asm
) {
11099 var strChunks
= asm
.split(' ')
11100 var chunks
= strChunks
.map(function (strChunk
) {
11102 if (strChunk
in opcodes
) {
11103 return opcodes
[strChunk
]
11107 return new Buffer(strChunk
, 'hex')
11111 return Script
.fromChunks(chunks
)
11114 Script
.fromBuffer = function (buffer
) {
11118 while (i
< buffer
.length
) {
11119 var opcode
= buffer
.readUInt8(i
)
11122 if ((opcode
> opcodes
.OP_0
) && (opcode
<= opcodes
.OP_PUSHDATA4
)) {
11123 var d
= bufferutils
.readPushDataInt(buffer
, i
)
11125 // did reading a pushDataInt fail? return non-chunked script
11126 if (d
=== null) return new Script(buffer
, [])
11129 // attempt to read too much data?
11130 if (i
+ d
.number
> buffer
.length
) return new Script(buffer
, [])
11132 var data
= buffer
.slice(i
, i
+ d
.number
)
11139 chunks
.push(opcode
)
11145 return new Script(buffer
, chunks
)
11148 Script
.fromChunks = function (chunks
) {
11149 typeForce('Array', chunks
)
11151 var bufferSize
= chunks
.reduce(function (accum
, chunk
) {
11153 if (Buffer
.isBuffer(chunk
)) {
11154 return accum
+ bufferutils
.pushDataSize(chunk
.length
) + chunk
.length
11161 var buffer
= new Buffer(bufferSize
)
11164 chunks
.forEach(function (chunk
) {
11166 if (Buffer
.isBuffer(chunk
)) {
11167 offset
+= bufferutils
.writePushDataInt(buffer
, chunk
.length
, offset
)
11169 chunk
.copy(buffer
, offset
)
11170 offset
+= chunk
.length
11174 buffer
.writeUInt8(chunk
, offset
)
11179 assert
.equal(offset
, buffer
.length
, 'Could not decode chunks')
11180 return new Script(buffer
, chunks
)
11183 Script
.fromHex = function (hex
) {
11184 return Script
.fromBuffer(new Buffer(hex
, 'hex'))
11187 Script
.EMPTY
= Script
.fromChunks([])
11189 Script
.prototype.getHash = function () {
11190 return crypto
.hash160(this.buffer
)
11193 // FIXME: doesn't work for data chunks, maybe time to use buffertools.compare...
11194 Script
.prototype.without = function (needle
) {
11195 return Script
.fromChunks(this.chunks
.filter(function (op
) {
11196 return op
!== needle
11200 var reverseOps
= []
11201 for (var op
in opcodes
) {
11202 var code
= opcodes
[op
]
11203 reverseOps
[code
] = op
11206 Script
.prototype.toASM = function () {
11207 return this.chunks
.map(function (chunk
) {
11209 if (Buffer
.isBuffer(chunk
)) {
11210 return chunk
.toString('hex')
11214 return reverseOps
[chunk
]
11219 Script
.prototype.toBuffer = function () {
11223 Script
.prototype.toHex = function () {
11224 return this.toBuffer().toString('hex')
11227 module
.exports
= Script
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
){
11232 var assert
= require('assert')
11233 var ops
= require('./opcodes')
11234 var typeForce
= require('typeforce')
11236 var ecurve
= require('ecurve')
11237 var curve
= ecurve
.getCurveByName('secp256k1')
11239 var ECSignature
= require('./ecsignature')
11240 var Script
= require('./script')
11242 function isCanonicalPubKey (buffer
) {
11243 if (!Buffer
.isBuffer(buffer
)) return false
11246 ecurve
.Point
.decodeFrom(curve
, buffer
)
11248 if (!(e
.message
.match(/Invalid
sequence (length
|tag
)/)))
11257 function isCanonicalSignature (buffer
) {
11258 if (!Buffer
.isBuffer(buffer
)) return false
11261 ECSignature
.parseScriptSignature(buffer
)
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
/))) {
11273 function isPubKeyHashInput (script
) {
11274 return script
.chunks
.length
=== 2 &&
11275 isCanonicalSignature(script
.chunks
[0]) &&
11276 isCanonicalPubKey(script
.chunks
[1])
11279 function 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
11289 function isPubKeyInput (script
) {
11290 return script
.chunks
.length
=== 1 &&
11291 isCanonicalSignature(script
.chunks
[0])
11294 function isPubKeyOutput (script
) {
11295 return script
.chunks
.length
=== 2 &&
11296 isCanonicalPubKey(script
.chunks
[0]) &&
11297 script
.chunks
[1] === ops
.OP_CHECKSIG
11300 function isScriptHashInput (script
, allowIncomplete
) {
11301 if (script
.chunks
.length
< 2) return false
11303 var lastChunk
= script
.chunks
[script
.chunks
.length
- 1]
11304 if (!Buffer
.isBuffer(lastChunk
)) return false
11306 var scriptSig
= Script
.fromChunks(script
.chunks
.slice(0, -1))
11307 var redeemScript
= Script
.fromBuffer(lastChunk
)
11309 // is redeemScript a valid script?
11310 if (redeemScript
.chunks
.length
=== 0) return false
11312 return classifyInput(scriptSig
, allowIncomplete
) === classifyOutput(redeemScript
)
11315 function 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
11323 // allowIncomplete is to account for combining signatures
11324 // See https://github.com/bitcoin/bitcoin/blob/f425050546644a36b0b8e0eb2f6934a3e0f6f80f/src/script/sign.cpp#L195-L197
11325 function isMultisigInput (script
, allowIncomplete
) {
11326 if (script
.chunks
.length
< 2) return false
11327 if (script
.chunks
[0] !== ops
.OP_0
) return false
11329 if (allowIncomplete
) {
11330 return script
.chunks
.slice(1).every(function (chunk
) {
11331 return chunk
=== ops
.OP_0
|| isCanonicalSignature(chunk
)
11335 return script
.chunks
.slice(1).every(isCanonicalSignature
)
11338 function isMultisigOutput (script
) {
11339 if (script
.chunks
.length
< 4) return false
11340 if (script
.chunks
[script
.chunks
.length
- 1] !== ops
.OP_CHECKMULTISIG
) return false
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
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
11352 var m
= mOp
- (ops
.OP_1
- 1)
11353 var n
= nOp
- (ops
.OP_1
- 1)
11354 if (n
< m
) return false
11356 var pubKeys
= script
.chunks
.slice(1, -2)
11357 if (n
< pubKeys
.length
) return false
11359 return pubKeys
.every(isCanonicalPubKey
)
11362 function isNullDataOutput (script
) {
11363 return script
.chunks
[0] === ops
.OP_RETURN
11366 function classifyOutput (script
) {
11367 typeForce('Script', script
)
11369 if (isPubKeyHashOutput(script
)) {
11370 return 'pubkeyhash'
11371 } else if (isScriptHashOutput(script
)) {
11372 return 'scripthash'
11373 } else if (isMultisigOutput(script
)) {
11375 } else if (isPubKeyOutput(script
)) {
11377 } else if (isNullDataOutput(script
)) {
11381 return 'nonstandard'
11384 function classifyInput (script
, allowIncomplete
) {
11385 typeForce('Script', script
)
11387 if (isPubKeyHashInput(script
)) {
11388 return 'pubkeyhash'
11389 } else if (isMultisigInput(script
, allowIncomplete
)) {
11391 } else if (isScriptHashInput(script
, allowIncomplete
)) {
11392 return 'scripthash'
11393 } else if (isPubKeyInput(script
)) {
11397 return 'nonstandard'
11400 // Standard Script Templates
11401 // {pubKey} OP_CHECKSIG
11402 function pubKeyOutput (pubKey
) {
11403 return Script
.fromChunks([
11409 // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
11410 function pubKeyHashOutput (hash
) {
11411 typeForce('Buffer', hash
)
11413 return Script
.fromChunks([
11417 ops
.OP_EQUALVERIFY
,
11422 // OP_HASH160 {scriptHash} OP_EQUAL
11423 function scriptHashOutput (hash
) {
11424 typeForce('Buffer', hash
)
11426 return Script
.fromChunks([
11433 // m [pubKeys ...] n OP_CHECKMULTISIG
11434 function multisigOutput (m
, pubKeys
) {
11435 typeForce(['ECPubKey'], pubKeys
)
11437 assert(pubKeys
.length
>= m
, 'Not enough pubKeys provided')
11439 var pubKeyBuffers
= pubKeys
.map(function (pubKey
) {
11440 return pubKey
.toBuffer()
11442 var n
= pubKeys
.length
11444 return Script
.fromChunks([].concat(
11445 (ops
.OP_1
- 1) + m
,
11447 (ops
.OP_1
- 1) + n
,
11448 ops
.OP_CHECKMULTISIG
11453 function pubKeyInput (signature
) {
11454 typeForce('Buffer', signature
)
11456 return Script
.fromChunks([signature
])
11459 // {signature} {pubKey}
11460 function pubKeyHashInput (signature
, pubKey
) {
11461 typeForce('Buffer', signature
)
11463 return Script
.fromChunks([signature
, pubKey
.toBuffer()])
11466 // <scriptSig> {serialized scriptPubKey script}
11467 function scriptHashInput (scriptSig
, scriptPubKey
) {
11468 return Script
.fromChunks([].concat(
11470 scriptPubKey
.toBuffer()
11474 // OP_0 [signatures ...]
11475 function multisigInput (signatures
, scriptPubKey
) {
11476 if (scriptPubKey
) {
11477 assert(isMultisigOutput(scriptPubKey
))
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)
11484 assert(signatures
.length
>= m
, 'Not enough signatures provided')
11485 assert(signatures
.length
<= n
, 'Too many signatures provided')
11488 return Script
.fromChunks([].concat(ops
.OP_0
, signatures
))
11491 function nullDataOutput (data
) {
11492 return Script
.fromChunks([ops
.OP_RETURN
, data
])
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
)
11521 nullDataOutput: nullDataOutput
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
){
11527 var assert
= require('assert')
11528 var bufferutils
= require('./bufferutils')
11529 var crypto
= require('./crypto')
11530 var typeForce
= require('typeforce')
11531 var opcodes
= require('./opcodes')
11532 var scripts
= require('./scripts')
11534 var Address
= require('./address')
11535 var ECSignature
= require('./ecsignature')
11536 var Script
= require('./script')
11538 function Transaction () {
11545 Transaction
.DEFAULT_SEQUENCE
= 0xffffffff
11546 Transaction
.SIGHASH_ALL
= 0x01
11547 Transaction
.SIGHASH_NONE
= 0x02
11548 Transaction
.SIGHASH_SINGLE
= 0x03
11549 Transaction
.SIGHASH_ANYONECANPAY
= 0x80
11551 Transaction
.fromBuffer = function (buffer
, __disableAssert
) {
11553 function readSlice (n
) {
11555 return buffer
.slice(offset
- n
, offset
)
11558 function readUInt32 () {
11559 var i
= buffer
.readUInt32LE(offset
)
11564 function readUInt64 () {
11565 var i
= bufferutils
.readUInt64LE(buffer
, offset
)
11570 function readVarInt () {
11571 var vi
= bufferutils
.readVarInt(buffer
, offset
)
11576 function readScript () {
11577 return Script
.fromBuffer(readSlice(readVarInt()))
11580 function readGenerationScript () {
11581 return new Script(readSlice(readVarInt()), [])
11584 var tx
= new Transaction()
11585 tx
.version
= readUInt32()
11587 var vinLen
= readVarInt()
11588 for (var i
= 0; i
< vinLen
; ++i
) {
11589 var hash
= readSlice(32)
11591 if (Transaction
.isCoinbaseHash(hash
)) {
11594 index: readUInt32(),
11595 script: readGenerationScript(),
11596 sequence: readUInt32()
11601 index: readUInt32(),
11602 script: readScript(),
11603 sequence: readUInt32()
11608 var voutLen
= readVarInt()
11609 for (i
= 0; i
< voutLen
; ++i
) {
11611 value: readUInt64(),
11612 script: readScript()
11616 tx
.locktime
= readUInt32()
11618 if (!__disableAssert
) {
11619 assert
.equal(offset
, buffer
.length
, 'Transaction has unexpected data')
11625 Transaction
.fromHex = function (hex
) {
11626 return Transaction
.fromBuffer(new Buffer(hex
, 'hex'))
11629 Transaction
.isCoinbaseHash = function (buffer
) {
11630 return Array
.prototype.every
.call(buffer
, function (x
) {
11636 * Create a new txIn.
11638 * Can be called with any of:
11640 * - A transaction and an index
11641 * - A transaction hash and an index
11643 * Note that this method does not sign the created input.
11645 Transaction
.prototype.addInput = function (hash
, index
, sequence
, script
) {
11646 if (sequence
=== undefined || sequence
=== null) {
11647 sequence
= Transaction
.DEFAULT_SEQUENCE
11650 script
= script
|| Script
.EMPTY
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()
11659 typeForce('Buffer', hash
)
11660 typeForce('Number', index
)
11661 typeForce('Number', sequence
)
11662 typeForce('Script', script
)
11664 assert
.equal(hash
.length
, 32, 'Expected hash length of 32, got ' + hash
.length
)
11666 // Add the input and return the input's index
11667 return (this.ins
.push({
11676 * Create a new txOut.
11678 * Can be called with:
11680 * - A base58 address string and a value
11681 * - An Address object and a value
11682 * - A scriptPubKey Script and a value
11684 Transaction
.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
)
11690 // Attempt to get a valid script if it's an Address object
11691 if (scriptPubKey
instanceof Address
) {
11692 scriptPubKey
= scriptPubKey
.toOutputScript()
11695 typeForce('Script', scriptPubKey
)
11696 typeForce('Number', value
)
11698 // Add the output and return the output's index
11699 return (this.outs
.push({
11700 script: scriptPubKey
,
11705 Transaction
.prototype.clone = function () {
11706 var newTx
= new Transaction()
11707 newTx
.version
= this.version
11708 newTx
.locktime
= this.locktime
11710 newTx
.ins
= this.ins
.map(function (txIn
) {
11714 script: txIn
.script
,
11715 sequence: txIn
.sequence
11719 newTx
.outs
= this.outs
.map(function (txOut
) {
11721 script: txOut
.script
,
11730 * Hash transaction for signing a specific input.
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.
11737 Transaction
.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, ...)')
11742 // swap the arguments (must be stored in tmp, arguments is special)
11743 var tmp
= arguments
[0]
11744 inIndex
= arguments
[1]
11745 prevOutScript
= tmp
11748 typeForce('Number', inIndex
)
11749 typeForce('Script', prevOutScript
)
11750 typeForce('Number', hashType
)
11752 assert(inIndex
>= 0, 'Invalid vin index')
11753 assert(inIndex
< this.ins
.length
, 'Invalid vin index')
11755 var txTmp
= this.clone()
11756 var hashScript
= prevOutScript
.without(opcodes
.OP_CODESEPARATOR
)
11758 // Blank out other inputs' signatures
11759 txTmp
.ins
.forEach(function (txIn
) {
11760 txIn
.script
= Script
.EMPTY
11762 txTmp
.ins
[inIndex
].script
= hashScript
11764 var hashTypeModifier
= hashType
& 0x1f
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')
11772 if (hashType
& Transaction
.SIGHASH_ANYONECANPAY
) {
11773 assert(false, 'SIGHASH_ANYONECANPAY not yet supported')
11776 var hashTypeBuffer
= new Buffer(4)
11777 hashTypeBuffer
.writeInt32LE(hashType
, 0)
11779 var buffer
= Buffer
.concat([txTmp
.toBuffer(), hashTypeBuffer
])
11780 return crypto
.hash256(buffer
)
11783 Transaction
.prototype.getHash = function () {
11784 return crypto
.hash256(this.toBuffer())
11787 Transaction
.prototype.getId = function () {
11788 // TxHash is little-endian, we need big-endian
11789 return bufferutils
.reverse(this.getHash()).toString('hex')
11792 Transaction
.prototype.toBuffer = function () {
11793 function scriptSize (script
) {
11794 var length
= script
.buffer
.length
11796 return bufferutils
.varIntSize(length
) + length
11799 var buffer
= new Buffer(
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)
11808 function writeSlice (slice
) {
11809 slice
.copy(buffer
, offset
)
11810 offset
+= slice
.length
11813 function writeUInt32 (i
) {
11814 buffer
.writeUInt32LE(i
, offset
)
11818 function writeUInt64 (i
) {
11819 bufferutils
.writeUInt64LE(buffer
, i
, offset
)
11823 function writeVarInt (i
) {
11824 var n
= bufferutils
.writeVarInt(buffer
, i
, offset
)
11828 writeUInt32(this.version
)
11829 writeVarInt(this.ins
.length
)
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
)
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
)
11846 writeUInt32(this.locktime
)
11851 Transaction
.prototype.toHex = function () {
11852 return this.toBuffer().toString('hex')
11855 Transaction
.prototype.setInputScript = function (index
, script
) {
11856 typeForce('Number', index
)
11857 typeForce('Script', script
)
11859 this.ins
[index
].script
= script
11862 // FIXME: remove in 2.x.y
11863 Transaction
.prototype.sign = function (index
, privKey
, hashType
) {
11864 console
.warn('Transaction.prototype.sign is deprecated. Use TransactionBuilder instead.')
11866 var prevOutScript
= privKey
.pub
.getAddress().toOutputScript()
11867 var signature
= this.signInput(index
, prevOutScript
, privKey
, hashType
)
11869 var scriptSig
= scripts
.pubKeyHashInput(signature
, privKey
.pub
)
11870 this.setInputScript(index
, scriptSig
)
11873 // FIXME: remove in 2.x.y
11874 Transaction
.prototype.signInput = function (index
, prevOutScript
, privKey
, hashType
) {
11875 console
.warn('Transaction.prototype.signInput is deprecated. Use TransactionBuilder instead.')
11877 hashType
= hashType
|| Transaction
.SIGHASH_ALL
11879 var hash
= this.hashForSignature(index
, prevOutScript
, hashType
)
11880 var signature
= privKey
.sign(hash
)
11882 return signature
.toScriptSignature(hashType
)
11885 // FIXME: remove in 2.x.y
11886 Transaction
.prototype.validateInput = function (index
, prevOutScript
, pubKey
, buffer
) {
11887 console
.warn('Transaction.prototype.validateInput is deprecated. Use TransactionBuilder instead.')
11889 var parsed
= ECSignature
.parseScriptSignature(buffer
)
11890 var hash
= this.hashForSignature(index
, prevOutScript
, parsed
.hashType
)
11892 return pubKey
.verify(hash
, parsed
.signature
)
11895 module
.exports
= Transaction
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
){
11900 var assert
= require('assert')
11901 var ops
= require('./opcodes')
11902 var scripts
= require('./scripts')
11904 var ECPubKey
= require('./ecpubkey')
11905 var ECSignature
= require('./ecsignature')
11906 var Script
= require('./script')
11907 var Transaction
= require('./transaction')
11909 function extractInput (txIn
) {
11911 var scriptSig
= txIn
.script
11913 var prevOutType
= scripts
.classifyInput(scriptSig
, true)
11916 // Re-classify if scriptHash
11917 if (prevOutType
=== 'scripthash') {
11918 redeemScript
= Script
.fromBuffer(scriptSig
.chunks
.slice(-1)[0])
11919 prevOutScript
= scripts
.scriptHashOutput(redeemScript
.getHash())
11921 scriptSig
= Script
.fromChunks(scriptSig
.chunks
.slice(0, -1))
11922 scriptType
= scripts
.classifyInput(scriptSig
, true)
11924 scriptType
= prevOutType
11927 // Extract hashType, pubKeys and signatures
11928 var hashType
, parsed
, pubKeys
, signatures
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()
11942 parsed
= ECSignature
.parseScriptSignature(scriptSig
.chunks
[0])
11943 hashType
= parsed
.hashType
11944 signatures
= [parsed
.signature
]
11946 if (redeemScript
) {
11947 pubKeys
= [ECPubKey
.fromBuffer(redeemScript
.chunks
[0])]
11954 signatures
= scriptSig
.chunks
.slice(1).map(function (chunk
) {
11955 if (chunk
=== ops
.OP_0
) return chunk
11957 var parsed
= ECSignature
.parseScriptSignature(chunk
)
11958 hashType
= parsed
.hashType
11960 return parsed
.signature
11963 if (redeemScript
) {
11964 pubKeys
= redeemScript
.chunks
.slice(1, -2).map(ECPubKey
.fromBuffer
)
11972 hashType: hashType
,
11973 prevOutScript: prevOutScript
,
11974 prevOutType: prevOutType
,
11976 redeemScript: redeemScript
,
11977 scriptType: scriptType
,
11978 signatures: signatures
11982 function TransactionBuilder () {
11983 this.prevTxMap
= {}
11984 this.prevOutScripts
= {}
11985 this.prevOutTypes
= {}
11988 this.tx
= new Transaction()
11991 TransactionBuilder
.fromTransaction = function (transaction
) {
11992 var txb
= new TransactionBuilder()
11994 // Copy other transaction fields
11995 txb
.tx
.version
= transaction
.version
11996 txb
.tx
.locktime
= transaction
.locktime
11998 // Extract/add inputs
11999 transaction
.ins
.forEach(function (txIn
) {
12000 txb
.addInput(txIn
.hash
, txIn
.index
, txIn
.sequence
)
12003 // Extract/add outputs
12004 transaction
.outs
.forEach(function (txOut
) {
12005 txb
.addOutput(txOut
.script
, txOut
.value
)
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')
12013 // Ignore empty scripts
12014 if (txIn
.script
.buffer
.length
=== 0) return {}
12016 return extractInput(txIn
)
12022 TransactionBuilder
.prototype.addInput = function (prevTx
, index
, sequence
, prevOutScript
) {
12026 if (typeof prevTx
=== 'string') {
12027 prevOutHash
= new Buffer(prevTx
, 'hex')
12029 // TxId hex is big-endian, we want little-endian hash
12030 Array
.prototype.reverse
.call(prevOutHash
)
12033 } else if (prevTx
instanceof Transaction
) {
12034 prevOutHash
= prevTx
.getHash()
12035 prevOutScript
= prevTx
.outs
[index
].script
12039 prevOutHash
= prevTx
12043 if (prevOutScript
) {
12044 var prevOutType
= scripts
.classifyOutput(prevOutScript
)
12046 // if we can, extract pubKey information
12047 switch (prevOutType
) {
12049 input
.pubKeys
= prevOutScript
.chunks
.slice(1, -2).map(ECPubKey
.fromBuffer
)
12054 input
.pubKeys
= prevOutScript
.chunks
.slice(0, 1).map(ECPubKey
.fromBuffer
)
12059 if (prevOutType
!== 'scripthash') {
12060 input
.scriptType
= prevOutType
12063 input
.prevOutScript
= prevOutScript
12064 input
.prevOutType
= prevOutType
12067 assert(this.inputs
.every(function (input2
) {
12068 if (input2
.hashType
=== undefined) return true
12070 return input2
.hashType
& Transaction
.SIGHASH_ANYONECANPAY
12071 }), 'No, this would invalidate signatures')
12073 var prevOut
= prevOutHash
.toString('hex') + ':' + index
12074 assert(!(prevOut
in this.prevTxMap
), 'Transaction is already an input')
12076 var vin
= this.tx
.addInput(prevOutHash
, index
, sequence
)
12077 this.inputs
[vin
] = input
12078 this.prevTxMap
[prevOut
] = vin
12083 TransactionBuilder
.prototype.addOutput = function (scriptPubKey
, value
) {
12084 assert(this.inputs
.every(function (input
) {
12085 if (input
.hashType
=== undefined) return true
12087 return (input
.hashType
& 0x1f) === Transaction
.SIGHASH_SINGLE
12088 }), 'No, this would invalidate signatures')
12090 return this.tx
.addOutput(scriptPubKey
, value
)
12093 TransactionBuilder
.prototype.build = function () {
12094 return this.__build(false)
12096 TransactionBuilder
.prototype.buildIncomplete = function () {
12097 return this.__build(true)
12100 var canSignTypes
= {
12101 'pubkeyhash': true,
12106 TransactionBuilder
.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')
12112 var tx
= this.tx
.clone()
12114 // Create script signatures from signature meta-data
12115 this.inputs
.forEach(function (input
, index
) {
12116 var scriptType
= input
.scriptType
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')
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])
12134 // Array.prototype.map is sparse-compatible
12135 var msSignatures
= input
.signatures
.map(function (signature
) {
12136 return signature
&& signature
.toScriptSignature(input
.hashType
)
12139 // fill in blanks with OP_0
12140 if (allowIncomplete
) {
12141 for (var i
= 0; i
< msSignatures
.length
; ++i
) {
12142 if (msSignatures
[i
]) continue
12144 msSignatures
[i
] = ops
.OP_0
12147 // Array.prototype.filter returns non-sparse array
12148 msSignatures
= msSignatures
.filter(function (x
) { return x
})
12151 var redeemScript
= allowIncomplete
? undefined : input
.redeemScript
12152 scriptSig
= scripts
.multisigInput(msSignatures
, redeemScript
)
12157 var pkSignature
= input
.signatures
[0].toScriptSignature(input
.hashType
)
12158 scriptSig
= scripts
.pubKeyInput(pkSignature
)
12164 // did we build a scriptSig?
12166 // wrap as scriptHash if necessary
12167 if (input
.prevOutType
=== 'scripthash') {
12168 scriptSig
= scripts
.scriptHashInput(scriptSig
, input
.redeemScript
)
12171 tx
.setInputScript(index
, scriptSig
)
12178 TransactionBuilder
.prototype.sign = function (index
, privKey
, redeemScript
, hashType
) {
12179 assert(index
in this.inputs
, 'No input at index: ' + index
)
12180 hashType
= hashType
|| Transaction
.SIGHASH_ALL
12182 var input
= this.inputs
[index
]
12183 var canSign
= input
.hashType
&&
12184 input
.prevOutScript
&&
12185 input
.prevOutType
&&
12187 input
.scriptType
&&
12190 // are we almost ready to sign?
12192 // if redeemScript was provided, enforce consistency
12193 if (redeemScript
) {
12194 assert
.deepEqual(input
.redeemScript
, redeemScript
, 'Inconsistent redeemScript')
12197 assert
.equal(input
.hashType
, hashType
, 'Inconsistent hashType')
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')
12207 var scriptHash
= input
.prevOutScript
.chunks
[1]
12208 assert
.deepEqual(scriptHash
, redeemScript
.getHash(), 'RedeemScript does not match ' + scriptHash
.toString('hex'))
12211 var scriptType
= scripts
.classifyOutput(redeemScript
)
12212 assert(scriptType
in canSignTypes
, 'RedeemScript not supported (' + scriptType
+ ')')
12215 switch (scriptType
) {
12217 pubKeys
= redeemScript
.chunks
.slice(1, -2).map(ECPubKey
.fromBuffer
)
12221 case 'pubkeyhash': {
12222 var pkh1
= redeemScript
.chunks
[2]
12223 var pkh2
= privKey
.pub
.getAddress().hash
12225 assert
.deepEqual(pkh1
, pkh2
, 'privateKey cannot sign for this input')
12226 pubKeys
= [privKey
.pub
]
12231 pubKeys
= redeemScript
.chunks
.slice(0, 1).map(ECPubKey
.fromBuffer
)
12236 if (!input
.prevOutScript
) {
12237 input
.prevOutScript
= scripts
.scriptHashOutput(redeemScript
.getHash())
12238 input
.prevOutType
= 'scripthash'
12241 input
.pubKeys
= pubKeys
12242 input
.redeemScript
= redeemScript
12243 input
.scriptType
= scriptType
12245 // cannot be pay-to-scriptHash
12247 assert
.notEqual(input
.prevOutType
, 'scripthash', 'PrevOutScript is P2SH, missing redeemScript')
12249 // can we otherwise sign this?
12250 if (input
.scriptType
) {
12251 assert(input
.pubKeys
, input
.scriptType
+ ' not supported')
12253 // we know nothin' Jon Snow, assume pubKeyHash
12255 input
.prevOutScript
= privKey
.pub
.getAddress().toOutputScript()
12256 input
.prevOutType
= 'pubkeyhash'
12257 input
.pubKeys
= [privKey
.pub
]
12258 input
.scriptType
= input
.prevOutType
12262 input
.hashType
= hashType
12263 input
.signatures
= input
.signatures
|| []
12266 var signatureScript
= input
.redeemScript
|| input
.prevOutScript
12267 var signatureHash
= this.tx
.hashForSignature(index
, signatureScript
, hashType
)
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()
12274 input
.signatures
= input
.pubKeys
.map(function (pubKey
) {
12277 // check for any matching signatures
12278 unmatched
.some(function (signature
, i
) {
12279 if (!pubKey
.verify(signatureHash
, signature
)) return false
12282 // remove matched signature from unmatched
12283 unmatched
.splice(i
, 1)
12288 return match
|| undefined
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
12296 assert(!input
.signatures
[i
], 'Signature already exists')
12297 var signature
= privKey
.sign(signatureHash
)
12298 input
.signatures
[i
] = signature
12301 }, this), 'privateKey cannot sign for this input')
12304 module
.exports
= TransactionBuilder
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
){
12309 var assert
= require('assert')
12310 var bufferutils
= require('./bufferutils')
12311 var typeForce
= require('typeforce')
12312 var networks
= require('./networks')
12313 var randomBytes
= require('randombytes')
12315 var Address
= require('./address')
12316 var HDNode
= require('./hdnode')
12317 var TransactionBuilder
= require('./transaction_builder')
12318 var Script
= require('./script')
12320 function Wallet (seed
, network
) {
12321 console
.warn('Wallet is deprecated and will be removed in 2.0.0, see #296')
12323 seed
= seed
|| randomBytes(32)
12324 network
= network
|| networks
.bitcoin
12326 // Stored in a closure to make accidental serialization less likely
12327 var masterKey
= HDNode
.fromSeedBuffer(seed
, network
)
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)
12335 this.addresses
= []
12336 this.changeAddresses
= []
12337 this.network
= network
12340 // FIXME: remove in 2.0.0
12341 this.unspentMap
= {}
12343 // FIXME: remove in 2.0.0
12345 this.newMasterKey = function (seed
) {
12346 console
.warn('newMasterKey is deprecated, please make a new Wallet instance instead')
12348 seed
= seed
|| randomBytes(32)
12349 masterKey
= HDNode
.fromSeedBuffer(seed
, network
)
12351 accountZero
= masterKey
.deriveHardened(0)
12352 externalAccount
= accountZero
.derive(0)
12353 internalAccount
= accountZero
.derive(1)
12356 me
.changeAddresses
= []
12362 this.getMasterKey = function () {
12365 this.getAccountZero = function () {
12368 this.getExternalAccount = function () {
12369 return externalAccount
12371 this.getInternalAccount = function () {
12372 return internalAccount
12376 Wallet
.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')
12383 fixedFee: arguments
[2],
12384 changeAddress: arguments
[3]
12389 options
= options
|| {}
12391 assert(value
> this.network
.dustThreshold
, value
+ ' must be above dust threshold (' + this.network
.dustThreshold
+ ' Satoshis)')
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
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
12408 var subTotal
= value
12410 var txb
= new TransactionBuilder()
12411 txb
.addOutput(to
, value
)
12413 for (var i
= 0; i
< unspents
.length
; ++i
) {
12414 var unspent
= unspents
[i
]
12415 addresses
.push(unspent
.address
)
12417 txb
.addInput(unspent
.txHash
, unspent
.index
)
12419 var fee
= fixedFee
=== undefined ? estimatePaddedFee(txb
.buildIncomplete(), this.network
) : fixedFee
12421 accum
+= unspent
.value
12422 subTotal
= value
+ fee
12424 if (accum
>= subTotal
) {
12425 var change
= accum
- subTotal
12427 if (change
> this.network
.dustThreshold
) {
12428 txb
.addOutput(changeAddress
|| this.getChangeAddress(), change
)
12435 assert(accum
>= subTotal
, 'Not enough funds (incl. fee): ' + accum
+ ' < ' + subTotal
)
12437 return this.signWith(txb
, addresses
).build()
12440 // FIXME: remove in 2.0.0
12441 Wallet
.prototype.processPendingTx = function (tx
) {
12442 this.__processTx(tx
, true)
12445 // FIXME: remove in 2.0.0
12446 Wallet
.prototype.processConfirmedTx = function (tx
) {
12447 this.__processTx(tx
, false)
12450 // FIXME: remove in 2.0.0
12451 Wallet
.prototype.__processTx = function (tx
, isPending
) {
12452 console
.warn('processTransaction is considered harmful, see issue #260 for more information')
12454 var txId
= tx
.getId()
12455 var txHash
= tx
.getHash()
12457 tx
.outs
.forEach(function (txOut
, i
) {
12461 address
= Address
.fromOutputScript(txOut
.script
, this.network
).toString()
12463 if (!(e
.message
.match(/has no matching Address
/)))
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
12472 // its unique, add it
12475 confirmations: 0, // no way to determine this without more information
12479 value: txOut
.value
,
12483 this.unspentMap
[lookup
] = unspent
12484 this.unspents
.push(unspent
)
12488 tx
.ins
.forEach(function (txIn
) {
12489 // copy and convert to big-endian hex
12490 var txInId
= bufferutils
.reverse(txIn
.hash
).toString('hex')
12492 var lookup
= txInId
+ ':' + txIn
.index
12493 if (!(lookup
in this.unspentMap
)) return
12495 var unspent
= this.unspentMap
[lookup
]
12498 unspent
.pending
= true
12499 unspent
.spent
= true
12501 delete this.unspentMap
[lookup
]
12503 this.unspents
= this.unspents
.filter(function (unspent2
) {
12504 return unspent
!== unspent2
12510 Wallet
.prototype.generateAddress = function () {
12511 var k
= this.addresses
.length
12512 var address
= this.getExternalAccount().derive(k
).getAddress()
12514 this.addresses
.push(address
.toString())
12516 return this.getReceiveAddress()
12519 Wallet
.prototype.generateChangeAddress = function () {
12520 var k
= this.changeAddresses
.length
12521 var address
= this.getInternalAccount().derive(k
).getAddress()
12523 this.changeAddresses
.push(address
.toString())
12525 return this.getChangeAddress()
12528 Wallet
.prototype.getAddress = function () {
12529 if (this.addresses
.length
=== 0) {
12530 this.generateAddress()
12533 return this.addresses
[this.addresses
.length
- 1]
12536 Wallet
.prototype.getBalance = function (minConf
) {
12537 minConf
= minConf
|| 0
12539 return this.unspents
.filter(function (unspent
) {
12540 return unspent
.confirmations
>= minConf
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
12550 Wallet
.prototype.getChangeAddress = function () {
12551 if (this.changeAddresses
.length
=== 0) {
12552 this.generateChangeAddress()
12555 return this.changeAddresses
[this.changeAddresses
.length
- 1]
12558 Wallet
.prototype.getInternalPrivateKey = function (index
) {
12559 return this.getInternalAccount().derive(index
).privKey
12562 Wallet
.prototype.getPrivateKey = function (index
) {
12563 return this.getExternalAccount().derive(index
).privKey
12566 Wallet
.prototype.getPrivateKeyForAddress = function (address
) {
12569 if ((index
= this.addresses
.indexOf(address
)) > -1) {
12570 return this.getPrivateKey(index
)
12573 if ((index
= this.changeAddresses
.indexOf(address
)) > -1) {
12574 return this.getInternalPrivateKey(index
)
12577 assert(false, 'Unknown address. Make sure the address is from the keychain and has been generated')
12580 Wallet
.prototype.getUnspentOutputs = function (minConf
) {
12581 minConf
= minConf
|| 0
12583 return this.unspents
.filter(function (unspent
) {
12584 return unspent
.confirmations
>= minConf
12586 // FIXME: remove spent filter in 2.0.0
12587 }).filter(function (unspent
) {
12588 return !unspent
.spent
12589 }).map(function (unspent
) {
12591 address: unspent
.address
,
12592 confirmations: unspent
.confirmations
,
12593 index: unspent
.index
,
12594 txId: unspent
.txId
,
12595 value: unspent
.value
,
12597 // FIXME: remove in 2.0.0
12598 hash: unspent
.txId
,
12599 pending: unspent
.pending
12604 Wallet
.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
12611 // FIXME: remove in 2.0.0
12612 if (unspent
.hash
!== undefined) {
12613 console
.warn('unspent.hash is deprecated, use unspent.txId instead')
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
12622 typeForce('String', txId
)
12623 typeForce('Number', index
)
12624 typeForce('Number', unspent
.value
)
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
)
12632 // FIXME: remove branch in 2.0.0
12633 if (unspent
.confirmations
!== undefined) {
12634 typeForce('Number', unspent
.confirmations
)
12637 var txHash
= bufferutils
.reverse(new Buffer(txId
, 'hex'))
12640 address: unspent
.address
,
12641 confirmations: unspent
.confirmations
|| 0,
12645 value: unspent
.value
,
12647 // FIXME: remove in 2.0.0
12648 pending: unspent
.pending
|| false
12651 // FIXME: remove in 2.0.0
12652 this.unspentMap
[txId
+ ':' + index
] = unspent
12658 Wallet
.prototype.signWith = function (tx
, addresses
) {
12659 addresses
.forEach(function (address
, i
) {
12660 var privKey
= this.getPrivateKeyForAddress(address
)
12662 tx
.sign(i
, privKey
)
12668 function estimatePaddedFee (tx
, network
) {
12669 var tmpTx
= tx
.clone()
12670 tmpTx
.addOutput(Script
.EMPTY
, network
.dustSoftThreshold
|| 0)
12672 return network
.estimateFee(tmpTx
)
12675 // FIXME: 1.0.0 shims, remove in 2.0.0
12676 Wallet
.prototype.getReceiveAddress
= Wallet
.prototype.getAddress
12677 Wallet
.prototype.createTx
= Wallet
.prototype.createTransaction
12679 module
.exports
= Wallet
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)