aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIan Coleman <coleman.ian@gmail.com>2017-08-05 15:14:45 +1000
committerIan Coleman <coleman.ian@gmail.com>2017-08-05 15:14:45 +1000
commit9987f0c184d6a29fb6073b99abe3473ffabf7c69 (patch)
treee3f1e405f21a5f34d0191c73bc21bf1acb753985
parentd2fea262c3ef16b2230c4f3db6ff13899bf10dc3 (diff)
downloadBIP39-9987f0c184d6a29fb6073b99abe3473ffabf7c69.tar.gz
BIP39-9987f0c184d6a29fb6073b99abe3473ffabf7c69.tar.zst
BIP39-9987f0c184d6a29fb6073b99abe3473ffabf7c69.zip
Release v0.2.0
-rw-r--r--bip39-standalone.html17392
-rw-r--r--changelog.md9
-rw-r--r--src/index.html2
3 files changed, 9924 insertions, 7479 deletions
diff --git a/bip39-standalone.html b/bip39-standalone.html
index 07c61f2..ea27a1f 100644
--- a/bip39-standalone.html
+++ b/bip39-standalone.html
@@ -118,7 +118,7 @@
118 <div class="container"> 118 <div class="container">
119 119
120 <h1 class="text-center">Mnemonic Code Converter</h1> 120 <h1 class="text-center">Mnemonic Code Converter</h1>
121 <p class="version">v0.1.2</p> 121 <p class="version">v0.2.0</p>
122 <hr> 122 <hr>
123 <div class="row"> 123 <div class="row">
124 <div class="col-md-12"> 124 <div class="col-md-12">
@@ -280,11 +280,14 @@
280 <div class="col-md-12"> 280 <div class="col-md-12">
281 <h2>Derivation Path</h2> 281 <h2>Derivation Path</h2>
282 <ul class="derivation-type nav nav-tabs" role="tablist"> 282 <ul class="derivation-type nav nav-tabs" role="tablist">
283 <li id="bip32-tab">
284 <a href="#bip32" role="tab" data-toggle="tab">BIP32</a>
285 </li>
283 <li id="bip44-tab" class="active"> 286 <li id="bip44-tab" class="active">
284 <a href="#bip44" role="tab" data-toggle="tab">BIP44</a> 287 <a href="#bip44" role="tab" data-toggle="tab">BIP44</a>
285 </li> 288 </li>
286 <li id="bip32-tab"> 289 <li id="bip49-tab">
287 <a href="#bip32" role="tab" data-toggle="tab">BIP32</a> 290 <a href="#bip49" role="tab" data-toggle="tab">BIP49</a>
288 </li> 291 </li>
289 </ul> 292 </ul>
290 <div class="derivation-type tab-content"> 293 <div class="derivation-type tab-content">
@@ -303,7 +306,7 @@
303 <a href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#purpose" target="_blank" data-translate>Purpose</a> 306 <a href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#purpose" target="_blank" data-translate>Purpose</a>
304 </label> 307 </label>
305 <div class="col-sm-10"> 308 <div class="col-sm-10">
306 <input id="purpose" type="text" class="purpose form-control" value="44"> 309 <input id="purpose" type="text" class="purpose form-control" value="44" readonly>
307 </div> 310 </div>
308 </div> 311 </div>
309 <div class="form-group"> 312 <div class="form-group">
@@ -311,7 +314,7 @@
311 <a href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#registered-coin-types" target="_blank" data-translate>Coin</a> 314 <a href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#registered-coin-types" target="_blank" data-translate>Coin</a>
312 </label> 315 </label>
313 <div class="col-sm-10"> 316 <div class="col-sm-10">
314 <input id="coin" type="text" class="coin form-control" value="0"> 317 <input id="coin" type="text" class="coin form-control" value="0" readonly>
315 </div> 318 </div>
316 </div> 319 </div>
317 <div class="form-group"> 320 <div class="form-group">
@@ -439,6 +442,96 @@
439 </div> 442 </div>
440 </form> 443 </form>
441 </div> 444 </div>
445 <div id="bip49" class="tab-pane">
446 <form class="form-horizontal" role="form">
447 <br>
448 <div class="unavailable hidden">
449 <div class="form-group">
450 <div class="col-sm-2"></div>
451 <div class="col-sm-10">
452 <p data-translate>BIP49 is unavailable for this coin.</p>
453 </div>
454 </div>
455 </div>
456 <div class="available">
457 <div class="col-sm-2"></div>
458 <div class="col-sm-10">
459 <p data-translate-html>
460 For more info see the
461 <a href="https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki" target="_blank">BIP49 spec</a>.
462 </p>
463 </div>
464 <div class="form-group">
465 <label for="purpose" class="col-sm-2 control-label">
466 <a href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#purpose" target="_blank" data-translate>Purpose</a>
467 </label>
468 <div class="col-sm-10">
469 <input id="purpose" type="text" class="purpose form-control" value="49" readonly>
470 </div>
471 </div>
472 <div class="form-group">
473 <label for="coin" class="col-sm-2 control-label">
474 <a href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#registered-coin-types" target="_blank" data-translate>Coin</a>
475 </label>
476 <div class="col-sm-10">
477 <input id="coin" type="text" class="coin form-control" value="0" readonly>
478 </div>
479 </div>
480 <div class="form-group">
481 <label for="account" class="col-sm-2 control-label">
482 <a href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#account" target="_blank" data-translate>Account</a>
483 </label>
484 <div class="col-sm-10">
485 <input id="account" type="text" class="account form-control" value="0">
486 </div>
487 </div>
488 <div class="form-group">
489 <label for="change" class="col-sm-2 control-label">
490 <a href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#change" target="_blank" data-translate>External / Internal</a>
491 </label>
492 <div class="col-sm-10">
493 <input id="change" type="text" class="change form-control" value="0">
494 </div>
495 </div>
496 <div class="form-group">
497 <label class="col-sm-2 control-label">
498 </label>
499 <div class="col-sm-10">
500 <p data-translate>The account extended keys can be used for importing to most BIP49 compatible wallets.</p>
501 </div>
502 </div>
503 <div class="form-group">
504 <label for="account-xprv" class="col-sm-2 control-label">
505 <span data-translate>Account Extended Private Key</span>
506 </label>
507 <div class="col-sm-10">
508 <textarea id="account-xprv" type="text" class="account-xprv form-control" readonly data-show-qr></textarea>
509 </div>
510 </div>
511 <div class="form-group">
512 <label for="account-xpub" class="col-sm-2 control-label">
513 <span data-translate>Account Extended Public Key</span>
514 </label>
515 <div class="col-sm-10">
516 <textarea id="account-xpub" type="text" class="account-xpub form-control" readonly data-show-qr></textarea>
517 </div>
518 </div>
519 <div class="form-group">
520 <label class="col-sm-2 control-label">
521 </label>
522 <div class="col-sm-10">
523 <p data-translate>The BIP32 derivation path and extended keys are the basis for the derived addresses.</p>
524 </div>
525 </div>
526 <div class="form-group">
527 <label for="bip49-path" class="col-sm-2 control-label" data-translate>BIP32 Derivation Path</label>
528 <div class="col-sm-10">
529 <input id="bip49-path" type="text" class="path form-control" value="m/49'/0'/0'/0" readonly="readonly">
530 </div>
531 </div>
532 </div>
533 </form>
534 </div>
442 </div> 535 </div>
443 <form class="form-horizontal" role="form"> 536 <form class="form-horizontal" role="form">
444 <div class="form-group"> 537 <div class="form-group">
@@ -7182,1712 +7275,52 @@ correctLevel:2,background:"#ffffff",foreground:"#000000"},h);return this.each(fu
7182j=Math.ceil((f+1)*b)-Math.floor(f*b);d.fillRect(Math.round(i*b),Math.round(f*e),g,j)}}else{a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();c=r("<table></table>").css("width",h.width+"px").css("height",h.height+"px").css("border","0px").css("border-collapse","collapse").css("background-color",h.background);d=h.width/a.getModuleCount();b=h.height/a.getModuleCount();for(e=0;e<a.getModuleCount();e++){f=r("<tr></tr>").css("height",b+"px").appendTo(c);for(i=0;i<a.getModuleCount();i++)r("<td></td>").css("width", 7275j=Math.ceil((f+1)*b)-Math.floor(f*b);d.fillRect(Math.round(i*b),Math.round(f*e),g,j)}}else{a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();c=r("<table></table>").css("width",h.width+"px").css("height",h.height+"px").css("border","0px").css("border-collapse","collapse").css("background-color",h.background);d=h.width/a.getModuleCount();b=h.height/a.getModuleCount();for(e=0;e<a.getModuleCount();e++){f=r("<tr></tr>").css("height",b+"px").appendTo(c);for(i=0;i<a.getModuleCount();i++)r("<td></td>").css("width",
7183d+"px").css("background-color",a.isDark(e,i)?h.foreground:h.background).appendTo(f)}}a=c;$(a).appendTo(this)})}})($); 7276d+"px").css("background-color",a.isDark(e,i)?h.foreground:h.background).appendTo(f)}}a=c;$(a).appendTo(this)})}})($);
7184</script> 7277</script>
7185 <script>(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){ 7278 <script>(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.bitcoinjs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
7186// (public) Constructor 7279(function (global){
7187function BigInteger(a, b, c) { 7280'use strict';
7188 if (!(this instanceof BigInteger))
7189 return new BigInteger(a, b, c)
7190
7191 if (a != null) {
7192 if ("number" == typeof a) this.fromNumber(a, b, c)
7193 else if (b == null && "string" != typeof a) this.fromString(a, 256)
7194 else this.fromString(a, b)
7195 }
7196}
7197
7198var proto = BigInteger.prototype
7199
7200// duck-typed isBigInteger
7201proto.__bigi = require('../package.json').version
7202BigInteger.isBigInteger = function (obj, check_ver) {
7203 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
7204}
7205
7206// Bits per digit
7207var dbits
7208
7209// am: Compute w_j += (x*this_i), propagate carries,
7210// c is initial carry, returns final carry.
7211// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
7212// We need to select the fastest one that works in this environment.
7213
7214// am1: use a single mult and divide to get the high bits,
7215// max digit bits should be 26 because
7216// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
7217function am1(i, x, w, j, c, n) {
7218 while (--n >= 0) {
7219 var v = x * this[i++] + w[j] + c
7220 c = Math.floor(v / 0x4000000)
7221 w[j++] = v & 0x3ffffff
7222 }
7223 return c
7224}
7225// am2 avoids a big mult-and-extract completely.
7226// Max digit bits should be <= 30 because we do bitwise ops
7227// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
7228function am2(i, x, w, j, c, n) {
7229 var xl = x & 0x7fff,
7230 xh = x >> 15
7231 while (--n >= 0) {
7232 var l = this[i] & 0x7fff
7233 var h = this[i++] >> 15
7234 var m = xh * l + h * xl
7235 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
7236 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
7237 w[j++] = l & 0x3fffffff
7238 }
7239 return c
7240}
7241// Alternately, set max digit bits to 28 since some
7242// browsers slow down when dealing with 32-bit numbers.
7243function am3(i, x, w, j, c, n) {
7244 var xl = x & 0x3fff,
7245 xh = x >> 14
7246 while (--n >= 0) {
7247 var l = this[i] & 0x3fff
7248 var h = this[i++] >> 14
7249 var m = xh * l + h * xl
7250 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
7251 c = (l >> 28) + (m >> 14) + xh * h
7252 w[j++] = l & 0xfffffff
7253 }
7254 return c
7255}
7256
7257// wtf?
7258BigInteger.prototype.am = am1
7259dbits = 26
7260
7261BigInteger.prototype.DB = dbits
7262BigInteger.prototype.DM = ((1 << dbits) - 1)
7263var DV = BigInteger.prototype.DV = (1 << dbits)
7264
7265var BI_FP = 52
7266BigInteger.prototype.FV = Math.pow(2, BI_FP)
7267BigInteger.prototype.F1 = BI_FP - dbits
7268BigInteger.prototype.F2 = 2 * dbits - BI_FP
7269
7270// Digit conversions
7271var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
7272var BI_RC = new Array()
7273var rr, vv
7274rr = "0".charCodeAt(0)
7275for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
7276rr = "a".charCodeAt(0)
7277for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
7278rr = "A".charCodeAt(0)
7279for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
7280
7281function int2char(n) {
7282 return BI_RM.charAt(n)
7283}
7284
7285function intAt(s, i) {
7286 var c = BI_RC[s.charCodeAt(i)]
7287 return (c == null) ? -1 : c
7288}
7289
7290// (protected) copy this to r
7291function bnpCopyTo(r) {
7292 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
7293 r.t = this.t
7294 r.s = this.s
7295}
7296
7297// (protected) set from integer value x, -DV <= x < DV
7298function bnpFromInt(x) {
7299 this.t = 1
7300 this.s = (x < 0) ? -1 : 0
7301 if (x > 0) this[0] = x
7302 else if (x < -1) this[0] = x + DV
7303 else this.t = 0
7304}
7305
7306// return bigint initialized to value
7307function nbv(i) {
7308 var r = new BigInteger()
7309 r.fromInt(i)
7310 return r
7311}
7312
7313// (protected) set from string and radix
7314function bnpFromString(s, b) {
7315 var self = this
7316
7317 var k
7318 if (b == 16) k = 4
7319 else if (b == 8) k = 3
7320 else if (b == 256) k = 8; // byte array
7321 else if (b == 2) k = 1
7322 else if (b == 32) k = 5
7323 else if (b == 4) k = 2
7324 else {
7325 self.fromRadix(s, b)
7326 return
7327 }
7328 self.t = 0
7329 self.s = 0
7330 var i = s.length,
7331 mi = false,
7332 sh = 0
7333 while (--i >= 0) {
7334 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
7335 if (x < 0) {
7336 if (s.charAt(i) == "-") mi = true
7337 continue
7338 }
7339 mi = false
7340 if (sh == 0)
7341 self[self.t++] = x
7342 else if (sh + k > self.DB) {
7343 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
7344 self[self.t++] = (x >> (self.DB - sh))
7345 } else
7346 self[self.t - 1] |= x << sh
7347 sh += k
7348 if (sh >= self.DB) sh -= self.DB
7349 }
7350 if (k == 8 && (s[0] & 0x80) != 0) {
7351 self.s = -1
7352 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
7353 }
7354 self.clamp()
7355 if (mi) BigInteger.ZERO.subTo(self, self)
7356}
7357
7358// (protected) clamp off excess high words
7359function bnpClamp() {
7360 var c = this.s & this.DM
7361 while (this.t > 0 && this[this.t - 1] == c)--this.t
7362}
7363
7364// (public) return string representation in given radix
7365function bnToString(b) {
7366 var self = this
7367 if (self.s < 0) return "-" + self.negate()
7368 .toString(b)
7369 var k
7370 if (b == 16) k = 4
7371 else if (b == 8) k = 3
7372 else if (b == 2) k = 1
7373 else if (b == 32) k = 5
7374 else if (b == 4) k = 2
7375 else return self.toRadix(b)
7376 var km = (1 << k) - 1,
7377 d, m = false,
7378 r = "",
7379 i = self.t
7380 var p = self.DB - (i * self.DB) % k
7381 if (i-- > 0) {
7382 if (p < self.DB && (d = self[i] >> p) > 0) {
7383 m = true
7384 r = int2char(d)
7385 }
7386 while (i >= 0) {
7387 if (p < k) {
7388 d = (self[i] & ((1 << p) - 1)) << (k - p)
7389 d |= self[--i] >> (p += self.DB - k)
7390 } else {
7391 d = (self[i] >> (p -= k)) & km
7392 if (p <= 0) {
7393 p += self.DB
7394 --i
7395 }
7396 }
7397 if (d > 0) m = true
7398 if (m) r += int2char(d)
7399 }
7400 }
7401 return m ? r : "0"
7402}
7403
7404// (public) -this
7405function bnNegate() {
7406 var r = new BigInteger()
7407 BigInteger.ZERO.subTo(this, r)
7408 return r
7409}
7410
7411// (public) |this|
7412function bnAbs() {
7413 return (this.s < 0) ? this.negate() : this
7414}
7415
7416// (public) return + if this > a, - if this < a, 0 if equal
7417function bnCompareTo(a) {
7418 var r = this.s - a.s
7419 if (r != 0) return r
7420 var i = this.t
7421 r = i - a.t
7422 if (r != 0) return (this.s < 0) ? -r : r
7423 while (--i >= 0)
7424 if ((r = this[i] - a[i]) != 0) return r
7425 return 0
7426}
7427
7428// returns bit length of the integer x
7429function nbits(x) {
7430 var r = 1,
7431 t
7432 if ((t = x >>> 16) != 0) {
7433 x = t
7434 r += 16
7435 }
7436 if ((t = x >> 8) != 0) {
7437 x = t
7438 r += 8
7439 }
7440 if ((t = x >> 4) != 0) {
7441 x = t
7442 r += 4
7443 }
7444 if ((t = x >> 2) != 0) {
7445 x = t
7446 r += 2
7447 }
7448 if ((t = x >> 1) != 0) {
7449 x = t
7450 r += 1
7451 }
7452 return r
7453}
7454
7455// (public) return the number of bits in "this"
7456function bnBitLength() {
7457 if (this.t <= 0) return 0
7458 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
7459}
7460
7461// (public) return the number of bytes in "this"
7462function bnByteLength() {
7463 return this.bitLength() >> 3
7464}
7465
7466// (protected) r = this << n*DB
7467function bnpDLShiftTo(n, r) {
7468 var i
7469 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
7470 for (i = n - 1; i >= 0; --i) r[i] = 0
7471 r.t = this.t + n
7472 r.s = this.s
7473}
7474
7475// (protected) r = this >> n*DB
7476function bnpDRShiftTo(n, r) {
7477 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
7478 r.t = Math.max(this.t - n, 0)
7479 r.s = this.s
7480}
7481
7482// (protected) r = this << n
7483function bnpLShiftTo(n, r) {
7484 var self = this
7485 var bs = n % self.DB
7486 var cbs = self.DB - bs
7487 var bm = (1 << cbs) - 1
7488 var ds = Math.floor(n / self.DB),
7489 c = (self.s << bs) & self.DM,
7490 i
7491 for (i = self.t - 1; i >= 0; --i) {
7492 r[i + ds + 1] = (self[i] >> cbs) | c
7493 c = (self[i] & bm) << bs
7494 }
7495 for (i = ds - 1; i >= 0; --i) r[i] = 0
7496 r[ds] = c
7497 r.t = self.t + ds + 1
7498 r.s = self.s
7499 r.clamp()
7500}
7501
7502// (protected) r = this >> n
7503function bnpRShiftTo(n, r) {
7504 var self = this
7505 r.s = self.s
7506 var ds = Math.floor(n / self.DB)
7507 if (ds >= self.t) {
7508 r.t = 0
7509 return
7510 }
7511 var bs = n % self.DB
7512 var cbs = self.DB - bs
7513 var bm = (1 << bs) - 1
7514 r[0] = self[ds] >> bs
7515 for (var i = ds + 1; i < self.t; ++i) {
7516 r[i - ds - 1] |= (self[i] & bm) << cbs
7517 r[i - ds] = self[i] >> bs
7518 }
7519 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
7520 r.t = self.t - ds
7521 r.clamp()
7522}
7523
7524// (protected) r = this - a
7525function bnpSubTo(a, r) {
7526 var self = this
7527 var i = 0,
7528 c = 0,
7529 m = Math.min(a.t, self.t)
7530 while (i < m) {
7531 c += self[i] - a[i]
7532 r[i++] = c & self.DM
7533 c >>= self.DB
7534 }
7535 if (a.t < self.t) {
7536 c -= a.s
7537 while (i < self.t) {
7538 c += self[i]
7539 r[i++] = c & self.DM
7540 c >>= self.DB
7541 }
7542 c += self.s
7543 } else {
7544 c += self.s
7545 while (i < a.t) {
7546 c -= a[i]
7547 r[i++] = c & self.DM
7548 c >>= self.DB
7549 }
7550 c -= a.s
7551 }
7552 r.s = (c < 0) ? -1 : 0
7553 if (c < -1) r[i++] = self.DV + c
7554 else if (c > 0) r[i++] = c
7555 r.t = i
7556 r.clamp()
7557}
7558
7559// (protected) r = this * a, r != this,a (HAC 14.12)
7560// "this" should be the larger one if appropriate.
7561function bnpMultiplyTo(a, r) {
7562 var x = this.abs(),
7563 y = a.abs()
7564 var i = x.t
7565 r.t = i + y.t
7566 while (--i >= 0) r[i] = 0
7567 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
7568 r.s = 0
7569 r.clamp()
7570 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
7571}
7572
7573// (protected) r = this^2, r != this (HAC 14.16)
7574function bnpSquareTo(r) {
7575 var x = this.abs()
7576 var i = r.t = 2 * x.t
7577 while (--i >= 0) r[i] = 0
7578 for (i = 0; i < x.t - 1; ++i) {
7579 var c = x.am(i, x[i], r, 2 * i, 0, 1)
7580 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
7581 r[i + x.t] -= x.DV
7582 r[i + x.t + 1] = 1
7583 }
7584 }
7585 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
7586 r.s = 0
7587 r.clamp()
7588}
7589
7590// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
7591// r != q, this != m. q or r may be null.
7592function bnpDivRemTo(m, q, r) {
7593 var self = this
7594 var pm = m.abs()
7595 if (pm.t <= 0) return
7596 var pt = self.abs()
7597 if (pt.t < pm.t) {
7598 if (q != null) q.fromInt(0)
7599 if (r != null) self.copyTo(r)
7600 return
7601 }
7602 if (r == null) r = new BigInteger()
7603 var y = new BigInteger(),
7604 ts = self.s,
7605 ms = m.s
7606 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
7607 if (nsh > 0) {
7608 pm.lShiftTo(nsh, y)
7609 pt.lShiftTo(nsh, r)
7610 } else {
7611 pm.copyTo(y)
7612 pt.copyTo(r)
7613 }
7614 var ys = y.t
7615 var y0 = y[ys - 1]
7616 if (y0 == 0) return
7617 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
7618 var d1 = self.FV / yt,
7619 d2 = (1 << self.F1) / yt,
7620 e = 1 << self.F2
7621 var i = r.t,
7622 j = i - ys,
7623 t = (q == null) ? new BigInteger() : q
7624 y.dlShiftTo(j, t)
7625 if (r.compareTo(t) >= 0) {
7626 r[r.t++] = 1
7627 r.subTo(t, r)
7628 }
7629 BigInteger.ONE.dlShiftTo(ys, t)
7630 t.subTo(y, y); // "negative" y so we can replace sub with am later
7631 while (y.t < ys) y[y.t++] = 0
7632 while (--j >= 0) {
7633 // Estimate quotient digit
7634 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
7635 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
7636 y.dlShiftTo(j, t)
7637 r.subTo(t, r)
7638 while (r[i] < --qd) r.subTo(t, r)
7639 }
7640 }
7641 if (q != null) {
7642 r.drShiftTo(ys, q)
7643 if (ts != ms) BigInteger.ZERO.subTo(q, q)
7644 }
7645 r.t = ys
7646 r.clamp()
7647 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
7648 if (ts < 0) BigInteger.ZERO.subTo(r, r)
7649}
7650
7651// (public) this mod a
7652function bnMod(a) {
7653 var r = new BigInteger()
7654 this.abs()
7655 .divRemTo(a, null, r)
7656 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
7657 return r
7658}
7659
7660// Modular reduction using "classic" algorithm
7661function Classic(m) {
7662 this.m = m
7663}
7664
7665function cConvert(x) {
7666 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
7667 else return x
7668}
7669
7670function cRevert(x) {
7671 return x
7672}
7673
7674function cReduce(x) {
7675 x.divRemTo(this.m, null, x)
7676}
7677
7678function cMulTo(x, y, r) {
7679 x.multiplyTo(y, r)
7680 this.reduce(r)
7681}
7682
7683function cSqrTo(x, r) {
7684 x.squareTo(r)
7685 this.reduce(r)
7686}
7687
7688Classic.prototype.convert = cConvert
7689Classic.prototype.revert = cRevert
7690Classic.prototype.reduce = cReduce
7691Classic.prototype.mulTo = cMulTo
7692Classic.prototype.sqrTo = cSqrTo
7693
7694// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
7695// justification:
7696// xy == 1 (mod m)
7697// xy = 1+km
7698// xy(2-xy) = (1+km)(1-km)
7699// x[y(2-xy)] = 1-k^2m^2
7700// x[y(2-xy)] == 1 (mod m^2)
7701// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
7702// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
7703// JS multiply "overflows" differently from C/C++, so care is needed here.
7704function bnpInvDigit() {
7705 if (this.t < 1) return 0
7706 var x = this[0]
7707 if ((x & 1) == 0) return 0
7708 var y = x & 3; // y == 1/x mod 2^2
7709 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
7710 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
7711 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
7712 // last step - calculate inverse mod DV directly
7713 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
7714 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
7715 // we really want the negative inverse, and -DV < y < DV
7716 return (y > 0) ? this.DV - y : -y
7717}
7718
7719// Montgomery reduction
7720function Montgomery(m) {
7721 this.m = m
7722 this.mp = m.invDigit()
7723 this.mpl = this.mp & 0x7fff
7724 this.mph = this.mp >> 15
7725 this.um = (1 << (m.DB - 15)) - 1
7726 this.mt2 = 2 * m.t
7727}
7728
7729// xR mod m
7730function montConvert(x) {
7731 var r = new BigInteger()
7732 x.abs()
7733 .dlShiftTo(this.m.t, r)
7734 r.divRemTo(this.m, null, r)
7735 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
7736 return r
7737}
7738
7739// x/R mod m
7740function montRevert(x) {
7741 var r = new BigInteger()
7742 x.copyTo(r)
7743 this.reduce(r)
7744 return r
7745}
7746
7747// x = x/R mod m (HAC 14.32)
7748function montReduce(x) {
7749 while (x.t <= this.mt2) // pad x so am has enough room later
7750 x[x.t++] = 0
7751 for (var i = 0; i < this.m.t; ++i) {
7752 // faster way of calculating u0 = x[i]*mp mod DV
7753 var j = x[i] & 0x7fff
7754 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
7755 // use am to combine the multiply-shift-add into one call
7756 j = i + this.m.t
7757 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
7758 // propagate carry
7759 while (x[j] >= x.DV) {
7760 x[j] -= x.DV
7761 x[++j]++
7762 }
7763 }
7764 x.clamp()
7765 x.drShiftTo(this.m.t, x)
7766 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
7767}
7768
7769// r = "x^2/R mod m"; x != r
7770function montSqrTo(x, r) {
7771 x.squareTo(r)
7772 this.reduce(r)
7773}
7774
7775// r = "xy/R mod m"; x,y != r
7776function montMulTo(x, y, r) {
7777 x.multiplyTo(y, r)
7778 this.reduce(r)
7779}
7780
7781Montgomery.prototype.convert = montConvert
7782Montgomery.prototype.revert = montRevert
7783Montgomery.prototype.reduce = montReduce
7784Montgomery.prototype.mulTo = montMulTo
7785Montgomery.prototype.sqrTo = montSqrTo
7786
7787// (protected) true iff this is even
7788function bnpIsEven() {
7789 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
7790}
7791
7792// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
7793function bnpExp(e, z) {
7794 if (e > 0xffffffff || e < 1) return BigInteger.ONE
7795 var r = new BigInteger(),
7796 r2 = new BigInteger(),
7797 g = z.convert(this),
7798 i = nbits(e) - 1
7799 g.copyTo(r)
7800 while (--i >= 0) {
7801 z.sqrTo(r, r2)
7802 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
7803 else {
7804 var t = r
7805 r = r2
7806 r2 = t
7807 }
7808 }
7809 return z.revert(r)
7810}
7811
7812// (public) this^e % m, 0 <= e < 2^32
7813function bnModPowInt(e, m) {
7814 var z
7815 if (e < 256 || m.isEven()) z = new Classic(m)
7816 else z = new Montgomery(m)
7817 return this.exp(e, z)
7818}
7819
7820// protected
7821proto.copyTo = bnpCopyTo
7822proto.fromInt = bnpFromInt
7823proto.fromString = bnpFromString
7824proto.clamp = bnpClamp
7825proto.dlShiftTo = bnpDLShiftTo
7826proto.drShiftTo = bnpDRShiftTo
7827proto.lShiftTo = bnpLShiftTo
7828proto.rShiftTo = bnpRShiftTo
7829proto.subTo = bnpSubTo
7830proto.multiplyTo = bnpMultiplyTo
7831proto.squareTo = bnpSquareTo
7832proto.divRemTo = bnpDivRemTo
7833proto.invDigit = bnpInvDigit
7834proto.isEven = bnpIsEven
7835proto.exp = bnpExp
7836
7837// public
7838proto.toString = bnToString
7839proto.negate = bnNegate
7840proto.abs = bnAbs
7841proto.compareTo = bnCompareTo
7842proto.bitLength = bnBitLength
7843proto.byteLength = bnByteLength
7844proto.mod = bnMod
7845proto.modPowInt = bnModPowInt
7846
7847// (public)
7848function bnClone() {
7849 var r = new BigInteger()
7850 this.copyTo(r)
7851 return r
7852}
7853
7854// (public) return value as integer
7855function bnIntValue() {
7856 if (this.s < 0) {
7857 if (this.t == 1) return this[0] - this.DV
7858 else if (this.t == 0) return -1
7859 } else if (this.t == 1) return this[0]
7860 else if (this.t == 0) return 0
7861 // assumes 16 < DB < 32
7862 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
7863}
7864
7865// (public) return value as byte
7866function bnByteValue() {
7867 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
7868}
7869
7870// (public) return value as short (assumes DB>=16)
7871function bnShortValue() {
7872 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
7873}
7874
7875// (protected) return x s.t. r^x < DV
7876function bnpChunkSize(r) {
7877 return Math.floor(Math.LN2 * this.DB / Math.log(r))
7878}
7879
7880// (public) 0 if this == 0, 1 if this > 0
7881function bnSigNum() {
7882 if (this.s < 0) return -1
7883 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
7884 else return 1
7885}
7886
7887// (protected) convert to radix string
7888function bnpToRadix(b) {
7889 if (b == null) b = 10
7890 if (this.signum() == 0 || b < 2 || b > 36) return "0"
7891 var cs = this.chunkSize(b)
7892 var a = Math.pow(b, cs)
7893 var d = nbv(a),
7894 y = new BigInteger(),
7895 z = new BigInteger(),
7896 r = ""
7897 this.divRemTo(d, y, z)
7898 while (y.signum() > 0) {
7899 r = (a + z.intValue())
7900 .toString(b)
7901 .substr(1) + r
7902 y.divRemTo(d, y, z)
7903 }
7904 return z.intValue()
7905 .toString(b) + r
7906}
7907
7908// (protected) convert from radix string
7909function bnpFromRadix(s, b) {
7910 var self = this
7911 self.fromInt(0)
7912 if (b == null) b = 10
7913 var cs = self.chunkSize(b)
7914 var d = Math.pow(b, cs),
7915 mi = false,
7916 j = 0,
7917 w = 0
7918 for (var i = 0; i < s.length; ++i) {
7919 var x = intAt(s, i)
7920 if (x < 0) {
7921 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
7922 continue
7923 }
7924 w = b * w + x
7925 if (++j >= cs) {
7926 self.dMultiply(d)
7927 self.dAddOffset(w, 0)
7928 j = 0
7929 w = 0
7930 }
7931 }
7932 if (j > 0) {
7933 self.dMultiply(Math.pow(b, j))
7934 self.dAddOffset(w, 0)
7935 }
7936 if (mi) BigInteger.ZERO.subTo(self, self)
7937}
7938
7939// (protected) alternate constructor
7940function bnpFromNumber(a, b, c) {
7941 var self = this
7942 if ("number" == typeof b) {
7943 // new BigInteger(int,int,RNG)
7944 if (a < 2) self.fromInt(1)
7945 else {
7946 self.fromNumber(a, c)
7947 if (!self.testBit(a - 1)) // force MSB set
7948 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
7949 if (self.isEven()) self.dAddOffset(1, 0); // force odd
7950 while (!self.isProbablePrime(b)) {
7951 self.dAddOffset(2, 0)
7952 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
7953 }
7954 }
7955 } else {
7956 // new BigInteger(int,RNG)
7957 var x = new Array(),
7958 t = a & 7
7959 x.length = (a >> 3) + 1
7960 b.nextBytes(x)
7961 if (t > 0) x[0] &= ((1 << t) - 1)
7962 else x[0] = 0
7963 self.fromString(x, 256)
7964 }
7965}
7966
7967// (public) convert to bigendian byte array
7968function bnToByteArray() {
7969 var self = this
7970 var i = self.t,
7971 r = new Array()
7972 r[0] = self.s
7973 var p = self.DB - (i * self.DB) % 8,
7974 d, k = 0
7975 if (i-- > 0) {
7976 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
7977 r[k++] = d | (self.s << (self.DB - p))
7978 while (i >= 0) {
7979 if (p < 8) {
7980 d = (self[i] & ((1 << p) - 1)) << (8 - p)
7981 d |= self[--i] >> (p += self.DB - 8)
7982 } else {
7983 d = (self[i] >> (p -= 8)) & 0xff
7984 if (p <= 0) {
7985 p += self.DB
7986 --i
7987 }
7988 }
7989 if ((d & 0x80) != 0) d |= -256
7990 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
7991 if (k > 0 || d != self.s) r[k++] = d
7992 }
7993 }
7994 return r
7995}
7996
7997function bnEquals(a) {
7998 return (this.compareTo(a) == 0)
7999}
8000
8001function bnMin(a) {
8002 return (this.compareTo(a) < 0) ? this : a
8003}
8004
8005function bnMax(a) {
8006 return (this.compareTo(a) > 0) ? this : a
8007}
8008
8009// (protected) r = this op a (bitwise)
8010function bnpBitwiseTo(a, op, r) {
8011 var self = this
8012 var i, f, m = Math.min(a.t, self.t)
8013 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
8014 if (a.t < self.t) {
8015 f = a.s & self.DM
8016 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
8017 r.t = self.t
8018 } else {
8019 f = self.s & self.DM
8020 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
8021 r.t = a.t
8022 }
8023 r.s = op(self.s, a.s)
8024 r.clamp()
8025}
8026
8027// (public) this & a
8028function op_and(x, y) {
8029 return x & y
8030}
8031
8032function bnAnd(a) {
8033 var r = new BigInteger()
8034 this.bitwiseTo(a, op_and, r)
8035 return r
8036}
8037
8038// (public) this | a
8039function op_or(x, y) {
8040 return x | y
8041}
8042
8043function bnOr(a) {
8044 var r = new BigInteger()
8045 this.bitwiseTo(a, op_or, r)
8046 return r
8047}
8048
8049// (public) this ^ a
8050function op_xor(x, y) {
8051 return x ^ y
8052}
8053
8054function bnXor(a) {
8055 var r = new BigInteger()
8056 this.bitwiseTo(a, op_xor, r)
8057 return r
8058}
8059
8060// (public) this & ~a
8061function op_andnot(x, y) {
8062 return x & ~y
8063}
8064
8065function bnAndNot(a) {
8066 var r = new BigInteger()
8067 this.bitwiseTo(a, op_andnot, r)
8068 return r
8069}
8070
8071// (public) ~this
8072function bnNot() {
8073 var r = new BigInteger()
8074 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
8075 r.t = this.t
8076 r.s = ~this.s
8077 return r
8078}
8079
8080// (public) this << n
8081function bnShiftLeft(n) {
8082 var r = new BigInteger()
8083 if (n < 0) this.rShiftTo(-n, r)
8084 else this.lShiftTo(n, r)
8085 return r
8086}
8087
8088// (public) this >> n
8089function bnShiftRight(n) {
8090 var r = new BigInteger()
8091 if (n < 0) this.lShiftTo(-n, r)
8092 else this.rShiftTo(n, r)
8093 return r
8094}
8095
8096// return index of lowest 1-bit in x, x < 2^31
8097function lbit(x) {
8098 if (x == 0) return -1
8099 var r = 0
8100 if ((x & 0xffff) == 0) {
8101 x >>= 16
8102 r += 16
8103 }
8104 if ((x & 0xff) == 0) {
8105 x >>= 8
8106 r += 8
8107 }
8108 if ((x & 0xf) == 0) {
8109 x >>= 4
8110 r += 4
8111 }
8112 if ((x & 3) == 0) {
8113 x >>= 2
8114 r += 2
8115 }
8116 if ((x & 1) == 0)++r
8117 return r
8118}
8119
8120// (public) returns index of lowest 1-bit (or -1 if none)
8121function bnGetLowestSetBit() {
8122 for (var i = 0; i < this.t; ++i)
8123 if (this[i] != 0) return i * this.DB + lbit(this[i])
8124 if (this.s < 0) return this.t * this.DB
8125 return -1
8126}
8127
8128// return number of 1 bits in x
8129function cbit(x) {
8130 var r = 0
8131 while (x != 0) {
8132 x &= x - 1
8133 ++r
8134 }
8135 return r
8136}
8137
8138// (public) return number of set bits
8139function bnBitCount() {
8140 var r = 0,
8141 x = this.s & this.DM
8142 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
8143 return r
8144}
8145
8146// (public) true iff nth bit is set
8147function bnTestBit(n) {
8148 var j = Math.floor(n / this.DB)
8149 if (j >= this.t) return (this.s != 0)
8150 return ((this[j] & (1 << (n % this.DB))) != 0)
8151}
8152
8153// (protected) this op (1<<n)
8154function bnpChangeBit(n, op) {
8155 var r = BigInteger.ONE.shiftLeft(n)
8156 this.bitwiseTo(r, op, r)
8157 return r
8158}
8159
8160// (public) this | (1<<n)
8161function bnSetBit(n) {
8162 return this.changeBit(n, op_or)
8163}
8164
8165// (public) this & ~(1<<n)
8166function bnClearBit(n) {
8167 return this.changeBit(n, op_andnot)
8168}
8169
8170// (public) this ^ (1<<n)
8171function bnFlipBit(n) {
8172 return this.changeBit(n, op_xor)
8173}
8174
8175// (protected) r = this + a
8176function bnpAddTo(a, r) {
8177 var self = this
8178
8179 var i = 0,
8180 c = 0,
8181 m = Math.min(a.t, self.t)
8182 while (i < m) {
8183 c += self[i] + a[i]
8184 r[i++] = c & self.DM
8185 c >>= self.DB
8186 }
8187 if (a.t < self.t) {
8188 c += a.s
8189 while (i < self.t) {
8190 c += self[i]
8191 r[i++] = c & self.DM
8192 c >>= self.DB
8193 }
8194 c += self.s
8195 } else {
8196 c += self.s
8197 while (i < a.t) {
8198 c += a[i]
8199 r[i++] = c & self.DM
8200 c >>= self.DB
8201 }
8202 c += a.s
8203 }
8204 r.s = (c < 0) ? -1 : 0
8205 if (c > 0) r[i++] = c
8206 else if (c < -1) r[i++] = self.DV + c
8207 r.t = i
8208 r.clamp()
8209}
8210
8211// (public) this + a
8212function bnAdd(a) {
8213 var r = new BigInteger()
8214 this.addTo(a, r)
8215 return r
8216}
8217
8218// (public) this - a
8219function bnSubtract(a) {
8220 var r = new BigInteger()
8221 this.subTo(a, r)
8222 return r
8223}
8224
8225// (public) this * a
8226function bnMultiply(a) {
8227 var r = new BigInteger()
8228 this.multiplyTo(a, r)
8229 return r
8230}
8231
8232// (public) this^2
8233function bnSquare() {
8234 var r = new BigInteger()
8235 this.squareTo(r)
8236 return r
8237}
8238
8239// (public) this / a
8240function bnDivide(a) {
8241 var r = new BigInteger()
8242 this.divRemTo(a, r, null)
8243 return r
8244}
8245
8246// (public) this % a
8247function bnRemainder(a) {
8248 var r = new BigInteger()
8249 this.divRemTo(a, null, r)
8250 return r
8251}
8252
8253// (public) [this/a,this%a]
8254function bnDivideAndRemainder(a) {
8255 var q = new BigInteger(),
8256 r = new BigInteger()
8257 this.divRemTo(a, q, r)
8258 return new Array(q, r)
8259}
8260
8261// (protected) this *= n, this >= 0, 1 < n < DV
8262function bnpDMultiply(n) {
8263 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
8264 ++this.t
8265 this.clamp()
8266}
8267
8268// (protected) this += n << w words, this >= 0
8269function bnpDAddOffset(n, w) {
8270 if (n == 0) return
8271 while (this.t <= w) this[this.t++] = 0
8272 this[w] += n
8273 while (this[w] >= this.DV) {
8274 this[w] -= this.DV
8275 if (++w >= this.t) this[this.t++] = 0
8276 ++this[w]
8277 }
8278}
8279
8280// A "null" reducer
8281function NullExp() {}
8282
8283function nNop(x) {
8284 return x
8285}
8286
8287function nMulTo(x, y, r) {
8288 x.multiplyTo(y, r)
8289}
8290
8291function nSqrTo(x, r) {
8292 x.squareTo(r)
8293}
8294
8295NullExp.prototype.convert = nNop
8296NullExp.prototype.revert = nNop
8297NullExp.prototype.mulTo = nMulTo
8298NullExp.prototype.sqrTo = nSqrTo
8299
8300// (public) this^e
8301function bnPow(e) {
8302 return this.exp(e, new NullExp())
8303}
8304
8305// (protected) r = lower n words of "this * a", a.t <= n
8306// "this" should be the larger one if appropriate.
8307function bnpMultiplyLowerTo(a, n, r) {
8308 var i = Math.min(this.t + a.t, n)
8309 r.s = 0; // assumes a,this >= 0
8310 r.t = i
8311 while (i > 0) r[--i] = 0
8312 var j
8313 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
8314 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
8315 r.clamp()
8316}
8317
8318// (protected) r = "this * a" without lower n words, n > 0
8319// "this" should be the larger one if appropriate.
8320function bnpMultiplyUpperTo(a, n, r) {
8321 --n
8322 var i = r.t = this.t + a.t - n
8323 r.s = 0; // assumes a,this >= 0
8324 while (--i >= 0) r[i] = 0
8325 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
8326 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
8327 r.clamp()
8328 r.drShiftTo(1, r)
8329}
8330
8331// Barrett modular reduction
8332function Barrett(m) {
8333 // setup Barrett
8334 this.r2 = new BigInteger()
8335 this.q3 = new BigInteger()
8336 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
8337 this.mu = this.r2.divide(m)
8338 this.m = m
8339}
8340
8341function barrettConvert(x) {
8342 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
8343 else if (x.compareTo(this.m) < 0) return x
8344 else {
8345 var r = new BigInteger()
8346 x.copyTo(r)
8347 this.reduce(r)
8348 return r
8349 }
8350}
8351
8352function barrettRevert(x) {
8353 return x
8354}
8355
8356// x = x mod m (HAC 14.42)
8357function barrettReduce(x) {
8358 var self = this
8359 x.drShiftTo(self.m.t - 1, self.r2)
8360 if (x.t > self.m.t + 1) {
8361 x.t = self.m.t + 1
8362 x.clamp()
8363 }
8364 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
8365 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
8366 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
8367 x.subTo(self.r2, x)
8368 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
8369}
8370
8371// r = x^2 mod m; x != r
8372function barrettSqrTo(x, r) {
8373 x.squareTo(r)
8374 this.reduce(r)
8375}
8376
8377// r = x*y mod m; x,y != r
8378function barrettMulTo(x, y, r) {
8379 x.multiplyTo(y, r)
8380 this.reduce(r)
8381}
8382
8383Barrett.prototype.convert = barrettConvert
8384Barrett.prototype.revert = barrettRevert
8385Barrett.prototype.reduce = barrettReduce
8386Barrett.prototype.mulTo = barrettMulTo
8387Barrett.prototype.sqrTo = barrettSqrTo
8388
8389// (public) this^e % m (HAC 14.85)
8390function bnModPow(e, m) {
8391 var i = e.bitLength(),
8392 k, r = nbv(1),
8393 z
8394 if (i <= 0) return r
8395 else if (i < 18) k = 1
8396 else if (i < 48) k = 3
8397 else if (i < 144) k = 4
8398 else if (i < 768) k = 5
8399 else k = 6
8400 if (i < 8)
8401 z = new Classic(m)
8402 else if (m.isEven())
8403 z = new Barrett(m)
8404 else
8405 z = new Montgomery(m)
8406
8407 // precomputation
8408 var g = new Array(),
8409 n = 3,
8410 k1 = k - 1,
8411 km = (1 << k) - 1
8412 g[1] = z.convert(this)
8413 if (k > 1) {
8414 var g2 = new BigInteger()
8415 z.sqrTo(g[1], g2)
8416 while (n <= km) {
8417 g[n] = new BigInteger()
8418 z.mulTo(g2, g[n - 2], g[n])
8419 n += 2
8420 }
8421 }
8422
8423 var j = e.t - 1,
8424 w, is1 = true,
8425 r2 = new BigInteger(),
8426 t
8427 i = nbits(e[j]) - 1
8428 while (j >= 0) {
8429 if (i >= k1) w = (e[j] >> (i - k1)) & km
8430 else {
8431 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
8432 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
8433 }
8434
8435 n = k
8436 while ((w & 1) == 0) {
8437 w >>= 1
8438 --n
8439 }
8440 if ((i -= n) < 0) {
8441 i += this.DB
8442 --j
8443 }
8444 if (is1) { // ret == 1, don't bother squaring or multiplying it
8445 g[w].copyTo(r)
8446 is1 = false
8447 } else {
8448 while (n > 1) {
8449 z.sqrTo(r, r2)
8450 z.sqrTo(r2, r)
8451 n -= 2
8452 }
8453 if (n > 0) z.sqrTo(r, r2)
8454 else {
8455 t = r
8456 r = r2
8457 r2 = t
8458 }
8459 z.mulTo(r2, g[w], r)
8460 }
8461 7281
8462 while (j >= 0 && (e[j] & (1 << i)) == 0) { 7282// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
8463 z.sqrTo(r, r2) 7283// original notice:
8464 t = r
8465 r = r2
8466 r2 = t
8467 if (--i < 0) {
8468 i = this.DB - 1
8469 --j
8470 }
8471 }
8472 }
8473 return z.revert(r)
8474}
8475 7284
8476// (public) gcd(this,a) (HAC 14.54) 7285/*!
8477function bnGCD(a) { 7286 * The buffer module from node.js, for the browser.
8478 var x = (this.s < 0) ? this.negate() : this.clone() 7287 *
8479 var y = (a.s < 0) ? a.negate() : a.clone() 7288 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
8480 if (x.compareTo(y) < 0) { 7289 * @license MIT
8481 var t = x 7290 */
8482 x = y 7291function compare(a, b) {
8483 y = t 7292 if (a === b) {
8484 } 7293 return 0;
8485 var i = x.getLowestSetBit(),
8486 g = y.getLowestSetBit()
8487 if (g < 0) return x
8488 if (i < g) g = i
8489 if (g > 0) {
8490 x.rShiftTo(g, x)
8491 y.rShiftTo(g, y)
8492 }
8493 while (x.signum() > 0) {
8494 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
8495 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
8496 if (x.compareTo(y) >= 0) {
8497 x.subTo(y, x)
8498 x.rShiftTo(1, x)
8499 } else {
8500 y.subTo(x, y)
8501 y.rShiftTo(1, y)
8502 }
8503 } 7294 }
8504 if (g > 0) y.lShiftTo(g, y)
8505 return y
8506}
8507 7295
8508// (protected) this % n, n < 2^26 7296 var x = a.length;
8509function bnpModInt(n) { 7297 var y = b.length;
8510 if (n <= 0) return 0
8511 var d = this.DV % n,
8512 r = (this.s < 0) ? n - 1 : 0
8513 if (this.t > 0)
8514 if (d == 0) r = this[0] % n
8515 else
8516 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
8517 return r
8518}
8519 7298
8520// (public) 1/this % m (HAC 14.61) 7299 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
8521function bnModInverse(m) { 7300 if (a[i] !== b[i]) {
8522 var ac = m.isEven() 7301 x = a[i];
8523 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO 7302 y = b[i];
8524 var u = m.clone(), 7303 break;
8525 v = this.clone()
8526 var a = nbv(1),
8527 b = nbv(0),
8528 c = nbv(0),
8529 d = nbv(1)
8530 while (u.signum() != 0) {
8531 while (u.isEven()) {
8532 u.rShiftTo(1, u)
8533 if (ac) {
8534 if (!a.isEven() || !b.isEven()) {
8535 a.addTo(this, a)
8536 b.subTo(m, b)
8537 }
8538 a.rShiftTo(1, a)
8539 } else if (!b.isEven()) b.subTo(m, b)
8540 b.rShiftTo(1, b)
8541 }
8542 while (v.isEven()) {
8543 v.rShiftTo(1, v)
8544 if (ac) {
8545 if (!c.isEven() || !d.isEven()) {
8546 c.addTo(this, c)
8547 d.subTo(m, d)
8548 }
8549 c.rShiftTo(1, c)
8550 } else if (!d.isEven()) d.subTo(m, d)
8551 d.rShiftTo(1, d)
8552 }
8553 if (u.compareTo(v) >= 0) {
8554 u.subTo(v, u)
8555 if (ac) a.subTo(c, a)
8556 b.subTo(d, b)
8557 } else {
8558 v.subTo(u, v)
8559 if (ac) c.subTo(a, c)
8560 d.subTo(b, d)
8561 } 7304 }
8562 } 7305 }
8563 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
8564 if (d.compareTo(m) >= 0) return d.subtract(m)
8565 if (d.signum() < 0) d.addTo(m, d)
8566 else return d
8567 if (d.signum() < 0) return d.add(m)
8568 else return d
8569}
8570
8571var lowprimes = [
8572 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
8573 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
8574 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
8575 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
8576 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
8577 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
8578 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
8579 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
8580 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
8581 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
8582 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
8583]
8584
8585var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
8586
8587// (public) test primality with certainty >= 1-.5^t
8588function bnIsProbablePrime(t) {
8589 var i, x = this.abs()
8590 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
8591 for (i = 0; i < lowprimes.length; ++i)
8592 if (x[0] == lowprimes[i]) return true
8593 return false
8594 }
8595 if (x.isEven()) return false
8596 i = 1
8597 while (i < lowprimes.length) {
8598 var m = lowprimes[i],
8599 j = i + 1
8600 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
8601 m = x.modInt(m)
8602 while (i < j) if (m % lowprimes[i++] == 0) return false
8603 }
8604 return x.millerRabin(t)
8605}
8606 7306
8607// (protected) true if probably prime (HAC 4.24, Miller-Rabin) 7307 if (x < y) {
8608function bnpMillerRabin(t) { 7308 return -1;
8609 var n1 = this.subtract(BigInteger.ONE)
8610 var k = n1.getLowestSetBit()
8611 if (k <= 0) return false
8612 var r = n1.shiftRight(k)
8613 t = (t + 1) >> 1
8614 if (t > lowprimes.length) t = lowprimes.length
8615 var a = new BigInteger(null)
8616 var j, bases = []
8617 for (var i = 0; i < t; ++i) {
8618 for (;;) {
8619 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
8620 if (bases.indexOf(j) == -1) break
8621 }
8622 bases.push(j)
8623 a.fromInt(j)
8624 var y = a.modPow(r, this)
8625 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
8626 var j = 1
8627 while (j++ < k && y.compareTo(n1) != 0) {
8628 y = y.modPowInt(2, this)
8629 if (y.compareTo(BigInteger.ONE) == 0) return false
8630 }
8631 if (y.compareTo(n1) != 0) return false
8632 }
8633 } 7309 }
8634 return true 7310 if (y < x) {
8635} 7311 return 1;
8636
8637// protected
8638proto.chunkSize = bnpChunkSize
8639proto.toRadix = bnpToRadix
8640proto.fromRadix = bnpFromRadix
8641proto.fromNumber = bnpFromNumber
8642proto.bitwiseTo = bnpBitwiseTo
8643proto.changeBit = bnpChangeBit
8644proto.addTo = bnpAddTo
8645proto.dMultiply = bnpDMultiply
8646proto.dAddOffset = bnpDAddOffset
8647proto.multiplyLowerTo = bnpMultiplyLowerTo
8648proto.multiplyUpperTo = bnpMultiplyUpperTo
8649proto.modInt = bnpModInt
8650proto.millerRabin = bnpMillerRabin
8651
8652// public
8653proto.clone = bnClone
8654proto.intValue = bnIntValue
8655proto.byteValue = bnByteValue
8656proto.shortValue = bnShortValue
8657proto.signum = bnSigNum
8658proto.toByteArray = bnToByteArray
8659proto.equals = bnEquals
8660proto.min = bnMin
8661proto.max = bnMax
8662proto.and = bnAnd
8663proto.or = bnOr
8664proto.xor = bnXor
8665proto.andNot = bnAndNot
8666proto.not = bnNot
8667proto.shiftLeft = bnShiftLeft
8668proto.shiftRight = bnShiftRight
8669proto.getLowestSetBit = bnGetLowestSetBit
8670proto.bitCount = bnBitCount
8671proto.testBit = bnTestBit
8672proto.setBit = bnSetBit
8673proto.clearBit = bnClearBit
8674proto.flipBit = bnFlipBit
8675proto.add = bnAdd
8676proto.subtract = bnSubtract
8677proto.multiply = bnMultiply
8678proto.divide = bnDivide
8679proto.remainder = bnRemainder
8680proto.divideAndRemainder = bnDivideAndRemainder
8681proto.modPow = bnModPow
8682proto.modInverse = bnModInverse
8683proto.pow = bnPow
8684proto.gcd = bnGCD
8685proto.isProbablePrime = bnIsProbablePrime
8686
8687// JSBN-specific extension
8688proto.square = bnSquare
8689
8690// constants
8691BigInteger.ZERO = nbv(0)
8692BigInteger.ONE = nbv(1)
8693BigInteger.valueOf = nbv
8694
8695module.exports = BigInteger
8696
8697},{"../package.json":4}],2:[function(require,module,exports){
8698(function (Buffer){
8699// FIXME: Kind of a weird way to throw exceptions, consider removing
8700var assert = require('assert')
8701var BigInteger = require('./bigi')
8702
8703/**
8704 * Turns a byte array into a big integer.
8705 *
8706 * This function will interpret a byte array as a big integer in big
8707 * endian notation.
8708 */
8709BigInteger.fromByteArrayUnsigned = function(byteArray) {
8710 // BigInteger expects a DER integer conformant byte array
8711 if (byteArray[0] & 0x80) {
8712 return new BigInteger([0].concat(byteArray))
8713 } 7312 }
8714 7313 return 0;
8715 return new BigInteger(byteArray)
8716}
8717
8718/**
8719 * Returns a byte array representation of the big integer.
8720 *
8721 * This returns the absolute of the contained value in big endian
8722 * form. A value of zero results in an empty array.
8723 */
8724BigInteger.prototype.toByteArrayUnsigned = function() {
8725 var byteArray = this.toByteArray()
8726 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
8727}
8728
8729BigInteger.fromDERInteger = function(byteArray) {
8730 return new BigInteger(byteArray)
8731} 7314}
8732 7315function isBuffer(b) {
8733/* 7316 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
8734 * Converts BigInteger to a DER integer representation. 7317 return global.Buffer.isBuffer(b);
8735 *
8736 * The format for this value uses the most significant bit as a sign
8737 * bit. If the most significant bit is already set and the integer is
8738 * positive, a 0x00 is prepended.
8739 *
8740 * Examples:
8741 *
8742 * 0 => 0x00
8743 * 1 => 0x01
8744 * -1 => 0xff
8745 * 127 => 0x7f
8746 * -127 => 0x81
8747 * 128 => 0x0080
8748 * -128 => 0x80
8749 * 255 => 0x00ff
8750 * -255 => 0xff01
8751 * 16300 => 0x3fac
8752 * -16300 => 0xc054
8753 * 62300 => 0x00f35c
8754 * -62300 => 0xff0ca4
8755*/
8756BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
8757
8758BigInteger.fromBuffer = function(buffer) {
8759 // BigInteger expects a DER integer conformant byte array
8760 if (buffer[0] & 0x80) {
8761 var byteArray = Array.prototype.slice.call(buffer)
8762
8763 return new BigInteger([0].concat(byteArray))
8764 } 7318 }
8765 7319 return !!(b != null && b._isBuffer);
8766 return new BigInteger(buffer)
8767}
8768
8769BigInteger.fromHex = function(hex) {
8770 if (hex === '') return BigInteger.ZERO
8771
8772 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
8773 assert.equal(hex.length % 2, 0, 'Incomplete hex')
8774 return new BigInteger(hex, 16)
8775}
8776
8777BigInteger.prototype.toBuffer = function(size) {
8778 var byteArray = this.toByteArrayUnsigned()
8779 var zeros = []
8780
8781 var padding = size - byteArray.length
8782 while (zeros.length < padding) zeros.push(0)
8783
8784 return new Buffer(zeros.concat(byteArray))
8785}
8786
8787BigInteger.prototype.toHex = function(size) {
8788 return this.toBuffer(size).toString('hex')
8789} 7320}
8790 7321
8791}).call(this,require("buffer").Buffer) 7322// based on node assert, original notice:
8792},{"./bigi":1,"assert":5,"buffer":7}],3:[function(require,module,exports){
8793var BigInteger = require('./bigi')
8794
8795//addons
8796require('./convert')
8797
8798module.exports = BigInteger
8799},{"./bigi":1,"./convert":2}],4:[function(require,module,exports){
8800module.exports={
8801 "name": "bigi",
8802 "version": "1.4.0",
8803 "description": "Big integers.",
8804 "keywords": [
8805 "cryptography",
8806 "math",
8807 "bitcoin",
8808 "arbitrary",
8809 "precision",
8810 "arithmetic",
8811 "big",
8812 "integer",
8813 "int",
8814 "number",
8815 "biginteger",
8816 "bigint",
8817 "bignumber",
8818 "decimal",
8819 "float"
8820 ],
8821 "devDependencies": {
8822 "mocha": "^1.20.1",
8823 "jshint": "^2.5.1",
8824 "coveralls": "^2.10.0",
8825 "istanbul": "^0.2.11"
8826 },
8827 "repository": {
8828 "url": "https://github.com/cryptocoinjs/bigi",
8829 "type": "git"
8830 },
8831 "main": "./lib/index.js",
8832 "scripts": {
8833 "test": "_mocha -- test/*.js",
8834 "jshint": "jshint --config jshint.json lib/*.js ; true",
8835 "unit": "mocha",
8836 "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
8837 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info"
8838 },
8839 "dependencies": {},
8840 "testling": {
8841 "files": "test/*.js",
8842 "harness": "mocha",
8843 "browsers": [
8844 "ie/9..latest",
8845 "firefox/latest",
8846 "chrome/latest",
8847 "safari/6.0..latest",
8848 "iphone/6.0..latest",
8849 "android-browser/4.2..latest"
8850 ]
8851 },
8852 "bugs": {
8853 "url": "https://github.com/cryptocoinjs/bigi/issues"
8854 },
8855 "homepage": "https://github.com/cryptocoinjs/bigi",
8856 "_id": "bigi@1.4.0",
8857 "dist": {
8858 "shasum": "90ac1aeac0a531216463bdb58f42c1e05c8407ac",
8859 "tarball": "http://registry.npmjs.org/bigi/-/bigi-1.4.0.tgz"
8860 },
8861 "_from": "bigi@^1.4.0",
8862 "_npmVersion": "1.4.3",
8863 "_npmUser": {
8864 "name": "jp",
8865 "email": "jprichardson@gmail.com"
8866 },
8867 "maintainers": [
8868 {
8869 "name": "jp",
8870 "email": "jprichardson@gmail.com"
8871 },
8872 {
8873 "name": "midnightlightning",
8874 "email": "boydb@midnightdesign.ws"
8875 },
8876 {
8877 "name": "sidazhang",
8878 "email": "sidazhang89@gmail.com"
8879 },
8880 {
8881 "name": "nadav",
8882 "email": "npm@shesek.info"
8883 }
8884 ],
8885 "directories": {},
8886 "_shasum": "90ac1aeac0a531216463bdb58f42c1e05c8407ac",
8887 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.0.tgz"
8888}
8889 7323
8890},{}],5:[function(require,module,exports){
8891// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 7324// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
8892// 7325//
8893// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! 7326// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
@@ -8912,14 +7345,36 @@ module.exports={
8912// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 7345// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
8913// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 7346// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8914 7347
8915// when used in node, this will actually load the util module we depend on
8916// versus loading the builtin util module as happens otherwise
8917// this is a bug in node module loading as far as I am concerned
8918var util = require('util/'); 7348var util = require('util/');
8919
8920var pSlice = Array.prototype.slice;
8921var hasOwn = Object.prototype.hasOwnProperty; 7349var hasOwn = Object.prototype.hasOwnProperty;
8922 7350var pSlice = Array.prototype.slice;
7351var functionsHaveNames = (function () {
7352 return function foo() {}.name === 'foo';
7353}());
7354function pToString (obj) {
7355 return Object.prototype.toString.call(obj);
7356}
7357function isView(arrbuf) {
7358 if (isBuffer(arrbuf)) {
7359 return false;
7360 }
7361 if (typeof global.ArrayBuffer !== 'function') {
7362 return false;
7363 }
7364 if (typeof ArrayBuffer.isView === 'function') {
7365 return ArrayBuffer.isView(arrbuf);
7366 }
7367 if (!arrbuf) {
7368 return false;
7369 }
7370 if (arrbuf instanceof DataView) {
7371 return true;
7372 }
7373 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
7374 return true;
7375 }
7376 return false;
7377}
8923// 1. The assert module provides functions that throw 7378// 1. The assert module provides functions that throw
8924// AssertionError's when particular conditions are not met. The 7379// AssertionError's when particular conditions are not met. The
8925// assert module must conform to the following interface. 7380// assert module must conform to the following interface.
@@ -8931,6 +7386,19 @@ var assert = module.exports = ok;
8931// actual: actual, 7386// actual: actual,
8932// expected: expected }) 7387// expected: expected })
8933 7388
7389var regex = /\s*function\s+([^\(\s]*)\s*/;
7390// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
7391function getName(func) {
7392 if (!util.isFunction(func)) {
7393 return;
7394 }
7395 if (functionsHaveNames) {
7396 return func.name;
7397 }
7398 var str = func.toString();
7399 var match = str.match(regex);
7400 return match && match[1];
7401}
8934assert.AssertionError = function AssertionError(options) { 7402assert.AssertionError = function AssertionError(options) {
8935 this.name = 'AssertionError'; 7403 this.name = 'AssertionError';
8936 this.actual = options.actual; 7404 this.actual = options.actual;
@@ -8944,18 +7412,16 @@ assert.AssertionError = function AssertionError(options) {
8944 this.generatedMessage = true; 7412 this.generatedMessage = true;
8945 } 7413 }
8946 var stackStartFunction = options.stackStartFunction || fail; 7414 var stackStartFunction = options.stackStartFunction || fail;
8947
8948 if (Error.captureStackTrace) { 7415 if (Error.captureStackTrace) {
8949 Error.captureStackTrace(this, stackStartFunction); 7416 Error.captureStackTrace(this, stackStartFunction);
8950 } 7417 } else {
8951 else {
8952 // non v8 browsers so we can have a stacktrace 7418 // non v8 browsers so we can have a stacktrace
8953 var err = new Error(); 7419 var err = new Error();
8954 if (err.stack) { 7420 if (err.stack) {
8955 var out = err.stack; 7421 var out = err.stack;
8956 7422
8957 // try to strip useless frames 7423 // try to strip useless frames
8958 var fn_name = stackStartFunction.name; 7424 var fn_name = getName(stackStartFunction);
8959 var idx = out.indexOf('\n' + fn_name); 7425 var idx = out.indexOf('\n' + fn_name);
8960 if (idx >= 0) { 7426 if (idx >= 0) {
8961 // once we have located the function frame 7427 // once we have located the function frame
@@ -8972,31 +7438,25 @@ assert.AssertionError = function AssertionError(options) {
8972// assert.AssertionError instanceof Error 7438// assert.AssertionError instanceof Error
8973util.inherits(assert.AssertionError, Error); 7439util.inherits(assert.AssertionError, Error);
8974 7440
8975function replacer(key, value) {
8976 if (util.isUndefined(value)) {
8977 return '' + value;
8978 }
8979 if (util.isNumber(value) && !isFinite(value)) {
8980 return value.toString();
8981 }
8982 if (util.isFunction(value) || util.isRegExp(value)) {
8983 return value.toString();
8984 }
8985 return value;
8986}
8987
8988function truncate(s, n) { 7441function truncate(s, n) {
8989 if (util.isString(s)) { 7442 if (typeof s === 'string') {
8990 return s.length < n ? s : s.slice(0, n); 7443 return s.length < n ? s : s.slice(0, n);
8991 } else { 7444 } else {
8992 return s; 7445 return s;
8993 } 7446 }
8994} 7447}
8995 7448function inspect(something) {
7449 if (functionsHaveNames || !util.isFunction(something)) {
7450 return util.inspect(something);
7451 }
7452 var rawname = getName(something);
7453 var name = rawname ? ': ' + rawname : '';
7454 return '[Function' + name + ']';
7455}
8996function getMessage(self) { 7456function getMessage(self) {
8997 return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + 7457 return truncate(inspect(self.actual), 128) + ' ' +
8998 self.operator + ' ' + 7458 self.operator + ' ' +
8999 truncate(JSON.stringify(self.expected, replacer), 128); 7459 truncate(inspect(self.expected), 128);
9000} 7460}
9001 7461
9002// At present only the three keys mentioned above are used and 7462// At present only the three keys mentioned above are used and
@@ -9056,24 +7516,23 @@ assert.notEqual = function notEqual(actual, expected, message) {
9056// assert.deepEqual(actual, expected, message_opt); 7516// assert.deepEqual(actual, expected, message_opt);
9057 7517
9058assert.deepEqual = function deepEqual(actual, expected, message) { 7518assert.deepEqual = function deepEqual(actual, expected, message) {
9059 if (!_deepEqual(actual, expected)) { 7519 if (!_deepEqual(actual, expected, false)) {
9060 fail(actual, expected, message, 'deepEqual', assert.deepEqual); 7520 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
9061 } 7521 }
9062}; 7522};
9063 7523
9064function _deepEqual(actual, expected) { 7524assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
7525 if (!_deepEqual(actual, expected, true)) {
7526 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
7527 }
7528};
7529
7530function _deepEqual(actual, expected, strict, memos) {
9065 // 7.1. All identical values are equivalent, as determined by ===. 7531 // 7.1. All identical values are equivalent, as determined by ===.
9066 if (actual === expected) { 7532 if (actual === expected) {
9067 return true; 7533 return true;
9068 7534 } else if (isBuffer(actual) && isBuffer(expected)) {
9069 } else if (util.isBuffer(actual) && util.isBuffer(expected)) { 7535 return compare(actual, expected) === 0;
9070 if (actual.length != expected.length) return false;
9071
9072 for (var i = 0; i < actual.length; i++) {
9073 if (actual[i] !== expected[i]) return false;
9074 }
9075
9076 return true;
9077 7536
9078 // 7.2. If the expected value is a Date object, the actual value is 7537 // 7.2. If the expected value is a Date object, the actual value is
9079 // equivalent if it is also a Date object that refers to the same time. 7538 // equivalent if it is also a Date object that refers to the same time.
@@ -9092,8 +7551,22 @@ function _deepEqual(actual, expected) {
9092 7551
9093 // 7.4. Other pairs that do not both pass typeof value == 'object', 7552 // 7.4. Other pairs that do not both pass typeof value == 'object',
9094 // equivalence is determined by ==. 7553 // equivalence is determined by ==.
9095 } else if (!util.isObject(actual) && !util.isObject(expected)) { 7554 } else if ((actual === null || typeof actual !== 'object') &&
9096 return actual == expected; 7555 (expected === null || typeof expected !== 'object')) {
7556 return strict ? actual === expected : actual == expected;
7557
7558 // If both values are instances of typed arrays, wrap their underlying
7559 // ArrayBuffers in a Buffer each to increase performance
7560 // This optimization requires the arrays to have the same type as checked by
7561 // Object.prototype.toString (aka pToString). Never perform binary
7562 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
7563 // bit patterns are not identical.
7564 } else if (isView(actual) && isView(expected) &&
7565 pToString(actual) === pToString(expected) &&
7566 !(actual instanceof Float32Array ||
7567 actual instanceof Float64Array)) {
7568 return compare(new Uint8Array(actual.buffer),
7569 new Uint8Array(expected.buffer)) === 0;
9097 7570
9098 // 7.5 For all other Object pairs, including Array objects, equivalence is 7571 // 7.5 For all other Object pairs, including Array objects, equivalence is
9099 // determined by having the same number of owned properties (as verified 7572 // determined by having the same number of owned properties (as verified
@@ -9101,8 +7574,22 @@ function _deepEqual(actual, expected) {
9101 // (although not necessarily the same order), equivalent values for every 7574 // (although not necessarily the same order), equivalent values for every
9102 // corresponding key, and an identical 'prototype' property. Note: this 7575 // corresponding key, and an identical 'prototype' property. Note: this
9103 // accounts for both named and indexed properties on Arrays. 7576 // accounts for both named and indexed properties on Arrays.
7577 } else if (isBuffer(actual) !== isBuffer(expected)) {
7578 return false;
9104 } else { 7579 } else {
9105 return objEquiv(actual, expected); 7580 memos = memos || {actual: [], expected: []};
7581
7582 var actualIndex = memos.actual.indexOf(actual);
7583 if (actualIndex !== -1) {
7584 if (actualIndex === memos.expected.indexOf(expected)) {
7585 return true;
7586 }
7587 }
7588
7589 memos.actual.push(actual);
7590 memos.expected.push(expected);
7591
7592 return objEquiv(actual, expected, strict, memos);
9106 } 7593 }
9107} 7594}
9108 7595
@@ -9110,44 +7597,44 @@ function isArguments(object) {
9110 return Object.prototype.toString.call(object) == '[object Arguments]'; 7597 return Object.prototype.toString.call(object) == '[object Arguments]';
9111} 7598}
9112 7599
9113function objEquiv(a, b) { 7600function objEquiv(a, b, strict, actualVisitedObjects) {
9114 if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) 7601 if (a === null || a === undefined || b === null || b === undefined)
9115 return false; 7602 return false;
9116 // an identical 'prototype' property.
9117 if (a.prototype !== b.prototype) return false;
9118 // if one is a primitive, the other must be same 7603 // if one is a primitive, the other must be same
9119 if (util.isPrimitive(a) || util.isPrimitive(b)) { 7604 if (util.isPrimitive(a) || util.isPrimitive(b))
9120 return a === b; 7605 return a === b;
9121 } 7606 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
9122 var aIsArgs = isArguments(a), 7607 return false;
9123 bIsArgs = isArguments(b); 7608 var aIsArgs = isArguments(a);
7609 var bIsArgs = isArguments(b);
9124 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) 7610 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
9125 return false; 7611 return false;
9126 if (aIsArgs) { 7612 if (aIsArgs) {
9127 a = pSlice.call(a); 7613 a = pSlice.call(a);
9128 b = pSlice.call(b); 7614 b = pSlice.call(b);
9129 return _deepEqual(a, b); 7615 return _deepEqual(a, b, strict);
9130 } 7616 }
9131 var ka = objectKeys(a), 7617 var ka = objectKeys(a);
9132 kb = objectKeys(b), 7618 var kb = objectKeys(b);
9133 key, i; 7619 var key, i;
9134 // having the same number of owned properties (keys incorporates 7620 // having the same number of owned properties (keys incorporates
9135 // hasOwnProperty) 7621 // hasOwnProperty)
9136 if (ka.length != kb.length) 7622 if (ka.length !== kb.length)
9137 return false; 7623 return false;
9138 //the same set of keys (although not necessarily the same order), 7624 //the same set of keys (although not necessarily the same order),
9139 ka.sort(); 7625 ka.sort();
9140 kb.sort(); 7626 kb.sort();
9141 //~~~cheap key test 7627 //~~~cheap key test
9142 for (i = ka.length - 1; i >= 0; i--) { 7628 for (i = ka.length - 1; i >= 0; i--) {
9143 if (ka[i] != kb[i]) 7629 if (ka[i] !== kb[i])
9144 return false; 7630 return false;
9145 } 7631 }
9146 //equivalent values for every corresponding key, and 7632 //equivalent values for every corresponding key, and
9147 //~~~possibly expensive deep test 7633 //~~~possibly expensive deep test
9148 for (i = ka.length - 1; i >= 0; i--) { 7634 for (i = ka.length - 1; i >= 0; i--) {
9149 key = ka[i]; 7635 key = ka[i];
9150 if (!_deepEqual(a[key], b[key])) return false; 7636 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
7637 return false;
9151 } 7638 }
9152 return true; 7639 return true;
9153} 7640}
@@ -9156,11 +7643,19 @@ function objEquiv(a, b) {
9156// assert.notDeepEqual(actual, expected, message_opt); 7643// assert.notDeepEqual(actual, expected, message_opt);
9157 7644
9158assert.notDeepEqual = function notDeepEqual(actual, expected, message) { 7645assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
9159 if (_deepEqual(actual, expected)) { 7646 if (_deepEqual(actual, expected, false)) {
9160 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); 7647 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
9161 } 7648 }
9162}; 7649};
9163 7650
7651assert.notDeepStrictEqual = notDeepStrictEqual;
7652function notDeepStrictEqual(actual, expected, message) {
7653 if (_deepEqual(actual, expected, true)) {
7654 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
7655 }
7656}
7657
7658
9164// 9. The strict equality assertion tests strict equality, as determined by ===. 7659// 9. The strict equality assertion tests strict equality, as determined by ===.
9165// assert.strictEqual(actual, expected, message_opt); 7660// assert.strictEqual(actual, expected, message_opt);
9166 7661
@@ -9186,28 +7681,46 @@ function expectedException(actual, expected) {
9186 7681
9187 if (Object.prototype.toString.call(expected) == '[object RegExp]') { 7682 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
9188 return expected.test(actual); 7683 return expected.test(actual);
9189 } else if (actual instanceof expected) {
9190 return true;
9191 } else if (expected.call({}, actual) === true) {
9192 return true;
9193 } 7684 }
9194 7685
9195 return false; 7686 try {
7687 if (actual instanceof expected) {
7688 return true;
7689 }
7690 } catch (e) {
7691 // Ignore. The instanceof check doesn't work for arrow functions.
7692 }
7693
7694 if (Error.isPrototypeOf(expected)) {
7695 return false;
7696 }
7697
7698 return expected.call({}, actual) === true;
7699}
7700
7701function _tryBlock(block) {
7702 var error;
7703 try {
7704 block();
7705 } catch (e) {
7706 error = e;
7707 }
7708 return error;
9196} 7709}
9197 7710
9198function _throws(shouldThrow, block, expected, message) { 7711function _throws(shouldThrow, block, expected, message) {
9199 var actual; 7712 var actual;
9200 7713
9201 if (util.isString(expected)) { 7714 if (typeof block !== 'function') {
7715 throw new TypeError('"block" argument must be a function');
7716 }
7717
7718 if (typeof expected === 'string') {
9202 message = expected; 7719 message = expected;
9203 expected = null; 7720 expected = null;
9204 } 7721 }
9205 7722
9206 try { 7723 actual = _tryBlock(block);
9207 block();
9208 } catch (e) {
9209 actual = e;
9210 }
9211 7724
9212 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + 7725 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
9213 (message ? ' ' + message : '.'); 7726 (message ? ' ' + message : '.');
@@ -9216,7 +7729,14 @@ function _throws(shouldThrow, block, expected, message) {
9216 fail(actual, expected, 'Missing expected exception' + message); 7729 fail(actual, expected, 'Missing expected exception' + message);
9217 } 7730 }
9218 7731
9219 if (!shouldThrow && expectedException(actual, expected)) { 7732 var userProvidedMessage = typeof message === 'string';
7733 var isUnwantedException = !shouldThrow && util.isError(actual);
7734 var isUnexpectedException = !shouldThrow && actual && !expected;
7735
7736 if ((isUnwantedException &&
7737 userProvidedMessage &&
7738 expectedException(actual, expected)) ||
7739 isUnexpectedException) {
9220 fail(actual, expected, 'Got unwanted exception' + message); 7740 fail(actual, expected, 'Got unwanted exception' + message);
9221 } 7741 }
9222 7742
@@ -9230,15 +7750,15 @@ function _throws(shouldThrow, block, expected, message) {
9230// assert.throws(block, Error_opt, message_opt); 7750// assert.throws(block, Error_opt, message_opt);
9231 7751
9232assert.throws = function(block, /*optional*/error, /*optional*/message) { 7752assert.throws = function(block, /*optional*/error, /*optional*/message) {
9233 _throws.apply(this, [true].concat(pSlice.call(arguments))); 7753 _throws(true, block, error, message);
9234}; 7754};
9235 7755
9236// EXTENSION! This is annoying to write outside this module. 7756// EXTENSION! This is annoying to write outside this module.
9237assert.doesNotThrow = function(block, /*optional*/message) { 7757assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
9238 _throws.apply(this, [false].concat(pSlice.call(arguments))); 7758 _throws(false, block, error, message);
9239}; 7759};
9240 7760
9241assert.ifError = function(err) { if (err) {throw err;}}; 7761assert.ifError = function(err) { if (err) throw err; };
9242 7762
9243var objectKeys = Object.keys || function (obj) { 7763var objectKeys = Object.keys || function (obj) {
9244 var keys = []; 7764 var keys = [];
@@ -9248,259 +7768,414 @@ var objectKeys = Object.keys || function (obj) {
9248 return keys; 7768 return keys;
9249}; 7769};
9250 7770
9251},{"util/":29}],6:[function(require,module,exports){ 7771}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7772},{"util/":32}],2:[function(require,module,exports){
7773'use strict'
9252 7774
9253},{}],7:[function(require,module,exports){ 7775exports.byteLength = byteLength
7776exports.toByteArray = toByteArray
7777exports.fromByteArray = fromByteArray
7778
7779var lookup = []
7780var revLookup = []
7781var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
7782
7783var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
7784for (var i = 0, len = code.length; i < len; ++i) {
7785 lookup[i] = code[i]
7786 revLookup[code.charCodeAt(i)] = i
7787}
7788
7789revLookup['-'.charCodeAt(0)] = 62
7790revLookup['_'.charCodeAt(0)] = 63
7791
7792function placeHoldersCount (b64) {
7793 var len = b64.length
7794 if (len % 4 > 0) {
7795 throw new Error('Invalid string. Length must be a multiple of 4')
7796 }
7797
7798 // the number of equal signs (place holders)
7799 // if there are two placeholders, than the two characters before it
7800 // represent one byte
7801 // if there is only one, then the three characters before it represent 2 bytes
7802 // this is just a cheap hack to not do indexOf twice
7803 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
7804}
7805
7806function byteLength (b64) {
7807 // base64 is 4/3 + up to two characters of the original data
7808 return (b64.length * 3 / 4) - placeHoldersCount(b64)
7809}
7810
7811function toByteArray (b64) {
7812 var i, l, tmp, placeHolders, arr
7813 var len = b64.length
7814 placeHolders = placeHoldersCount(b64)
7815
7816 arr = new Arr((len * 3 / 4) - placeHolders)
7817
7818 // if there are placeholders, only get up to the last complete 4 chars
7819 l = placeHolders > 0 ? len - 4 : len
7820
7821 var L = 0
7822
7823 for (i = 0; i < l; i += 4) {
7824 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
7825 arr[L++] = (tmp >> 16) & 0xFF
7826 arr[L++] = (tmp >> 8) & 0xFF
7827 arr[L++] = tmp & 0xFF
7828 }
7829
7830 if (placeHolders === 2) {
7831 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
7832 arr[L++] = tmp & 0xFF
7833 } else if (placeHolders === 1) {
7834 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
7835 arr[L++] = (tmp >> 8) & 0xFF
7836 arr[L++] = tmp & 0xFF
7837 }
7838
7839 return arr
7840}
7841
7842function tripletToBase64 (num) {
7843 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
7844}
7845
7846function encodeChunk (uint8, start, end) {
7847 var tmp
7848 var output = []
7849 for (var i = start; i < end; i += 3) {
7850 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
7851 output.push(tripletToBase64(tmp))
7852 }
7853 return output.join('')
7854}
7855
7856function fromByteArray (uint8) {
7857 var tmp
7858 var len = uint8.length
7859 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
7860 var output = ''
7861 var parts = []
7862 var maxChunkLength = 16383 // must be multiple of 3
7863
7864 // go through the array every three bytes, we'll deal with trailing stuff later
7865 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
7866 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
7867 }
7868
7869 // pad the end with zeros, but make sure to not forget the extra bytes
7870 if (extraBytes === 1) {
7871 tmp = uint8[len - 1]
7872 output += lookup[tmp >> 2]
7873 output += lookup[(tmp << 4) & 0x3F]
7874 output += '=='
7875 } else if (extraBytes === 2) {
7876 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
7877 output += lookup[tmp >> 10]
7878 output += lookup[(tmp >> 4) & 0x3F]
7879 output += lookup[(tmp << 2) & 0x3F]
7880 output += '='
7881 }
7882
7883 parts.push(output)
7884
7885 return parts.join('')
7886}
7887
7888},{}],3:[function(require,module,exports){
7889
7890},{}],4:[function(require,module,exports){
9254/*! 7891/*!
9255 * The buffer module from node.js, for the browser. 7892 * The buffer module from node.js, for the browser.
9256 * 7893 *
9257 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> 7894 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
9258 * @license MIT 7895 * @license MIT
9259 */ 7896 */
7897/* eslint-disable no-proto */
7898
7899'use strict'
9260 7900
9261var base64 = require('base64-js') 7901var base64 = require('base64-js')
9262var ieee754 = require('ieee754') 7902var ieee754 = require('ieee754')
9263var isArray = require('is-array')
9264 7903
9265exports.Buffer = Buffer 7904exports.Buffer = Buffer
9266exports.SlowBuffer = SlowBuffer 7905exports.SlowBuffer = SlowBuffer
9267exports.INSPECT_MAX_BYTES = 50 7906exports.INSPECT_MAX_BYTES = 50
9268Buffer.poolSize = 8192 // not used by this implementation
9269 7907
9270var rootParent = {} 7908var K_MAX_LENGTH = 0x7fffffff
7909exports.kMaxLength = K_MAX_LENGTH
9271 7910
9272/** 7911/**
9273 * If `Buffer.TYPED_ARRAY_SUPPORT`: 7912 * If `Buffer.TYPED_ARRAY_SUPPORT`:
9274 * === true Use Uint8Array implementation (fastest) 7913 * === true Use Uint8Array implementation (fastest)
9275 * === false Use Object implementation (most compatible, even IE6) 7914 * === false Print warning and recommend using `buffer` v4.x which has an Object
7915 * implementation (most compatible, even IE6)
9276 * 7916 *
9277 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, 7917 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
9278 * Opera 11.6+, iOS 4.2+. 7918 * Opera 11.6+, iOS 4.2+.
9279 * 7919 *
9280 * Due to various browser bugs, sometimes the Object implementation will be used even 7920 * We report that the browser does not support typed arrays if the are not subclassable
9281 * when the browser supports typed arrays. 7921 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
9282 * 7922 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
9283 * Note: 7923 * for __proto__ and has a buggy typed array implementation.
9284 *
9285 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
9286 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
9287 *
9288 * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
9289 * on objects.
9290 *
9291 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
9292 *
9293 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
9294 * incorrect length in some situations.
9295
9296 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
9297 * get the Object implementation, which is slower but behaves correctly.
9298 */ 7924 */
9299Buffer.TYPED_ARRAY_SUPPORT = (function () { 7925Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
9300 function Bar () {} 7926
7927if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
7928 typeof console.error === 'function') {
7929 console.error(
7930 'This browser lacks typed array (Uint8Array) support which is required by ' +
7931 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
7932 )
7933}
7934
7935function typedArraySupport () {
7936 // Can typed array instances can be augmented?
9301 try { 7937 try {
9302 var arr = new Uint8Array(1) 7938 var arr = new Uint8Array(1)
9303 arr.foo = function () { return 42 } 7939 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
9304 arr.constructor = Bar 7940 return arr.foo() === 42
9305 return arr.foo() === 42 && // typed array instances can be augmented
9306 arr.constructor === Bar && // constructor can be set
9307 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
9308 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
9309 } catch (e) { 7941 } catch (e) {
9310 return false 7942 return false
9311 } 7943 }
9312})() 7944}
9313 7945
9314function kMaxLength () { 7946function createBuffer (length) {
9315 return Buffer.TYPED_ARRAY_SUPPORT 7947 if (length > K_MAX_LENGTH) {
9316 ? 0x7fffffff 7948 throw new RangeError('Invalid typed array length')
9317 : 0x3fffffff 7949 }
7950 // Return an augmented `Uint8Array` instance
7951 var buf = new Uint8Array(length)
7952 buf.__proto__ = Buffer.prototype
7953 return buf
9318} 7954}
9319 7955
9320/** 7956/**
9321 * Class: Buffer 7957 * The Buffer constructor returns instances of `Uint8Array` that have their
9322 * ============= 7958 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
9323 * 7959 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
9324 * The Buffer constructor returns instances of `Uint8Array` that are augmented 7960 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
9325 * with function properties for all the node `Buffer` API functions. We use 7961 * returns a single octet.
9326 * `Uint8Array` so that square bracket notation works as expected -- it returns
9327 * a single octet.
9328 * 7962 *
9329 * By augmenting the instances, we can avoid modifying the `Uint8Array` 7963 * The `Uint8Array` prototype remains unmodified.
9330 * prototype.
9331 */ 7964 */
9332function Buffer (arg) {
9333 if (!(this instanceof Buffer)) {
9334 // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
9335 if (arguments.length > 1) return new Buffer(arg, arguments[1])
9336 return new Buffer(arg)
9337 }
9338
9339 this.length = 0
9340 this.parent = undefined
9341 7965
7966function Buffer (arg, encodingOrOffset, length) {
9342 // Common case. 7967 // Common case.
9343 if (typeof arg === 'number') { 7968 if (typeof arg === 'number') {
9344 return fromNumber(this, arg) 7969 if (typeof encodingOrOffset === 'string') {
9345 } 7970 throw new Error(
9346 7971 'If encoding is specified then the first argument must be a string'
9347 // Slightly less common case. 7972 )
9348 if (typeof arg === 'string') { 7973 }
9349 return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') 7974 return allocUnsafe(arg)
9350 } 7975 }
7976 return from(arg, encodingOrOffset, length)
7977}
9351 7978
9352 // Unusual. 7979// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
9353 return fromObject(this, arg) 7980if (typeof Symbol !== 'undefined' && Symbol.species &&
7981 Buffer[Symbol.species] === Buffer) {
7982 Object.defineProperty(Buffer, Symbol.species, {
7983 value: null,
7984 configurable: true,
7985 enumerable: false,
7986 writable: false
7987 })
9354} 7988}
9355 7989
9356function fromNumber (that, length) { 7990Buffer.poolSize = 8192 // not used by this implementation
9357 that = allocate(that, length < 0 ? 0 : checked(length) | 0) 7991
9358 if (!Buffer.TYPED_ARRAY_SUPPORT) { 7992function from (value, encodingOrOffset, length) {
9359 for (var i = 0; i < length; i++) { 7993 if (typeof value === 'number') {
9360 that[i] = 0 7994 throw new TypeError('"value" argument must not be a number')
9361 }
9362 } 7995 }
9363 return that
9364}
9365 7996
9366function fromString (that, string, encoding) { 7997 if (value instanceof ArrayBuffer) {
9367 if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' 7998 return fromArrayBuffer(value, encodingOrOffset, length)
7999 }
9368 8000
9369 // Assumption: byteLength() return value is always < kMaxLength. 8001 if (typeof value === 'string') {
9370 var length = byteLength(string, encoding) | 0 8002 return fromString(value, encodingOrOffset)
9371 that = allocate(that, length) 8003 }
9372 8004
9373 that.write(string, encoding) 8005 return fromObject(value)
9374 return that
9375} 8006}
9376 8007
9377function fromObject (that, object) { 8008/**
9378 if (Buffer.isBuffer(object)) return fromBuffer(that, object) 8009 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
8010 * if value is a number.
8011 * Buffer.from(str[, encoding])
8012 * Buffer.from(array)
8013 * Buffer.from(buffer)
8014 * Buffer.from(arrayBuffer[, byteOffset[, length]])
8015 **/
8016Buffer.from = function (value, encodingOrOffset, length) {
8017 return from(value, encodingOrOffset, length)
8018}
9379 8019
9380 if (isArray(object)) return fromArray(that, object) 8020// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
8021// https://github.com/feross/buffer/pull/148
8022Buffer.prototype.__proto__ = Uint8Array.prototype
8023Buffer.__proto__ = Uint8Array
9381 8024
9382 if (object == null) { 8025function assertSize (size) {
9383 throw new TypeError('must start with number, buffer, array or string') 8026 if (typeof size !== 'number') {
8027 throw new TypeError('"size" argument must be a number')
8028 } else if (size < 0) {
8029 throw new RangeError('"size" argument must not be negative')
9384 } 8030 }
8031}
9385 8032
9386 if (typeof ArrayBuffer !== 'undefined') { 8033function alloc (size, fill, encoding) {
9387 if (object.buffer instanceof ArrayBuffer) { 8034 assertSize(size)
9388 return fromTypedArray(that, object) 8035 if (size <= 0) {
9389 } 8036 return createBuffer(size)
9390 if (object instanceof ArrayBuffer) {
9391 return fromArrayBuffer(that, object)
9392 }
9393 } 8037 }
8038 if (fill !== undefined) {
8039 // Only pay attention to encoding if it's a string. This
8040 // prevents accidentally sending in a number that would
8041 // be interpretted as a start offset.
8042 return typeof encoding === 'string'
8043 ? createBuffer(size).fill(fill, encoding)
8044 : createBuffer(size).fill(fill)
8045 }
8046 return createBuffer(size)
8047}
9394 8048
9395 if (object.length) return fromArrayLike(that, object) 8049/**
8050 * Creates a new filled Buffer instance.
8051 * alloc(size[, fill[, encoding]])
8052 **/
8053Buffer.alloc = function (size, fill, encoding) {
8054 return alloc(size, fill, encoding)
8055}
9396 8056
9397 return fromJsonObject(that, object) 8057function allocUnsafe (size) {
8058 assertSize(size)
8059 return createBuffer(size < 0 ? 0 : checked(size) | 0)
9398} 8060}
9399 8061
9400function fromBuffer (that, buffer) { 8062/**
9401 var length = checked(buffer.length) | 0 8063 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
9402 that = allocate(that, length) 8064 * */
9403 buffer.copy(that, 0, 0, length) 8065Buffer.allocUnsafe = function (size) {
9404 return that 8066 return allocUnsafe(size)
8067}
8068/**
8069 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
8070 */
8071Buffer.allocUnsafeSlow = function (size) {
8072 return allocUnsafe(size)
9405} 8073}
9406 8074
9407function fromArray (that, array) { 8075function fromString (string, encoding) {
9408 var length = checked(array.length) | 0 8076 if (typeof encoding !== 'string' || encoding === '') {
9409 that = allocate(that, length) 8077 encoding = 'utf8'
9410 for (var i = 0; i < length; i += 1) {
9411 that[i] = array[i] & 255
9412 } 8078 }
9413 return that
9414}
9415 8079
9416// Duplicate of fromArray() to keep fromArray() monomorphic. 8080 if (!Buffer.isEncoding(encoding)) {
9417function fromTypedArray (that, array) { 8081 throw new TypeError('"encoding" must be a valid string encoding')
9418 var length = checked(array.length) | 0
9419 that = allocate(that, length)
9420 // Truncating the elements is probably not what people expect from typed
9421 // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
9422 // of the old Buffer constructor.
9423 for (var i = 0; i < length; i += 1) {
9424 that[i] = array[i] & 255
9425 } 8082 }
9426 return that
9427}
9428 8083
9429function fromArrayBuffer (that, array) { 8084 var length = byteLength(string, encoding) | 0
9430 if (Buffer.TYPED_ARRAY_SUPPORT) { 8085 var buf = createBuffer(length)
9431 // Return an augmented `Uint8Array` instance, for best performance 8086
9432 array.byteLength 8087 var actual = buf.write(string, encoding)
9433 that = Buffer._augment(new Uint8Array(array)) 8088
9434 } else { 8089 if (actual !== length) {
9435 // Fallback: Return an object instance of the Buffer class 8090 // Writing a hex string, for example, that contains invalid characters will
9436 that = fromTypedArray(that, new Uint8Array(array)) 8091 // cause everything after the first invalid character to be ignored. (e.g.
8092 // 'abxxcd' will be treated as 'ab')
8093 buf = buf.slice(0, actual)
9437 } 8094 }
9438 return that 8095
8096 return buf
9439} 8097}
9440 8098
9441function fromArrayLike (that, array) { 8099function fromArrayLike (array) {
9442 var length = checked(array.length) | 0 8100 var length = array.length < 0 ? 0 : checked(array.length) | 0
9443 that = allocate(that, length) 8101 var buf = createBuffer(length)
9444 for (var i = 0; i < length; i += 1) { 8102 for (var i = 0; i < length; i += 1) {
9445 that[i] = array[i] & 255 8103 buf[i] = array[i] & 255
9446 } 8104 }
9447 return that 8105 return buf
9448} 8106}
9449 8107
9450// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. 8108function fromArrayBuffer (array, byteOffset, length) {
9451// Returns a zero-length buffer for inputs that don't conform to the spec. 8109 if (byteOffset < 0 || array.byteLength < byteOffset) {
9452function fromJsonObject (that, object) { 8110 throw new RangeError('\'offset\' is out of bounds')
9453 var array 8111 }
9454 var length = 0
9455 8112
9456 if (object.type === 'Buffer' && isArray(object.data)) { 8113 if (array.byteLength < byteOffset + (length || 0)) {
9457 array = object.data 8114 throw new RangeError('\'length\' is out of bounds')
9458 length = checked(array.length) | 0
9459 } 8115 }
9460 that = allocate(that, length)
9461 8116
9462 for (var i = 0; i < length; i += 1) { 8117 var buf
9463 that[i] = array[i] & 255 8118 if (byteOffset === undefined && length === undefined) {
8119 buf = new Uint8Array(array)
8120 } else if (length === undefined) {
8121 buf = new Uint8Array(array, byteOffset)
8122 } else {
8123 buf = new Uint8Array(array, byteOffset, length)
9464 } 8124 }
9465 return that 8125
8126 // Return an augmented `Uint8Array` instance
8127 buf.__proto__ = Buffer.prototype
8128 return buf
9466} 8129}
9467 8130
9468function allocate (that, length) { 8131function fromObject (obj) {
9469 if (Buffer.TYPED_ARRAY_SUPPORT) { 8132 if (Buffer.isBuffer(obj)) {
9470 // Return an augmented `Uint8Array` instance, for best performance 8133 var len = checked(obj.length) | 0
9471 that = Buffer._augment(new Uint8Array(length)) 8134 var buf = createBuffer(len)
9472 } else { 8135
9473 // Fallback: Return an object instance of the Buffer class 8136 if (buf.length === 0) {
9474 that.length = length 8137 return buf
9475 that._isBuffer = true 8138 }
8139
8140 obj.copy(buf, 0, 0, len)
8141 return buf
9476 } 8142 }
9477 8143
9478 var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 8144 if (obj) {
9479 if (fromPool) that.parent = rootParent 8145 if (isArrayBufferView(obj) || 'length' in obj) {
8146 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
8147 return createBuffer(0)
8148 }
8149 return fromArrayLike(obj)
8150 }
9480 8151
9481 return that 8152 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
8153 return fromArrayLike(obj.data)
8154 }
8155 }
8156
8157 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
9482} 8158}
9483 8159
9484function checked (length) { 8160function checked (length) {
9485 // Note: cannot use `length < kMaxLength` here because that fails when 8161 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
9486 // length is NaN (which is otherwise coerced to zero.) 8162 // length is NaN (which is otherwise coerced to zero.)
9487 if (length >= kMaxLength()) { 8163 if (length >= K_MAX_LENGTH) {
9488 throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 8164 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
9489 'size: 0x' + kMaxLength().toString(16) + ' bytes') 8165 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
9490 } 8166 }
9491 return length | 0 8167 return length | 0
9492} 8168}
9493 8169
9494function SlowBuffer (subject, encoding) { 8170function SlowBuffer (length) {
9495 if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) 8171 if (+length != length) { // eslint-disable-line eqeqeq
9496 8172 length = 0
9497 var buf = new Buffer(subject, encoding) 8173 }
9498 delete buf.parent 8174 return Buffer.alloc(+length)
9499 return buf
9500} 8175}
9501 8176
9502Buffer.isBuffer = function isBuffer (b) { 8177Buffer.isBuffer = function isBuffer (b) {
9503 return !!(b != null && b._isBuffer) 8178 return b != null && b._isBuffer === true
9504} 8179}
9505 8180
9506Buffer.compare = function compare (a, b) { 8181Buffer.compare = function compare (a, b) {
@@ -9513,17 +8188,12 @@ Buffer.compare = function compare (a, b) {
9513 var x = a.length 8188 var x = a.length
9514 var y = b.length 8189 var y = b.length
9515 8190
9516 var i = 0 8191 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
9517 var len = Math.min(x, y) 8192 if (a[i] !== b[i]) {
9518 while (i < len) { 8193 x = a[i]
9519 if (a[i] !== b[i]) break 8194 y = b[i]
9520 8195 break
9521 ++i 8196 }
9522 }
9523
9524 if (i !== len) {
9525 x = a[i]
9526 y = b[i]
9527 } 8197 }
9528 8198
9529 if (x < y) return -1 8199 if (x < y) return -1
@@ -9537,9 +8207,9 @@ Buffer.isEncoding = function isEncoding (encoding) {
9537 case 'utf8': 8207 case 'utf8':
9538 case 'utf-8': 8208 case 'utf-8':
9539 case 'ascii': 8209 case 'ascii':
8210 case 'latin1':
9540 case 'binary': 8211 case 'binary':
9541 case 'base64': 8212 case 'base64':
9542 case 'raw':
9543 case 'ucs2': 8213 case 'ucs2':
9544 case 'ucs-2': 8214 case 'ucs-2':
9545 case 'utf16le': 8215 case 'utf16le':
@@ -9551,32 +8221,45 @@ Buffer.isEncoding = function isEncoding (encoding) {
9551} 8221}
9552 8222
9553Buffer.concat = function concat (list, length) { 8223Buffer.concat = function concat (list, length) {
9554 if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') 8224 if (!Array.isArray(list)) {
8225 throw new TypeError('"list" argument must be an Array of Buffers')
8226 }
9555 8227
9556 if (list.length === 0) { 8228 if (list.length === 0) {
9557 return new Buffer(0) 8229 return Buffer.alloc(0)
9558 } 8230 }
9559 8231
9560 var i 8232 var i
9561 if (length === undefined) { 8233 if (length === undefined) {
9562 length = 0 8234 length = 0
9563 for (i = 0; i < list.length; i++) { 8235 for (i = 0; i < list.length; ++i) {
9564 length += list[i].length 8236 length += list[i].length
9565 } 8237 }
9566 } 8238 }
9567 8239
9568 var buf = new Buffer(length) 8240 var buffer = Buffer.allocUnsafe(length)
9569 var pos = 0 8241 var pos = 0
9570 for (i = 0; i < list.length; i++) { 8242 for (i = 0; i < list.length; ++i) {
9571 var item = list[i] 8243 var buf = list[i]
9572 item.copy(buf, pos) 8244 if (!Buffer.isBuffer(buf)) {
9573 pos += item.length 8245 throw new TypeError('"list" argument must be an Array of Buffers')
8246 }
8247 buf.copy(buffer, pos)
8248 pos += buf.length
9574 } 8249 }
9575 return buf 8250 return buffer
9576} 8251}
9577 8252
9578function byteLength (string, encoding) { 8253function byteLength (string, encoding) {
9579 if (typeof string !== 'string') string = '' + string 8254 if (Buffer.isBuffer(string)) {
8255 return string.length
8256 }
8257 if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
8258 return string.byteLength
8259 }
8260 if (typeof string !== 'string') {
8261 string = '' + string
8262 }
9580 8263
9581 var len = string.length 8264 var len = string.length
9582 if (len === 0) return 0 8265 if (len === 0) return 0
@@ -9586,13 +8269,12 @@ function byteLength (string, encoding) {
9586 for (;;) { 8269 for (;;) {
9587 switch (encoding) { 8270 switch (encoding) {
9588 case 'ascii': 8271 case 'ascii':
8272 case 'latin1':
9589 case 'binary': 8273 case 'binary':
9590 // Deprecated
9591 case 'raw':
9592 case 'raws':
9593 return len 8274 return len
9594 case 'utf8': 8275 case 'utf8':
9595 case 'utf-8': 8276 case 'utf-8':
8277 case undefined:
9596 return utf8ToBytes(string).length 8278 return utf8ToBytes(string).length
9597 case 'ucs2': 8279 case 'ucs2':
9598 case 'ucs-2': 8280 case 'ucs-2':
@@ -9612,20 +8294,42 @@ function byteLength (string, encoding) {
9612} 8294}
9613Buffer.byteLength = byteLength 8295Buffer.byteLength = byteLength
9614 8296
9615// pre-set for values that may exist in the future
9616Buffer.prototype.length = undefined
9617Buffer.prototype.parent = undefined
9618
9619function slowToString (encoding, start, end) { 8297function slowToString (encoding, start, end) {
9620 var loweredCase = false 8298 var loweredCase = false
9621 8299
9622 start = start | 0 8300 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
9623 end = end === undefined || end === Infinity ? this.length : end | 0 8301 // property of a typed array.
8302
8303 // This behaves neither like String nor Uint8Array in that we set start/end
8304 // to their upper/lower bounds if the value passed is out of range.
8305 // undefined is handled specially as per ECMA-262 6th Edition,
8306 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
8307 if (start === undefined || start < 0) {
8308 start = 0
8309 }
8310 // Return early if start > this.length. Done here to prevent potential uint32
8311 // coercion fail below.
8312 if (start > this.length) {
8313 return ''
8314 }
8315
8316 if (end === undefined || end > this.length) {
8317 end = this.length
8318 }
8319
8320 if (end <= 0) {
8321 return ''
8322 }
8323
8324 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
8325 end >>>= 0
8326 start >>>= 0
8327
8328 if (end <= start) {
8329 return ''
8330 }
9624 8331
9625 if (!encoding) encoding = 'utf8' 8332 if (!encoding) encoding = 'utf8'
9626 if (start < 0) start = 0
9627 if (end > this.length) end = this.length
9628 if (end <= start) return ''
9629 8333
9630 while (true) { 8334 while (true) {
9631 switch (encoding) { 8335 switch (encoding) {
@@ -9639,8 +8343,9 @@ function slowToString (encoding, start, end) {
9639 case 'ascii': 8343 case 'ascii':
9640 return asciiSlice(this, start, end) 8344 return asciiSlice(this, start, end)
9641 8345
8346 case 'latin1':
9642 case 'binary': 8347 case 'binary':
9643 return binarySlice(this, start, end) 8348 return latin1Slice(this, start, end)
9644 8349
9645 case 'base64': 8350 case 'base64':
9646 return base64Slice(this, start, end) 8351 return base64Slice(this, start, end)
@@ -9659,8 +8364,59 @@ function slowToString (encoding, start, end) {
9659 } 8364 }
9660} 8365}
9661 8366
8367// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
8368// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
8369// reliably in a browserify context because there could be multiple different
8370// copies of the 'buffer' package in use. This method works even for Buffer
8371// instances that were created from another copy of the `buffer` package.
8372// See: https://github.com/feross/buffer/issues/154
8373Buffer.prototype._isBuffer = true
8374
8375function swap (b, n, m) {
8376 var i = b[n]
8377 b[n] = b[m]
8378 b[m] = i
8379}
8380
8381Buffer.prototype.swap16 = function swap16 () {
8382 var len = this.length
8383 if (len % 2 !== 0) {
8384 throw new RangeError('Buffer size must be a multiple of 16-bits')
8385 }
8386 for (var i = 0; i < len; i += 2) {
8387 swap(this, i, i + 1)
8388 }
8389 return this
8390}
8391
8392Buffer.prototype.swap32 = function swap32 () {
8393 var len = this.length
8394 if (len % 4 !== 0) {
8395 throw new RangeError('Buffer size must be a multiple of 32-bits')
8396 }
8397 for (var i = 0; i < len; i += 4) {
8398 swap(this, i, i + 3)
8399 swap(this, i + 1, i + 2)
8400 }
8401 return this
8402}
8403
8404Buffer.prototype.swap64 = function swap64 () {
8405 var len = this.length
8406 if (len % 8 !== 0) {
8407 throw new RangeError('Buffer size must be a multiple of 64-bits')
8408 }
8409 for (var i = 0; i < len; i += 8) {
8410 swap(this, i, i + 7)
8411 swap(this, i + 1, i + 6)
8412 swap(this, i + 2, i + 5)
8413 swap(this, i + 3, i + 4)
8414 }
8415 return this
8416}
8417
9662Buffer.prototype.toString = function toString () { 8418Buffer.prototype.toString = function toString () {
9663 var length = this.length | 0 8419 var length = this.length
9664 if (length === 0) return '' 8420 if (length === 0) return ''
9665 if (arguments.length === 0) return utf8Slice(this, 0, length) 8421 if (arguments.length === 0) return utf8Slice(this, 0, length)
9666 return slowToString.apply(this, arguments) 8422 return slowToString.apply(this, arguments)
@@ -9682,63 +8438,196 @@ Buffer.prototype.inspect = function inspect () {
9682 return '<Buffer ' + str + '>' 8438 return '<Buffer ' + str + '>'
9683} 8439}
9684 8440
9685Buffer.prototype.compare = function compare (b) { 8441Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
9686 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') 8442 if (!Buffer.isBuffer(target)) {
9687 if (this === b) return 0 8443 throw new TypeError('Argument must be a Buffer')
9688 return Buffer.compare(this, b) 8444 }
8445
8446 if (start === undefined) {
8447 start = 0
8448 }
8449 if (end === undefined) {
8450 end = target ? target.length : 0
8451 }
8452 if (thisStart === undefined) {
8453 thisStart = 0
8454 }
8455 if (thisEnd === undefined) {
8456 thisEnd = this.length
8457 }
8458
8459 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
8460 throw new RangeError('out of range index')
8461 }
8462
8463 if (thisStart >= thisEnd && start >= end) {
8464 return 0
8465 }
8466 if (thisStart >= thisEnd) {
8467 return -1
8468 }
8469 if (start >= end) {
8470 return 1
8471 }
8472
8473 start >>>= 0
8474 end >>>= 0
8475 thisStart >>>= 0
8476 thisEnd >>>= 0
8477
8478 if (this === target) return 0
8479
8480 var x = thisEnd - thisStart
8481 var y = end - start
8482 var len = Math.min(x, y)
8483
8484 var thisCopy = this.slice(thisStart, thisEnd)
8485 var targetCopy = target.slice(start, end)
8486
8487 for (var i = 0; i < len; ++i) {
8488 if (thisCopy[i] !== targetCopy[i]) {
8489 x = thisCopy[i]
8490 y = targetCopy[i]
8491 break
8492 }
8493 }
8494
8495 if (x < y) return -1
8496 if (y < x) return 1
8497 return 0
9689} 8498}
9690 8499
9691Buffer.prototype.indexOf = function indexOf (val, byteOffset) { 8500// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
9692 if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff 8501// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
9693 else if (byteOffset < -0x80000000) byteOffset = -0x80000000 8502//
9694 byteOffset >>= 0 8503// Arguments:
8504// - buffer - a Buffer to search
8505// - val - a string, Buffer, or number
8506// - byteOffset - an index into `buffer`; will be clamped to an int32
8507// - encoding - an optional encoding, relevant is val is a string
8508// - dir - true for indexOf, false for lastIndexOf
8509function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
8510 // Empty buffer means no match
8511 if (buffer.length === 0) return -1
9695 8512
9696 if (this.length === 0) return -1 8513 // Normalize byteOffset
9697 if (byteOffset >= this.length) return -1 8514 if (typeof byteOffset === 'string') {
8515 encoding = byteOffset
8516 byteOffset = 0
8517 } else if (byteOffset > 0x7fffffff) {
8518 byteOffset = 0x7fffffff
8519 } else if (byteOffset < -0x80000000) {
8520 byteOffset = -0x80000000
8521 }
8522 byteOffset = +byteOffset // Coerce to Number.
8523 if (numberIsNaN(byteOffset)) {
8524 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
8525 byteOffset = dir ? 0 : (buffer.length - 1)
8526 }
9698 8527
9699 // Negative offsets start from the end of the buffer 8528 // Normalize byteOffset: negative offsets start from the end of the buffer
9700 if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) 8529 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
8530 if (byteOffset >= buffer.length) {
8531 if (dir) return -1
8532 else byteOffset = buffer.length - 1
8533 } else if (byteOffset < 0) {
8534 if (dir) byteOffset = 0
8535 else return -1
8536 }
9701 8537
8538 // Normalize val
9702 if (typeof val === 'string') { 8539 if (typeof val === 'string') {
9703 if (val.length === 0) return -1 // special case: looking for empty string always fails 8540 val = Buffer.from(val, encoding)
9704 return String.prototype.indexOf.call(this, val, byteOffset)
9705 } 8541 }
8542
8543 // Finally, search either indexOf (if dir is true) or lastIndexOf
9706 if (Buffer.isBuffer(val)) { 8544 if (Buffer.isBuffer(val)) {
9707 return arrayIndexOf(this, val, byteOffset) 8545 // Special case: looking for empty string/buffer always fails
8546 if (val.length === 0) {
8547 return -1
8548 }
8549 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
8550 } else if (typeof val === 'number') {
8551 val = val & 0xFF // Search for a byte value [0-255]
8552 if (typeof Uint8Array.prototype.indexOf === 'function') {
8553 if (dir) {
8554 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
8555 } else {
8556 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
8557 }
8558 }
8559 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
9708 } 8560 }
9709 if (typeof val === 'number') { 8561
9710 if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { 8562 throw new TypeError('val must be string, number or Buffer')
9711 return Uint8Array.prototype.indexOf.call(this, val, byteOffset) 8563}
8564
8565function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
8566 var indexSize = 1
8567 var arrLength = arr.length
8568 var valLength = val.length
8569
8570 if (encoding !== undefined) {
8571 encoding = String(encoding).toLowerCase()
8572 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
8573 encoding === 'utf16le' || encoding === 'utf-16le') {
8574 if (arr.length < 2 || val.length < 2) {
8575 return -1
8576 }
8577 indexSize = 2
8578 arrLength /= 2
8579 valLength /= 2
8580 byteOffset /= 2
8581 }
8582 }
8583
8584 function read (buf, i) {
8585 if (indexSize === 1) {
8586 return buf[i]
8587 } else {
8588 return buf.readUInt16BE(i * indexSize)
9712 } 8589 }
9713 return arrayIndexOf(this, [ val ], byteOffset)
9714 } 8590 }
9715 8591
9716 function arrayIndexOf (arr, val, byteOffset) { 8592 var i
8593 if (dir) {
9717 var foundIndex = -1 8594 var foundIndex = -1
9718 for (var i = 0; byteOffset + i < arr.length; i++) { 8595 for (i = byteOffset; i < arrLength; i++) {
9719 if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { 8596 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
9720 if (foundIndex === -1) foundIndex = i 8597 if (foundIndex === -1) foundIndex = i
9721 if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex 8598 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
9722 } else { 8599 } else {
8600 if (foundIndex !== -1) i -= i - foundIndex
9723 foundIndex = -1 8601 foundIndex = -1
9724 } 8602 }
9725 } 8603 }
9726 return -1 8604 } else {
8605 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
8606 for (i = byteOffset; i >= 0; i--) {
8607 var found = true
8608 for (var j = 0; j < valLength; j++) {
8609 if (read(arr, i + j) !== read(val, j)) {
8610 found = false
8611 break
8612 }
8613 }
8614 if (found) return i
8615 }
9727 } 8616 }
9728 8617
9729 throw new TypeError('val must be string, number or Buffer') 8618 return -1
9730} 8619}
9731 8620
9732// `get` is deprecated 8621Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
9733Buffer.prototype.get = function get (offset) { 8622 return this.indexOf(val, byteOffset, encoding) !== -1
9734 console.log('.get() is deprecated. Access using array indexes instead.')
9735 return this.readUInt8(offset)
9736} 8623}
9737 8624
9738// `set` is deprecated 8625Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
9739Buffer.prototype.set = function set (v, offset) { 8626 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
9740 console.log('.set() is deprecated. Access using array indexes instead.') 8627}
9741 return this.writeUInt8(v, offset) 8628
8629Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
8630 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
9742} 8631}
9743 8632
9744function hexWrite (buf, string, offset, length) { 8633function hexWrite (buf, string, offset, length) {
@@ -9755,14 +8644,14 @@ function hexWrite (buf, string, offset, length) {
9755 8644
9756 // must be an even number of digits 8645 // must be an even number of digits
9757 var strLen = string.length 8646 var strLen = string.length
9758 if (strLen % 2 !== 0) throw new Error('Invalid hex string') 8647 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
9759 8648
9760 if (length > strLen / 2) { 8649 if (length > strLen / 2) {
9761 length = strLen / 2 8650 length = strLen / 2
9762 } 8651 }
9763 for (var i = 0; i < length; i++) { 8652 for (var i = 0; i < length; ++i) {
9764 var parsed = parseInt(string.substr(i * 2, 2), 16) 8653 var parsed = parseInt(string.substr(i * 2, 2), 16)
9765 if (isNaN(parsed)) throw new Error('Invalid hex string') 8654 if (numberIsNaN(parsed)) return i
9766 buf[offset + i] = parsed 8655 buf[offset + i] = parsed
9767 } 8656 }
9768 return i 8657 return i
@@ -9776,7 +8665,7 @@ function asciiWrite (buf, string, offset, length) {
9776 return blitBuffer(asciiToBytes(string), buf, offset, length) 8665 return blitBuffer(asciiToBytes(string), buf, offset, length)
9777} 8666}
9778 8667
9779function binaryWrite (buf, string, offset, length) { 8668function latin1Write (buf, string, offset, length) {
9780 return asciiWrite(buf, string, offset, length) 8669 return asciiWrite(buf, string, offset, length)
9781} 8670}
9782 8671
@@ -9801,27 +8690,25 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
9801 offset = 0 8690 offset = 0
9802 // Buffer#write(string, offset[, length][, encoding]) 8691 // Buffer#write(string, offset[, length][, encoding])
9803 } else if (isFinite(offset)) { 8692 } else if (isFinite(offset)) {
9804 offset = offset | 0 8693 offset = offset >>> 0
9805 if (isFinite(length)) { 8694 if (isFinite(length)) {
9806 length = length | 0 8695 length = length >>> 0
9807 if (encoding === undefined) encoding = 'utf8' 8696 if (encoding === undefined) encoding = 'utf8'
9808 } else { 8697 } else {
9809 encoding = length 8698 encoding = length
9810 length = undefined 8699 length = undefined
9811 } 8700 }
9812 // legacy write(string, encoding, offset, length) - remove in v0.13
9813 } else { 8701 } else {
9814 var swap = encoding 8702 throw new Error(
9815 encoding = offset 8703 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
9816 offset = length | 0 8704 )
9817 length = swap
9818 } 8705 }
9819 8706
9820 var remaining = this.length - offset 8707 var remaining = this.length - offset
9821 if (length === undefined || length > remaining) length = remaining 8708 if (length === undefined || length > remaining) length = remaining
9822 8709
9823 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { 8710 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
9824 throw new RangeError('attempt to write outside buffer bounds') 8711 throw new RangeError('Attempt to write outside buffer bounds')
9825 } 8712 }
9826 8713
9827 if (!encoding) encoding = 'utf8' 8714 if (!encoding) encoding = 'utf8'
@@ -9839,8 +8726,9 @@ Buffer.prototype.write = function write (string, offset, length, encoding) {
9839 case 'ascii': 8726 case 'ascii':
9840 return asciiWrite(this, string, offset, length) 8727 return asciiWrite(this, string, offset, length)
9841 8728
8729 case 'latin1':
9842 case 'binary': 8730 case 'binary':
9843 return binaryWrite(this, string, offset, length) 8731 return latin1Write(this, string, offset, length)
9844 8732
9845 case 'base64': 8733 case 'base64':
9846 // Warning: maxLength not taken into account in base64Write 8734 // Warning: maxLength not taken into account in base64Write
@@ -9877,31 +8765,20 @@ function base64Slice (buf, start, end) {
9877 8765
9878function utf8Slice (buf, start, end) { 8766function utf8Slice (buf, start, end) {
9879 end = Math.min(buf.length, end) 8767 end = Math.min(buf.length, end)
9880 var firstByte
9881 var secondByte
9882 var thirdByte
9883 var fourthByte
9884 var bytesPerSequence
9885 var tempCodePoint
9886 var codePoint
9887 var res = [] 8768 var res = []
9888 var i = start
9889
9890 for (; i < end; i += bytesPerSequence) {
9891 firstByte = buf[i]
9892 codePoint = 0xFFFD
9893 8769
9894 if (firstByte > 0xEF) { 8770 var i = start
9895 bytesPerSequence = 4 8771 while (i < end) {
9896 } else if (firstByte > 0xDF) { 8772 var firstByte = buf[i]
9897 bytesPerSequence = 3 8773 var codePoint = null
9898 } else if (firstByte > 0xBF) { 8774 var bytesPerSequence = (firstByte > 0xEF) ? 4
9899 bytesPerSequence = 2 8775 : (firstByte > 0xDF) ? 3
9900 } else { 8776 : (firstByte > 0xBF) ? 2
9901 bytesPerSequence = 1 8777 : 1
9902 }
9903 8778
9904 if (i + bytesPerSequence <= end) { 8779 if (i + bytesPerSequence <= end) {
8780 var secondByte, thirdByte, fourthByte, tempCodePoint
8781
9905 switch (bytesPerSequence) { 8782 switch (bytesPerSequence) {
9906 case 1: 8783 case 1:
9907 if (firstByte < 0x80) { 8784 if (firstByte < 0x80) {
@@ -9940,8 +8817,10 @@ function utf8Slice (buf, start, end) {
9940 } 8817 }
9941 } 8818 }
9942 8819
9943 if (codePoint === 0xFFFD) { 8820 if (codePoint === null) {
9944 // we generated an invalid codePoint so make sure to only advance by 1 byte 8821 // we did not generate a valid codePoint so insert a
8822 // replacement char (U+FFFD) and advance only 1 byte
8823 codePoint = 0xFFFD
9945 bytesPerSequence = 1 8824 bytesPerSequence = 1
9946 } else if (codePoint > 0xFFFF) { 8825 } else if (codePoint > 0xFFFF) {
9947 // encode to utf16 (surrogate pair dance) 8826 // encode to utf16 (surrogate pair dance)
@@ -9951,26 +8830,50 @@ function utf8Slice (buf, start, end) {
9951 } 8830 }
9952 8831
9953 res.push(codePoint) 8832 res.push(codePoint)
8833 i += bytesPerSequence
8834 }
8835
8836 return decodeCodePointsArray(res)
8837}
8838
8839// Based on http://stackoverflow.com/a/22747272/680742, the browser with
8840// the lowest limit is Chrome, with 0x10000 args.
8841// We go 1 magnitude less, for safety
8842var MAX_ARGUMENTS_LENGTH = 0x1000
8843
8844function decodeCodePointsArray (codePoints) {
8845 var len = codePoints.length
8846 if (len <= MAX_ARGUMENTS_LENGTH) {
8847 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
9954 } 8848 }
9955 8849
9956 return String.fromCharCode.apply(String, res) 8850 // Decode in chunks to avoid "call stack size exceeded".
8851 var res = ''
8852 var i = 0
8853 while (i < len) {
8854 res += String.fromCharCode.apply(
8855 String,
8856 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
8857 )
8858 }
8859 return res
9957} 8860}
9958 8861
9959function asciiSlice (buf, start, end) { 8862function asciiSlice (buf, start, end) {
9960 var ret = '' 8863 var ret = ''
9961 end = Math.min(buf.length, end) 8864 end = Math.min(buf.length, end)
9962 8865
9963 for (var i = start; i < end; i++) { 8866 for (var i = start; i < end; ++i) {
9964 ret += String.fromCharCode(buf[i] & 0x7F) 8867 ret += String.fromCharCode(buf[i] & 0x7F)
9965 } 8868 }
9966 return ret 8869 return ret
9967} 8870}
9968 8871
9969function binarySlice (buf, start, end) { 8872function latin1Slice (buf, start, end) {
9970 var ret = '' 8873 var ret = ''
9971 end = Math.min(buf.length, end) 8874 end = Math.min(buf.length, end)
9972 8875
9973 for (var i = start; i < end; i++) { 8876 for (var i = start; i < end; ++i) {
9974 ret += String.fromCharCode(buf[i]) 8877 ret += String.fromCharCode(buf[i])
9975 } 8878 }
9976 return ret 8879 return ret
@@ -9983,7 +8886,7 @@ function hexSlice (buf, start, end) {
9983 if (!end || end < 0 || end > len) end = len 8886 if (!end || end < 0 || end > len) end = len
9984 8887
9985 var out = '' 8888 var out = ''
9986 for (var i = start; i < end; i++) { 8889 for (var i = start; i < end; ++i) {
9987 out += toHex(buf[i]) 8890 out += toHex(buf[i])
9988 } 8891 }
9989 return out 8892 return out
@@ -9993,7 +8896,7 @@ function utf16leSlice (buf, start, end) {
9993 var bytes = buf.slice(start, end) 8896 var bytes = buf.slice(start, end)
9994 var res = '' 8897 var res = ''
9995 for (var i = 0; i < bytes.length; i += 2) { 8898 for (var i = 0; i < bytes.length; i += 2) {
9996 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) 8899 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
9997 } 8900 }
9998 return res 8901 return res
9999} 8902}
@@ -10019,19 +8922,9 @@ Buffer.prototype.slice = function slice (start, end) {
10019 8922
10020 if (end < start) end = start 8923 if (end < start) end = start
10021 8924
10022 var newBuf 8925 var newBuf = this.subarray(start, end)
10023 if (Buffer.TYPED_ARRAY_SUPPORT) { 8926 // Return an augmented `Uint8Array` instance
10024 newBuf = Buffer._augment(this.subarray(start, end)) 8927 newBuf.__proto__ = Buffer.prototype
10025 } else {
10026 var sliceLen = end - start
10027 newBuf = new Buffer(sliceLen, undefined)
10028 for (var i = 0; i < sliceLen; i++) {
10029 newBuf[i] = this[i + start]
10030 }
10031 }
10032
10033 if (newBuf.length) newBuf.parent = this.parent || this
10034
10035 return newBuf 8928 return newBuf
10036} 8929}
10037 8930
@@ -10044,8 +8937,8 @@ function checkOffset (offset, ext, length) {
10044} 8937}
10045 8938
10046Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { 8939Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
10047 offset = offset | 0 8940 offset = offset >>> 0
10048 byteLength = byteLength | 0 8941 byteLength = byteLength >>> 0
10049 if (!noAssert) checkOffset(offset, byteLength, this.length) 8942 if (!noAssert) checkOffset(offset, byteLength, this.length)
10050 8943
10051 var val = this[offset] 8944 var val = this[offset]
@@ -10059,8 +8952,8 @@ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert)
10059} 8952}
10060 8953
10061Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { 8954Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
10062 offset = offset | 0 8955 offset = offset >>> 0
10063 byteLength = byteLength | 0 8956 byteLength = byteLength >>> 0
10064 if (!noAssert) { 8957 if (!noAssert) {
10065 checkOffset(offset, byteLength, this.length) 8958 checkOffset(offset, byteLength, this.length)
10066 } 8959 }
@@ -10075,21 +8968,25 @@ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert)
10075} 8968}
10076 8969
10077Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { 8970Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
8971 offset = offset >>> 0
10078 if (!noAssert) checkOffset(offset, 1, this.length) 8972 if (!noAssert) checkOffset(offset, 1, this.length)
10079 return this[offset] 8973 return this[offset]
10080} 8974}
10081 8975
10082Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { 8976Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
8977 offset = offset >>> 0
10083 if (!noAssert) checkOffset(offset, 2, this.length) 8978 if (!noAssert) checkOffset(offset, 2, this.length)
10084 return this[offset] | (this[offset + 1] << 8) 8979 return this[offset] | (this[offset + 1] << 8)
10085} 8980}
10086 8981
10087Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { 8982Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
8983 offset = offset >>> 0
10088 if (!noAssert) checkOffset(offset, 2, this.length) 8984 if (!noAssert) checkOffset(offset, 2, this.length)
10089 return (this[offset] << 8) | this[offset + 1] 8985 return (this[offset] << 8) | this[offset + 1]
10090} 8986}
10091 8987
10092Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { 8988Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
8989 offset = offset >>> 0
10093 if (!noAssert) checkOffset(offset, 4, this.length) 8990 if (!noAssert) checkOffset(offset, 4, this.length)
10094 8991
10095 return ((this[offset]) | 8992 return ((this[offset]) |
@@ -10099,6 +8996,7 @@ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
10099} 8996}
10100 8997
10101Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { 8998Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
8999 offset = offset >>> 0
10102 if (!noAssert) checkOffset(offset, 4, this.length) 9000 if (!noAssert) checkOffset(offset, 4, this.length)
10103 9001
10104 return (this[offset] * 0x1000000) + 9002 return (this[offset] * 0x1000000) +
@@ -10108,8 +9006,8 @@ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
10108} 9006}
10109 9007
10110Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { 9008Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
10111 offset = offset | 0 9009 offset = offset >>> 0
10112 byteLength = byteLength | 0 9010 byteLength = byteLength >>> 0
10113 if (!noAssert) checkOffset(offset, byteLength, this.length) 9011 if (!noAssert) checkOffset(offset, byteLength, this.length)
10114 9012
10115 var val = this[offset] 9013 var val = this[offset]
@@ -10126,8 +9024,8 @@ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
10126} 9024}
10127 9025
10128Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { 9026Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
10129 offset = offset | 0 9027 offset = offset >>> 0
10130 byteLength = byteLength | 0 9028 byteLength = byteLength >>> 0
10131 if (!noAssert) checkOffset(offset, byteLength, this.length) 9029 if (!noAssert) checkOffset(offset, byteLength, this.length)
10132 9030
10133 var i = byteLength 9031 var i = byteLength
@@ -10144,24 +9042,28 @@ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
10144} 9042}
10145 9043
10146Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { 9044Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
9045 offset = offset >>> 0
10147 if (!noAssert) checkOffset(offset, 1, this.length) 9046 if (!noAssert) checkOffset(offset, 1, this.length)
10148 if (!(this[offset] & 0x80)) return (this[offset]) 9047 if (!(this[offset] & 0x80)) return (this[offset])
10149 return ((0xff - this[offset] + 1) * -1) 9048 return ((0xff - this[offset] + 1) * -1)
10150} 9049}
10151 9050
10152Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { 9051Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
9052 offset = offset >>> 0
10153 if (!noAssert) checkOffset(offset, 2, this.length) 9053 if (!noAssert) checkOffset(offset, 2, this.length)
10154 var val = this[offset] | (this[offset + 1] << 8) 9054 var val = this[offset] | (this[offset + 1] << 8)
10155 return (val & 0x8000) ? val | 0xFFFF0000 : val 9055 return (val & 0x8000) ? val | 0xFFFF0000 : val
10156} 9056}
10157 9057
10158Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { 9058Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
9059 offset = offset >>> 0
10159 if (!noAssert) checkOffset(offset, 2, this.length) 9060 if (!noAssert) checkOffset(offset, 2, this.length)
10160 var val = this[offset + 1] | (this[offset] << 8) 9061 var val = this[offset + 1] | (this[offset] << 8)
10161 return (val & 0x8000) ? val | 0xFFFF0000 : val 9062 return (val & 0x8000) ? val | 0xFFFF0000 : val
10162} 9063}
10163 9064
10164Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { 9065Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
9066 offset = offset >>> 0
10165 if (!noAssert) checkOffset(offset, 4, this.length) 9067 if (!noAssert) checkOffset(offset, 4, this.length)
10166 9068
10167 return (this[offset]) | 9069 return (this[offset]) |
@@ -10171,6 +9073,7 @@ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
10171} 9073}
10172 9074
10173Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { 9075Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
9076 offset = offset >>> 0
10174 if (!noAssert) checkOffset(offset, 4, this.length) 9077 if (!noAssert) checkOffset(offset, 4, this.length)
10175 9078
10176 return (this[offset] << 24) | 9079 return (this[offset] << 24) |
@@ -10180,36 +9083,43 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
10180} 9083}
10181 9084
10182Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { 9085Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
9086 offset = offset >>> 0
10183 if (!noAssert) checkOffset(offset, 4, this.length) 9087 if (!noAssert) checkOffset(offset, 4, this.length)
10184 return ieee754.read(this, offset, true, 23, 4) 9088 return ieee754.read(this, offset, true, 23, 4)
10185} 9089}
10186 9090
10187Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { 9091Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
9092 offset = offset >>> 0
10188 if (!noAssert) checkOffset(offset, 4, this.length) 9093 if (!noAssert) checkOffset(offset, 4, this.length)
10189 return ieee754.read(this, offset, false, 23, 4) 9094 return ieee754.read(this, offset, false, 23, 4)
10190} 9095}
10191 9096
10192Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { 9097Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
9098 offset = offset >>> 0
10193 if (!noAssert) checkOffset(offset, 8, this.length) 9099 if (!noAssert) checkOffset(offset, 8, this.length)
10194 return ieee754.read(this, offset, true, 52, 8) 9100 return ieee754.read(this, offset, true, 52, 8)
10195} 9101}
10196 9102
10197Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { 9103Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
9104 offset = offset >>> 0
10198 if (!noAssert) checkOffset(offset, 8, this.length) 9105 if (!noAssert) checkOffset(offset, 8, this.length)
10199 return ieee754.read(this, offset, false, 52, 8) 9106 return ieee754.read(this, offset, false, 52, 8)
10200} 9107}
10201 9108
10202function checkInt (buf, value, offset, ext, max, min) { 9109function checkInt (buf, value, offset, ext, max, min) {
10203 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') 9110 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
10204 if (value > max || value < min) throw new RangeError('value is out of bounds') 9111 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
10205 if (offset + ext > buf.length) throw new RangeError('index out of range') 9112 if (offset + ext > buf.length) throw new RangeError('Index out of range')
10206} 9113}
10207 9114
10208Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { 9115Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
10209 value = +value 9116 value = +value
10210 offset = offset | 0 9117 offset = offset >>> 0
10211 byteLength = byteLength | 0 9118 byteLength = byteLength >>> 0
10212 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) 9119 if (!noAssert) {
9120 var maxBytes = Math.pow(2, 8 * byteLength) - 1
9121 checkInt(this, value, offset, byteLength, maxBytes, 0)
9122 }
10213 9123
10214 var mul = 1 9124 var mul = 1
10215 var i = 0 9125 var i = 0
@@ -10223,9 +9133,12 @@ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength,
10223 9133
10224Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { 9134Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
10225 value = +value 9135 value = +value
10226 offset = offset | 0 9136 offset = offset >>> 0
10227 byteLength = byteLength | 0 9137 byteLength = byteLength >>> 0
10228 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) 9138 if (!noAssert) {
9139 var maxBytes = Math.pow(2, 8 * byteLength) - 1
9140 checkInt(this, value, offset, byteLength, maxBytes, 0)
9141 }
10229 9142
10230 var i = byteLength - 1 9143 var i = byteLength - 1
10231 var mul = 1 9144 var mul = 1
@@ -10239,98 +9152,69 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength,
10239 9152
10240Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { 9153Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
10241 value = +value 9154 value = +value
10242 offset = offset | 0 9155 offset = offset >>> 0
10243 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) 9156 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
10244 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) 9157 this[offset] = (value & 0xff)
10245 this[offset] = value
10246 return offset + 1 9158 return offset + 1
10247} 9159}
10248 9160
10249function objectWriteUInt16 (buf, value, offset, littleEndian) {
10250 if (value < 0) value = 0xffff + value + 1
10251 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
10252 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
10253 (littleEndian ? i : 1 - i) * 8
10254 }
10255}
10256
10257Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { 9161Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
10258 value = +value 9162 value = +value
10259 offset = offset | 0 9163 offset = offset >>> 0
10260 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) 9164 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
10261 if (Buffer.TYPED_ARRAY_SUPPORT) { 9165 this[offset] = (value & 0xff)
10262 this[offset] = value 9166 this[offset + 1] = (value >>> 8)
10263 this[offset + 1] = (value >>> 8)
10264 } else {
10265 objectWriteUInt16(this, value, offset, true)
10266 }
10267 return offset + 2 9167 return offset + 2
10268} 9168}
10269 9169
10270Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { 9170Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
10271 value = +value 9171 value = +value
10272 offset = offset | 0 9172 offset = offset >>> 0
10273 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) 9173 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
10274 if (Buffer.TYPED_ARRAY_SUPPORT) { 9174 this[offset] = (value >>> 8)
10275 this[offset] = (value >>> 8) 9175 this[offset + 1] = (value & 0xff)
10276 this[offset + 1] = value
10277 } else {
10278 objectWriteUInt16(this, value, offset, false)
10279 }
10280 return offset + 2 9176 return offset + 2
10281} 9177}
10282 9178
10283function objectWriteUInt32 (buf, value, offset, littleEndian) {
10284 if (value < 0) value = 0xffffffff + value + 1
10285 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
10286 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
10287 }
10288}
10289
10290Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { 9179Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
10291 value = +value 9180 value = +value
10292 offset = offset | 0 9181 offset = offset >>> 0
10293 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) 9182 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
10294 if (Buffer.TYPED_ARRAY_SUPPORT) { 9183 this[offset + 3] = (value >>> 24)
10295 this[offset + 3] = (value >>> 24) 9184 this[offset + 2] = (value >>> 16)
10296 this[offset + 2] = (value >>> 16) 9185 this[offset + 1] = (value >>> 8)
10297 this[offset + 1] = (value >>> 8) 9186 this[offset] = (value & 0xff)
10298 this[offset] = value
10299 } else {
10300 objectWriteUInt32(this, value, offset, true)
10301 }
10302 return offset + 4 9187 return offset + 4
10303} 9188}
10304 9189
10305Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { 9190Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
10306 value = +value 9191 value = +value
10307 offset = offset | 0 9192 offset = offset >>> 0
10308 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) 9193 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
10309 if (Buffer.TYPED_ARRAY_SUPPORT) { 9194 this[offset] = (value >>> 24)
10310 this[offset] = (value >>> 24) 9195 this[offset + 1] = (value >>> 16)
10311 this[offset + 1] = (value >>> 16) 9196 this[offset + 2] = (value >>> 8)
10312 this[offset + 2] = (value >>> 8) 9197 this[offset + 3] = (value & 0xff)
10313 this[offset + 3] = value
10314 } else {
10315 objectWriteUInt32(this, value, offset, false)
10316 }
10317 return offset + 4 9198 return offset + 4
10318} 9199}
10319 9200
10320Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { 9201Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
10321 value = +value 9202 value = +value
10322 offset = offset | 0 9203 offset = offset >>> 0
10323 if (!noAssert) { 9204 if (!noAssert) {
10324 var limit = Math.pow(2, 8 * byteLength - 1) 9205 var limit = Math.pow(2, (8 * byteLength) - 1)
10325 9206
10326 checkInt(this, value, offset, byteLength, limit - 1, -limit) 9207 checkInt(this, value, offset, byteLength, limit - 1, -limit)
10327 } 9208 }
10328 9209
10329 var i = 0 9210 var i = 0
10330 var mul = 1 9211 var mul = 1
10331 var sub = value < 0 ? 1 : 0 9212 var sub = 0
10332 this[offset] = value & 0xFF 9213 this[offset] = value & 0xFF
10333 while (++i < byteLength && (mul *= 0x100)) { 9214 while (++i < byteLength && (mul *= 0x100)) {
9215 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
9216 sub = 1
9217 }
10334 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF 9218 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
10335 } 9219 }
10336 9220
@@ -10339,18 +9223,21 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no
10339 9223
10340Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { 9224Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
10341 value = +value 9225 value = +value
10342 offset = offset | 0 9226 offset = offset >>> 0
10343 if (!noAssert) { 9227 if (!noAssert) {
10344 var limit = Math.pow(2, 8 * byteLength - 1) 9228 var limit = Math.pow(2, (8 * byteLength) - 1)
10345 9229
10346 checkInt(this, value, offset, byteLength, limit - 1, -limit) 9230 checkInt(this, value, offset, byteLength, limit - 1, -limit)
10347 } 9231 }
10348 9232
10349 var i = byteLength - 1 9233 var i = byteLength - 1
10350 var mul = 1 9234 var mul = 1
10351 var sub = value < 0 ? 1 : 0 9235 var sub = 0
10352 this[offset + i] = value & 0xFF 9236 this[offset + i] = value & 0xFF
10353 while (--i >= 0 && (mul *= 0x100)) { 9237 while (--i >= 0 && (mul *= 0x100)) {
9238 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
9239 sub = 1
9240 }
10354 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF 9241 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
10355 } 9242 }
10356 9243
@@ -10359,78 +9246,62 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no
10359 9246
10360Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { 9247Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
10361 value = +value 9248 value = +value
10362 offset = offset | 0 9249 offset = offset >>> 0
10363 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) 9250 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
10364 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
10365 if (value < 0) value = 0xff + value + 1 9251 if (value < 0) value = 0xff + value + 1
10366 this[offset] = value 9252 this[offset] = (value & 0xff)
10367 return offset + 1 9253 return offset + 1
10368} 9254}
10369 9255
10370Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { 9256Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
10371 value = +value 9257 value = +value
10372 offset = offset | 0 9258 offset = offset >>> 0
10373 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) 9259 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
10374 if (Buffer.TYPED_ARRAY_SUPPORT) { 9260 this[offset] = (value & 0xff)
10375 this[offset] = value 9261 this[offset + 1] = (value >>> 8)
10376 this[offset + 1] = (value >>> 8)
10377 } else {
10378 objectWriteUInt16(this, value, offset, true)
10379 }
10380 return offset + 2 9262 return offset + 2
10381} 9263}
10382 9264
10383Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { 9265Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
10384 value = +value 9266 value = +value
10385 offset = offset | 0 9267 offset = offset >>> 0
10386 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) 9268 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
10387 if (Buffer.TYPED_ARRAY_SUPPORT) { 9269 this[offset] = (value >>> 8)
10388 this[offset] = (value >>> 8) 9270 this[offset + 1] = (value & 0xff)
10389 this[offset + 1] = value
10390 } else {
10391 objectWriteUInt16(this, value, offset, false)
10392 }
10393 return offset + 2 9271 return offset + 2
10394} 9272}
10395 9273
10396Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { 9274Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
10397 value = +value 9275 value = +value
10398 offset = offset | 0 9276 offset = offset >>> 0
10399 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) 9277 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
10400 if (Buffer.TYPED_ARRAY_SUPPORT) { 9278 this[offset] = (value & 0xff)
10401 this[offset] = value 9279 this[offset + 1] = (value >>> 8)
10402 this[offset + 1] = (value >>> 8) 9280 this[offset + 2] = (value >>> 16)
10403 this[offset + 2] = (value >>> 16) 9281 this[offset + 3] = (value >>> 24)
10404 this[offset + 3] = (value >>> 24)
10405 } else {
10406 objectWriteUInt32(this, value, offset, true)
10407 }
10408 return offset + 4 9282 return offset + 4
10409} 9283}
10410 9284
10411Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { 9285Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
10412 value = +value 9286 value = +value
10413 offset = offset | 0 9287 offset = offset >>> 0
10414 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) 9288 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
10415 if (value < 0) value = 0xffffffff + value + 1 9289 if (value < 0) value = 0xffffffff + value + 1
10416 if (Buffer.TYPED_ARRAY_SUPPORT) { 9290 this[offset] = (value >>> 24)
10417 this[offset] = (value >>> 24) 9291 this[offset + 1] = (value >>> 16)
10418 this[offset + 1] = (value >>> 16) 9292 this[offset + 2] = (value >>> 8)
10419 this[offset + 2] = (value >>> 8) 9293 this[offset + 3] = (value & 0xff)
10420 this[offset + 3] = value
10421 } else {
10422 objectWriteUInt32(this, value, offset, false)
10423 }
10424 return offset + 4 9294 return offset + 4
10425} 9295}
10426 9296
10427function checkIEEE754 (buf, value, offset, ext, max, min) { 9297function checkIEEE754 (buf, value, offset, ext, max, min) {
10428 if (value > max || value < min) throw new RangeError('value is out of bounds') 9298 if (offset + ext > buf.length) throw new RangeError('Index out of range')
10429 if (offset + ext > buf.length) throw new RangeError('index out of range') 9299 if (offset < 0) throw new RangeError('Index out of range')
10430 if (offset < 0) throw new RangeError('index out of range')
10431} 9300}
10432 9301
10433function writeFloat (buf, value, offset, littleEndian, noAssert) { 9302function writeFloat (buf, value, offset, littleEndian, noAssert) {
9303 value = +value
9304 offset = offset >>> 0
10434 if (!noAssert) { 9305 if (!noAssert) {
10435 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) 9306 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
10436 } 9307 }
@@ -10447,6 +9318,8 @@ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert)
10447} 9318}
10448 9319
10449function writeDouble (buf, value, offset, littleEndian, noAssert) { 9320function writeDouble (buf, value, offset, littleEndian, noAssert) {
9321 value = +value
9322 offset = offset >>> 0
10450 if (!noAssert) { 9323 if (!noAssert) {
10451 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) 9324 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
10452 } 9325 }
@@ -10492,148 +9365,96 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
10492 9365
10493 if (this === target && start < targetStart && targetStart < end) { 9366 if (this === target && start < targetStart && targetStart < end) {
10494 // descending copy from end 9367 // descending copy from end
10495 for (i = len - 1; i >= 0; i--) { 9368 for (i = len - 1; i >= 0; --i) {
10496 target[i + targetStart] = this[i + start] 9369 target[i + targetStart] = this[i + start]
10497 } 9370 }
10498 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { 9371 } else if (len < 1000) {
10499 // ascending copy from start 9372 // ascending copy from start
10500 for (i = 0; i < len; i++) { 9373 for (i = 0; i < len; ++i) {
10501 target[i + targetStart] = this[i + start] 9374 target[i + targetStart] = this[i + start]
10502 } 9375 }
10503 } else { 9376 } else {
10504 target._set(this.subarray(start, start + len), targetStart) 9377 Uint8Array.prototype.set.call(
9378 target,
9379 this.subarray(start, start + len),
9380 targetStart
9381 )
10505 } 9382 }
10506 9383
10507 return len 9384 return len
10508} 9385}
10509 9386
10510// fill(value, start=0, end=buffer.length) 9387// Usage:
10511Buffer.prototype.fill = function fill (value, start, end) { 9388// buffer.fill(number[, offset[, end]])
10512 if (!value) value = 0 9389// buffer.fill(buffer[, offset[, end]])
10513 if (!start) start = 0 9390// buffer.fill(string[, offset[, end]][, encoding])
10514 if (!end) end = this.length 9391Buffer.prototype.fill = function fill (val, start, end, encoding) {
9392 // Handle string cases:
9393 if (typeof val === 'string') {
9394 if (typeof start === 'string') {
9395 encoding = start
9396 start = 0
9397 end = this.length
9398 } else if (typeof end === 'string') {
9399 encoding = end
9400 end = this.length
9401 }
9402 if (val.length === 1) {
9403 var code = val.charCodeAt(0)
9404 if (code < 256) {
9405 val = code
9406 }
9407 }
9408 if (encoding !== undefined && typeof encoding !== 'string') {
9409 throw new TypeError('encoding must be a string')
9410 }
9411 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
9412 throw new TypeError('Unknown encoding: ' + encoding)
9413 }
9414 } else if (typeof val === 'number') {
9415 val = val & 255
9416 }
10515 9417
10516 if (end < start) throw new RangeError('end < start') 9418 // Invalid ranges are not set to a default, so can range check early.
9419 if (start < 0 || this.length < start || this.length < end) {
9420 throw new RangeError('Out of range index')
9421 }
9422
9423 if (end <= start) {
9424 return this
9425 }
10517 9426
10518 // Fill 0 bytes; we're done 9427 start = start >>> 0
10519 if (end === start) return 9428 end = end === undefined ? this.length : end >>> 0
10520 if (this.length === 0) return
10521 9429
10522 if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') 9430 if (!val) val = 0
10523 if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
10524 9431
10525 var i 9432 var i
10526 if (typeof value === 'number') { 9433 if (typeof val === 'number') {
10527 for (i = start; i < end; i++) { 9434 for (i = start; i < end; ++i) {
10528 this[i] = value 9435 this[i] = val
10529 } 9436 }
10530 } else { 9437 } else {
10531 var bytes = utf8ToBytes(value.toString()) 9438 var bytes = Buffer.isBuffer(val)
9439 ? val
9440 : new Buffer(val, encoding)
10532 var len = bytes.length 9441 var len = bytes.length
10533 for (i = start; i < end; i++) { 9442 for (i = 0; i < end - start; ++i) {
10534 this[i] = bytes[i % len] 9443 this[i + start] = bytes[i % len]
10535 } 9444 }
10536 } 9445 }
10537 9446
10538 return this 9447 return this
10539} 9448}
10540 9449
10541/**
10542 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
10543 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
10544 */
10545Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
10546 if (typeof Uint8Array !== 'undefined') {
10547 if (Buffer.TYPED_ARRAY_SUPPORT) {
10548 return (new Buffer(this)).buffer
10549 } else {
10550 var buf = new Uint8Array(this.length)
10551 for (var i = 0, len = buf.length; i < len; i += 1) {
10552 buf[i] = this[i]
10553 }
10554 return buf.buffer
10555 }
10556 } else {
10557 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
10558 }
10559}
10560
10561// HELPER FUNCTIONS 9450// HELPER FUNCTIONS
10562// ================ 9451// ================
10563 9452
10564var BP = Buffer.prototype 9453var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
10565
10566/**
10567 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
10568 */
10569Buffer._augment = function _augment (arr) {
10570 arr.constructor = Buffer
10571 arr._isBuffer = true
10572
10573 // save reference to original Uint8Array set method before overwriting
10574 arr._set = arr.set
10575
10576 // deprecated
10577 arr.get = BP.get
10578 arr.set = BP.set
10579
10580 arr.write = BP.write
10581 arr.toString = BP.toString
10582 arr.toLocaleString = BP.toString
10583 arr.toJSON = BP.toJSON
10584 arr.equals = BP.equals
10585 arr.compare = BP.compare
10586 arr.indexOf = BP.indexOf
10587 arr.copy = BP.copy
10588 arr.slice = BP.slice
10589 arr.readUIntLE = BP.readUIntLE
10590 arr.readUIntBE = BP.readUIntBE
10591 arr.readUInt8 = BP.readUInt8
10592 arr.readUInt16LE = BP.readUInt16LE
10593 arr.readUInt16BE = BP.readUInt16BE
10594 arr.readUInt32LE = BP.readUInt32LE
10595 arr.readUInt32BE = BP.readUInt32BE
10596 arr.readIntLE = BP.readIntLE
10597 arr.readIntBE = BP.readIntBE
10598 arr.readInt8 = BP.readInt8
10599 arr.readInt16LE = BP.readInt16LE
10600 arr.readInt16BE = BP.readInt16BE
10601 arr.readInt32LE = BP.readInt32LE
10602 arr.readInt32BE = BP.readInt32BE
10603 arr.readFloatLE = BP.readFloatLE
10604 arr.readFloatBE = BP.readFloatBE
10605 arr.readDoubleLE = BP.readDoubleLE
10606 arr.readDoubleBE = BP.readDoubleBE
10607 arr.writeUInt8 = BP.writeUInt8
10608 arr.writeUIntLE = BP.writeUIntLE
10609 arr.writeUIntBE = BP.writeUIntBE
10610 arr.writeUInt16LE = BP.writeUInt16LE
10611 arr.writeUInt16BE = BP.writeUInt16BE
10612 arr.writeUInt32LE = BP.writeUInt32LE
10613 arr.writeUInt32BE = BP.writeUInt32BE
10614 arr.writeIntLE = BP.writeIntLE
10615 arr.writeIntBE = BP.writeIntBE
10616 arr.writeInt8 = BP.writeInt8
10617 arr.writeInt16LE = BP.writeInt16LE
10618 arr.writeInt16BE = BP.writeInt16BE
10619 arr.writeInt32LE = BP.writeInt32LE
10620 arr.writeInt32BE = BP.writeInt32BE
10621 arr.writeFloatLE = BP.writeFloatLE
10622 arr.writeFloatBE = BP.writeFloatBE
10623 arr.writeDoubleLE = BP.writeDoubleLE
10624 arr.writeDoubleBE = BP.writeDoubleBE
10625 arr.fill = BP.fill
10626 arr.inspect = BP.inspect
10627 arr.toArrayBuffer = BP.toArrayBuffer
10628
10629 return arr
10630}
10631
10632var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
10633 9454
10634function base64clean (str) { 9455function base64clean (str) {
10635 // Node strips out invalid characters like \n and \t from the string, base64-js does not 9456 // Node strips out invalid characters like \n and \t from the string, base64-js does not
10636 str = stringtrim(str).replace(INVALID_BASE64_RE, '') 9457 str = str.trim().replace(INVALID_BASE64_RE, '')
10637 // Node converts strings with length < 2 to '' 9458 // Node converts strings with length < 2 to ''
10638 if (str.length < 2) return '' 9459 if (str.length < 2) return ''
10639 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not 9460 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
@@ -10643,11 +9464,6 @@ function base64clean (str) {
10643 return str 9464 return str
10644} 9465}
10645 9466
10646function stringtrim (str) {
10647 if (str.trim) return str.trim()
10648 return str.replace(/^\s+|\s+$/g, '')
10649}
10650
10651function toHex (n) { 9467function toHex (n) {
10652 if (n < 16) return '0' + n.toString(16) 9468 if (n < 16) return '0' + n.toString(16)
10653 return n.toString(16) 9469 return n.toString(16)
@@ -10660,7 +9476,7 @@ function utf8ToBytes (string, units) {
10660 var leadSurrogate = null 9476 var leadSurrogate = null
10661 var bytes = [] 9477 var bytes = []
10662 9478
10663 for (var i = 0; i < length; i++) { 9479 for (var i = 0; i < length; ++i) {
10664 codePoint = string.charCodeAt(i) 9480 codePoint = string.charCodeAt(i)
10665 9481
10666 // is surrogate component 9482 // is surrogate component
@@ -10672,7 +9488,6 @@ function utf8ToBytes (string, units) {
10672 // unexpected trail 9488 // unexpected trail
10673 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) 9489 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
10674 continue 9490 continue
10675
10676 } else if (i + 1 === length) { 9491 } else if (i + 1 === length) {
10677 // unpaired lead 9492 // unpaired lead
10678 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) 9493 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
@@ -10693,8 +9508,7 @@ function utf8ToBytes (string, units) {
10693 } 9508 }
10694 9509
10695 // valid surrogate pair 9510 // valid surrogate pair
10696 codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 9511 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
10697
10698 } else if (leadSurrogate) { 9512 } else if (leadSurrogate) {
10699 // valid bmp char, but last char was a lead 9513 // valid bmp char, but last char was a lead
10700 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) 9514 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
@@ -10737,7 +9551,7 @@ function utf8ToBytes (string, units) {
10737 9551
10738function asciiToBytes (str) { 9552function asciiToBytes (str) {
10739 var byteArray = [] 9553 var byteArray = []
10740 for (var i = 0; i < str.length; i++) { 9554 for (var i = 0; i < str.length; ++i) {
10741 // Node's code seems to be doing this and not & 0x7F.. 9555 // Node's code seems to be doing this and not & 0x7F..
10742 byteArray.push(str.charCodeAt(i) & 0xFF) 9556 byteArray.push(str.charCodeAt(i) & 0xFF)
10743 } 9557 }
@@ -10747,7 +9561,7 @@ function asciiToBytes (str) {
10747function utf16leToBytes (str, units) { 9561function utf16leToBytes (str, units) {
10748 var c, hi, lo 9562 var c, hi, lo
10749 var byteArray = [] 9563 var byteArray = []
10750 for (var i = 0; i < str.length; i++) { 9564 for (var i = 0; i < str.length; ++i) {
10751 if ((units -= 2) < 0) break 9565 if ((units -= 2) < 0) break
10752 9566
10753 c = str.charCodeAt(i) 9567 c = str.charCodeAt(i)
@@ -10765,261 +9579,134 @@ function base64ToBytes (str) {
10765} 9579}
10766 9580
10767function blitBuffer (src, dst, offset, length) { 9581function blitBuffer (src, dst, offset, length) {
10768 for (var i = 0; i < length; i++) { 9582 for (var i = 0; i < length; ++i) {
10769 if ((i + offset >= dst.length) || (i >= src.length)) break 9583 if ((i + offset >= dst.length) || (i >= src.length)) break
10770 dst[i + offset] = src[i] 9584 dst[i + offset] = src[i]
10771 } 9585 }
10772 return i 9586 return i
10773} 9587}
10774 9588
10775},{"base64-js":8,"ieee754":9,"is-array":10}],8:[function(require,module,exports){ 9589// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
10776var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; 9590function isArrayBufferView (obj) {
10777 9591 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
10778;(function (exports) { 9592}
10779 'use strict';
10780
10781 var Arr = (typeof Uint8Array !== 'undefined')
10782 ? Uint8Array
10783 : Array
10784
10785 var PLUS = '+'.charCodeAt(0)
10786 var SLASH = '/'.charCodeAt(0)
10787 var NUMBER = '0'.charCodeAt(0)
10788 var LOWER = 'a'.charCodeAt(0)
10789 var UPPER = 'A'.charCodeAt(0)
10790 var PLUS_URL_SAFE = '-'.charCodeAt(0)
10791 var SLASH_URL_SAFE = '_'.charCodeAt(0)
10792
10793 function decode (elt) {
10794 var code = elt.charCodeAt(0)
10795 if (code === PLUS ||
10796 code === PLUS_URL_SAFE)
10797 return 62 // '+'
10798 if (code === SLASH ||
10799 code === SLASH_URL_SAFE)
10800 return 63 // '/'
10801 if (code < NUMBER)
10802 return -1 //no match
10803 if (code < NUMBER + 10)
10804 return code - NUMBER + 26 + 26
10805 if (code < UPPER + 26)
10806 return code - UPPER
10807 if (code < LOWER + 26)
10808 return code - LOWER + 26
10809 }
10810
10811 function b64ToByteArray (b64) {
10812 var i, j, l, tmp, placeHolders, arr
10813
10814 if (b64.length % 4 > 0) {
10815 throw new Error('Invalid string. Length must be a multiple of 4')
10816 }
10817
10818 // the number of equal signs (place holders)
10819 // if there are two placeholders, than the two characters before it
10820 // represent one byte
10821 // if there is only one, then the three characters before it represent 2 bytes
10822 // this is just a cheap hack to not do indexOf twice
10823 var len = b64.length
10824 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
10825
10826 // base64 is 4/3 + up to two characters of the original data
10827 arr = new Arr(b64.length * 3 / 4 - placeHolders)
10828
10829 // if there are placeholders, only get up to the last complete 4 chars
10830 l = placeHolders > 0 ? b64.length - 4 : b64.length
10831
10832 var L = 0
10833
10834 function push (v) {
10835 arr[L++] = v
10836 }
10837
10838 for (i = 0, j = 0; i < l; i += 4, j += 3) {
10839 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
10840 push((tmp & 0xFF0000) >> 16)
10841 push((tmp & 0xFF00) >> 8)
10842 push(tmp & 0xFF)
10843 }
10844
10845 if (placeHolders === 2) {
10846 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
10847 push(tmp & 0xFF)
10848 } else if (placeHolders === 1) {
10849 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
10850 push((tmp >> 8) & 0xFF)
10851 push(tmp & 0xFF)
10852 }
10853
10854 return arr
10855 }
10856
10857 function uint8ToBase64 (uint8) {
10858 var i,
10859 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
10860 output = "",
10861 temp, length
10862
10863 function encode (num) {
10864 return lookup.charAt(num)
10865 }
10866
10867 function tripletToBase64 (num) {
10868 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
10869 }
10870
10871 // go through the array every three bytes, we'll deal with trailing stuff later
10872 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
10873 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
10874 output += tripletToBase64(temp)
10875 }
10876
10877 // pad the end with zeros, but make sure to not forget the extra bytes
10878 switch (extraBytes) {
10879 case 1:
10880 temp = uint8[uint8.length - 1]
10881 output += encode(temp >> 2)
10882 output += encode((temp << 4) & 0x3F)
10883 output += '=='
10884 break
10885 case 2:
10886 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
10887 output += encode(temp >> 10)
10888 output += encode((temp >> 4) & 0x3F)
10889 output += encode((temp << 2) & 0x3F)
10890 output += '='
10891 break
10892 }
10893
10894 return output
10895 }
10896
10897 exports.toByteArray = b64ToByteArray
10898 exports.fromByteArray = uint8ToBase64
10899}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
10900
10901},{}],9:[function(require,module,exports){
10902exports.read = function (buffer, offset, isLE, mLen, nBytes) {
10903 var e, m
10904 var eLen = nBytes * 8 - mLen - 1
10905 var eMax = (1 << eLen) - 1
10906 var eBias = eMax >> 1
10907 var nBits = -7
10908 var i = isLE ? (nBytes - 1) : 0
10909 var d = isLE ? -1 : 1
10910 var s = buffer[offset + i]
10911 9593
10912 i += d 9594function numberIsNaN (obj) {
9595 return obj !== obj // eslint-disable-line no-self-compare
9596}
10913 9597
10914 e = s & ((1 << (-nBits)) - 1) 9598},{"base64-js":2,"ieee754":7}],5:[function(require,module,exports){
10915 s >>= (-nBits) 9599(function (Buffer){
10916 nBits += eLen 9600// Copyright Joyent, Inc. and other Node contributors.
10917 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} 9601//
9602// Permission is hereby granted, free of charge, to any person obtaining a
9603// copy of this software and associated documentation files (the
9604// "Software"), to deal in the Software without restriction, including
9605// without limitation the rights to use, copy, modify, merge, publish,
9606// distribute, sublicense, and/or sell copies of the Software, and to permit
9607// persons to whom the Software is furnished to do so, subject to the
9608// following conditions:
9609//
9610// The above copyright notice and this permission notice shall be included
9611// in all copies or substantial portions of the Software.
9612//
9613// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9614// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9615// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9616// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9617// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9618// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9619// USE OR OTHER DEALINGS IN THE SOFTWARE.
10918 9620
10919 m = e & ((1 << (-nBits)) - 1) 9621// NOTE: These type checking functions intentionally don't use `instanceof`
10920 e >>= (-nBits) 9622// because it is fragile and can be easily faked with `Object.create()`.
10921 nBits += mLen
10922 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10923 9623
10924 if (e === 0) { 9624function isArray(arg) {
10925 e = 1 - eBias 9625 if (Array.isArray) {
10926 } else if (e === eMax) { 9626 return Array.isArray(arg);
10927 return m ? NaN : ((s ? -1 : 1) * Infinity)
10928 } else {
10929 m = m + Math.pow(2, mLen)
10930 e = e - eBias
10931 } 9627 }
10932 return (s ? -1 : 1) * m * Math.pow(2, e - mLen) 9628 return objectToString(arg) === '[object Array]';
10933} 9629}
9630exports.isArray = isArray;
10934 9631
10935exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { 9632function isBoolean(arg) {
10936 var e, m, c 9633 return typeof arg === 'boolean';
10937 var eLen = nBytes * 8 - mLen - 1 9634}
10938 var eMax = (1 << eLen) - 1 9635exports.isBoolean = isBoolean;
10939 var eBias = eMax >> 1
10940 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
10941 var i = isLE ? 0 : (nBytes - 1)
10942 var d = isLE ? 1 : -1
10943 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
10944 9636
10945 value = Math.abs(value) 9637function isNull(arg) {
9638 return arg === null;
9639}
9640exports.isNull = isNull;
10946 9641
10947 if (isNaN(value) || value === Infinity) { 9642function isNullOrUndefined(arg) {
10948 m = isNaN(value) ? 1 : 0 9643 return arg == null;
10949 e = eMax 9644}
10950 } else { 9645exports.isNullOrUndefined = isNullOrUndefined;
10951 e = Math.floor(Math.log(value) / Math.LN2)
10952 if (value * (c = Math.pow(2, -e)) < 1) {
10953 e--
10954 c *= 2
10955 }
10956 if (e + eBias >= 1) {
10957 value += rt / c
10958 } else {
10959 value += rt * Math.pow(2, 1 - eBias)
10960 }
10961 if (value * c >= 2) {
10962 e++
10963 c /= 2
10964 }
10965 9646
10966 if (e + eBias >= eMax) { 9647function isNumber(arg) {
10967 m = 0 9648 return typeof arg === 'number';
10968 e = eMax 9649}
10969 } else if (e + eBias >= 1) { 9650exports.isNumber = isNumber;
10970 m = (value * c - 1) * Math.pow(2, mLen)
10971 e = e + eBias
10972 } else {
10973 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
10974 e = 0
10975 }
10976 }
10977 9651
10978 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} 9652function isString(arg) {
9653 return typeof arg === 'string';
9654}
9655exports.isString = isString;
10979 9656
10980 e = (e << mLen) | m 9657function isSymbol(arg) {
10981 eLen += mLen 9658 return typeof arg === 'symbol';
10982 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} 9659}
9660exports.isSymbol = isSymbol;
10983 9661
10984 buffer[offset + i - d] |= s * 128 9662function isUndefined(arg) {
9663 return arg === void 0;
10985} 9664}
9665exports.isUndefined = isUndefined;
10986 9666
10987},{}],10:[function(require,module,exports){ 9667function isRegExp(re) {
9668 return objectToString(re) === '[object RegExp]';
9669}
9670exports.isRegExp = isRegExp;
10988 9671
10989/** 9672function isObject(arg) {
10990 * isArray 9673 return typeof arg === 'object' && arg !== null;
10991 */ 9674}
9675exports.isObject = isObject;
10992 9676
10993var isArray = Array.isArray; 9677function isDate(d) {
9678 return objectToString(d) === '[object Date]';
9679}
9680exports.isDate = isDate;
10994 9681
10995/** 9682function isError(e) {
10996 * toString 9683 return (objectToString(e) === '[object Error]' || e instanceof Error);
10997 */ 9684}
9685exports.isError = isError;
10998 9686
10999var str = Object.prototype.toString; 9687function isFunction(arg) {
9688 return typeof arg === 'function';
9689}
9690exports.isFunction = isFunction;
11000 9691
11001/** 9692function isPrimitive(arg) {
11002 * Whether or not the given `val` 9693 return arg === null ||
11003 * is an array. 9694 typeof arg === 'boolean' ||
11004 * 9695 typeof arg === 'number' ||
11005 * example: 9696 typeof arg === 'string' ||
11006 * 9697 typeof arg === 'symbol' || // ES6 symbol
11007 * isArray([]); 9698 typeof arg === 'undefined';
11008 * // > true 9699}
11009 * isArray(arguments); 9700exports.isPrimitive = isPrimitive;
11010 * // > false
11011 * isArray('');
11012 * // > false
11013 *
11014 * @param {mixed} val
11015 * @return {bool}
11016 */
11017 9701
11018module.exports = isArray || function (val) { 9702exports.isBuffer = Buffer.isBuffer;
11019 return !! val && '[object Array]' == str.call(val);
11020};
11021 9703
11022},{}],11:[function(require,module,exports){ 9704function objectToString(o) {
9705 return Object.prototype.toString.call(o);
9706}
9707
9708}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
9709},{"../../is-buffer/index.js":9}],6:[function(require,module,exports){
11023// Copyright Joyent, Inc. and other Node contributors. 9710// Copyright Joyent, Inc. and other Node contributors.
11024// 9711//
11025// Permission is hereby granted, free of charge, to any person obtaining a 9712// Permission is hereby granted, free of charge, to any person obtaining a
@@ -11079,8 +9766,12 @@ EventEmitter.prototype.emit = function(type) {
11079 er = arguments[1]; 9766 er = arguments[1];
11080 if (er instanceof Error) { 9767 if (er instanceof Error) {
11081 throw er; // Unhandled 'error' event 9768 throw er; // Unhandled 'error' event
9769 } else {
9770 // At least give some kind of context to the user
9771 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
9772 err.context = er;
9773 throw err;
11082 } 9774 }
11083 throw TypeError('Uncaught, unspecified "error" event.');
11084 } 9775 }
11085 } 9776 }
11086 9777
@@ -11103,18 +9794,11 @@ EventEmitter.prototype.emit = function(type) {
11103 break; 9794 break;
11104 // slower 9795 // slower
11105 default: 9796 default:
11106 len = arguments.length; 9797 args = Array.prototype.slice.call(arguments, 1);
11107 args = new Array(len - 1);
11108 for (i = 1; i < len; i++)
11109 args[i - 1] = arguments[i];
11110 handler.apply(this, args); 9798 handler.apply(this, args);
11111 } 9799 }
11112 } else if (isObject(handler)) { 9800 } else if (isObject(handler)) {
11113 len = arguments.length; 9801 args = Array.prototype.slice.call(arguments, 1);
11114 args = new Array(len - 1);
11115 for (i = 1; i < len; i++)
11116 args[i - 1] = arguments[i];
11117
11118 listeners = handler.slice(); 9802 listeners = handler.slice();
11119 len = listeners.length; 9803 len = listeners.length;
11120 for (i = 0; i < len; i++) 9804 for (i = 0; i < len; i++)
@@ -11152,7 +9836,6 @@ EventEmitter.prototype.addListener = function(type, listener) {
11152 9836
11153 // Check for listener leak 9837 // Check for listener leak
11154 if (isObject(this._events[type]) && !this._events[type].warned) { 9838 if (isObject(this._events[type]) && !this._events[type].warned) {
11155 var m;
11156 if (!isUndefined(this._maxListeners)) { 9839 if (!isUndefined(this._maxListeners)) {
11157 m = this._maxListeners; 9840 m = this._maxListeners;
11158 } else { 9841 } else {
@@ -11274,7 +9957,7 @@ EventEmitter.prototype.removeAllListeners = function(type) {
11274 9957
11275 if (isFunction(listeners)) { 9958 if (isFunction(listeners)) {
11276 this.removeListener(type, listeners); 9959 this.removeListener(type, listeners);
11277 } else { 9960 } else if (listeners) {
11278 // LIFO order 9961 // LIFO order
11279 while (listeners.length) 9962 while (listeners.length)
11280 this.removeListener(type, listeners[listeners.length - 1]); 9963 this.removeListener(type, listeners[listeners.length - 1]);
@@ -11295,15 +9978,20 @@ EventEmitter.prototype.listeners = function(type) {
11295 return ret; 9978 return ret;
11296}; 9979};
11297 9980
9981EventEmitter.prototype.listenerCount = function(type) {
9982 if (this._events) {
9983 var evlistener = this._events[type];
9984
9985 if (isFunction(evlistener))
9986 return 1;
9987 else if (evlistener)
9988 return evlistener.length;
9989 }
9990 return 0;
9991};
9992
11298EventEmitter.listenerCount = function(emitter, type) { 9993EventEmitter.listenerCount = function(emitter, type) {
11299 var ret; 9994 return emitter.listenerCount(type);
11300 if (!emitter._events || !emitter._events[type])
11301 ret = 0;
11302 else if (isFunction(emitter._events[type]))
11303 ret = 1;
11304 else
11305 ret = emitter._events[type].length;
11306 return ret;
11307}; 9995};
11308 9996
11309function isFunction(arg) { 9997function isFunction(arg) {
@@ -11322,7 +10010,93 @@ function isUndefined(arg) {
11322 return arg === void 0; 10010 return arg === void 0;
11323} 10011}
11324 10012
11325},{}],12:[function(require,module,exports){ 10013},{}],7:[function(require,module,exports){
10014exports.read = function (buffer, offset, isLE, mLen, nBytes) {
10015 var e, m
10016 var eLen = nBytes * 8 - mLen - 1
10017 var eMax = (1 << eLen) - 1
10018 var eBias = eMax >> 1
10019 var nBits = -7
10020 var i = isLE ? (nBytes - 1) : 0
10021 var d = isLE ? -1 : 1
10022 var s = buffer[offset + i]
10023
10024 i += d
10025
10026 e = s & ((1 << (-nBits)) - 1)
10027 s >>= (-nBits)
10028 nBits += eLen
10029 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10030
10031 m = e & ((1 << (-nBits)) - 1)
10032 e >>= (-nBits)
10033 nBits += mLen
10034 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10035
10036 if (e === 0) {
10037 e = 1 - eBias
10038 } else if (e === eMax) {
10039 return m ? NaN : ((s ? -1 : 1) * Infinity)
10040 } else {
10041 m = m + Math.pow(2, mLen)
10042 e = e - eBias
10043 }
10044 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
10045}
10046
10047exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
10048 var e, m, c
10049 var eLen = nBytes * 8 - mLen - 1
10050 var eMax = (1 << eLen) - 1
10051 var eBias = eMax >> 1
10052 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
10053 var i = isLE ? 0 : (nBytes - 1)
10054 var d = isLE ? 1 : -1
10055 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
10056
10057 value = Math.abs(value)
10058
10059 if (isNaN(value) || value === Infinity) {
10060 m = isNaN(value) ? 1 : 0
10061 e = eMax
10062 } else {
10063 e = Math.floor(Math.log(value) / Math.LN2)
10064 if (value * (c = Math.pow(2, -e)) < 1) {
10065 e--
10066 c *= 2
10067 }
10068 if (e + eBias >= 1) {
10069 value += rt / c
10070 } else {
10071 value += rt * Math.pow(2, 1 - eBias)
10072 }
10073 if (value * c >= 2) {
10074 e++
10075 c /= 2
10076 }
10077
10078 if (e + eBias >= eMax) {
10079 m = 0
10080 e = eMax
10081 } else if (e + eBias >= 1) {
10082 m = (value * c - 1) * Math.pow(2, mLen)
10083 e = e + eBias
10084 } else {
10085 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
10086 e = 0
10087 }
10088 }
10089
10090 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
10091
10092 e = (e << mLen) | m
10093 eLen += mLen
10094 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
10095
10096 buffer[offset + i - d] |= s * 128
10097}
10098
10099},{}],8:[function(require,module,exports){
11326if (typeof Object.create === 'function') { 10100if (typeof Object.create === 'function') {
11327 // implementation from standard node.js 'util' module 10101 // implementation from standard node.js 'util' module
11328 module.exports = function inherits(ctor, superCtor) { 10102 module.exports = function inherits(ctor, superCtor) {
@@ -11347,21 +10121,182 @@ if (typeof Object.create === 'function') {
11347 } 10121 }
11348} 10122}
11349 10123
11350},{}],13:[function(require,module,exports){ 10124},{}],9:[function(require,module,exports){
10125/*!
10126 * Determine if an object is a Buffer
10127 *
10128 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
10129 * @license MIT
10130 */
10131
10132// The _isBuffer check is for Safari 5-7 support, because it's missing
10133// Object.prototype.constructor. Remove this eventually
10134module.exports = function (obj) {
10135 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
10136}
10137
10138function isBuffer (obj) {
10139 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
10140}
10141
10142// For Node v0.10 support. Remove this eventually.
10143function isSlowBuffer (obj) {
10144 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
10145}
10146
10147},{}],10:[function(require,module,exports){
10148var toString = {}.toString;
10149
11351module.exports = Array.isArray || function (arr) { 10150module.exports = Array.isArray || function (arr) {
11352 return Object.prototype.toString.call(arr) == '[object Array]'; 10151 return toString.call(arr) == '[object Array]';
11353}; 10152};
11354 10153
11355},{}],14:[function(require,module,exports){ 10154},{}],11:[function(require,module,exports){
11356// shim for using process in browser 10155(function (process){
10156'use strict';
11357 10157
10158if (!process.version ||
10159 process.version.indexOf('v0.') === 0 ||
10160 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
10161 module.exports = nextTick;
10162} else {
10163 module.exports = process.nextTick;
10164}
10165
10166function nextTick(fn, arg1, arg2, arg3) {
10167 if (typeof fn !== 'function') {
10168 throw new TypeError('"callback" argument must be a function');
10169 }
10170 var len = arguments.length;
10171 var args, i;
10172 switch (len) {
10173 case 0:
10174 case 1:
10175 return process.nextTick(fn);
10176 case 2:
10177 return process.nextTick(function afterTickOne() {
10178 fn.call(null, arg1);
10179 });
10180 case 3:
10181 return process.nextTick(function afterTickTwo() {
10182 fn.call(null, arg1, arg2);
10183 });
10184 case 4:
10185 return process.nextTick(function afterTickThree() {
10186 fn.call(null, arg1, arg2, arg3);
10187 });
10188 default:
10189 args = new Array(len - 1);
10190 i = 0;
10191 while (i < args.length) {
10192 args[i++] = arguments[i];
10193 }
10194 return process.nextTick(function afterTick() {
10195 fn.apply(null, args);
10196 });
10197 }
10198}
10199
10200}).call(this,require('_process'))
10201},{"_process":12}],12:[function(require,module,exports){
10202// shim for using process in browser
11358var process = module.exports = {}; 10203var process = module.exports = {};
10204
10205// cached from whatever global is present so that test runners that stub it
10206// don't break things. But we need to wrap it in a try catch in case it is
10207// wrapped in strict mode code which doesn't define any globals. It's inside a
10208// function because try/catches deoptimize in certain engines.
10209
10210var cachedSetTimeout;
10211var cachedClearTimeout;
10212
10213function defaultSetTimout() {
10214 throw new Error('setTimeout has not been defined');
10215}
10216function defaultClearTimeout () {
10217 throw new Error('clearTimeout has not been defined');
10218}
10219(function () {
10220 try {
10221 if (typeof setTimeout === 'function') {
10222 cachedSetTimeout = setTimeout;
10223 } else {
10224 cachedSetTimeout = defaultSetTimout;
10225 }
10226 } catch (e) {
10227 cachedSetTimeout = defaultSetTimout;
10228 }
10229 try {
10230 if (typeof clearTimeout === 'function') {
10231 cachedClearTimeout = clearTimeout;
10232 } else {
10233 cachedClearTimeout = defaultClearTimeout;
10234 }
10235 } catch (e) {
10236 cachedClearTimeout = defaultClearTimeout;
10237 }
10238} ())
10239function runTimeout(fun) {
10240 if (cachedSetTimeout === setTimeout) {
10241 //normal enviroments in sane situations
10242 return setTimeout(fun, 0);
10243 }
10244 // if setTimeout wasn't available but was latter defined
10245 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
10246 cachedSetTimeout = setTimeout;
10247 return setTimeout(fun, 0);
10248 }
10249 try {
10250 // when when somebody has screwed with setTimeout but no I.E. maddness
10251 return cachedSetTimeout(fun, 0);
10252 } catch(e){
10253 try {
10254 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10255 return cachedSetTimeout.call(null, fun, 0);
10256 } catch(e){
10257 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
10258 return cachedSetTimeout.call(this, fun, 0);
10259 }
10260 }
10261
10262
10263}
10264function runClearTimeout(marker) {
10265 if (cachedClearTimeout === clearTimeout) {
10266 //normal enviroments in sane situations
10267 return clearTimeout(marker);
10268 }
10269 // if clearTimeout wasn't available but was latter defined
10270 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
10271 cachedClearTimeout = clearTimeout;
10272 return clearTimeout(marker);
10273 }
10274 try {
10275 // when when somebody has screwed with setTimeout but no I.E. maddness
10276 return cachedClearTimeout(marker);
10277 } catch (e){
10278 try {
10279 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10280 return cachedClearTimeout.call(null, marker);
10281 } catch (e){
10282 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
10283 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
10284 return cachedClearTimeout.call(this, marker);
10285 }
10286 }
10287
10288
10289
10290}
11359var queue = []; 10291var queue = [];
11360var draining = false; 10292var draining = false;
11361var currentQueue; 10293var currentQueue;
11362var queueIndex = -1; 10294var queueIndex = -1;
11363 10295
11364function cleanUpNextTick() { 10296function cleanUpNextTick() {
10297 if (!draining || !currentQueue) {
10298 return;
10299 }
11365 draining = false; 10300 draining = false;
11366 if (currentQueue.length) { 10301 if (currentQueue.length) {
11367 queue = currentQueue.concat(queue); 10302 queue = currentQueue.concat(queue);
@@ -11377,7 +10312,7 @@ function drainQueue() {
11377 if (draining) { 10312 if (draining) {
11378 return; 10313 return;
11379 } 10314 }
11380 var timeout = setTimeout(cleanUpNextTick); 10315 var timeout = runTimeout(cleanUpNextTick);
11381 draining = true; 10316 draining = true;
11382 10317
11383 var len = queue.length; 10318 var len = queue.length;
@@ -11385,14 +10320,16 @@ function drainQueue() {
11385 currentQueue = queue; 10320 currentQueue = queue;
11386 queue = []; 10321 queue = [];
11387 while (++queueIndex < len) { 10322 while (++queueIndex < len) {
11388 currentQueue[queueIndex].run(); 10323 if (currentQueue) {
10324 currentQueue[queueIndex].run();
10325 }
11389 } 10326 }
11390 queueIndex = -1; 10327 queueIndex = -1;
11391 len = queue.length; 10328 len = queue.length;
11392 } 10329 }
11393 currentQueue = null; 10330 currentQueue = null;
11394 draining = false; 10331 draining = false;
11395 clearTimeout(timeout); 10332 runClearTimeout(timeout);
11396} 10333}
11397 10334
11398process.nextTick = function (fun) { 10335process.nextTick = function (fun) {
@@ -11404,7 +10341,7 @@ process.nextTick = function (fun) {
11404 } 10341 }
11405 queue.push(new Item(fun, args)); 10342 queue.push(new Item(fun, args));
11406 if (queue.length === 1 && !draining) { 10343 if (queue.length === 1 && !draining) {
11407 setTimeout(drainQueue, 0); 10344 runTimeout(drainQueue);
11408 } 10345 }
11409}; 10346};
11410 10347
@@ -11432,23 +10369,25 @@ process.off = noop;
11432process.removeListener = noop; 10369process.removeListener = noop;
11433process.removeAllListeners = noop; 10370process.removeAllListeners = noop;
11434process.emit = noop; 10371process.emit = noop;
10372process.prependListener = noop;
10373process.prependOnceListener = noop;
10374
10375process.listeners = function (name) { return [] }
11435 10376
11436process.binding = function (name) { 10377process.binding = function (name) {
11437 throw new Error('process.binding is not supported'); 10378 throw new Error('process.binding is not supported');
11438}; 10379};
11439 10380
11440// TODO(shtylman)
11441process.cwd = function () { return '/' }; 10381process.cwd = function () { return '/' };
11442process.chdir = function (dir) { 10382process.chdir = function (dir) {
11443 throw new Error('process.chdir is not supported'); 10383 throw new Error('process.chdir is not supported');
11444}; 10384};
11445process.umask = function() { return 0; }; 10385process.umask = function() { return 0; };
11446 10386
11447},{}],15:[function(require,module,exports){ 10387},{}],13:[function(require,module,exports){
11448module.exports = require("./lib/_stream_duplex.js") 10388module.exports = require('./lib/_stream_duplex.js');
11449 10389
11450},{"./lib/_stream_duplex.js":16}],16:[function(require,module,exports){ 10390},{"./lib/_stream_duplex.js":14}],14:[function(require,module,exports){
11451(function (process){
11452// Copyright Joyent, Inc. and other Node contributors. 10391// Copyright Joyent, Inc. and other Node contributors.
11453// 10392//
11454// Permission is hereby granted, free of charge, to any person obtaining a 10393// Permission is hereby granted, free of charge, to any person obtaining a
@@ -11475,16 +10414,23 @@ module.exports = require("./lib/_stream_duplex.js")
11475// prototypally inherits from Readable, and then parasitically from 10414// prototypally inherits from Readable, and then parasitically from
11476// Writable. 10415// Writable.
11477 10416
11478module.exports = Duplex; 10417'use strict';
10418
10419/*<replacement>*/
10420
10421var processNextTick = require('process-nextick-args');
10422/*</replacement>*/
11479 10423
11480/*<replacement>*/ 10424/*<replacement>*/
11481var objectKeys = Object.keys || function (obj) { 10425var objectKeys = Object.keys || function (obj) {
11482 var keys = []; 10426 var keys = [];
11483 for (var key in obj) keys.push(key); 10427 for (var key in obj) {
11484 return keys; 10428 keys.push(key);
11485} 10429 }return keys;
10430};
11486/*</replacement>*/ 10431/*</replacement>*/
11487 10432
10433module.exports = Duplex;
11488 10434
11489/*<replacement>*/ 10435/*<replacement>*/
11490var util = require('core-util-is'); 10436var util = require('core-util-is');
@@ -11496,27 +10442,24 @@ var Writable = require('./_stream_writable');
11496 10442
11497util.inherits(Duplex, Readable); 10443util.inherits(Duplex, Readable);
11498 10444
11499forEach(objectKeys(Writable.prototype), function(method) { 10445var keys = objectKeys(Writable.prototype);
11500 if (!Duplex.prototype[method]) 10446for (var v = 0; v < keys.length; v++) {
11501 Duplex.prototype[method] = Writable.prototype[method]; 10447 var method = keys[v];
11502}); 10448 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
10449}
11503 10450
11504function Duplex(options) { 10451function Duplex(options) {
11505 if (!(this instanceof Duplex)) 10452 if (!(this instanceof Duplex)) return new Duplex(options);
11506 return new Duplex(options);
11507 10453
11508 Readable.call(this, options); 10454 Readable.call(this, options);
11509 Writable.call(this, options); 10455 Writable.call(this, options);
11510 10456
11511 if (options && options.readable === false) 10457 if (options && options.readable === false) this.readable = false;
11512 this.readable = false;
11513 10458
11514 if (options && options.writable === false) 10459 if (options && options.writable === false) this.writable = false;
11515 this.writable = false;
11516 10460
11517 this.allowHalfOpen = true; 10461 this.allowHalfOpen = true;
11518 if (options && options.allowHalfOpen === false) 10462 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
11519 this.allowHalfOpen = false;
11520 10463
11521 this.once('end', onend); 10464 this.once('end', onend);
11522} 10465}
@@ -11525,22 +10468,51 @@ function Duplex(options) {
11525function onend() { 10468function onend() {
11526 // if we allow half-open state, or if the writable side ended, 10469 // if we allow half-open state, or if the writable side ended,
11527 // then we're ok. 10470 // then we're ok.
11528 if (this.allowHalfOpen || this._writableState.ended) 10471 if (this.allowHalfOpen || this._writableState.ended) return;
11529 return;
11530 10472
11531 // no more data can be written. 10473 // no more data can be written.
11532 // But allow more writes to happen in this tick. 10474 // But allow more writes to happen in this tick.
11533 process.nextTick(this.end.bind(this)); 10475 processNextTick(onEndNT, this);
11534} 10476}
11535 10477
11536function forEach (xs, f) { 10478function onEndNT(self) {
10479 self.end();
10480}
10481
10482Object.defineProperty(Duplex.prototype, 'destroyed', {
10483 get: function () {
10484 if (this._readableState === undefined || this._writableState === undefined) {
10485 return false;
10486 }
10487 return this._readableState.destroyed && this._writableState.destroyed;
10488 },
10489 set: function (value) {
10490 // we ignore the value if the stream
10491 // has not been initialized yet
10492 if (this._readableState === undefined || this._writableState === undefined) {
10493 return;
10494 }
10495
10496 // backward compatibility, the user is explicitly
10497 // managing destroyed
10498 this._readableState.destroyed = value;
10499 this._writableState.destroyed = value;
10500 }
10501});
10502
10503Duplex.prototype._destroy = function (err, cb) {
10504 this.push(null);
10505 this.end();
10506
10507 processNextTick(cb, err);
10508};
10509
10510function forEach(xs, f) {
11537 for (var i = 0, l = xs.length; i < l; i++) { 10511 for (var i = 0, l = xs.length; i < l; i++) {
11538 f(xs[i], i); 10512 f(xs[i], i);
11539 } 10513 }
11540} 10514}
11541 10515},{"./_stream_readable":16,"./_stream_writable":18,"core-util-is":5,"inherits":8,"process-nextick-args":11}],15:[function(require,module,exports){
11542}).call(this,require('_process'))
11543},{"./_stream_readable":18,"./_stream_writable":20,"_process":14,"core-util-is":21,"inherits":12}],17:[function(require,module,exports){
11544// Copyright Joyent, Inc. and other Node contributors. 10516// Copyright Joyent, Inc. and other Node contributors.
11545// 10517//
11546// Permission is hereby granted, free of charge, to any person obtaining a 10518// Permission is hereby granted, free of charge, to any person obtaining a
@@ -11566,6 +10538,8 @@ function forEach (xs, f) {
11566// basically just the most minimal sort of Transform stream. 10538// basically just the most minimal sort of Transform stream.
11567// Every written chunk gets output as-is. 10539// Every written chunk gets output as-is.
11568 10540
10541'use strict';
10542
11569module.exports = PassThrough; 10543module.exports = PassThrough;
11570 10544
11571var Transform = require('./_stream_transform'); 10545var Transform = require('./_stream_transform');
@@ -11578,18 +10552,16 @@ util.inherits = require('inherits');
11578util.inherits(PassThrough, Transform); 10552util.inherits(PassThrough, Transform);
11579 10553
11580function PassThrough(options) { 10554function PassThrough(options) {
11581 if (!(this instanceof PassThrough)) 10555 if (!(this instanceof PassThrough)) return new PassThrough(options);
11582 return new PassThrough(options);
11583 10556
11584 Transform.call(this, options); 10557 Transform.call(this, options);
11585} 10558}
11586 10559
11587PassThrough.prototype._transform = function(chunk, encoding, cb) { 10560PassThrough.prototype._transform = function (chunk, encoding, cb) {
11588 cb(null, chunk); 10561 cb(null, chunk);
11589}; 10562};
11590 10563},{"./_stream_transform":17,"core-util-is":5,"inherits":8}],16:[function(require,module,exports){
11591},{"./_stream_transform":19,"core-util-is":21,"inherits":12}],18:[function(require,module,exports){ 10564(function (process,global){
11592(function (process){
11593// Copyright Joyent, Inc. and other Node contributors. 10565// Copyright Joyent, Inc. and other Node contributors.
11594// 10566//
11595// Permission is hereby granted, free of charge, to any person obtaining a 10567// Permission is hereby granted, free of charge, to any person obtaining a
@@ -11611,64 +10583,111 @@ PassThrough.prototype._transform = function(chunk, encoding, cb) {
11611// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 10583// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11612// USE OR OTHER DEALINGS IN THE SOFTWARE. 10584// USE OR OTHER DEALINGS IN THE SOFTWARE.
11613 10585
10586'use strict';
10587
10588/*<replacement>*/
10589
10590var processNextTick = require('process-nextick-args');
10591/*</replacement>*/
10592
11614module.exports = Readable; 10593module.exports = Readable;
11615 10594
11616/*<replacement>*/ 10595/*<replacement>*/
11617var isArray = require('isarray'); 10596var isArray = require('isarray');
11618/*</replacement>*/ 10597/*</replacement>*/
11619 10598
11620
11621/*<replacement>*/ 10599/*<replacement>*/
11622var Buffer = require('buffer').Buffer; 10600var Duplex;
11623/*</replacement>*/ 10601/*</replacement>*/
11624 10602
11625Readable.ReadableState = ReadableState; 10603Readable.ReadableState = ReadableState;
11626 10604
10605/*<replacement>*/
11627var EE = require('events').EventEmitter; 10606var EE = require('events').EventEmitter;
11628 10607
11629/*<replacement>*/ 10608var EElistenerCount = function (emitter, type) {
11630if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11631 return emitter.listeners(type).length; 10609 return emitter.listeners(type).length;
11632}; 10610};
11633/*</replacement>*/ 10611/*</replacement>*/
11634 10612
11635var Stream = require('stream'); 10613/*<replacement>*/
10614var Stream = require('./internal/streams/stream');
10615/*</replacement>*/
10616
10617// TODO(bmeurer): Change this back to const once hole checks are
10618// properly optimized away early in Ignition+TurboFan.
10619/*<replacement>*/
10620var Buffer = require('safe-buffer').Buffer;
10621var OurUint8Array = global.Uint8Array || function () {};
10622function _uint8ArrayToBuffer(chunk) {
10623 return Buffer.from(chunk);
10624}
10625function _isUint8Array(obj) {
10626 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
10627}
10628/*</replacement>*/
11636 10629
11637/*<replacement>*/ 10630/*<replacement>*/
11638var util = require('core-util-is'); 10631var util = require('core-util-is');
11639util.inherits = require('inherits'); 10632util.inherits = require('inherits');
11640/*</replacement>*/ 10633/*</replacement>*/
11641 10634
11642var StringDecoder;
11643
11644
11645/*<replacement>*/ 10635/*<replacement>*/
11646var debug = require('util'); 10636var debugUtil = require('util');
11647if (debug && debug.debuglog) { 10637var debug = void 0;
11648 debug = debug.debuglog('stream'); 10638if (debugUtil && debugUtil.debuglog) {
10639 debug = debugUtil.debuglog('stream');
11649} else { 10640} else {
11650 debug = function () {}; 10641 debug = function () {};
11651} 10642}
11652/*</replacement>*/ 10643/*</replacement>*/
11653 10644
10645var BufferList = require('./internal/streams/BufferList');
10646var destroyImpl = require('./internal/streams/destroy');
10647var StringDecoder;
11654 10648
11655util.inherits(Readable, Stream); 10649util.inherits(Readable, Stream);
11656 10650
10651var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
10652
10653function prependListener(emitter, event, fn) {
10654 // Sadly this is not cacheable as some libraries bundle their own
10655 // event emitter implementation with them.
10656 if (typeof emitter.prependListener === 'function') {
10657 return emitter.prependListener(event, fn);
10658 } else {
10659 // This is a hack to make sure that our error handler is attached before any
10660 // userland ones. NEVER DO THIS. This is here only because this code needs
10661 // to continue to work with older versions of Node.js that do not include
10662 // the prependListener() method. The goal is to eventually remove this hack.
10663 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
10664 }
10665}
10666
11657function ReadableState(options, stream) { 10667function ReadableState(options, stream) {
11658 var Duplex = require('./_stream_duplex'); 10668 Duplex = Duplex || require('./_stream_duplex');
11659 10669
11660 options = options || {}; 10670 options = options || {};
11661 10671
10672 // object stream flag. Used to make read(n) ignore n and to
10673 // make all the buffer merging and length checks go away
10674 this.objectMode = !!options.objectMode;
10675
10676 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
10677
11662 // the point at which it stops calling _read() to fill the buffer 10678 // the point at which it stops calling _read() to fill the buffer
11663 // Note: 0 is a valid value, means "don't call _read preemptively ever" 10679 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11664 var hwm = options.highWaterMark; 10680 var hwm = options.highWaterMark;
11665 var defaultHwm = options.objectMode ? 16 : 16 * 1024; 10681 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
11666 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; 10682 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
11667 10683
11668 // cast to ints. 10684 // cast to ints.
11669 this.highWaterMark = ~~this.highWaterMark; 10685 this.highWaterMark = Math.floor(this.highWaterMark);
11670 10686
11671 this.buffer = []; 10687 // A linked list is used to store data chunks instead of an array because the
10688 // linked list can remove elements from the beginning faster than
10689 // array.shift()
10690 this.buffer = new BufferList();
11672 this.length = 0; 10691 this.length = 0;
11673 this.pipes = null; 10692 this.pipes = null;
11674 this.pipesCount = 0; 10693 this.pipesCount = 0;
@@ -11677,10 +10696,10 @@ function ReadableState(options, stream) {
11677 this.endEmitted = false; 10696 this.endEmitted = false;
11678 this.reading = false; 10697 this.reading = false;
11679 10698
11680 // a flag to be able to tell if the onwrite cb is called immediately, 10699 // a flag to be able to tell if the event 'readable'/'data' is emitted
11681 // or on a later tick. We set this to true at first, because any 10700 // immediately, or on a later tick. We set this to true at first, because
11682 // actions that shouldn't happen until "later" should generally also 10701 // any actions that shouldn't happen until "later" should generally also
11683 // not happen before the first write call. 10702 // not happen before the first read call.
11684 this.sync = true; 10703 this.sync = true;
11685 10704
11686 // whenever we return null, then we set a flag to say 10705 // whenever we return null, then we set a flag to say
@@ -11688,24 +10707,16 @@ function ReadableState(options, stream) {
11688 this.needReadable = false; 10707 this.needReadable = false;
11689 this.emittedReadable = false; 10708 this.emittedReadable = false;
11690 this.readableListening = false; 10709 this.readableListening = false;
10710 this.resumeScheduled = false;
11691 10711
11692 10712 // has it been destroyed
11693 // object stream flag. Used to make read(n) ignore n and to 10713 this.destroyed = false;
11694 // make all the buffer merging and length checks go away
11695 this.objectMode = !!options.objectMode;
11696
11697 if (stream instanceof Duplex)
11698 this.objectMode = this.objectMode || !!options.readableObjectMode;
11699 10714
11700 // Crypto is kind of old and crusty. Historically, its default string 10715 // Crypto is kind of old and crusty. Historically, its default string
11701 // encoding is 'binary' so we have to make this configurable. 10716 // encoding is 'binary' so we have to make this configurable.
11702 // Everything else in the universe uses 'utf8', though. 10717 // Everything else in the universe uses 'utf8', though.
11703 this.defaultEncoding = options.defaultEncoding || 'utf8'; 10718 this.defaultEncoding = options.defaultEncoding || 'utf8';
11704 10719
11705 // when piping, we only care about 'readable' events that happen
11706 // after read()ing all the bytes and not getting any pushback.
11707 this.ranOut = false;
11708
11709 // the number of writers that are awaiting a drain event in .pipe()s 10720 // the number of writers that are awaiting a drain event in .pipe()s
11710 this.awaitDrain = 0; 10721 this.awaitDrain = 0;
11711 10722
@@ -11715,99 +10726,144 @@ function ReadableState(options, stream) {
11715 this.decoder = null; 10726 this.decoder = null;
11716 this.encoding = null; 10727 this.encoding = null;
11717 if (options.encoding) { 10728 if (options.encoding) {
11718 if (!StringDecoder) 10729 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
11719 StringDecoder = require('string_decoder/').StringDecoder;
11720 this.decoder = new StringDecoder(options.encoding); 10730 this.decoder = new StringDecoder(options.encoding);
11721 this.encoding = options.encoding; 10731 this.encoding = options.encoding;
11722 } 10732 }
11723} 10733}
11724 10734
11725function Readable(options) { 10735function Readable(options) {
11726 var Duplex = require('./_stream_duplex'); 10736 Duplex = Duplex || require('./_stream_duplex');
11727 10737
11728 if (!(this instanceof Readable)) 10738 if (!(this instanceof Readable)) return new Readable(options);
11729 return new Readable(options);
11730 10739
11731 this._readableState = new ReadableState(options, this); 10740 this._readableState = new ReadableState(options, this);
11732 10741
11733 // legacy 10742 // legacy
11734 this.readable = true; 10743 this.readable = true;
11735 10744
10745 if (options) {
10746 if (typeof options.read === 'function') this._read = options.read;
10747
10748 if (typeof options.destroy === 'function') this._destroy = options.destroy;
10749 }
10750
11736 Stream.call(this); 10751 Stream.call(this);
11737} 10752}
11738 10753
10754Object.defineProperty(Readable.prototype, 'destroyed', {
10755 get: function () {
10756 if (this._readableState === undefined) {
10757 return false;
10758 }
10759 return this._readableState.destroyed;
10760 },
10761 set: function (value) {
10762 // we ignore the value if the stream
10763 // has not been initialized yet
10764 if (!this._readableState) {
10765 return;
10766 }
10767
10768 // backward compatibility, the user is explicitly
10769 // managing destroyed
10770 this._readableState.destroyed = value;
10771 }
10772});
10773
10774Readable.prototype.destroy = destroyImpl.destroy;
10775Readable.prototype._undestroy = destroyImpl.undestroy;
10776Readable.prototype._destroy = function (err, cb) {
10777 this.push(null);
10778 cb(err);
10779};
10780
11739// Manually shove something into the read() buffer. 10781// Manually shove something into the read() buffer.
11740// This returns true if the highWaterMark has not been hit yet, 10782// This returns true if the highWaterMark has not been hit yet,
11741// similar to how Writable.write() returns true if you should 10783// similar to how Writable.write() returns true if you should
11742// write() some more. 10784// write() some more.
11743Readable.prototype.push = function(chunk, encoding) { 10785Readable.prototype.push = function (chunk, encoding) {
11744 var state = this._readableState; 10786 var state = this._readableState;
11745 10787 var skipChunkCheck;
11746 if (util.isString(chunk) && !state.objectMode) { 10788
11747 encoding = encoding || state.defaultEncoding; 10789 if (!state.objectMode) {
11748 if (encoding !== state.encoding) { 10790 if (typeof chunk === 'string') {
11749 chunk = new Buffer(chunk, encoding); 10791 encoding = encoding || state.defaultEncoding;
11750 encoding = ''; 10792 if (encoding !== state.encoding) {
10793 chunk = Buffer.from(chunk, encoding);
10794 encoding = '';
10795 }
10796 skipChunkCheck = true;
11751 } 10797 }
10798 } else {
10799 skipChunkCheck = true;
11752 } 10800 }
11753 10801
11754 return readableAddChunk(this, state, chunk, encoding, false); 10802 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
11755}; 10803};
11756 10804
11757// Unshift should *always* be something directly out of read() 10805// Unshift should *always* be something directly out of read()
11758Readable.prototype.unshift = function(chunk) { 10806Readable.prototype.unshift = function (chunk) {
11759 var state = this._readableState; 10807 return readableAddChunk(this, chunk, null, true, false);
11760 return readableAddChunk(this, state, chunk, '', true);
11761}; 10808};
11762 10809
11763function readableAddChunk(stream, state, chunk, encoding, addToFront) { 10810function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
11764 var er = chunkInvalid(state, chunk); 10811 var state = stream._readableState;
11765 if (er) { 10812 if (chunk === null) {
11766 stream.emit('error', er);
11767 } else if (util.isNullOrUndefined(chunk)) {
11768 state.reading = false; 10813 state.reading = false;
11769 if (!state.ended) 10814 onEofChunk(stream, state);
11770 onEofChunk(stream, state); 10815 } else {
11771 } else if (state.objectMode || chunk && chunk.length > 0) { 10816 var er;
11772 if (state.ended && !addToFront) { 10817 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
11773 var e = new Error('stream.push() after EOF'); 10818 if (er) {
11774 stream.emit('error', e); 10819 stream.emit('error', er);
11775 } else if (state.endEmitted && addToFront) { 10820 } else if (state.objectMode || chunk && chunk.length > 0) {
11776 var e = new Error('stream.unshift() after end event'); 10821 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
11777 stream.emit('error', e); 10822 chunk = _uint8ArrayToBuffer(chunk);
11778 } else { 10823 }
11779 if (state.decoder && !addToFront && !encoding)
11780 chunk = state.decoder.write(chunk);
11781
11782 if (!addToFront)
11783 state.reading = false;
11784 10824
11785 // if we want the data now, just emit it. 10825 if (addToFront) {
11786 if (state.flowing && state.length === 0 && !state.sync) { 10826 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
11787 stream.emit('data', chunk); 10827 } else if (state.ended) {
11788 stream.read(0); 10828 stream.emit('error', new Error('stream.push() after EOF'));
11789 } else { 10829 } else {
11790 // update the buffer info. 10830 state.reading = false;
11791 state.length += state.objectMode ? 1 : chunk.length; 10831 if (state.decoder && !encoding) {
11792 if (addToFront) 10832 chunk = state.decoder.write(chunk);
11793 state.buffer.unshift(chunk); 10833 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
11794 else 10834 } else {
11795 state.buffer.push(chunk); 10835 addChunk(stream, state, chunk, false);
11796 10836 }
11797 if (state.needReadable)
11798 emitReadable(stream);
11799 } 10837 }
11800 10838 } else if (!addToFront) {
11801 maybeReadMore(stream, state); 10839 state.reading = false;
11802 } 10840 }
11803 } else if (!addToFront) {
11804 state.reading = false;
11805 } 10841 }
11806 10842
11807 return needMoreData(state); 10843 return needMoreData(state);
11808} 10844}
11809 10845
10846function addChunk(stream, state, chunk, addToFront) {
10847 if (state.flowing && state.length === 0 && !state.sync) {
10848 stream.emit('data', chunk);
10849 stream.read(0);
10850 } else {
10851 // update the buffer info.
10852 state.length += state.objectMode ? 1 : chunk.length;
10853 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
11810 10854
10855 if (state.needReadable) emitReadable(stream);
10856 }
10857 maybeReadMore(stream, state);
10858}
10859
10860function chunkInvalid(state, chunk) {
10861 var er;
10862 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
10863 er = new TypeError('Invalid non-string/buffer chunk');
10864 }
10865 return er;
10866}
11811 10867
11812// if it's past the high water mark, we can push in some more. 10868// if it's past the high water mark, we can push in some more.
11813// Also, if we have no data yet, we can stand some 10869// Also, if we have no data yet, we can stand some
@@ -11817,92 +10873,75 @@ function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11817// needReadable was set, then we ought to push more, so that another 10873// needReadable was set, then we ought to push more, so that another
11818// 'readable' event will be triggered. 10874// 'readable' event will be triggered.
11819function needMoreData(state) { 10875function needMoreData(state) {
11820 return !state.ended && 10876 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
11821 (state.needReadable ||
11822 state.length < state.highWaterMark ||
11823 state.length === 0);
11824} 10877}
11825 10878
10879Readable.prototype.isPaused = function () {
10880 return this._readableState.flowing === false;
10881};
10882
11826// backwards compatibility. 10883// backwards compatibility.
11827Readable.prototype.setEncoding = function(enc) { 10884Readable.prototype.setEncoding = function (enc) {
11828 if (!StringDecoder) 10885 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
11829 StringDecoder = require('string_decoder/').StringDecoder;
11830 this._readableState.decoder = new StringDecoder(enc); 10886 this._readableState.decoder = new StringDecoder(enc);
11831 this._readableState.encoding = enc; 10887 this._readableState.encoding = enc;
11832 return this; 10888 return this;
11833}; 10889};
11834 10890
11835// Don't raise the hwm > 128MB 10891// Don't raise the hwm > 8MB
11836var MAX_HWM = 0x800000; 10892var MAX_HWM = 0x800000;
11837function roundUpToNextPowerOf2(n) { 10893function computeNewHighWaterMark(n) {
11838 if (n >= MAX_HWM) { 10894 if (n >= MAX_HWM) {
11839 n = MAX_HWM; 10895 n = MAX_HWM;
11840 } else { 10896 } else {
11841 // Get the next highest power of 2 10897 // Get the next highest power of 2 to prevent increasing hwm excessively in
10898 // tiny amounts
11842 n--; 10899 n--;
11843 for (var p = 1; p < 32; p <<= 1) n |= n >> p; 10900 n |= n >>> 1;
10901 n |= n >>> 2;
10902 n |= n >>> 4;
10903 n |= n >>> 8;
10904 n |= n >>> 16;
11844 n++; 10905 n++;
11845 } 10906 }
11846 return n; 10907 return n;
11847} 10908}
11848 10909
10910// This function is designed to be inlinable, so please take care when making
10911// changes to the function body.
11849function howMuchToRead(n, state) { 10912function howMuchToRead(n, state) {
11850 if (state.length === 0 && state.ended) 10913 if (n <= 0 || state.length === 0 && state.ended) return 0;
11851 return 0; 10914 if (state.objectMode) return 1;
11852 10915 if (n !== n) {
11853 if (state.objectMode) 10916 // Only flow one buffer at a time
11854 return n === 0 ? 0 : 1; 10917 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
11855
11856 if (isNaN(n) || util.isNull(n)) {
11857 // only flow one buffer at a time
11858 if (state.flowing && state.buffer.length)
11859 return state.buffer[0].length;
11860 else
11861 return state.length;
11862 } 10918 }
11863 10919 // If we're asking for more than the current hwm, then raise the hwm.
11864 if (n <= 0) 10920 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
10921 if (n <= state.length) return n;
10922 // Don't have enough
10923 if (!state.ended) {
10924 state.needReadable = true;
11865 return 0; 10925 return 0;
11866
11867 // If we're asking for more than the target buffer level,
11868 // then raise the water mark. Bump up to the next highest
11869 // power of 2, to prevent increasing it excessively in tiny
11870 // amounts.
11871 if (n > state.highWaterMark)
11872 state.highWaterMark = roundUpToNextPowerOf2(n);
11873
11874 // don't have that much. return null, unless we've ended.
11875 if (n > state.length) {
11876 if (!state.ended) {
11877 state.needReadable = true;
11878 return 0;
11879 } else
11880 return state.length;
11881 } 10926 }
11882 10927 return state.length;
11883 return n;
11884} 10928}
11885 10929
11886// you can override either this method, or the async _read(n) below. 10930// you can override either this method, or the async _read(n) below.
11887Readable.prototype.read = function(n) { 10931Readable.prototype.read = function (n) {
11888 debug('read', n); 10932 debug('read', n);
10933 n = parseInt(n, 10);
11889 var state = this._readableState; 10934 var state = this._readableState;
11890 var nOrig = n; 10935 var nOrig = n;
11891 10936
11892 if (!util.isNumber(n) || n > 0) 10937 if (n !== 0) state.emittedReadable = false;
11893 state.emittedReadable = false;
11894 10938
11895 // if we're doing read(0) to trigger a readable event, but we 10939 // if we're doing read(0) to trigger a readable event, but we
11896 // already have a bunch of data in the buffer, then just trigger 10940 // already have a bunch of data in the buffer, then just trigger
11897 // the 'readable' event and move on. 10941 // the 'readable' event and move on.
11898 if (n === 0 && 10942 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
11899 state.needReadable &&
11900 (state.length >= state.highWaterMark || state.ended)) {
11901 debug('read: emitReadable', state.length, state.ended); 10943 debug('read: emitReadable', state.length, state.ended);
11902 if (state.length === 0 && state.ended) 10944 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
11903 endReadable(this);
11904 else
11905 emitReadable(this);
11906 return null; 10945 return null;
11907 } 10946 }
11908 10947
@@ -11910,8 +10949,7 @@ Readable.prototype.read = function(n) {
11910 10949
11911 // if we've ended, and we're now clear, then finish it up. 10950 // if we've ended, and we're now clear, then finish it up.
11912 if (n === 0 && state.ended) { 10951 if (n === 0 && state.ended) {
11913 if (state.length === 0) 10952 if (state.length === 0) endReadable(this);
11914 endReadable(this);
11915 return null; 10953 return null;
11916 } 10954 }
11917 10955
@@ -11952,67 +10990,47 @@ Readable.prototype.read = function(n) {
11952 if (state.ended || state.reading) { 10990 if (state.ended || state.reading) {
11953 doRead = false; 10991 doRead = false;
11954 debug('reading or ended', doRead); 10992 debug('reading or ended', doRead);
11955 } 10993 } else if (doRead) {
11956
11957 if (doRead) {
11958 debug('do read'); 10994 debug('do read');
11959 state.reading = true; 10995 state.reading = true;
11960 state.sync = true; 10996 state.sync = true;
11961 // if the length is currently zero, then we *need* a readable event. 10997 // if the length is currently zero, then we *need* a readable event.
11962 if (state.length === 0) 10998 if (state.length === 0) state.needReadable = true;
11963 state.needReadable = true;
11964 // call internal read method 10999 // call internal read method
11965 this._read(state.highWaterMark); 11000 this._read(state.highWaterMark);
11966 state.sync = false; 11001 state.sync = false;
11002 // If _read pushed data synchronously, then `reading` will be false,
11003 // and we need to re-evaluate how much data we can return to the user.
11004 if (!state.reading) n = howMuchToRead(nOrig, state);
11967 } 11005 }
11968 11006
11969 // If _read pushed data synchronously, then `reading` will be false,
11970 // and we need to re-evaluate how much data we can return to the user.
11971 if (doRead && !state.reading)
11972 n = howMuchToRead(nOrig, state);
11973
11974 var ret; 11007 var ret;
11975 if (n > 0) 11008 if (n > 0) ret = fromList(n, state);else ret = null;
11976 ret = fromList(n, state);
11977 else
11978 ret = null;
11979 11009
11980 if (util.isNull(ret)) { 11010 if (ret === null) {
11981 state.needReadable = true; 11011 state.needReadable = true;
11982 n = 0; 11012 n = 0;
11013 } else {
11014 state.length -= n;
11983 } 11015 }
11984 11016
11985 state.length -= n; 11017 if (state.length === 0) {
11986 11018 // If we have nothing in the buffer, then we want to know
11987 // If we have nothing in the buffer, then we want to know 11019 // as soon as we *do* get something into the buffer.
11988 // as soon as we *do* get something into the buffer. 11020 if (!state.ended) state.needReadable = true;
11989 if (state.length === 0 && !state.ended)
11990 state.needReadable = true;
11991 11021
11992 // If we tried to read() past the EOF, then emit end on the next tick. 11022 // If we tried to read() past the EOF, then emit end on the next tick.
11993 if (nOrig !== n && state.ended && state.length === 0) 11023 if (nOrig !== n && state.ended) endReadable(this);
11994 endReadable(this); 11024 }
11995 11025
11996 if (!util.isNull(ret)) 11026 if (ret !== null) this.emit('data', ret);
11997 this.emit('data', ret);
11998 11027
11999 return ret; 11028 return ret;
12000}; 11029};
12001 11030
12002function chunkInvalid(state, chunk) {
12003 var er = null;
12004 if (!util.isBuffer(chunk) &&
12005 !util.isString(chunk) &&
12006 !util.isNullOrUndefined(chunk) &&
12007 !state.objectMode) {
12008 er = new TypeError('Invalid non-string/buffer chunk');
12009 }
12010 return er;
12011}
12012
12013
12014function onEofChunk(stream, state) { 11031function onEofChunk(stream, state) {
12015 if (state.decoder && !state.ended) { 11032 if (state.ended) return;
11033 if (state.decoder) {
12016 var chunk = state.decoder.end(); 11034 var chunk = state.decoder.end();
12017 if (chunk && chunk.length) { 11035 if (chunk && chunk.length) {
12018 state.buffer.push(chunk); 11036 state.buffer.push(chunk);
@@ -12034,12 +11052,7 @@ function emitReadable(stream) {
12034 if (!state.emittedReadable) { 11052 if (!state.emittedReadable) {
12035 debug('emitReadable', state.flowing); 11053 debug('emitReadable', state.flowing);
12036 state.emittedReadable = true; 11054 state.emittedReadable = true;
12037 if (state.sync) 11055 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
12038 process.nextTick(function() {
12039 emitReadable_(stream);
12040 });
12041 else
12042 emitReadable_(stream);
12043 } 11056 }
12044} 11057}
12045 11058
@@ -12049,7 +11062,6 @@ function emitReadable_(stream) {
12049 flow(stream); 11062 flow(stream);
12050} 11063}
12051 11064
12052
12053// at this point, the user has presumably seen the 'readable' event, 11065// at this point, the user has presumably seen the 'readable' event,
12054// and called read() to consume some data. that may have triggered 11066// and called read() to consume some data. that may have triggered
12055// in turn another _read(n) call, in which case reading = true if 11067// in turn another _read(n) call, in which case reading = true if
@@ -12059,23 +11071,18 @@ function emitReadable_(stream) {
12059function maybeReadMore(stream, state) { 11071function maybeReadMore(stream, state) {
12060 if (!state.readingMore) { 11072 if (!state.readingMore) {
12061 state.readingMore = true; 11073 state.readingMore = true;
12062 process.nextTick(function() { 11074 processNextTick(maybeReadMore_, stream, state);
12063 maybeReadMore_(stream, state);
12064 });
12065 } 11075 }
12066} 11076}
12067 11077
12068function maybeReadMore_(stream, state) { 11078function maybeReadMore_(stream, state) {
12069 var len = state.length; 11079 var len = state.length;
12070 while (!state.reading && !state.flowing && !state.ended && 11080 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
12071 state.length < state.highWaterMark) {
12072 debug('maybeReadMore read 0'); 11081 debug('maybeReadMore read 0');
12073 stream.read(0); 11082 stream.read(0);
12074 if (len === state.length) 11083 if (len === state.length)
12075 // didn't get any data, stop spinning. 11084 // didn't get any data, stop spinning.
12076 break; 11085 break;else len = state.length;
12077 else
12078 len = state.length;
12079 } 11086 }
12080 state.readingMore = false; 11087 state.readingMore = false;
12081} 11088}
@@ -12084,11 +11091,11 @@ function maybeReadMore_(stream, state) {
12084// call cb(er, data) where data is <= n in length. 11091// call cb(er, data) where data is <= n in length.
12085// for virtual (non-string, non-buffer) streams, "length" is somewhat 11092// for virtual (non-string, non-buffer) streams, "length" is somewhat
12086// arbitrary, and perhaps not very meaningful. 11093// arbitrary, and perhaps not very meaningful.
12087Readable.prototype._read = function(n) { 11094Readable.prototype._read = function (n) {
12088 this.emit('error', new Error('not implemented')); 11095 this.emit('error', new Error('_read() is not implemented'));
12089}; 11096};
12090 11097
12091Readable.prototype.pipe = function(dest, pipeOpts) { 11098Readable.prototype.pipe = function (dest, pipeOpts) {
12092 var src = this; 11099 var src = this;
12093 var state = this._readableState; 11100 var state = this._readableState;
12094 11101
@@ -12106,21 +11113,19 @@ Readable.prototype.pipe = function(dest, pipeOpts) {
12106 state.pipesCount += 1; 11113 state.pipesCount += 1;
12107 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); 11114 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
12108 11115
12109 var doEnd = (!pipeOpts || pipeOpts.end !== false) && 11116 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
12110 dest !== process.stdout &&
12111 dest !== process.stderr;
12112 11117
12113 var endFn = doEnd ? onend : cleanup; 11118 var endFn = doEnd ? onend : unpipe;
12114 if (state.endEmitted) 11119 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
12115 process.nextTick(endFn);
12116 else
12117 src.once('end', endFn);
12118 11120
12119 dest.on('unpipe', onunpipe); 11121 dest.on('unpipe', onunpipe);
12120 function onunpipe(readable) { 11122 function onunpipe(readable, unpipeInfo) {
12121 debug('onunpipe'); 11123 debug('onunpipe');
12122 if (readable === src) { 11124 if (readable === src) {
12123 cleanup(); 11125 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
11126 unpipeInfo.hasUnpiped = true;
11127 cleanup();
11128 }
12124 } 11129 }
12125 } 11130 }
12126 11131
@@ -12136,6 +11141,7 @@ Readable.prototype.pipe = function(dest, pipeOpts) {
12136 var ondrain = pipeOnDrain(src); 11141 var ondrain = pipeOnDrain(src);
12137 dest.on('drain', ondrain); 11142 dest.on('drain', ondrain);
12138 11143
11144 var cleanedUp = false;
12139 function cleanup() { 11145 function cleanup() {
12140 debug('cleanup'); 11146 debug('cleanup');
12141 // cleanup event handlers once the pipe is broken 11147 // cleanup event handlers once the pipe is broken
@@ -12145,27 +11151,39 @@ Readable.prototype.pipe = function(dest, pipeOpts) {
12145 dest.removeListener('error', onerror); 11151 dest.removeListener('error', onerror);
12146 dest.removeListener('unpipe', onunpipe); 11152 dest.removeListener('unpipe', onunpipe);
12147 src.removeListener('end', onend); 11153 src.removeListener('end', onend);
12148 src.removeListener('end', cleanup); 11154 src.removeListener('end', unpipe);
12149 src.removeListener('data', ondata); 11155 src.removeListener('data', ondata);
12150 11156
11157 cleanedUp = true;
11158
12151 // if the reader is waiting for a drain event from this 11159 // if the reader is waiting for a drain event from this
12152 // specific writer, then it would cause it to never start 11160 // specific writer, then it would cause it to never start
12153 // flowing again. 11161 // flowing again.
12154 // So, if this is awaiting a drain, then we just call it now. 11162 // So, if this is awaiting a drain, then we just call it now.
12155 // If we don't know, then assume that we are waiting for one. 11163 // If we don't know, then assume that we are waiting for one.
12156 if (state.awaitDrain && 11164 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
12157 (!dest._writableState || dest._writableState.needDrain))
12158 ondrain();
12159 } 11165 }
12160 11166
11167 // If the user pushes more data while we're writing to dest then we'll end up
11168 // in ondata again. However, we only want to increase awaitDrain once because
11169 // dest will only emit one 'drain' event for the multiple writes.
11170 // => Introduce a guard on increasing awaitDrain.
11171 var increasedAwaitDrain = false;
12161 src.on('data', ondata); 11172 src.on('data', ondata);
12162 function ondata(chunk) { 11173 function ondata(chunk) {
12163 debug('ondata'); 11174 debug('ondata');
11175 increasedAwaitDrain = false;
12164 var ret = dest.write(chunk); 11176 var ret = dest.write(chunk);
12165 if (false === ret) { 11177 if (false === ret && !increasedAwaitDrain) {
12166 debug('false write response, pause', 11178 // If the user unpiped during `dest.write()`, it is possible
12167 src._readableState.awaitDrain); 11179 // to get stuck in a permanently paused state if that write
12168 src._readableState.awaitDrain++; 11180 // also returned false.
11181 // => Check whether `dest` is still a piping destination.
11182 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
11183 debug('false write response, pause', src._readableState.awaitDrain);
11184 src._readableState.awaitDrain++;
11185 increasedAwaitDrain = true;
11186 }
12169 src.pause(); 11187 src.pause();
12170 } 11188 }
12171 } 11189 }
@@ -12176,19 +11194,11 @@ Readable.prototype.pipe = function(dest, pipeOpts) {
12176 debug('onerror', er); 11194 debug('onerror', er);
12177 unpipe(); 11195 unpipe();
12178 dest.removeListener('error', onerror); 11196 dest.removeListener('error', onerror);
12179 if (EE.listenerCount(dest, 'error') === 0) 11197 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
12180 dest.emit('error', er); 11198 }
12181 }
12182 // This is a brutally ugly hack to make sure that our error handler
12183 // is attached before any userland ones. NEVER DO THIS.
12184 if (!dest._events || !dest._events.error)
12185 dest.on('error', onerror);
12186 else if (isArray(dest._events.error))
12187 dest._events.error.unshift(onerror);
12188 else
12189 dest._events.error = [onerror, dest._events.error];
12190
12191 11199
11200 // Make sure our error handler is attached before userland ones.
11201 prependListener(dest, 'error', onerror);
12192 11202
12193 // Both close and finish should trigger unpipe, but only once. 11203 // Both close and finish should trigger unpipe, but only once.
12194 function onclose() { 11204 function onclose() {
@@ -12221,41 +11231,36 @@ Readable.prototype.pipe = function(dest, pipeOpts) {
12221}; 11231};
12222 11232
12223function pipeOnDrain(src) { 11233function pipeOnDrain(src) {
12224 return function() { 11234 return function () {
12225 var state = src._readableState; 11235 var state = src._readableState;
12226 debug('pipeOnDrain', state.awaitDrain); 11236 debug('pipeOnDrain', state.awaitDrain);
12227 if (state.awaitDrain) 11237 if (state.awaitDrain) state.awaitDrain--;
12228 state.awaitDrain--; 11238 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
12229 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
12230 state.flowing = true; 11239 state.flowing = true;
12231 flow(src); 11240 flow(src);
12232 } 11241 }
12233 }; 11242 };
12234} 11243}
12235 11244
12236 11245Readable.prototype.unpipe = function (dest) {
12237Readable.prototype.unpipe = function(dest) {
12238 var state = this._readableState; 11246 var state = this._readableState;
11247 var unpipeInfo = { hasUnpiped: false };
12239 11248
12240 // if we're not piping anywhere, then do nothing. 11249 // if we're not piping anywhere, then do nothing.
12241 if (state.pipesCount === 0) 11250 if (state.pipesCount === 0) return this;
12242 return this;
12243 11251
12244 // just one destination. most common case. 11252 // just one destination. most common case.
12245 if (state.pipesCount === 1) { 11253 if (state.pipesCount === 1) {
12246 // passed in one, but it's not the right one. 11254 // passed in one, but it's not the right one.
12247 if (dest && dest !== state.pipes) 11255 if (dest && dest !== state.pipes) return this;
12248 return this;
12249 11256
12250 if (!dest) 11257 if (!dest) dest = state.pipes;
12251 dest = state.pipes;
12252 11258
12253 // got a match. 11259 // got a match.
12254 state.pipes = null; 11260 state.pipes = null;
12255 state.pipesCount = 0; 11261 state.pipesCount = 0;
12256 state.flowing = false; 11262 state.flowing = false;
12257 if (dest) 11263 if (dest) dest.emit('unpipe', this, unpipeInfo);
12258 dest.emit('unpipe', this);
12259 return this; 11264 return this;
12260 } 11265 }
12261 11266
@@ -12269,51 +11274,41 @@ Readable.prototype.unpipe = function(dest) {
12269 state.pipesCount = 0; 11274 state.pipesCount = 0;
12270 state.flowing = false; 11275 state.flowing = false;
12271 11276
12272 for (var i = 0; i < len; i++) 11277 for (var i = 0; i < len; i++) {
12273 dests[i].emit('unpipe', this); 11278 dests[i].emit('unpipe', this, unpipeInfo);
12274 return this; 11279 }return this;
12275 } 11280 }
12276 11281
12277 // try to find the right one. 11282 // try to find the right one.
12278 var i = indexOf(state.pipes, dest); 11283 var index = indexOf(state.pipes, dest);
12279 if (i === -1) 11284 if (index === -1) return this;
12280 return this;
12281 11285
12282 state.pipes.splice(i, 1); 11286 state.pipes.splice(index, 1);
12283 state.pipesCount -= 1; 11287 state.pipesCount -= 1;
12284 if (state.pipesCount === 1) 11288 if (state.pipesCount === 1) state.pipes = state.pipes[0];
12285 state.pipes = state.pipes[0];
12286 11289
12287 dest.emit('unpipe', this); 11290 dest.emit('unpipe', this, unpipeInfo);
12288 11291
12289 return this; 11292 return this;
12290}; 11293};
12291 11294
12292// set up data events if they are asked for 11295// set up data events if they are asked for
12293// Ensure readable listeners eventually get something 11296// Ensure readable listeners eventually get something
12294Readable.prototype.on = function(ev, fn) { 11297Readable.prototype.on = function (ev, fn) {
12295 var res = Stream.prototype.on.call(this, ev, fn); 11298 var res = Stream.prototype.on.call(this, ev, fn);
12296 11299
12297 // If listening to data, and it has not explicitly been paused, 11300 if (ev === 'data') {
12298 // then call resume to start the flow of data on the next tick. 11301 // Start flowing on next tick if stream isn't explicitly paused
12299 if (ev === 'data' && false !== this._readableState.flowing) { 11302 if (this._readableState.flowing !== false) this.resume();
12300 this.resume(); 11303 } else if (ev === 'readable') {
12301 }
12302
12303 if (ev === 'readable' && this.readable) {
12304 var state = this._readableState; 11304 var state = this._readableState;
12305 if (!state.readableListening) { 11305 if (!state.endEmitted && !state.readableListening) {
12306 state.readableListening = true; 11306 state.readableListening = state.needReadable = true;
12307 state.emittedReadable = false; 11307 state.emittedReadable = false;
12308 state.needReadable = true;
12309 if (!state.reading) { 11308 if (!state.reading) {
12310 var self = this; 11309 processNextTick(nReadingNextTick, this);
12311 process.nextTick(function() {
12312 debug('readable nexttick read 0');
12313 self.read(0);
12314 });
12315 } else if (state.length) { 11310 } else if (state.length) {
12316 emitReadable(this, state); 11311 emitReadable(this);
12317 } 11312 }
12318 } 11313 }
12319 } 11314 }
@@ -12322,17 +11317,18 @@ Readable.prototype.on = function(ev, fn) {
12322}; 11317};
12323Readable.prototype.addListener = Readable.prototype.on; 11318Readable.prototype.addListener = Readable.prototype.on;
12324 11319
11320function nReadingNextTick(self) {
11321 debug('readable nexttick read 0');
11322 self.read(0);
11323}
11324
12325// pause() and resume() are remnants of the legacy readable stream API 11325// pause() and resume() are remnants of the legacy readable stream API
12326// If the user uses them, then switch into old mode. 11326// If the user uses them, then switch into old mode.
12327Readable.prototype.resume = function() { 11327Readable.prototype.resume = function () {
12328 var state = this._readableState; 11328 var state = this._readableState;
12329 if (!state.flowing) { 11329 if (!state.flowing) {
12330 debug('resume'); 11330 debug('resume');
12331 state.flowing = true; 11331 state.flowing = true;
12332 if (!state.reading) {
12333 debug('resume read 0');
12334 this.read(0);
12335 }
12336 resume(this, state); 11332 resume(this, state);
12337 } 11333 }
12338 return this; 11334 return this;
@@ -12341,21 +11337,24 @@ Readable.prototype.resume = function() {
12341function resume(stream, state) { 11337function resume(stream, state) {
12342 if (!state.resumeScheduled) { 11338 if (!state.resumeScheduled) {
12343 state.resumeScheduled = true; 11339 state.resumeScheduled = true;
12344 process.nextTick(function() { 11340 processNextTick(resume_, stream, state);
12345 resume_(stream, state);
12346 });
12347 } 11341 }
12348} 11342}
12349 11343
12350function resume_(stream, state) { 11344function resume_(stream, state) {
11345 if (!state.reading) {
11346 debug('resume read 0');
11347 stream.read(0);
11348 }
11349
12351 state.resumeScheduled = false; 11350 state.resumeScheduled = false;
11351 state.awaitDrain = 0;
12352 stream.emit('resume'); 11352 stream.emit('resume');
12353 flow(stream); 11353 flow(stream);
12354 if (state.flowing && !state.reading) 11354 if (state.flowing && !state.reading) stream.read(0);
12355 stream.read(0);
12356} 11355}
12357 11356
12358Readable.prototype.pause = function() { 11357Readable.prototype.pause = function () {
12359 debug('call pause flowing=%j', this._readableState.flowing); 11358 debug('call pause flowing=%j', this._readableState.flowing);
12360 if (false !== this._readableState.flowing) { 11359 if (false !== this._readableState.flowing) {
12361 debug('pause'); 11360 debug('pause');
@@ -12368,38 +11367,33 @@ Readable.prototype.pause = function() {
12368function flow(stream) { 11367function flow(stream) {
12369 var state = stream._readableState; 11368 var state = stream._readableState;
12370 debug('flow', state.flowing); 11369 debug('flow', state.flowing);
12371 if (state.flowing) { 11370 while (state.flowing && stream.read() !== null) {}
12372 do {
12373 var chunk = stream.read();
12374 } while (null !== chunk && state.flowing);
12375 }
12376} 11371}
12377 11372
12378// wrap an old-style stream as the async data source. 11373// wrap an old-style stream as the async data source.
12379// This is *not* part of the readable stream interface. 11374// This is *not* part of the readable stream interface.
12380// It is an ugly unfortunate mess of history. 11375// It is an ugly unfortunate mess of history.
12381Readable.prototype.wrap = function(stream) { 11376Readable.prototype.wrap = function (stream) {
12382 var state = this._readableState; 11377 var state = this._readableState;
12383 var paused = false; 11378 var paused = false;
12384 11379
12385 var self = this; 11380 var self = this;
12386 stream.on('end', function() { 11381 stream.on('end', function () {
12387 debug('wrapped end'); 11382 debug('wrapped end');
12388 if (state.decoder && !state.ended) { 11383 if (state.decoder && !state.ended) {
12389 var chunk = state.decoder.end(); 11384 var chunk = state.decoder.end();
12390 if (chunk && chunk.length) 11385 if (chunk && chunk.length) self.push(chunk);
12391 self.push(chunk);
12392 } 11386 }
12393 11387
12394 self.push(null); 11388 self.push(null);
12395 }); 11389 });
12396 11390
12397 stream.on('data', function(chunk) { 11391 stream.on('data', function (chunk) {
12398 debug('wrapped data'); 11392 debug('wrapped data');
12399 if (state.decoder) 11393 if (state.decoder) chunk = state.decoder.write(chunk);
12400 chunk = state.decoder.write(chunk); 11394
12401 if (!chunk || !state.objectMode && !chunk.length) 11395 // don't skip over falsy values in objectMode
12402 return; 11396 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
12403 11397
12404 var ret = self.push(chunk); 11398 var ret = self.push(chunk);
12405 if (!ret) { 11399 if (!ret) {
@@ -12411,22 +11405,23 @@ Readable.prototype.wrap = function(stream) {
12411 // proxy all the other methods. 11405 // proxy all the other methods.
12412 // important when wrapping filters and duplexes. 11406 // important when wrapping filters and duplexes.
12413 for (var i in stream) { 11407 for (var i in stream) {
12414 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { 11408 if (this[i] === undefined && typeof stream[i] === 'function') {
12415 this[i] = function(method) { return function() { 11409 this[i] = function (method) {
12416 return stream[method].apply(stream, arguments); 11410 return function () {
12417 }}(i); 11411 return stream[method].apply(stream, arguments);
11412 };
11413 }(i);
12418 } 11414 }
12419 } 11415 }
12420 11416
12421 // proxy certain important events. 11417 // proxy certain important events.
12422 var events = ['error', 'close', 'destroy', 'pause', 'resume']; 11418 for (var n = 0; n < kProxyEvents.length; n++) {
12423 forEach(events, function(ev) { 11419 stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
12424 stream.on(ev, self.emit.bind(self, ev)); 11420 }
12425 });
12426 11421
12427 // when we try to consume some more bytes, simply unpause the 11422 // when we try to consume some more bytes, simply unpause the
12428 // underlying stream. 11423 // underlying stream.
12429 self._read = function(n) { 11424 self._read = function (n) {
12430 debug('wrapped _read', n); 11425 debug('wrapped _read', n);
12431 if (paused) { 11426 if (paused) {
12432 paused = false; 11427 paused = false;
@@ -12437,74 +11432,106 @@ Readable.prototype.wrap = function(stream) {
12437 return self; 11432 return self;
12438}; 11433};
12439 11434
12440
12441
12442// exposed for testing purposes only. 11435// exposed for testing purposes only.
12443Readable._fromList = fromList; 11436Readable._fromList = fromList;
12444 11437
12445// Pluck off n bytes from an array of buffers. 11438// Pluck off n bytes from an array of buffers.
12446// Length is the combined lengths of all the buffers in the list. 11439// Length is the combined lengths of all the buffers in the list.
11440// This function is designed to be inlinable, so please take care when making
11441// changes to the function body.
12447function fromList(n, state) { 11442function fromList(n, state) {
12448 var list = state.buffer; 11443 // nothing buffered
12449 var length = state.length; 11444 if (state.length === 0) return null;
12450 var stringMode = !!state.decoder; 11445
12451 var objectMode = !!state.objectMode;
12452 var ret; 11446 var ret;
11447 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
11448 // read it all, truncate the list
11449 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
11450 state.buffer.clear();
11451 } else {
11452 // read part of list
11453 ret = fromListPartial(n, state.buffer, state.decoder);
11454 }
12453 11455
12454 // nothing in the list, definitely empty. 11456 return ret;
12455 if (list.length === 0) 11457}
12456 return null;
12457 11458
12458 if (length === 0) 11459// Extracts only enough buffered data to satisfy the amount requested.
12459 ret = null; 11460// This function is designed to be inlinable, so please take care when making
12460 else if (objectMode) 11461// changes to the function body.
11462function fromListPartial(n, list, hasStrings) {
11463 var ret;
11464 if (n < list.head.data.length) {
11465 // slice is the same for buffers and strings
11466 ret = list.head.data.slice(0, n);
11467 list.head.data = list.head.data.slice(n);
11468 } else if (n === list.head.data.length) {
11469 // first chunk is a perfect match
12461 ret = list.shift(); 11470 ret = list.shift();
12462 else if (!n || n >= length) {
12463 // read it all, truncate the array.
12464 if (stringMode)
12465 ret = list.join('');
12466 else
12467 ret = Buffer.concat(list, length);
12468 list.length = 0;
12469 } else { 11471 } else {
12470 // read just some of it. 11472 // result spans more than one buffer
12471 if (n < list[0].length) { 11473 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
12472 // just take a part of the first list item. 11474 }
12473 // slice is the same for buffers and strings. 11475 return ret;
12474 var buf = list[0]; 11476}
12475 ret = buf.slice(0, n);
12476 list[0] = buf.slice(n);
12477 } else if (n === list[0].length) {
12478 // first list is a perfect match
12479 ret = list.shift();
12480 } else {
12481 // complex case.
12482 // we have enough to cover it, but it spans past the first buffer.
12483 if (stringMode)
12484 ret = '';
12485 else
12486 ret = new Buffer(n);
12487
12488 var c = 0;
12489 for (var i = 0, l = list.length; i < l && c < n; i++) {
12490 var buf = list[0];
12491 var cpy = Math.min(n - c, buf.length);
12492
12493 if (stringMode)
12494 ret += buf.slice(0, cpy);
12495 else
12496 buf.copy(ret, c, 0, cpy);
12497
12498 if (cpy < buf.length)
12499 list[0] = buf.slice(cpy);
12500 else
12501 list.shift();
12502 11477
12503 c += cpy; 11478// Copies a specified amount of characters from the list of buffered data
11479// chunks.
11480// This function is designed to be inlinable, so please take care when making
11481// changes to the function body.
11482function copyFromBufferString(n, list) {
11483 var p = list.head;
11484 var c = 1;
11485 var ret = p.data;
11486 n -= ret.length;
11487 while (p = p.next) {
11488 var str = p.data;
11489 var nb = n > str.length ? str.length : n;
11490 if (nb === str.length) ret += str;else ret += str.slice(0, n);
11491 n -= nb;
11492 if (n === 0) {
11493 if (nb === str.length) {
11494 ++c;
11495 if (p.next) list.head = p.next;else list.head = list.tail = null;
11496 } else {
11497 list.head = p;
11498 p.data = str.slice(nb);
12504 } 11499 }
11500 break;
12505 } 11501 }
11502 ++c;
12506 } 11503 }
11504 list.length -= c;
11505 return ret;
11506}
12507 11507
11508// Copies a specified amount of bytes from the list of buffered data chunks.
11509// This function is designed to be inlinable, so please take care when making
11510// changes to the function body.
11511function copyFromBuffer(n, list) {
11512 var ret = Buffer.allocUnsafe(n);
11513 var p = list.head;
11514 var c = 1;
11515 p.data.copy(ret);
11516 n -= p.data.length;
11517 while (p = p.next) {
11518 var buf = p.data;
11519 var nb = n > buf.length ? buf.length : n;
11520 buf.copy(ret, ret.length - n, 0, nb);
11521 n -= nb;
11522 if (n === 0) {
11523 if (nb === buf.length) {
11524 ++c;
11525 if (p.next) list.head = p.next;else list.head = list.tail = null;
11526 } else {
11527 list.head = p;
11528 p.data = buf.slice(nb);
11529 }
11530 break;
11531 }
11532 ++c;
11533 }
11534 list.length -= c;
12508 return ret; 11535 return ret;
12509} 11536}
12510 11537
@@ -12513,37 +11540,37 @@ function endReadable(stream) {
12513 11540
12514 // If we get here before consuming all the bytes, then that is a 11541 // If we get here before consuming all the bytes, then that is a
12515 // bug in node. Should never happen. 11542 // bug in node. Should never happen.
12516 if (state.length > 0) 11543 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
12517 throw new Error('endReadable called on non-empty stream');
12518 11544
12519 if (!state.endEmitted) { 11545 if (!state.endEmitted) {
12520 state.ended = true; 11546 state.ended = true;
12521 process.nextTick(function() { 11547 processNextTick(endReadableNT, state, stream);
12522 // Check that we didn't get one last unshift.
12523 if (!state.endEmitted && state.length === 0) {
12524 state.endEmitted = true;
12525 stream.readable = false;
12526 stream.emit('end');
12527 }
12528 });
12529 } 11548 }
12530} 11549}
12531 11550
12532function forEach (xs, f) { 11551function endReadableNT(state, stream) {
11552 // Check that we didn't get one last unshift.
11553 if (!state.endEmitted && state.length === 0) {
11554 state.endEmitted = true;
11555 stream.readable = false;
11556 stream.emit('end');
11557 }
11558}
11559
11560function forEach(xs, f) {
12533 for (var i = 0, l = xs.length; i < l; i++) { 11561 for (var i = 0, l = xs.length; i < l; i++) {
12534 f(xs[i], i); 11562 f(xs[i], i);
12535 } 11563 }
12536} 11564}
12537 11565
12538function indexOf (xs, x) { 11566function indexOf(xs, x) {
12539 for (var i = 0, l = xs.length; i < l; i++) { 11567 for (var i = 0, l = xs.length; i < l; i++) {
12540 if (xs[i] === x) return i; 11568 if (xs[i] === x) return i;
12541 } 11569 }
12542 return -1; 11570 return -1;
12543} 11571}
12544 11572}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12545}).call(this,require('_process')) 11573},{"./_stream_duplex":14,"./internal/streams/BufferList":19,"./internal/streams/destroy":20,"./internal/streams/stream":21,"_process":12,"core-util-is":5,"events":6,"inherits":8,"isarray":10,"process-nextick-args":11,"safe-buffer":26,"string_decoder/":28,"util":3}],17:[function(require,module,exports){
12546},{"./_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){
12547// Copyright Joyent, Inc. and other Node contributors. 11574// Copyright Joyent, Inc. and other Node contributors.
12548// 11575//
12549// Permission is hereby granted, free of charge, to any person obtaining a 11576// Permission is hereby granted, free of charge, to any person obtaining a
@@ -12565,7 +11592,6 @@ function indexOf (xs, x) {
12565// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 11592// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12566// USE OR OTHER DEALINGS IN THE SOFTWARE. 11593// USE OR OTHER DEALINGS IN THE SOFTWARE.
12567 11594
12568
12569// a transform stream is a readable/writable stream where you do 11595// a transform stream is a readable/writable stream where you do
12570// something with the data. Sometimes it's called a "filter", 11596// something with the data. Sometimes it's called a "filter",
12571// but that's not a great name for it, since that implies a thing where 11597// but that's not a great name for it, since that implies a thing where
@@ -12608,6 +11634,8 @@ function indexOf (xs, x) {
12608// would be consumed, and then the rest would wait (un-transformed) until 11634// would be consumed, and then the rest would wait (un-transformed) until
12609// the results of the previous transformed chunk were consumed. 11635// the results of the previous transformed chunk were consumed.
12610 11636
11637'use strict';
11638
12611module.exports = Transform; 11639module.exports = Transform;
12612 11640
12613var Duplex = require('./_stream_duplex'); 11641var Duplex = require('./_stream_duplex');
@@ -12619,9 +11647,8 @@ util.inherits = require('inherits');
12619 11647
12620util.inherits(Transform, Duplex); 11648util.inherits(Transform, Duplex);
12621 11649
12622 11650function TransformState(stream) {
12623function TransformState(options, stream) { 11651 this.afterTransform = function (er, data) {
12624 this.afterTransform = function(er, data) {
12625 return afterTransform(stream, er, data); 11652 return afterTransform(stream, er, data);
12626 }; 11653 };
12627 11654
@@ -12629,6 +11656,7 @@ function TransformState(options, stream) {
12629 this.transforming = false; 11656 this.transforming = false;
12630 this.writecb = null; 11657 this.writecb = null;
12631 this.writechunk = null; 11658 this.writechunk = null;
11659 this.writeencoding = null;
12632} 11660}
12633 11661
12634function afterTransform(stream, er, data) { 11662function afterTransform(stream, er, data) {
@@ -12637,17 +11665,16 @@ function afterTransform(stream, er, data) {
12637 11665
12638 var cb = ts.writecb; 11666 var cb = ts.writecb;
12639 11667
12640 if (!cb) 11668 if (!cb) {
12641 return stream.emit('error', new Error('no writecb in Transform class')); 11669 return stream.emit('error', new Error('write callback called multiple times'));
11670 }
12642 11671
12643 ts.writechunk = null; 11672 ts.writechunk = null;
12644 ts.writecb = null; 11673 ts.writecb = null;
12645 11674
12646 if (!util.isNullOrUndefined(data)) 11675 if (data !== null && data !== undefined) stream.push(data);
12647 stream.push(data);
12648 11676
12649 if (cb) 11677 cb(er);
12650 cb(er);
12651 11678
12652 var rs = stream._readableState; 11679 var rs = stream._readableState;
12653 rs.reading = false; 11680 rs.reading = false;
@@ -12656,16 +11683,13 @@ function afterTransform(stream, er, data) {
12656 } 11683 }
12657} 11684}
12658 11685
12659
12660function Transform(options) { 11686function Transform(options) {
12661 if (!(this instanceof Transform)) 11687 if (!(this instanceof Transform)) return new Transform(options);
12662 return new Transform(options);
12663 11688
12664 Duplex.call(this, options); 11689 Duplex.call(this, options);
12665 11690
12666 this._transformState = new TransformState(options, this); 11691 this._transformState = new TransformState(this);
12667 11692
12668 // when the writable side finishes, then flush out anything remaining.
12669 var stream = this; 11693 var stream = this;
12670 11694
12671 // start out asking for a readable event once data is transformed. 11695 // start out asking for a readable event once data is transformed.
@@ -12676,17 +11700,21 @@ function Transform(options) {
12676 // sync guard flag. 11700 // sync guard flag.
12677 this._readableState.sync = false; 11701 this._readableState.sync = false;
12678 11702
12679 this.once('prefinish', function() { 11703 if (options) {
12680 if (util.isFunction(this._flush)) 11704 if (typeof options.transform === 'function') this._transform = options.transform;
12681 this._flush(function(er) { 11705
12682 done(stream, er); 11706 if (typeof options.flush === 'function') this._flush = options.flush;
12683 }); 11707 }
12684 else 11708
12685 done(stream); 11709 // When the writable side finishes, then flush out anything remaining.
11710 this.once('prefinish', function () {
11711 if (typeof this._flush === 'function') this._flush(function (er, data) {
11712 done(stream, er, data);
11713 });else done(stream);
12686 }); 11714 });
12687} 11715}
12688 11716
12689Transform.prototype.push = function(chunk, encoding) { 11717Transform.prototype.push = function (chunk, encoding) {
12690 this._transformState.needTransform = false; 11718 this._transformState.needTransform = false;
12691 return Duplex.prototype.push.call(this, chunk, encoding); 11719 return Duplex.prototype.push.call(this, chunk, encoding);
12692}; 11720};
@@ -12701,31 +11729,28 @@ Transform.prototype.push = function(chunk, encoding) {
12701// Call `cb(err)` when you are done with this chunk. If you pass 11729// Call `cb(err)` when you are done with this chunk. If you pass
12702// an error, then that'll put the hurt on the whole operation. If you 11730// an error, then that'll put the hurt on the whole operation. If you
12703// never call cb(), then you'll never get another chunk. 11731// never call cb(), then you'll never get another chunk.
12704Transform.prototype._transform = function(chunk, encoding, cb) { 11732Transform.prototype._transform = function (chunk, encoding, cb) {
12705 throw new Error('not implemented'); 11733 throw new Error('_transform() is not implemented');
12706}; 11734};
12707 11735
12708Transform.prototype._write = function(chunk, encoding, cb) { 11736Transform.prototype._write = function (chunk, encoding, cb) {
12709 var ts = this._transformState; 11737 var ts = this._transformState;
12710 ts.writecb = cb; 11738 ts.writecb = cb;
12711 ts.writechunk = chunk; 11739 ts.writechunk = chunk;
12712 ts.writeencoding = encoding; 11740 ts.writeencoding = encoding;
12713 if (!ts.transforming) { 11741 if (!ts.transforming) {
12714 var rs = this._readableState; 11742 var rs = this._readableState;
12715 if (ts.needTransform || 11743 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
12716 rs.needReadable ||
12717 rs.length < rs.highWaterMark)
12718 this._read(rs.highWaterMark);
12719 } 11744 }
12720}; 11745};
12721 11746
12722// Doesn't matter what the args are here. 11747// Doesn't matter what the args are here.
12723// _transform does all the work. 11748// _transform does all the work.
12724// That we got here means that the readable side wants more data. 11749// That we got here means that the readable side wants more data.
12725Transform.prototype._read = function(n) { 11750Transform.prototype._read = function (n) {
12726 var ts = this._transformState; 11751 var ts = this._transformState;
12727 11752
12728 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { 11753 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
12729 ts.transforming = true; 11754 ts.transforming = true;
12730 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); 11755 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12731 } else { 11756 } else {
@@ -12735,27 +11760,33 @@ Transform.prototype._read = function(n) {
12735 } 11760 }
12736}; 11761};
12737 11762
11763Transform.prototype._destroy = function (err, cb) {
11764 var _this = this;
11765
11766 Duplex.prototype._destroy.call(this, err, function (err2) {
11767 cb(err2);
11768 _this.emit('close');
11769 });
11770};
11771
11772function done(stream, er, data) {
11773 if (er) return stream.emit('error', er);
12738 11774
12739function done(stream, er) { 11775 if (data !== null && data !== undefined) stream.push(data);
12740 if (er)
12741 return stream.emit('error', er);
12742 11776
12743 // if there's nothing in the write buffer, then that means 11777 // if there's nothing in the write buffer, then that means
12744 // that nothing more will ever be provided 11778 // that nothing more will ever be provided
12745 var ws = stream._writableState; 11779 var ws = stream._writableState;
12746 var ts = stream._transformState; 11780 var ts = stream._transformState;
12747 11781
12748 if (ws.length) 11782 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
12749 throw new Error('calling transform done when ws.length != 0');
12750 11783
12751 if (ts.transforming) 11784 if (ts.transforming) throw new Error('Calling transform done when still transforming');
12752 throw new Error('calling transform done when still transforming');
12753 11785
12754 return stream.push(null); 11786 return stream.push(null);
12755} 11787}
12756 11788},{"./_stream_duplex":14,"core-util-is":5,"inherits":8}],18:[function(require,module,exports){
12757},{"./_stream_duplex":16,"core-util-is":21,"inherits":12}],20:[function(require,module,exports){ 11789(function (process,global){
12758(function (process){
12759// Copyright Joyent, Inc. and other Node contributors. 11790// Copyright Joyent, Inc. and other Node contributors.
12760// 11791//
12761// Permission is hereby granted, free of charge, to any person obtaining a 11792// Permission is hereby granted, free of charge, to any person obtaining a
@@ -12778,55 +11809,106 @@ function done(stream, er) {
12778// USE OR OTHER DEALINGS IN THE SOFTWARE. 11809// USE OR OTHER DEALINGS IN THE SOFTWARE.
12779 11810
12780// A bit simpler than readable streams. 11811// A bit simpler than readable streams.
12781// Implement an async ._write(chunk, cb), and it'll handle all 11812// Implement an async ._write(chunk, encoding, cb), and it'll handle all
12782// the drain event emission and buffering. 11813// the drain event emission and buffering.
12783 11814
11815'use strict';
11816
11817/*<replacement>*/
11818
11819var processNextTick = require('process-nextick-args');
11820/*</replacement>*/
11821
12784module.exports = Writable; 11822module.exports = Writable;
12785 11823
11824/* <replacement> */
11825function WriteReq(chunk, encoding, cb) {
11826 this.chunk = chunk;
11827 this.encoding = encoding;
11828 this.callback = cb;
11829 this.next = null;
11830}
11831
11832// It seems a linked list but it is not
11833// there will be only 2 of these for each stream
11834function CorkedRequest(state) {
11835 var _this = this;
11836
11837 this.next = null;
11838 this.entry = null;
11839 this.finish = function () {
11840 onCorkedFinish(_this, state);
11841 };
11842}
11843/* </replacement> */
11844
12786/*<replacement>*/ 11845/*<replacement>*/
12787var Buffer = require('buffer').Buffer; 11846var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
12788/*</replacement>*/ 11847/*</replacement>*/
12789 11848
12790Writable.WritableState = WritableState; 11849/*<replacement>*/
11850var Duplex;
11851/*</replacement>*/
12791 11852
11853Writable.WritableState = WritableState;
12792 11854
12793/*<replacement>*/ 11855/*<replacement>*/
12794var util = require('core-util-is'); 11856var util = require('core-util-is');
12795util.inherits = require('inherits'); 11857util.inherits = require('inherits');
12796/*</replacement>*/ 11858/*</replacement>*/
12797 11859
12798var Stream = require('stream'); 11860/*<replacement>*/
11861var internalUtil = {
11862 deprecate: require('util-deprecate')
11863};
11864/*</replacement>*/
12799 11865
12800util.inherits(Writable, Stream); 11866/*<replacement>*/
11867var Stream = require('./internal/streams/stream');
11868/*</replacement>*/
12801 11869
12802function WriteReq(chunk, encoding, cb) { 11870/*<replacement>*/
12803 this.chunk = chunk; 11871var Buffer = require('safe-buffer').Buffer;
12804 this.encoding = encoding; 11872var OurUint8Array = global.Uint8Array || function () {};
12805 this.callback = cb; 11873function _uint8ArrayToBuffer(chunk) {
11874 return Buffer.from(chunk);
11875}
11876function _isUint8Array(obj) {
11877 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
12806} 11878}
11879/*</replacement>*/
11880
11881var destroyImpl = require('./internal/streams/destroy');
11882
11883util.inherits(Writable, Stream);
11884
11885function nop() {}
12807 11886
12808function WritableState(options, stream) { 11887function WritableState(options, stream) {
12809 var Duplex = require('./_stream_duplex'); 11888 Duplex = Duplex || require('./_stream_duplex');
12810 11889
12811 options = options || {}; 11890 options = options || {};
12812 11891
12813 // the point at which write() starts returning false
12814 // Note: 0 is a valid value, means that we always return false if
12815 // the entire buffer is not flushed immediately on write()
12816 var hwm = options.highWaterMark;
12817 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
12818 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
12819
12820 // object stream flag to indicate whether or not this stream 11892 // object stream flag to indicate whether or not this stream
12821 // contains buffers or objects. 11893 // contains buffers or objects.
12822 this.objectMode = !!options.objectMode; 11894 this.objectMode = !!options.objectMode;
12823 11895
12824 if (stream instanceof Duplex) 11896 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
12825 this.objectMode = this.objectMode || !!options.writableObjectMode; 11897
11898 // the point at which write() starts returning false
11899 // Note: 0 is a valid value, means that we always return false if
11900 // the entire buffer is not flushed immediately on write()
11901 var hwm = options.highWaterMark;
11902 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
11903 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
12826 11904
12827 // cast to ints. 11905 // cast to ints.
12828 this.highWaterMark = ~~this.highWaterMark; 11906 this.highWaterMark = Math.floor(this.highWaterMark);
11907
11908 // if _final has been called
11909 this.finalCalled = false;
12829 11910
11911 // drain event flag.
12830 this.needDrain = false; 11912 this.needDrain = false;
12831 // at the start of calling end() 11913 // at the start of calling end()
12832 this.ending = false; 11914 this.ending = false;
@@ -12835,6 +11917,9 @@ function WritableState(options, stream) {
12835 // when 'finish' is emitted 11917 // when 'finish' is emitted
12836 this.finished = false; 11918 this.finished = false;
12837 11919
11920 // has it been destroyed
11921 this.destroyed = false;
11922
12838 // should we decode strings into buffers before passing to _write? 11923 // should we decode strings into buffers before passing to _write?
12839 // this is here so that some node-core streams can optimize string 11924 // this is here so that some node-core streams can optimize string
12840 // handling at a lower level. 11925 // handling at a lower level.
@@ -12869,7 +11954,7 @@ function WritableState(options, stream) {
12869 this.bufferProcessing = false; 11954 this.bufferProcessing = false;
12870 11955
12871 // the callback that's passed to _write(chunk,cb) 11956 // the callback that's passed to _write(chunk,cb)
12872 this.onwrite = function(er) { 11957 this.onwrite = function (er) {
12873 onwrite(stream, er); 11958 onwrite(stream, er);
12874 }; 11959 };
12875 11960
@@ -12879,7 +11964,8 @@ function WritableState(options, stream) {
12879 // the amount that is being written when _write is called. 11964 // the amount that is being written when _write is called.
12880 this.writelen = 0; 11965 this.writelen = 0;
12881 11966
12882 this.buffer = []; 11967 this.bufferedRequest = null;
11968 this.lastBufferedRequest = null;
12883 11969
12884 // number of pending user-supplied write callbacks 11970 // number of pending user-supplied write callbacks
12885 // this must be 0 before 'finish' can be emitted 11971 // this must be 0 before 'finish' can be emitted
@@ -12891,113 +11977,170 @@ function WritableState(options, stream) {
12891 11977
12892 // True if the error was already emitted and should not be thrown again 11978 // True if the error was already emitted and should not be thrown again
12893 this.errorEmitted = false; 11979 this.errorEmitted = false;
11980
11981 // count buffered requests
11982 this.bufferedRequestCount = 0;
11983
11984 // allocate the first CorkedRequest, there is always
11985 // one allocated and free to use, and we maintain at most two
11986 this.corkedRequestsFree = new CorkedRequest(this);
11987}
11988
11989WritableState.prototype.getBuffer = function getBuffer() {
11990 var current = this.bufferedRequest;
11991 var out = [];
11992 while (current) {
11993 out.push(current);
11994 current = current.next;
11995 }
11996 return out;
11997};
11998
11999(function () {
12000 try {
12001 Object.defineProperty(WritableState.prototype, 'buffer', {
12002 get: internalUtil.deprecate(function () {
12003 return this.getBuffer();
12004 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
12005 });
12006 } catch (_) {}
12007})();
12008
12009// Test _writableState for inheritance to account for Duplex streams,
12010// whose prototype chain only points to Readable.
12011var realHasInstance;
12012if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
12013 realHasInstance = Function.prototype[Symbol.hasInstance];
12014 Object.defineProperty(Writable, Symbol.hasInstance, {
12015 value: function (object) {
12016 if (realHasInstance.call(this, object)) return true;
12017
12018 return object && object._writableState instanceof WritableState;
12019 }
12020 });
12021} else {
12022 realHasInstance = function (object) {
12023 return object instanceof this;
12024 };
12894} 12025}
12895 12026
12896function Writable(options) { 12027function Writable(options) {
12897 var Duplex = require('./_stream_duplex'); 12028 Duplex = Duplex || require('./_stream_duplex');
12898 12029
12899 // Writable ctor is applied to Duplexes, though they're not 12030 // Writable ctor is applied to Duplexes, too.
12900 // instanceof Writable, they're instanceof Readable. 12031 // `realHasInstance` is necessary because using plain `instanceof`
12901 if (!(this instanceof Writable) && !(this instanceof Duplex)) 12032 // would return false, as no `_writableState` property is attached.
12033
12034 // Trying to use the custom `instanceof` for Writable here will also break the
12035 // Node.js LazyTransform implementation, which has a non-trivial getter for
12036 // `_writableState` that would lead to infinite recursion.
12037 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
12902 return new Writable(options); 12038 return new Writable(options);
12039 }
12903 12040
12904 this._writableState = new WritableState(options, this); 12041 this._writableState = new WritableState(options, this);
12905 12042
12906 // legacy. 12043 // legacy.
12907 this.writable = true; 12044 this.writable = true;
12908 12045
12046 if (options) {
12047 if (typeof options.write === 'function') this._write = options.write;
12048
12049 if (typeof options.writev === 'function') this._writev = options.writev;
12050
12051 if (typeof options.destroy === 'function') this._destroy = options.destroy;
12052
12053 if (typeof options.final === 'function') this._final = options.final;
12054 }
12055
12909 Stream.call(this); 12056 Stream.call(this);
12910} 12057}
12911 12058
12912// Otherwise people can pipe Writable streams, which is just wrong. 12059// Otherwise people can pipe Writable streams, which is just wrong.
12913Writable.prototype.pipe = function() { 12060Writable.prototype.pipe = function () {
12914 this.emit('error', new Error('Cannot pipe. Not readable.')); 12061 this.emit('error', new Error('Cannot pipe, not readable'));
12915}; 12062};
12916 12063
12917 12064function writeAfterEnd(stream, cb) {
12918function writeAfterEnd(stream, state, cb) {
12919 var er = new Error('write after end'); 12065 var er = new Error('write after end');
12920 // TODO: defer error events consistently everywhere, not just the cb 12066 // TODO: defer error events consistently everywhere, not just the cb
12921 stream.emit('error', er); 12067 stream.emit('error', er);
12922 process.nextTick(function() { 12068 processNextTick(cb, er);
12923 cb(er);
12924 });
12925} 12069}
12926 12070
12927// If we get something that is not a buffer, string, null, or undefined, 12071// Checks that a user-supplied chunk is valid, especially for the particular
12928// and we're not in objectMode, then that's an error. 12072// mode the stream is in. Currently this means that `null` is never accepted
12929// Otherwise stream chunks are all considered to be of length=1, and the 12073// and undefined/non-string values are only allowed in object mode.
12930// watermarks determine how many objects to keep in the buffer, rather than
12931// how many bytes or characters.
12932function validChunk(stream, state, chunk, cb) { 12074function validChunk(stream, state, chunk, cb) {
12933 var valid = true; 12075 var valid = true;
12934 if (!util.isBuffer(chunk) && 12076 var er = false;
12935 !util.isString(chunk) && 12077
12936 !util.isNullOrUndefined(chunk) && 12078 if (chunk === null) {
12937 !state.objectMode) { 12079 er = new TypeError('May not write null values to stream');
12938 var er = new TypeError('Invalid non-string/buffer chunk'); 12080 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
12081 er = new TypeError('Invalid non-string/buffer chunk');
12082 }
12083 if (er) {
12939 stream.emit('error', er); 12084 stream.emit('error', er);
12940 process.nextTick(function() { 12085 processNextTick(cb, er);
12941 cb(er);
12942 });
12943 valid = false; 12086 valid = false;
12944 } 12087 }
12945 return valid; 12088 return valid;
12946} 12089}
12947 12090
12948Writable.prototype.write = function(chunk, encoding, cb) { 12091Writable.prototype.write = function (chunk, encoding, cb) {
12949 var state = this._writableState; 12092 var state = this._writableState;
12950 var ret = false; 12093 var ret = false;
12094 var isBuf = _isUint8Array(chunk) && !state.objectMode;
12095
12096 if (isBuf && !Buffer.isBuffer(chunk)) {
12097 chunk = _uint8ArrayToBuffer(chunk);
12098 }
12951 12099
12952 if (util.isFunction(encoding)) { 12100 if (typeof encoding === 'function') {
12953 cb = encoding; 12101 cb = encoding;
12954 encoding = null; 12102 encoding = null;
12955 } 12103 }
12956 12104
12957 if (util.isBuffer(chunk)) 12105 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
12958 encoding = 'buffer';
12959 else if (!encoding)
12960 encoding = state.defaultEncoding;
12961 12106
12962 if (!util.isFunction(cb)) 12107 if (typeof cb !== 'function') cb = nop;
12963 cb = function() {};
12964 12108
12965 if (state.ended) 12109 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
12966 writeAfterEnd(this, state, cb);
12967 else if (validChunk(this, state, chunk, cb)) {
12968 state.pendingcb++; 12110 state.pendingcb++;
12969 ret = writeOrBuffer(this, state, chunk, encoding, cb); 12111 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
12970 } 12112 }
12971 12113
12972 return ret; 12114 return ret;
12973}; 12115};
12974 12116
12975Writable.prototype.cork = function() { 12117Writable.prototype.cork = function () {
12976 var state = this._writableState; 12118 var state = this._writableState;
12977 12119
12978 state.corked++; 12120 state.corked++;
12979}; 12121};
12980 12122
12981Writable.prototype.uncork = function() { 12123Writable.prototype.uncork = function () {
12982 var state = this._writableState; 12124 var state = this._writableState;
12983 12125
12984 if (state.corked) { 12126 if (state.corked) {
12985 state.corked--; 12127 state.corked--;
12986 12128
12987 if (!state.writing && 12129 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
12988 !state.corked &&
12989 !state.finished &&
12990 !state.bufferProcessing &&
12991 state.buffer.length)
12992 clearBuffer(this, state);
12993 } 12130 }
12994}; 12131};
12995 12132
12133Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
12134 // node::ParseEncoding() requires lower case.
12135 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
12136 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
12137 this._writableState.defaultEncoding = encoding;
12138 return this;
12139};
12140
12996function decodeChunk(state, chunk, encoding) { 12141function decodeChunk(state, chunk, encoding) {
12997 if (!state.objectMode && 12142 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
12998 state.decodeStrings !== false && 12143 chunk = Buffer.from(chunk, encoding);
12999 util.isString(chunk)) {
13000 chunk = new Buffer(chunk, encoding);
13001 } 12144 }
13002 return chunk; 12145 return chunk;
13003} 12146}
@@ -13005,23 +12148,41 @@ function decodeChunk(state, chunk, encoding) {
13005// if we're already writing something, then just put this 12148// if we're already writing something, then just put this
13006// in the queue, and wait our turn. Otherwise, call _write 12149// in the queue, and wait our turn. Otherwise, call _write
13007// If we return false, then we need a drain event, so set that flag. 12150// If we return false, then we need a drain event, so set that flag.
13008function writeOrBuffer(stream, state, chunk, encoding, cb) { 12151function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
13009 chunk = decodeChunk(state, chunk, encoding); 12152 if (!isBuf) {
13010 if (util.isBuffer(chunk)) 12153 var newChunk = decodeChunk(state, chunk, encoding);
13011 encoding = 'buffer'; 12154 if (chunk !== newChunk) {
12155 isBuf = true;
12156 encoding = 'buffer';
12157 chunk = newChunk;
12158 }
12159 }
13012 var len = state.objectMode ? 1 : chunk.length; 12160 var len = state.objectMode ? 1 : chunk.length;
13013 12161
13014 state.length += len; 12162 state.length += len;
13015 12163
13016 var ret = state.length < state.highWaterMark; 12164 var ret = state.length < state.highWaterMark;
13017 // we must ensure that previous needDrain will not be reset to false. 12165 // we must ensure that previous needDrain will not be reset to false.
13018 if (!ret) 12166 if (!ret) state.needDrain = true;
13019 state.needDrain = true;
13020 12167
13021 if (state.writing || state.corked) 12168 if (state.writing || state.corked) {
13022 state.buffer.push(new WriteReq(chunk, encoding, cb)); 12169 var last = state.lastBufferedRequest;
13023 else 12170 state.lastBufferedRequest = {
12171 chunk: chunk,
12172 encoding: encoding,
12173 isBuf: isBuf,
12174 callback: cb,
12175 next: null
12176 };
12177 if (last) {
12178 last.next = state.lastBufferedRequest;
12179 } else {
12180 state.bufferedRequest = state.lastBufferedRequest;
12181 }
12182 state.bufferedRequestCount += 1;
12183 } else {
13024 doWrite(stream, state, false, len, chunk, encoding, cb); 12184 doWrite(stream, state, false, len, chunk, encoding, cb);
12185 }
13025 12186
13026 return ret; 12187 return ret;
13027} 12188}
@@ -13031,26 +12192,32 @@ function doWrite(stream, state, writev, len, chunk, encoding, cb) {
13031 state.writecb = cb; 12192 state.writecb = cb;
13032 state.writing = true; 12193 state.writing = true;
13033 state.sync = true; 12194 state.sync = true;
13034 if (writev) 12195 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
13035 stream._writev(chunk, state.onwrite);
13036 else
13037 stream._write(chunk, encoding, state.onwrite);
13038 state.sync = false; 12196 state.sync = false;
13039} 12197}
13040 12198
13041function onwriteError(stream, state, sync, er, cb) { 12199function onwriteError(stream, state, sync, er, cb) {
13042 if (sync) 12200 --state.pendingcb;
13043 process.nextTick(function() { 12201
13044 state.pendingcb--; 12202 if (sync) {
13045 cb(er); 12203 // defer the callback if we are being called synchronously
13046 }); 12204 // to avoid piling up things on the stack
13047 else { 12205 processNextTick(cb, er);
13048 state.pendingcb--; 12206 // this can emit finish, and it will always happen
12207 // after error
12208 processNextTick(finishMaybe, stream, state);
12209 stream._writableState.errorEmitted = true;
12210 stream.emit('error', er);
12211 } else {
12212 // the caller expect this to happen before if
12213 // it is async
13049 cb(er); 12214 cb(er);
12215 stream._writableState.errorEmitted = true;
12216 stream.emit('error', er);
12217 // this can emit finish, but finish must
12218 // always follow error
12219 finishMaybe(stream, state);
13050 } 12220 }
13051
13052 stream._writableState.errorEmitted = true;
13053 stream.emit('error', er);
13054} 12221}
13055 12222
13056function onwriteStateUpdate(state) { 12223function onwriteStateUpdate(state) {
@@ -13067,23 +12234,18 @@ function onwrite(stream, er) {
13067 12234
13068 onwriteStateUpdate(state); 12235 onwriteStateUpdate(state);
13069 12236
13070 if (er) 12237 if (er) onwriteError(stream, state, sync, er, cb);else {
13071 onwriteError(stream, state, sync, er, cb);
13072 else {
13073 // Check if we're actually ready to finish, but don't emit yet 12238 // Check if we're actually ready to finish, but don't emit yet
13074 var finished = needFinish(stream, state); 12239 var finished = needFinish(state);
13075 12240
13076 if (!finished && 12241 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
13077 !state.corked &&
13078 !state.bufferProcessing &&
13079 state.buffer.length) {
13080 clearBuffer(stream, state); 12242 clearBuffer(stream, state);
13081 } 12243 }
13082 12244
13083 if (sync) { 12245 if (sync) {
13084 process.nextTick(function() { 12246 /*<replacement>*/
13085 afterWrite(stream, state, finished, cb); 12247 asyncWrite(afterWrite, stream, state, finished, cb);
13086 }); 12248 /*</replacement>*/
13087 } else { 12249 } else {
13088 afterWrite(stream, state, finished, cb); 12250 afterWrite(stream, state, finished, cb);
13089 } 12251 }
@@ -13091,8 +12253,7 @@ function onwrite(stream, er) {
13091} 12253}
13092 12254
13093function afterWrite(stream, state, finished, cb) { 12255function afterWrite(stream, state, finished, cb) {
13094 if (!finished) 12256 if (!finished) onwriteDrain(stream, state);
13095 onwriteDrain(stream, state);
13096 state.pendingcb--; 12257 state.pendingcb--;
13097 cb(); 12258 cb();
13098 finishMaybe(stream, state); 12259 finishMaybe(stream, state);
@@ -13108,80 +12269,86 @@ function onwriteDrain(stream, state) {
13108 } 12269 }
13109} 12270}
13110 12271
13111
13112// if there's something in the buffer waiting, then process it 12272// if there's something in the buffer waiting, then process it
13113function clearBuffer(stream, state) { 12273function clearBuffer(stream, state) {
13114 state.bufferProcessing = true; 12274 state.bufferProcessing = true;
12275 var entry = state.bufferedRequest;
13115 12276
13116 if (stream._writev && state.buffer.length > 1) { 12277 if (stream._writev && entry && entry.next) {
13117 // Fast case, write everything using _writev() 12278 // Fast case, write everything using _writev()
13118 var cbs = []; 12279 var l = state.bufferedRequestCount;
13119 for (var c = 0; c < state.buffer.length; c++) 12280 var buffer = new Array(l);
13120 cbs.push(state.buffer[c].callback); 12281 var holder = state.corkedRequestsFree;
12282 holder.entry = entry;
13121 12283
13122 // count the one we are adding, as well. 12284 var count = 0;
13123 // TODO(isaacs) clean this up 12285 var allBuffers = true;
13124 state.pendingcb++; 12286 while (entry) {
13125 doWrite(stream, state, true, state.length, state.buffer, '', function(err) { 12287 buffer[count] = entry;
13126 for (var i = 0; i < cbs.length; i++) { 12288 if (!entry.isBuf) allBuffers = false;
13127 state.pendingcb--; 12289 entry = entry.next;
13128 cbs[i](err); 12290 count += 1;
13129 } 12291 }
13130 }); 12292 buffer.allBuffers = allBuffers;
13131 12293
13132 // Clear buffer 12294 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
13133 state.buffer = []; 12295
12296 // doWrite is almost always async, defer these to save a bit of time
12297 // as the hot path ends with doWrite
12298 state.pendingcb++;
12299 state.lastBufferedRequest = null;
12300 if (holder.next) {
12301 state.corkedRequestsFree = holder.next;
12302 holder.next = null;
12303 } else {
12304 state.corkedRequestsFree = new CorkedRequest(state);
12305 }
13134 } else { 12306 } else {
13135 // Slow case, write chunks one-by-one 12307 // Slow case, write chunks one-by-one
13136 for (var c = 0; c < state.buffer.length; c++) { 12308 while (entry) {
13137 var entry = state.buffer[c];
13138 var chunk = entry.chunk; 12309 var chunk = entry.chunk;
13139 var encoding = entry.encoding; 12310 var encoding = entry.encoding;
13140 var cb = entry.callback; 12311 var cb = entry.callback;
13141 var len = state.objectMode ? 1 : chunk.length; 12312 var len = state.objectMode ? 1 : chunk.length;
13142 12313
13143 doWrite(stream, state, false, len, chunk, encoding, cb); 12314 doWrite(stream, state, false, len, chunk, encoding, cb);
13144 12315 entry = entry.next;
13145 // if we didn't call the onwrite immediately, then 12316 // if we didn't call the onwrite immediately, then
13146 // it means that we need to wait until it does. 12317 // it means that we need to wait until it does.
13147 // also, that means that the chunk and cb are currently 12318 // also, that means that the chunk and cb are currently
13148 // being processed, so move the buffer counter past them. 12319 // being processed, so move the buffer counter past them.
13149 if (state.writing) { 12320 if (state.writing) {
13150 c++;
13151 break; 12321 break;
13152 } 12322 }
13153 } 12323 }
13154 12324
13155 if (c < state.buffer.length) 12325 if (entry === null) state.lastBufferedRequest = null;
13156 state.buffer = state.buffer.slice(c);
13157 else
13158 state.buffer.length = 0;
13159 } 12326 }
13160 12327
12328 state.bufferedRequestCount = 0;
12329 state.bufferedRequest = entry;
13161 state.bufferProcessing = false; 12330 state.bufferProcessing = false;
13162} 12331}
13163 12332
13164Writable.prototype._write = function(chunk, encoding, cb) { 12333Writable.prototype._write = function (chunk, encoding, cb) {
13165 cb(new Error('not implemented')); 12334 cb(new Error('_write() is not implemented'));
13166
13167}; 12335};
13168 12336
13169Writable.prototype._writev = null; 12337Writable.prototype._writev = null;
13170 12338
13171Writable.prototype.end = function(chunk, encoding, cb) { 12339Writable.prototype.end = function (chunk, encoding, cb) {
13172 var state = this._writableState; 12340 var state = this._writableState;
13173 12341
13174 if (util.isFunction(chunk)) { 12342 if (typeof chunk === 'function') {
13175 cb = chunk; 12343 cb = chunk;
13176 chunk = null; 12344 chunk = null;
13177 encoding = null; 12345 encoding = null;
13178 } else if (util.isFunction(encoding)) { 12346 } else if (typeof encoding === 'function') {
13179 cb = encoding; 12347 cb = encoding;
13180 encoding = null; 12348 encoding = null;
13181 } 12349 }
13182 12350
13183 if (!util.isNullOrUndefined(chunk)) 12351 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
13184 this.write(chunk, encoding);
13185 12352
13186 // .end() fully uncorks 12353 // .end() fully uncorks
13187 if (state.corked) { 12354 if (state.corked) {
@@ -13190,34 +12357,44 @@ Writable.prototype.end = function(chunk, encoding, cb) {
13190 } 12357 }
13191 12358
13192 // ignore unnecessary end() calls. 12359 // ignore unnecessary end() calls.
13193 if (!state.ending && !state.finished) 12360 if (!state.ending && !state.finished) endWritable(this, state, cb);
13194 endWritable(this, state, cb);
13195}; 12361};
13196 12362
13197 12363function needFinish(state) {
13198function needFinish(stream, state) { 12364 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
13199 return (state.ending &&
13200 state.length === 0 &&
13201 !state.finished &&
13202 !state.writing);
13203} 12365}
13204 12366function callFinal(stream, state) {
13205function prefinish(stream, state) { 12367 stream._final(function (err) {
13206 if (!state.prefinished) { 12368 state.pendingcb--;
12369 if (err) {
12370 stream.emit('error', err);
12371 }
13207 state.prefinished = true; 12372 state.prefinished = true;
13208 stream.emit('prefinish'); 12373 stream.emit('prefinish');
12374 finishMaybe(stream, state);
12375 });
12376}
12377function prefinish(stream, state) {
12378 if (!state.prefinished && !state.finalCalled) {
12379 if (typeof stream._final === 'function') {
12380 state.pendingcb++;
12381 state.finalCalled = true;
12382 processNextTick(callFinal, stream, state);
12383 } else {
12384 state.prefinished = true;
12385 stream.emit('prefinish');
12386 }
13209 } 12387 }
13210} 12388}
13211 12389
13212function finishMaybe(stream, state) { 12390function finishMaybe(stream, state) {
13213 var need = needFinish(stream, state); 12391 var need = needFinish(state);
13214 if (need) { 12392 if (need) {
12393 prefinish(stream, state);
13215 if (state.pendingcb === 0) { 12394 if (state.pendingcb === 0) {
13216 prefinish(stream, state);
13217 state.finished = true; 12395 state.finished = true;
13218 stream.emit('finish'); 12396 stream.emit('finish');
13219 } else 12397 }
13220 prefinish(stream, state);
13221 } 12398 }
13222 return need; 12399 return need;
13223} 12400}
@@ -13226,144 +12403,289 @@ function endWritable(stream, state, cb) {
13226 state.ending = true; 12403 state.ending = true;
13227 finishMaybe(stream, state); 12404 finishMaybe(stream, state);
13228 if (cb) { 12405 if (cb) {
13229 if (state.finished) 12406 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
13230 process.nextTick(cb);
13231 else
13232 stream.once('finish', cb);
13233 } 12407 }
13234 state.ended = true; 12408 state.ended = true;
12409 stream.writable = false;
13235} 12410}
13236 12411
13237}).call(this,require('_process')) 12412function onCorkedFinish(corkReq, state, err) {
13238},{"./_stream_duplex":16,"_process":14,"buffer":7,"core-util-is":21,"inherits":12,"stream":26}],21:[function(require,module,exports){ 12413 var entry = corkReq.entry;
13239(function (Buffer){ 12414 corkReq.entry = null;
13240// Copyright Joyent, Inc. and other Node contributors. 12415 while (entry) {
13241// 12416 var cb = entry.callback;
13242// Permission is hereby granted, free of charge, to any person obtaining a 12417 state.pendingcb--;
13243// copy of this software and associated documentation files (the 12418 cb(err);
13244// "Software"), to deal in the Software without restriction, including 12419 entry = entry.next;
13245// without limitation the rights to use, copy, modify, merge, publish, 12420 }
13246// distribute, sublicense, and/or sell copies of the Software, and to permit 12421 if (state.corkedRequestsFree) {
13247// persons to whom the Software is furnished to do so, subject to the 12422 state.corkedRequestsFree.next = corkReq;
13248// following conditions: 12423 } else {
13249// 12424 state.corkedRequestsFree = corkReq;
13250// The above copyright notice and this permission notice shall be included 12425 }
13251// in all copies or substantial portions of the Software.
13252//
13253// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13254// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13255// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13256// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13257// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13258// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13259// USE OR OTHER DEALINGS IN THE SOFTWARE.
13260
13261// NOTE: These type checking functions intentionally don't use `instanceof`
13262// because it is fragile and can be easily faked with `Object.create()`.
13263function isArray(ar) {
13264 return Array.isArray(ar);
13265} 12426}
13266exports.isArray = isArray;
13267 12427
13268function isBoolean(arg) { 12428Object.defineProperty(Writable.prototype, 'destroyed', {
13269 return typeof arg === 'boolean'; 12429 get: function () {
13270} 12430 if (this._writableState === undefined) {
13271exports.isBoolean = isBoolean; 12431 return false;
12432 }
12433 return this._writableState.destroyed;
12434 },
12435 set: function (value) {
12436 // we ignore the value if the stream
12437 // has not been initialized yet
12438 if (!this._writableState) {
12439 return;
12440 }
13272 12441
13273function isNull(arg) { 12442 // backward compatibility, the user is explicitly
13274 return arg === null; 12443 // managing destroyed
13275} 12444 this._writableState.destroyed = value;
13276exports.isNull = isNull; 12445 }
12446});
13277 12447
13278function isNullOrUndefined(arg) { 12448Writable.prototype.destroy = destroyImpl.destroy;
13279 return arg == null; 12449Writable.prototype._undestroy = destroyImpl.undestroy;
13280} 12450Writable.prototype._destroy = function (err, cb) {
13281exports.isNullOrUndefined = isNullOrUndefined; 12451 this.end();
12452 cb(err);
12453};
12454}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12455},{"./_stream_duplex":14,"./internal/streams/destroy":20,"./internal/streams/stream":21,"_process":12,"core-util-is":5,"inherits":8,"process-nextick-args":11,"safe-buffer":26,"util-deprecate":29}],19:[function(require,module,exports){
12456'use strict';
13282 12457
13283function isNumber(arg) { 12458/*<replacement>*/
13284 return typeof arg === 'number';
13285}
13286exports.isNumber = isNumber;
13287 12459
13288function isString(arg) { 12460function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13289 return typeof arg === 'string';
13290}
13291exports.isString = isString;
13292 12461
13293function isSymbol(arg) { 12462var Buffer = require('safe-buffer').Buffer;
13294 return typeof arg === 'symbol'; 12463/*</replacement>*/
13295}
13296exports.isSymbol = isSymbol;
13297 12464
13298function isUndefined(arg) { 12465function copyBuffer(src, target, offset) {
13299 return arg === void 0; 12466 src.copy(target, offset);
13300} 12467}
13301exports.isUndefined = isUndefined;
13302 12468
13303function isRegExp(re) { 12469module.exports = function () {
13304 return isObject(re) && objectToString(re) === '[object RegExp]'; 12470 function BufferList() {
13305} 12471 _classCallCheck(this, BufferList);
13306exports.isRegExp = isRegExp;
13307 12472
13308function isObject(arg) { 12473 this.head = null;
13309 return typeof arg === 'object' && arg !== null; 12474 this.tail = null;
13310} 12475 this.length = 0;
13311exports.isObject = isObject; 12476 }
13312 12477
13313function isDate(d) { 12478 BufferList.prototype.push = function push(v) {
13314 return isObject(d) && objectToString(d) === '[object Date]'; 12479 var entry = { data: v, next: null };
13315} 12480 if (this.length > 0) this.tail.next = entry;else this.head = entry;
13316exports.isDate = isDate; 12481 this.tail = entry;
12482 ++this.length;
12483 };
13317 12484
13318function isError(e) { 12485 BufferList.prototype.unshift = function unshift(v) {
13319 return isObject(e) && 12486 var entry = { data: v, next: this.head };
13320 (objectToString(e) === '[object Error]' || e instanceof Error); 12487 if (this.length === 0) this.tail = entry;
13321} 12488 this.head = entry;
13322exports.isError = isError; 12489 ++this.length;
12490 };
13323 12491
13324function isFunction(arg) { 12492 BufferList.prototype.shift = function shift() {
13325 return typeof arg === 'function'; 12493 if (this.length === 0) return;
13326} 12494 var ret = this.head.data;
13327exports.isFunction = isFunction; 12495 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
12496 --this.length;
12497 return ret;
12498 };
13328 12499
13329function isPrimitive(arg) { 12500 BufferList.prototype.clear = function clear() {
13330 return arg === null || 12501 this.head = this.tail = null;
13331 typeof arg === 'boolean' || 12502 this.length = 0;
13332 typeof arg === 'number' || 12503 };
13333 typeof arg === 'string' || 12504
13334 typeof arg === 'symbol' || // ES6 symbol 12505 BufferList.prototype.join = function join(s) {
13335 typeof arg === 'undefined'; 12506 if (this.length === 0) return '';
12507 var p = this.head;
12508 var ret = '' + p.data;
12509 while (p = p.next) {
12510 ret += s + p.data;
12511 }return ret;
12512 };
12513
12514 BufferList.prototype.concat = function concat(n) {
12515 if (this.length === 0) return Buffer.alloc(0);
12516 if (this.length === 1) return this.head.data;
12517 var ret = Buffer.allocUnsafe(n >>> 0);
12518 var p = this.head;
12519 var i = 0;
12520 while (p) {
12521 copyBuffer(p.data, ret, i);
12522 i += p.data.length;
12523 p = p.next;
12524 }
12525 return ret;
12526 };
12527
12528 return BufferList;
12529}();
12530},{"safe-buffer":26}],20:[function(require,module,exports){
12531'use strict';
12532
12533/*<replacement>*/
12534
12535var processNextTick = require('process-nextick-args');
12536/*</replacement>*/
12537
12538// undocumented cb() API, needed for core, not for public API
12539function destroy(err, cb) {
12540 var _this = this;
12541
12542 var readableDestroyed = this._readableState && this._readableState.destroyed;
12543 var writableDestroyed = this._writableState && this._writableState.destroyed;
12544
12545 if (readableDestroyed || writableDestroyed) {
12546 if (cb) {
12547 cb(err);
12548 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
12549 processNextTick(emitErrorNT, this, err);
12550 }
12551 return;
12552 }
12553
12554 // we set destroyed to true before firing error callbacks in order
12555 // to make it re-entrance safe in case destroy() is called within callbacks
12556
12557 if (this._readableState) {
12558 this._readableState.destroyed = true;
12559 }
12560
12561 // if this is a duplex stream mark the writable part as destroyed as well
12562 if (this._writableState) {
12563 this._writableState.destroyed = true;
12564 }
12565
12566 this._destroy(err || null, function (err) {
12567 if (!cb && err) {
12568 processNextTick(emitErrorNT, _this, err);
12569 if (_this._writableState) {
12570 _this._writableState.errorEmitted = true;
12571 }
12572 } else if (cb) {
12573 cb(err);
12574 }
12575 });
13336} 12576}
13337exports.isPrimitive = isPrimitive;
13338 12577
13339function isBuffer(arg) { 12578function undestroy() {
13340 return Buffer.isBuffer(arg); 12579 if (this._readableState) {
12580 this._readableState.destroyed = false;
12581 this._readableState.reading = false;
12582 this._readableState.ended = false;
12583 this._readableState.endEmitted = false;
12584 }
12585
12586 if (this._writableState) {
12587 this._writableState.destroyed = false;
12588 this._writableState.ended = false;
12589 this._writableState.ending = false;
12590 this._writableState.finished = false;
12591 this._writableState.errorEmitted = false;
12592 }
13341} 12593}
13342exports.isBuffer = isBuffer;
13343 12594
13344function objectToString(o) { 12595function emitErrorNT(self, err) {
13345 return Object.prototype.toString.call(o); 12596 self.emit('error', err);
13346} 12597}
13347}).call(this,require("buffer").Buffer)
13348},{"buffer":7}],22:[function(require,module,exports){
13349module.exports = require("./lib/_stream_passthrough.js")
13350 12598
13351},{"./lib/_stream_passthrough.js":17}],23:[function(require,module,exports){ 12599module.exports = {
12600 destroy: destroy,
12601 undestroy: undestroy
12602};
12603},{"process-nextick-args":11}],21:[function(require,module,exports){
12604module.exports = require('events').EventEmitter;
12605
12606},{"events":6}],22:[function(require,module,exports){
12607module.exports = require('./readable').PassThrough
12608
12609},{"./readable":23}],23:[function(require,module,exports){
13352exports = module.exports = require('./lib/_stream_readable.js'); 12610exports = module.exports = require('./lib/_stream_readable.js');
13353exports.Stream = require('stream'); 12611exports.Stream = exports;
13354exports.Readable = exports; 12612exports.Readable = exports;
13355exports.Writable = require('./lib/_stream_writable.js'); 12613exports.Writable = require('./lib/_stream_writable.js');
13356exports.Duplex = require('./lib/_stream_duplex.js'); 12614exports.Duplex = require('./lib/_stream_duplex.js');
13357exports.Transform = require('./lib/_stream_transform.js'); 12615exports.Transform = require('./lib/_stream_transform.js');
13358exports.PassThrough = require('./lib/_stream_passthrough.js'); 12616exports.PassThrough = require('./lib/_stream_passthrough.js');
13359 12617
13360},{"./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){ 12618},{"./lib/_stream_duplex.js":14,"./lib/_stream_passthrough.js":15,"./lib/_stream_readable.js":16,"./lib/_stream_transform.js":17,"./lib/_stream_writable.js":18}],24:[function(require,module,exports){
13361module.exports = require("./lib/_stream_transform.js") 12619module.exports = require('./readable').Transform
13362 12620
13363},{"./lib/_stream_transform.js":19}],25:[function(require,module,exports){ 12621},{"./readable":23}],25:[function(require,module,exports){
13364module.exports = require("./lib/_stream_writable.js") 12622module.exports = require('./lib/_stream_writable.js');
12623
12624},{"./lib/_stream_writable.js":18}],26:[function(require,module,exports){
12625/* eslint-disable node/no-deprecated-api */
12626var buffer = require('buffer')
12627var Buffer = buffer.Buffer
12628
12629// alternative to using Object.keys for old browsers
12630function copyProps (src, dst) {
12631 for (var key in src) {
12632 dst[key] = src[key]
12633 }
12634}
12635if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
12636 module.exports = buffer
12637} else {
12638 // Copy properties from require('buffer')
12639 copyProps(buffer, exports)
12640 exports.Buffer = SafeBuffer
12641}
12642
12643function SafeBuffer (arg, encodingOrOffset, length) {
12644 return Buffer(arg, encodingOrOffset, length)
12645}
13365 12646
13366},{"./lib/_stream_writable.js":20}],26:[function(require,module,exports){ 12647// Copy static methods from Buffer
12648copyProps(Buffer, SafeBuffer)
12649
12650SafeBuffer.from = function (arg, encodingOrOffset, length) {
12651 if (typeof arg === 'number') {
12652 throw new TypeError('Argument must not be a number')
12653 }
12654 return Buffer(arg, encodingOrOffset, length)
12655}
12656
12657SafeBuffer.alloc = function (size, fill, encoding) {
12658 if (typeof size !== 'number') {
12659 throw new TypeError('Argument must be a number')
12660 }
12661 var buf = Buffer(size)
12662 if (fill !== undefined) {
12663 if (typeof encoding === 'string') {
12664 buf.fill(fill, encoding)
12665 } else {
12666 buf.fill(fill)
12667 }
12668 } else {
12669 buf.fill(0)
12670 }
12671 return buf
12672}
12673
12674SafeBuffer.allocUnsafe = function (size) {
12675 if (typeof size !== 'number') {
12676 throw new TypeError('Argument must be a number')
12677 }
12678 return Buffer(size)
12679}
12680
12681SafeBuffer.allocUnsafeSlow = function (size) {
12682 if (typeof size !== 'number') {
12683 throw new TypeError('Argument must be a number')
12684 }
12685 return buffer.SlowBuffer(size)
12686}
12687
12688},{"buffer":4}],27:[function(require,module,exports){
13367// Copyright Joyent, Inc. and other Node contributors. 12689// Copyright Joyent, Inc. and other Node contributors.
13368// 12690//
13369// Permission is hereby granted, free of charge, to any person obtaining a 12691// Permission is hereby granted, free of charge, to any person obtaining a
@@ -13492,237 +12814,360 @@ Stream.prototype.pipe = function(dest, options) {
13492 return dest; 12814 return dest;
13493}; 12815};
13494 12816
13495},{"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){ 12817},{"events":6,"inherits":8,"readable-stream/duplex.js":13,"readable-stream/passthrough.js":22,"readable-stream/readable.js":23,"readable-stream/transform.js":24,"readable-stream/writable.js":25}],28:[function(require,module,exports){
13496// Copyright Joyent, Inc. and other Node contributors. 12818'use strict';
13497//
13498// Permission is hereby granted, free of charge, to any person obtaining a
13499// copy of this software and associated documentation files (the
13500// "Software"), to deal in the Software without restriction, including
13501// without limitation the rights to use, copy, modify, merge, publish,
13502// distribute, sublicense, and/or sell copies of the Software, and to permit
13503// persons to whom the Software is furnished to do so, subject to the
13504// following conditions:
13505//
13506// The above copyright notice and this permission notice shall be included
13507// in all copies or substantial portions of the Software.
13508//
13509// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13510// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13511// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13512// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13513// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13514// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13515// USE OR OTHER DEALINGS IN THE SOFTWARE.
13516
13517var Buffer = require('buffer').Buffer;
13518 12819
13519var isBufferEncoding = Buffer.isEncoding 12820var Buffer = require('safe-buffer').Buffer;
13520 || function(encoding) {
13521 switch (encoding && encoding.toLowerCase()) {
13522 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;
13523 default: return false;
13524 }
13525 }
13526 12821
12822var isEncoding = Buffer.isEncoding || function (encoding) {
12823 encoding = '' + encoding;
12824 switch (encoding && encoding.toLowerCase()) {
12825 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':
12826 return true;
12827 default:
12828 return false;
12829 }
12830};
13527 12831
13528function assertEncoding(encoding) { 12832function _normalizeEncoding(enc) {
13529 if (encoding && !isBufferEncoding(encoding)) { 12833 if (!enc) return 'utf8';
13530 throw new Error('Unknown encoding: ' + encoding); 12834 var retried;
12835 while (true) {
12836 switch (enc) {
12837 case 'utf8':
12838 case 'utf-8':
12839 return 'utf8';
12840 case 'ucs2':
12841 case 'ucs-2':
12842 case 'utf16le':
12843 case 'utf-16le':
12844 return 'utf16le';
12845 case 'latin1':
12846 case 'binary':
12847 return 'latin1';
12848 case 'base64':
12849 case 'ascii':
12850 case 'hex':
12851 return enc;
12852 default:
12853 if (retried) return; // undefined
12854 enc = ('' + enc).toLowerCase();
12855 retried = true;
12856 }
13531 } 12857 }
12858};
12859
12860// Do not cache `Buffer.isEncoding` when checking encoding names as some
12861// modules monkey-patch it to support additional encodings
12862function normalizeEncoding(enc) {
12863 var nenc = _normalizeEncoding(enc);
12864 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
12865 return nenc || enc;
13532} 12866}
13533 12867
13534// StringDecoder provides an interface for efficiently splitting a series of 12868// StringDecoder provides an interface for efficiently splitting a series of
13535// buffers into a series of JS strings without breaking apart multi-byte 12869// buffers into a series of JS strings without breaking apart multi-byte
13536// characters. CESU-8 is handled as part of the UTF-8 encoding. 12870// characters.
13537// 12871exports.StringDecoder = StringDecoder;
13538// @TODO Handling all encodings inside a single object makes it very difficult 12872function StringDecoder(encoding) {
13539// to reason about this code, so it should be split up in the future. 12873 this.encoding = normalizeEncoding(encoding);
13540// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code 12874 var nb;
13541// points as used by CESU-8.
13542var StringDecoder = exports.StringDecoder = function(encoding) {
13543 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13544 assertEncoding(encoding);
13545 switch (this.encoding) { 12875 switch (this.encoding) {
13546 case 'utf8':
13547 // CESU-8 represents each of Surrogate Pair by 3-bytes
13548 this.surrogateSize = 3;
13549 break;
13550 case 'ucs2':
13551 case 'utf16le': 12876 case 'utf16le':
13552 // UTF-16 represents each of Surrogate Pair by 2-bytes 12877 this.text = utf16Text;
13553 this.surrogateSize = 2; 12878 this.end = utf16End;
13554 this.detectIncompleteChar = utf16DetectIncompleteChar; 12879 nb = 4;
12880 break;
12881 case 'utf8':
12882 this.fillLast = utf8FillLast;
12883 nb = 4;
13555 break; 12884 break;
13556 case 'base64': 12885 case 'base64':
13557 // Base-64 stores 3 bytes in 4 chars, and pads the remainder. 12886 this.text = base64Text;
13558 this.surrogateSize = 3; 12887 this.end = base64End;
13559 this.detectIncompleteChar = base64DetectIncompleteChar; 12888 nb = 3;
13560 break; 12889 break;
13561 default: 12890 default:
13562 this.write = passThroughWrite; 12891 this.write = simpleWrite;
12892 this.end = simpleEnd;
13563 return; 12893 return;
13564 } 12894 }
12895 this.lastNeed = 0;
12896 this.lastTotal = 0;
12897 this.lastChar = Buffer.allocUnsafe(nb);
12898}
13565 12899
13566 // Enough space to store all bytes of a single character. UTF-8 needs 4 12900StringDecoder.prototype.write = function (buf) {
13567 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). 12901 if (buf.length === 0) return '';
13568 this.charBuffer = new Buffer(6); 12902 var r;
13569 // Number of bytes received for the current incomplete multi-byte character. 12903 var i;
13570 this.charReceived = 0; 12904 if (this.lastNeed) {
13571 // Number of bytes expected for the current incomplete multi-byte character. 12905 r = this.fillLast(buf);
13572 this.charLength = 0; 12906 if (r === undefined) return '';
12907 i = this.lastNeed;
12908 this.lastNeed = 0;
12909 } else {
12910 i = 0;
12911 }
12912 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
12913 return r || '';
13573}; 12914};
13574 12915
12916StringDecoder.prototype.end = utf8End;
13575 12917
13576// write decodes the given buffer and returns it as JS string that is 12918// Returns only complete characters in a Buffer
13577// guaranteed to not contain any partial multi-byte characters. Any partial 12919StringDecoder.prototype.text = utf8Text;
13578// character found at the end of the buffer is buffered up, and will be
13579// returned when calling write again with the remaining bytes.
13580//
13581// Note: Converting a Buffer containing an orphan surrogate to a String
13582// currently works, but converting a String to a Buffer (via `new Buffer`, or
13583// Buffer#write) will replace incomplete surrogates with the unicode
13584// replacement character. See https://codereview.chromium.org/121173009/ .
13585StringDecoder.prototype.write = function(buffer) {
13586 var charStr = '';
13587 // if our last write ended with an incomplete multibyte character
13588 while (this.charLength) {
13589 // determine how many remaining bytes this buffer has to offer for this char
13590 var available = (buffer.length >= this.charLength - this.charReceived) ?
13591 this.charLength - this.charReceived :
13592 buffer.length;
13593
13594 // add the new bytes to the char buffer
13595 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13596 this.charReceived += available;
13597
13598 if (this.charReceived < this.charLength) {
13599 // still not enough chars in this buffer? wait for more ...
13600 return '';
13601 }
13602 12920
13603 // remove bytes belonging to the current character from the buffer 12921// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
13604 buffer = buffer.slice(available, buffer.length); 12922StringDecoder.prototype.fillLast = function (buf) {
12923 if (this.lastNeed <= buf.length) {
12924 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
12925 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
12926 }
12927 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
12928 this.lastNeed -= buf.length;
12929};
13605 12930
13606 // get the character that was split 12931// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
13607 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); 12932// continuation byte.
12933function utf8CheckByte(byte) {
12934 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
12935 return -1;
12936}
13608 12937
13609 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character 12938// Checks at most 3 bytes at the end of a Buffer in order to detect an
13610 var charCode = charStr.charCodeAt(charStr.length - 1); 12939// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
13611 if (charCode >= 0xD800 && charCode <= 0xDBFF) { 12940// needed to complete the UTF-8 character (if applicable) are returned.
13612 this.charLength += this.surrogateSize; 12941function utf8CheckIncomplete(self, buf, i) {
13613 charStr = ''; 12942 var j = buf.length - 1;
13614 continue; 12943 if (j < i) return 0;
12944 var nb = utf8CheckByte(buf[j]);
12945 if (nb >= 0) {
12946 if (nb > 0) self.lastNeed = nb - 1;
12947 return nb;
12948 }
12949 if (--j < i) return 0;
12950 nb = utf8CheckByte(buf[j]);
12951 if (nb >= 0) {
12952 if (nb > 0) self.lastNeed = nb - 2;
12953 return nb;
12954 }
12955 if (--j < i) return 0;
12956 nb = utf8CheckByte(buf[j]);
12957 if (nb >= 0) {
12958 if (nb > 0) {
12959 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
13615 } 12960 }
13616 this.charReceived = this.charLength = 0; 12961 return nb;
12962 }
12963 return 0;
12964}
13617 12965
13618 // if there are no more bytes in this buffer, just emit our char 12966// Validates as many continuation bytes for a multi-byte UTF-8 character as
13619 if (buffer.length === 0) { 12967// needed or are available. If we see a non-continuation byte where we expect
13620 return charStr; 12968// one, we "replace" the validated continuation bytes we've seen so far with
12969// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
12970// behavior. The continuation byte check is included three times in the case
12971// where all of the continuation bytes for a character exist in the same buffer.
12972// It is also done this way as a slight performance increase instead of using a
12973// loop.
12974function utf8CheckExtraBytes(self, buf, p) {
12975 if ((buf[0] & 0xC0) !== 0x80) {
12976 self.lastNeed = 0;
12977 return '\ufffd'.repeat(p);
12978 }
12979 if (self.lastNeed > 1 && buf.length > 1) {
12980 if ((buf[1] & 0xC0) !== 0x80) {
12981 self.lastNeed = 1;
12982 return '\ufffd'.repeat(p + 1);
12983 }
12984 if (self.lastNeed > 2 && buf.length > 2) {
12985 if ((buf[2] & 0xC0) !== 0x80) {
12986 self.lastNeed = 2;
12987 return '\ufffd'.repeat(p + 2);
12988 }
13621 } 12989 }
13622 break;
13623 } 12990 }
12991}
13624 12992
13625 // determine and set charLength / charReceived 12993// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
13626 this.detectIncompleteChar(buffer); 12994function utf8FillLast(buf) {
13627 12995 var p = this.lastTotal - this.lastNeed;
13628 var end = buffer.length; 12996 var r = utf8CheckExtraBytes(this, buf, p);
13629 if (this.charLength) { 12997 if (r !== undefined) return r;
13630 // buffer the incomplete character bytes we got 12998 if (this.lastNeed <= buf.length) {
13631 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); 12999 buf.copy(this.lastChar, p, 0, this.lastNeed);
13632 end -= this.charReceived; 13000 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
13633 } 13001 }
13002 buf.copy(this.lastChar, p, 0, buf.length);
13003 this.lastNeed -= buf.length;
13004}
13634 13005
13635 charStr += buffer.toString(this.encoding, 0, end); 13006// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
13007// partial character, the character's bytes are buffered until the required
13008// number of bytes are available.
13009function utf8Text(buf, i) {
13010 var total = utf8CheckIncomplete(this, buf, i);
13011 if (!this.lastNeed) return buf.toString('utf8', i);
13012 this.lastTotal = total;
13013 var end = buf.length - (total - this.lastNeed);
13014 buf.copy(this.lastChar, 0, end);
13015 return buf.toString('utf8', i, end);
13016}
13636 13017
13637 var end = charStr.length - 1; 13018// For UTF-8, a replacement character for each buffered byte of a (partial)
13638 var charCode = charStr.charCodeAt(end); 13019// character needs to be added to the output.
13639 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character 13020function utf8End(buf) {
13640 if (charCode >= 0xD800 && charCode <= 0xDBFF) { 13021 var r = buf && buf.length ? this.write(buf) : '';
13641 var size = this.surrogateSize; 13022 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
13642 this.charLength += size; 13023 return r;
13643 this.charReceived += size; 13024}
13644 this.charBuffer.copy(this.charBuffer, size, 0, size); 13025
13645 buffer.copy(this.charBuffer, 0, 0, size); 13026// UTF-16LE typically needs two bytes per character, but even if we have an even
13646 return charStr.substring(0, end); 13027// number of bytes available, we need to check if we end on a leading/high
13028// surrogate. In that case, we need to wait for the next two bytes in order to
13029// decode the last character properly.
13030function utf16Text(buf, i) {
13031 if ((buf.length - i) % 2 === 0) {
13032 var r = buf.toString('utf16le', i);
13033 if (r) {
13034 var c = r.charCodeAt(r.length - 1);
13035 if (c >= 0xD800 && c <= 0xDBFF) {
13036 this.lastNeed = 2;
13037 this.lastTotal = 4;
13038 this.lastChar[0] = buf[buf.length - 2];
13039 this.lastChar[1] = buf[buf.length - 1];
13040 return r.slice(0, -1);
13041 }
13042 }
13043 return r;
13647 } 13044 }
13045 this.lastNeed = 1;
13046 this.lastTotal = 2;
13047 this.lastChar[0] = buf[buf.length - 1];
13048 return buf.toString('utf16le', i, buf.length - 1);
13049}
13648 13050
13649 // or just emit the charStr 13051// For UTF-16LE we do not explicitly append special replacement characters if we
13650 return charStr; 13052// end on a partial character, we simply let v8 handle that.
13651}; 13053function utf16End(buf) {
13054 var r = buf && buf.length ? this.write(buf) : '';
13055 if (this.lastNeed) {
13056 var end = this.lastTotal - this.lastNeed;
13057 return r + this.lastChar.toString('utf16le', 0, end);
13058 }
13059 return r;
13060}
13652 13061
13653// detectIncompleteChar determines if there is an incomplete UTF-8 character at 13062function base64Text(buf, i) {
13654// the end of the given buffer. If so, it sets this.charLength to the byte 13063 var n = (buf.length - i) % 3;
13655// length that character, and sets this.charReceived to the number of bytes 13064 if (n === 0) return buf.toString('base64', i);
13656// that are available for this character. 13065 this.lastNeed = 3 - n;
13657StringDecoder.prototype.detectIncompleteChar = function(buffer) { 13066 this.lastTotal = 3;
13658 // determine how many bytes we have to check at the end of this buffer 13067 if (n === 1) {
13659 var i = (buffer.length >= 3) ? 3 : buffer.length; 13068 this.lastChar[0] = buf[buf.length - 1];
13069 } else {
13070 this.lastChar[0] = buf[buf.length - 2];
13071 this.lastChar[1] = buf[buf.length - 1];
13072 }
13073 return buf.toString('base64', i, buf.length - n);
13074}
13660 13075
13661 // Figure out if one of the last i bytes of our buffer announces an 13076function base64End(buf) {
13662 // incomplete char. 13077 var r = buf && buf.length ? this.write(buf) : '';
13663 for (; i > 0; i--) { 13078 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
13664 var c = buffer[buffer.length - i]; 13079 return r;
13080}
13665 13081
13666 // See http://en.wikipedia.org/wiki/UTF-8#Description 13082// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
13083function simpleWrite(buf) {
13084 return buf.toString(this.encoding);
13085}
13667 13086
13668 // 110XXXXX 13087function simpleEnd(buf) {
13669 if (i == 1 && c >> 5 == 0x06) { 13088 return buf && buf.length ? this.write(buf) : '';
13670 this.charLength = 2; 13089}
13671 break; 13090},{"safe-buffer":26}],29:[function(require,module,exports){
13672 } 13091(function (global){
13673 13092
13674 // 1110XXXX 13093/**
13675 if (i <= 2 && c >> 4 == 0x0E) { 13094 * Module exports.
13676 this.charLength = 3; 13095 */
13677 break;
13678 }
13679 13096
13680 // 11110XXX 13097module.exports = deprecate;
13681 if (i <= 3 && c >> 3 == 0x1E) {
13682 this.charLength = 4;
13683 break;
13684 }
13685 }
13686 this.charReceived = i;
13687};
13688 13098
13689StringDecoder.prototype.end = function(buffer) { 13099/**
13690 var res = ''; 13100 * Mark that a method should not be used.
13691 if (buffer && buffer.length) 13101 * Returns a modified function which warns once by default.
13692 res = this.write(buffer); 13102 *
13103 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
13104 *
13105 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
13106 * will throw an Error when invoked.
13107 *
13108 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
13109 * will invoke `console.trace()` instead of `console.error()`.
13110 *
13111 * @param {Function} fn - the function to deprecate
13112 * @param {String} msg - the string to print to the console when `fn` is invoked
13113 * @returns {Function} a new "deprecated" version of `fn`
13114 * @api public
13115 */
13693 13116
13694 if (this.charReceived) { 13117function deprecate (fn, msg) {
13695 var cr = this.charReceived; 13118 if (config('noDeprecation')) {
13696 var buf = this.charBuffer; 13119 return fn;
13697 var enc = this.encoding;
13698 res += buf.slice(0, cr).toString(enc);
13699 } 13120 }
13700 13121
13701 return res; 13122 var warned = false;
13702}; 13123 function deprecated() {
13124 if (!warned) {
13125 if (config('throwDeprecation')) {
13126 throw new Error(msg);
13127 } else if (config('traceDeprecation')) {
13128 console.trace(msg);
13129 } else {
13130 console.warn(msg);
13131 }
13132 warned = true;
13133 }
13134 return fn.apply(this, arguments);
13135 }
13703 13136
13704function passThroughWrite(buffer) { 13137 return deprecated;
13705 return buffer.toString(this.encoding);
13706} 13138}
13707 13139
13708function utf16DetectIncompleteChar(buffer) { 13140/**
13709 this.charReceived = buffer.length % 2; 13141 * Checks `localStorage` for boolean values for the given `name`.
13710 this.charLength = this.charReceived ? 2 : 0; 13142 *
13711} 13143 * @param {String} name
13144 * @returns {Boolean}
13145 * @api private
13146 */
13712 13147
13713function base64DetectIncompleteChar(buffer) { 13148function config (name) {
13714 this.charReceived = buffer.length % 3; 13149 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
13715 this.charLength = this.charReceived ? 3 : 0; 13150 try {
13151 if (!global.localStorage) return false;
13152 } catch (_) {
13153 return false;
13154 }
13155 var val = global.localStorage[name];
13156 if (null == val) return false;
13157 return String(val).toLowerCase() === 'true';
13716} 13158}
13717 13159
13718},{"buffer":7}],28:[function(require,module,exports){ 13160}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13161},{}],30:[function(require,module,exports){
13162arguments[4][8][0].apply(exports,arguments)
13163},{"dup":8}],31:[function(require,module,exports){
13719module.exports = function isBuffer(arg) { 13164module.exports = function isBuffer(arg) {
13720 return arg && typeof arg === 'object' 13165 return arg && typeof arg === 'object'
13721 && typeof arg.copy === 'function' 13166 && typeof arg.copy === 'function'
13722 && typeof arg.fill === 'function' 13167 && typeof arg.fill === 'function'
13723 && typeof arg.readUInt8 === 'function'; 13168 && typeof arg.readUInt8 === 'function';
13724} 13169}
13725},{}],29:[function(require,module,exports){ 13170},{}],32:[function(require,module,exports){
13726(function (process,global){ 13171(function (process,global){
13727// Copyright Joyent, Inc. and other Node contributors. 13172// Copyright Joyent, Inc. and other Node contributors.
13728// 13173//
@@ -14312,2369 +13757,2167 @@ function hasOwnProperty(obj, prop) {
14312} 13757}
14313 13758
14314}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 13759}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
14315},{"./support/isBuffer":28,"_process":14,"inherits":12}],30:[function(require,module,exports){ 13760},{"./support/isBuffer":31,"_process":12,"inherits":30}],33:[function(require,module,exports){
14316// Base58 encoding/decoding 13761module.exports = {
13762 base58: require('bs58'),
13763 bitcoin: require('bitcoinjs-lib'),
13764 ecurve: require('ecurve'),
13765 BigInteger: require('bigi')
13766}
13767
13768},{"bigi":37,"bitcoinjs-lib":50,"bs58":79,"ecurve":89}],34:[function(require,module,exports){
13769// base-x encoding
13770// Forked from https://github.com/cryptocoinjs/bs58
14317// Originally written by Mike Hearn for BitcoinJ 13771// Originally written by Mike Hearn for BitcoinJ
14318// Copyright (c) 2011 Google Inc 13772// Copyright (c) 2011 Google Inc
14319// Ported to JavaScript by Stefan Thomas 13773// Ported to JavaScript by Stefan Thomas
14320// Merged Buffer refactorings from base58-native by Stephen Pair 13774// Merged Buffer refactorings from base58-native by Stephen Pair
14321// Copyright (c) 2013 BitPay Inc 13775// Copyright (c) 2013 BitPay Inc
14322 13776
14323var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' 13777var Buffer = require('safe-buffer').Buffer
14324var ALPHABET_MAP = {}
14325for(var i = 0; i < ALPHABET.length; i++) {
14326 ALPHABET_MAP[ALPHABET.charAt(i)] = i
14327}
14328var BASE = 58
14329
14330function encode(buffer) {
14331 if (buffer.length === 0) return ''
14332 13778
14333 var i, j, digits = [0] 13779module.exports = function base (ALPHABET) {
14334 for (i = 0; i < buffer.length; i++) { 13780 var ALPHABET_MAP = {}
14335 for (j = 0; j < digits.length; j++) digits[j] <<= 8 13781 var BASE = ALPHABET.length
13782 var LEADER = ALPHABET.charAt(0)
14336 13783
14337 digits[0] += buffer[i] 13784 // pre-compute lookup table
13785 for (var z = 0; z < ALPHABET.length; z++) {
13786 var x = ALPHABET.charAt(z)
14338 13787
14339 var carry = 0 13788 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
14340 for (j = 0; j < digits.length; ++j) { 13789 ALPHABET_MAP[x] = z
14341 digits[j] += carry 13790 }
14342 13791
14343 carry = (digits[j] / BASE) | 0 13792 function encode (source) {
14344 digits[j] %= BASE 13793 if (source.length === 0) return ''
14345 }
14346 13794
14347 while (carry) { 13795 var digits = [0]
14348 digits.push(carry % BASE) 13796 for (var i = 0; i < source.length; ++i) {
13797 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
13798 carry += digits[j] << 8
13799 digits[j] = carry % BASE
13800 carry = (carry / BASE) | 0
13801 }
14349 13802
14350 carry = (carry / BASE) | 0 13803 while (carry > 0) {
13804 digits.push(carry % BASE)
13805 carry = (carry / BASE) | 0
13806 }
14351 } 13807 }
14352 }
14353 13808
14354 // deal with leading zeros 13809 var string = ''
14355 for (i = 0; buffer[i] === 0 && i < buffer.length - 1; i++) digits.push(0)
14356 13810
14357 // convert digits to a string 13811 // deal with leading zeros
14358 var stringOutput = "" 13812 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += ALPHABET[0]
14359 for (var i = digits.length - 1; i >= 0; i--) { 13813 // convert digits to a string
14360 stringOutput = stringOutput + ALPHABET[digits[i]] 13814 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
14361 }
14362 return stringOutput
14363}
14364 13815
14365function decode(string) { 13816 return string
14366 if (string.length === 0) return [] 13817 }
14367 13818
14368 var i, j, bytes = [0] 13819 function decodeUnsafe (string) {
14369 for (i = 0; i < string.length; i++) { 13820 if (string.length === 0) return Buffer.allocUnsafe(0)
14370 var c = string[i]
14371 if (!(c in ALPHABET_MAP)) throw new Error('Non-base58 character')
14372 13821
14373 for (j = 0; j < bytes.length; j++) bytes[j] *= BASE 13822 var bytes = [0]
14374 bytes[0] += ALPHABET_MAP[c] 13823 for (var i = 0; i < string.length; i++) {
13824 var value = ALPHABET_MAP[string[i]]
13825 if (value === undefined) return
14375 13826
14376 var carry = 0 13827 for (var j = 0, carry = value; j < bytes.length; ++j) {
14377 for (j = 0; j < bytes.length; ++j) { 13828 carry += bytes[j] * BASE
14378 bytes[j] += carry 13829 bytes[j] = carry & 0xff
13830 carry >>= 8
13831 }
14379 13832
14380 carry = bytes[j] >> 8 13833 while (carry > 0) {
14381 bytes[j] &= 0xff 13834 bytes.push(carry & 0xff)
13835 carry >>= 8
13836 }
14382 } 13837 }
14383 13838
14384 while (carry) { 13839 // deal with leading zeros
14385 bytes.push(carry & 0xff) 13840 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
14386 13841 bytes.push(0)
14387 carry >>= 8
14388 } 13842 }
14389 }
14390
14391 // deal with leading zeros
14392 for (i = 0; string[i] === '1' && i < string.length - 1; i++) bytes.push(0)
14393
14394 return bytes.reverse()
14395}
14396
14397module.exports = {
14398 encode: encode,
14399 decode: decode
14400}
14401
14402},{}],31:[function(require,module,exports){
14403(function (Buffer){
14404'use strict'
14405 13843
14406var base58 = require('bs58') 13844 return Buffer.from(bytes.reverse())
14407var createHash = require('create-hash') 13845 }
14408 13846
14409// SHA256(SHA256(buffer)) 13847 function decode (string) {
14410function sha256x2 (buffer) { 13848 var buffer = decodeUnsafe(string)
14411 buffer = createHash('sha256').update(buffer).digest() 13849 if (buffer) return buffer
14412 return createHash('sha256').update(buffer).digest()
14413}
14414 13850
14415// Encode a buffer as a base58-check encoded string 13851 throw new Error('Non-base' + BASE + ' character')
14416function encode (payload) { 13852 }
14417 var checksum = sha256x2(payload).slice(0, 4)
14418 13853
14419 return base58.encode(Buffer.concat([ 13854 return {
14420 payload, 13855 encode: encode,
14421 checksum 13856 decodeUnsafe: decodeUnsafe,
14422 ])) 13857 decode: decode
13858 }
14423} 13859}
14424 13860
14425// Decode a base58-check encoded string to a buffer 13861},{"safe-buffer":98}],35:[function(require,module,exports){
14426function decode (string) { 13862// (public) Constructor
14427 var buffer = new Buffer(base58.decode(string)) 13863function BigInteger(a, b, c) {
14428 13864 if (!(this instanceof BigInteger))
14429 var payload = buffer.slice(0, -4) 13865 return new BigInteger(a, b, c)
14430 var checksum = buffer.slice(-4)
14431 var newChecksum = sha256x2(payload).slice(0, 4)
14432
14433 for (var i = 0; i < newChecksum.length; ++i) {
14434 if (newChecksum[i] === checksum[i]) continue
14435 13866
14436 throw new Error('Invalid checksum') 13867 if (a != null) {
13868 if ("number" == typeof a) this.fromNumber(a, b, c)
13869 else if (b == null && "string" != typeof a) this.fromString(a, 256)
13870 else this.fromString(a, b)
14437 } 13871 }
14438
14439 return payload
14440}
14441
14442module.exports = {
14443 encode: encode,
14444 decode: decode
14445} 13872}
14446 13873
14447}).call(this,require("buffer").Buffer) 13874var proto = BigInteger.prototype
14448},{"bs58":30,"buffer":7,"create-hash":32}],32:[function(require,module,exports){
14449(function (Buffer){
14450'use strict';
14451var inherits = require('inherits')
14452var md5 = require('./md5')
14453var rmd160 = require('ripemd160')
14454var sha = require('sha.js')
14455
14456var Transform = require('stream').Transform
14457
14458function HashNoConstructor(hash) {
14459 Transform.call(this)
14460 13875
14461 this._hash = hash 13876// duck-typed isBigInteger
14462 this.buffers = [] 13877proto.__bigi = require('../package.json').version
13878BigInteger.isBigInteger = function (obj, check_ver) {
13879 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
14463} 13880}
14464 13881
14465inherits(HashNoConstructor, Transform) 13882// Bits per digit
14466 13883var dbits
14467HashNoConstructor.prototype._transform = function (data, _, next) {
14468 this.buffers.push(data)
14469 13884
14470 next() 13885// am: Compute w_j += (x*this_i), propagate carries,
14471} 13886// c is initial carry, returns final carry.
13887// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
13888// We need to select the fastest one that works in this environment.
14472 13889
14473HashNoConstructor.prototype._flush = function (next) { 13890// am1: use a single mult and divide to get the high bits,
14474 this.push(this.digest()) 13891// max digit bits should be 26 because
14475 next() 13892// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
13893function am1(i, x, w, j, c, n) {
13894 while (--n >= 0) {
13895 var v = x * this[i++] + w[j] + c
13896 c = Math.floor(v / 0x4000000)
13897 w[j++] = v & 0x3ffffff
13898 }
13899 return c
14476} 13900}
14477 13901// am2 avoids a big mult-and-extract completely.
14478HashNoConstructor.prototype.update = function (data, enc) { 13902// Max digit bits should be <= 30 because we do bitwise ops
14479 if (typeof data === 'string') { 13903// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
14480 data = new Buffer(data, enc) 13904function am2(i, x, w, j, c, n) {
13905 var xl = x & 0x7fff,
13906 xh = x >> 15
13907 while (--n >= 0) {
13908 var l = this[i] & 0x7fff
13909 var h = this[i++] >> 15
13910 var m = xh * l + h * xl
13911 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
13912 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
13913 w[j++] = l & 0x3fffffff
14481 } 13914 }
14482 13915 return c
14483 this.buffers.push(data)
14484 return this
14485} 13916}
14486 13917// Alternately, set max digit bits to 28 since some
14487HashNoConstructor.prototype.digest = function (enc) { 13918// browsers slow down when dealing with 32-bit numbers.
14488 var buf = Buffer.concat(this.buffers) 13919function am3(i, x, w, j, c, n) {
14489 var r = this._hash(buf) 13920 var xl = x & 0x3fff,
14490 this.buffers = null 13921 xh = x >> 14
14491 13922 while (--n >= 0) {
14492 return enc ? r.toString(enc) : r 13923 var l = this[i] & 0x3fff
13924 var h = this[i++] >> 14
13925 var m = xh * l + h * xl
13926 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
13927 c = (l >> 28) + (m >> 14) + xh * h
13928 w[j++] = l & 0xfffffff
13929 }
13930 return c
14493} 13931}
14494 13932
14495function Hash(hash) { 13933// wtf?
14496 Transform.call(this) 13934BigInteger.prototype.am = am1
14497 13935dbits = 26
14498 this._hash = hash
14499}
14500 13936
14501inherits(Hash, Transform) 13937BigInteger.prototype.DB = dbits
13938BigInteger.prototype.DM = ((1 << dbits) - 1)
13939var DV = BigInteger.prototype.DV = (1 << dbits)
14502 13940
14503Hash.prototype._transform = function (data, enc, next) { 13941var BI_FP = 52
14504 if (enc) data = new Buffer(data, enc) 13942BigInteger.prototype.FV = Math.pow(2, BI_FP)
13943BigInteger.prototype.F1 = BI_FP - dbits
13944BigInteger.prototype.F2 = 2 * dbits - BI_FP
14505 13945
14506 this._hash.update(data) 13946// Digit conversions
13947var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
13948var BI_RC = new Array()
13949var rr, vv
13950rr = "0".charCodeAt(0)
13951for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
13952rr = "a".charCodeAt(0)
13953for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
13954rr = "A".charCodeAt(0)
13955for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
14507 13956
14508 next() 13957function int2char(n) {
13958 return BI_RM.charAt(n)
14509} 13959}
14510 13960
14511Hash.prototype._flush = function (next) { 13961function intAt(s, i) {
14512 this.push(this._hash.digest()) 13962 var c = BI_RC[s.charCodeAt(i)]
14513 this._hash = null 13963 return (c == null) ? -1 : c
14514
14515 next()
14516} 13964}
14517 13965
14518Hash.prototype.update = function (data, enc) { 13966// (protected) copy this to r
14519 if (typeof data === 'string') { 13967function bnpCopyTo(r) {
14520 data = new Buffer(data, enc) 13968 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
14521 } 13969 r.t = this.t
14522 13970 r.s = this.s
14523 this._hash.update(data)
14524 return this
14525} 13971}
14526 13972
14527Hash.prototype.digest = function (enc) { 13973// (protected) set from integer value x, -DV <= x < DV
14528 var outData = this._hash.digest() 13974function bnpFromInt(x) {
14529 13975 this.t = 1
14530 return enc ? outData.toString(enc) : outData 13976 this.s = (x < 0) ? -1 : 0
13977 if (x > 0) this[0] = x
13978 else if (x < -1) this[0] = x + DV
13979 else this.t = 0
14531} 13980}
14532 13981
14533module.exports = function createHash (alg) { 13982// return bigint initialized to value
14534 if ('md5' === alg) return new HashNoConstructor(md5) 13983function nbv(i) {
14535 if ('rmd160' === alg) return new HashNoConstructor(rmd160) 13984 var r = new BigInteger()
14536 13985 r.fromInt(i)
14537 return new Hash(sha(alg)) 13986 return r
14538} 13987}
14539 13988
14540}).call(this,require("buffer").Buffer) 13989// (protected) set from string and radix
14541},{"./md5":34,"buffer":7,"inherits":35,"ripemd160":36,"sha.js":38,"stream":26}],33:[function(require,module,exports){ 13990function bnpFromString(s, b) {
14542(function (Buffer){ 13991 var self = this
14543'use strict';
14544var intSize = 4;
14545var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
14546var chrsz = 8;
14547 13992
14548function toArray(buf, bigEndian) { 13993 var k
14549 if ((buf.length % intSize) !== 0) { 13994 if (b == 16) k = 4
14550 var len = buf.length + (intSize - (buf.length % intSize)); 13995 else if (b == 8) k = 3
14551 buf = Buffer.concat([buf, zeroBuffer], len); 13996 else if (b == 256) k = 8; // byte array
13997 else if (b == 2) k = 1
13998 else if (b == 32) k = 5
13999 else if (b == 4) k = 2
14000 else {
14001 self.fromRadix(s, b)
14002 return
14552 } 14003 }
14553 14004 self.t = 0
14554 var arr = []; 14005 self.s = 0
14555 var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; 14006 var i = s.length,
14556 for (var i = 0; i < buf.length; i += intSize) { 14007 mi = false,
14557 arr.push(fn.call(buf, i)); 14008 sh = 0
14009 while (--i >= 0) {
14010 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
14011 if (x < 0) {
14012 if (s.charAt(i) == "-") mi = true
14013 continue
14014 }
14015 mi = false
14016 if (sh == 0)
14017 self[self.t++] = x
14018 else if (sh + k > self.DB) {
14019 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
14020 self[self.t++] = (x >> (self.DB - sh))
14021 } else
14022 self[self.t - 1] |= x << sh
14023 sh += k
14024 if (sh >= self.DB) sh -= self.DB
14558 } 14025 }
14559 return arr; 14026 if (k == 8 && (s[0] & 0x80) != 0) {
14560} 14027 self.s = -1
14561 14028 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
14562function toBuffer(arr, size, bigEndian) {
14563 var buf = new Buffer(size);
14564 var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
14565 for (var i = 0; i < arr.length; i++) {
14566 fn.call(buf, arr[i], i * 4, true);
14567 } 14029 }
14568 return buf; 14030 self.clamp()
14031 if (mi) BigInteger.ZERO.subTo(self, self)
14569} 14032}
14570 14033
14571function hash(buf, fn, hashSize, bigEndian) { 14034// (protected) clamp off excess high words
14572 if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); 14035function bnpClamp() {
14573 var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); 14036 var c = this.s & this.DM
14574 return toBuffer(arr, hashSize, bigEndian); 14037 while (this.t > 0 && this[this.t - 1] == c)--this.t
14575} 14038}
14576exports.hash = hash;
14577}).call(this,require("buffer").Buffer)
14578},{"buffer":7}],34:[function(require,module,exports){
14579'use strict';
14580/*
14581 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
14582 * Digest Algorithm, as defined in RFC 1321.
14583 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
14584 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14585 * Distributed under the BSD License
14586 * See http://pajhome.org.uk/crypt/md5 for more info.
14587 */
14588
14589var helpers = require('./helpers');
14590 14039
14591/* 14040// (public) return string representation in given radix
14592 * Calculate the MD5 of an array of little-endian words, and a bit length 14041function bnToString(b) {
14593 */ 14042 var self = this
14594function core_md5(x, len) 14043 if (self.s < 0) return "-" + self.negate()
14595{ 14044 .toString(b)
14596 /* append padding */ 14045 var k
14597 x[len >> 5] |= 0x80 << ((len) % 32); 14046 if (b == 16) k = 4
14598 x[(((len + 64) >>> 9) << 4) + 14] = len; 14047 else if (b == 8) k = 3
14599 14048 else if (b == 2) k = 1
14600 var a = 1732584193; 14049 else if (b == 32) k = 5
14601 var b = -271733879; 14050 else if (b == 4) k = 2
14602 var c = -1732584194; 14051 else return self.toRadix(b)
14603 var d = 271733878; 14052 var km = (1 << k) - 1,
14604 14053 d, m = false,
14605 for(var i = 0; i < x.length; i += 16) 14054 r = "",
14606 { 14055 i = self.t
14607 var olda = a; 14056 var p = self.DB - (i * self.DB) % k
14608 var oldb = b; 14057 if (i-- > 0) {
14609 var oldc = c; 14058 if (p < self.DB && (d = self[i] >> p) > 0) {
14610 var oldd = d; 14059 m = true
14611 14060 r = int2char(d)
14612 a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); 14061 }
14613 d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); 14062 while (i >= 0) {
14614 c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); 14063 if (p < k) {
14615 b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); 14064 d = (self[i] & ((1 << p) - 1)) << (k - p)
14616 a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); 14065 d |= self[--i] >> (p += self.DB - k)
14617 d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); 14066 } else {
14618 c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); 14067 d = (self[i] >> (p -= k)) & km
14619 b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); 14068 if (p <= 0) {
14620 a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); 14069 p += self.DB
14621 d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); 14070 --i
14622 c = md5_ff(c, d, a, b, x[i+10], 17, -42063); 14071 }
14623 b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); 14072 }
14624 a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); 14073 if (d > 0) m = true
14625 d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); 14074 if (m) r += int2char(d)
14626 c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); 14075 }
14627 b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
14628
14629 a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
14630 d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
14631 c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
14632 b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
14633 a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
14634 d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
14635 c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
14636 b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
14637 a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
14638 d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
14639 c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
14640 b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
14641 a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
14642 d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
14643 c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
14644 b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
14645
14646 a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
14647 d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
14648 c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
14649 b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
14650 a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
14651 d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
14652 c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
14653 b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
14654 a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
14655 d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
14656 c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
14657 b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
14658 a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
14659 d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
14660 c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
14661 b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
14662
14663 a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
14664 d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
14665 c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
14666 b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
14667 a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
14668 d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
14669 c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
14670 b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
14671 a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
14672 d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
14673 c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
14674 b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
14675 a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
14676 d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
14677 c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
14678 b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
14679
14680 a = safe_add(a, olda);
14681 b = safe_add(b, oldb);
14682 c = safe_add(c, oldc);
14683 d = safe_add(d, oldd);
14684 } 14076 }
14685 return Array(a, b, c, d); 14077 return m ? r : "0"
14686
14687} 14078}
14688 14079
14689/* 14080// (public) -this
14690 * These functions implement the four basic operations the algorithm uses. 14081function bnNegate() {
14691 */ 14082 var r = new BigInteger()
14692function md5_cmn(q, a, b, x, s, t) 14083 BigInteger.ZERO.subTo(this, r)
14693{ 14084 return r
14694 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
14695}
14696function md5_ff(a, b, c, d, x, s, t)
14697{
14698 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
14699}
14700function md5_gg(a, b, c, d, x, s, t)
14701{
14702 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
14703}
14704function md5_hh(a, b, c, d, x, s, t)
14705{
14706 return md5_cmn(b ^ c ^ d, a, b, x, s, t);
14707}
14708function md5_ii(a, b, c, d, x, s, t)
14709{
14710 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
14711} 14085}
14712 14086
14713/* 14087// (public) |this|
14714 * Add integers, wrapping at 2^32. This uses 16-bit operations internally 14088function bnAbs() {
14715 * to work around bugs in some JS interpreters. 14089 return (this.s < 0) ? this.negate() : this
14716 */
14717function safe_add(x, y)
14718{
14719 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
14720 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
14721 return (msw << 16) | (lsw & 0xFFFF);
14722} 14090}
14723 14091
14724/* 14092// (public) return + if this > a, - if this < a, 0 if equal
14725 * Bitwise rotate a 32-bit number to the left. 14093function bnCompareTo(a) {
14726 */ 14094 var r = this.s - a.s
14727function bit_rol(num, cnt) 14095 if (r != 0) return r
14728{ 14096 var i = this.t
14729 return (num << cnt) | (num >>> (32 - cnt)); 14097 r = i - a.t
14098 if (r != 0) return (this.s < 0) ? -r : r
14099 while (--i >= 0)
14100 if ((r = this[i] - a[i]) != 0) return r
14101 return 0
14730} 14102}
14731 14103
14732module.exports = function md5(buf) { 14104// returns bit length of the integer x
14733 return helpers.hash(buf, core_md5, 16); 14105function nbits(x) {
14734}; 14106 var r = 1,
14735},{"./helpers":33}],35:[function(require,module,exports){ 14107 t
14736arguments[4][12][0].apply(exports,arguments) 14108 if ((t = x >>> 16) != 0) {
14737},{"dup":12}],36:[function(require,module,exports){ 14109 x = t
14738(function (Buffer){ 14110 r += 16
14739/*
14740CryptoJS v3.1.2
14741code.google.com/p/crypto-js
14742(c) 2009-2013 by Jeff Mott. All rights reserved.
14743code.google.com/p/crypto-js/wiki/License
14744*/
14745/** @preserve
14746(c) 2012 by Cédric Mesnil. All rights reserved.
14747
14748Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
14749
14750 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
14751 - 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.
14752
14753THIS 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.
14754*/
14755
14756// constants table
14757var zl = [
14758 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14759 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
14760 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
14761 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
14762 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
14763]
14764
14765var zr = [
14766 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
14767 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
14768 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
14769 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
14770 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
14771]
14772
14773var sl = [
14774 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
14775 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
14776 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
14777 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
14778 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
14779]
14780
14781var sr = [
14782 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
14783 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
14784 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
14785 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
14786 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
14787]
14788
14789var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
14790var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
14791
14792function bytesToWords (bytes) {
14793 var words = []
14794 for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
14795 words[b >>> 5] |= bytes[i] << (24 - b % 32)
14796 } 14111 }
14797 return words 14112 if ((t = x >> 8) != 0) {
14798} 14113 x = t
14799 14114 r += 8
14800function wordsToBytes (words) {
14801 var bytes = []
14802 for (var b = 0; b < words.length * 32; b += 8) {
14803 bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF)
14804 } 14115 }
14805 return bytes 14116 if ((t = x >> 4) != 0) {
14806} 14117 x = t
14807 14118 r += 4
14808function processBlock (H, M, offset) {
14809 // swap endian
14810 for (var i = 0; i < 16; i++) {
14811 var offset_i = offset + i
14812 var M_offset_i = M[offset_i]
14813
14814 // Swap
14815 M[offset_i] = (
14816 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
14817 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
14818 )
14819 } 14119 }
14820 14120 if ((t = x >> 2) != 0) {
14821 // Working variables 14121 x = t
14822 var al, bl, cl, dl, el 14122 r += 2
14823 var ar, br, cr, dr, er
14824
14825 ar = al = H[0]
14826 br = bl = H[1]
14827 cr = cl = H[2]
14828 dr = dl = H[3]
14829 er = el = H[4]
14830
14831 // computation
14832 var t
14833 for (i = 0; i < 80; i += 1) {
14834 t = (al + M[offset + zl[i]]) | 0
14835 if (i < 16) {
14836 t += f1(bl, cl, dl) + hl[0]
14837 } else if (i < 32) {
14838 t += f2(bl, cl, dl) + hl[1]
14839 } else if (i < 48) {
14840 t += f3(bl, cl, dl) + hl[2]
14841 } else if (i < 64) {
14842 t += f4(bl, cl, dl) + hl[3]
14843 } else {// if (i<80) {
14844 t += f5(bl, cl, dl) + hl[4]
14845 }
14846 t = t | 0
14847 t = rotl(t, sl[i])
14848 t = (t + el) | 0
14849 al = el
14850 el = dl
14851 dl = rotl(cl, 10)
14852 cl = bl
14853 bl = t
14854
14855 t = (ar + M[offset + zr[i]]) | 0
14856 if (i < 16) {
14857 t += f5(br, cr, dr) + hr[0]
14858 } else if (i < 32) {
14859 t += f4(br, cr, dr) + hr[1]
14860 } else if (i < 48) {
14861 t += f3(br, cr, dr) + hr[2]
14862 } else if (i < 64) {
14863 t += f2(br, cr, dr) + hr[3]
14864 } else {// if (i<80) {
14865 t += f1(br, cr, dr) + hr[4]
14866 }
14867
14868 t = t | 0
14869 t = rotl(t, sr[i])
14870 t = (t + er) | 0
14871 ar = er
14872 er = dr
14873 dr = rotl(cr, 10)
14874 cr = br
14875 br = t
14876 } 14123 }
14877 14124 if ((t = x >> 1) != 0) {
14878 // intermediate hash value 14125 x = t
14879 t = (H[1] + cl + dr) | 0 14126 r += 1
14880 H[1] = (H[2] + dl + er) | 0 14127 }
14881 H[2] = (H[3] + el + ar) | 0 14128 return r
14882 H[3] = (H[4] + al + br) | 0
14883 H[4] = (H[0] + bl + cr) | 0
14884 H[0] = t
14885}
14886
14887function f1 (x, y, z) {
14888 return ((x) ^ (y) ^ (z))
14889}
14890
14891function f2 (x, y, z) {
14892 return (((x) & (y)) | ((~x) & (z)))
14893} 14129}
14894 14130
14895function f3 (x, y, z) { 14131// (public) return the number of bits in "this"
14896 return (((x) | (~(y))) ^ (z)) 14132function bnBitLength() {
14133 if (this.t <= 0) return 0
14134 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
14897} 14135}
14898 14136
14899function f4 (x, y, z) { 14137// (public) return the number of bytes in "this"
14900 return (((x) & (z)) | ((y) & (~(z)))) 14138function bnByteLength() {
14139 return this.bitLength() >> 3
14901} 14140}
14902 14141
14903function f5 (x, y, z) { 14142// (protected) r = this << n*DB
14904 return ((x) ^ ((y) | (~(z)))) 14143function bnpDLShiftTo(n, r) {
14144 var i
14145 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
14146 for (i = n - 1; i >= 0; --i) r[i] = 0
14147 r.t = this.t + n
14148 r.s = this.s
14905} 14149}
14906 14150
14907function rotl (x, n) { 14151// (protected) r = this >> n*DB
14908 return (x << n) | (x >>> (32 - n)) 14152function bnpDRShiftTo(n, r) {
14153 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
14154 r.t = Math.max(this.t - n, 0)
14155 r.s = this.s
14909} 14156}
14910 14157
14911function ripemd160 (message) { 14158// (protected) r = this << n
14912 var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] 14159function bnpLShiftTo(n, r) {
14913 14160 var self = this
14914 if (typeof message === 'string') { 14161 var bs = n % self.DB
14915 message = new Buffer(message, 'utf8') 14162 var cbs = self.DB - bs
14163 var bm = (1 << cbs) - 1
14164 var ds = Math.floor(n / self.DB),
14165 c = (self.s << bs) & self.DM,
14166 i
14167 for (i = self.t - 1; i >= 0; --i) {
14168 r[i + ds + 1] = (self[i] >> cbs) | c
14169 c = (self[i] & bm) << bs
14916 } 14170 }
14171 for (i = ds - 1; i >= 0; --i) r[i] = 0
14172 r[ds] = c
14173 r.t = self.t + ds + 1
14174 r.s = self.s
14175 r.clamp()
14176}
14917 14177
14918 var m = bytesToWords(message) 14178// (protected) r = this >> n
14919 14179function bnpRShiftTo(n, r) {
14920 var nBitsLeft = message.length * 8 14180 var self = this
14921 var nBitsTotal = message.length * 8 14181 r.s = self.s
14922 14182 var ds = Math.floor(n / self.DB)
14923 // Add padding 14183 if (ds >= self.t) {
14924 m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) 14184 r.t = 0
14925 m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( 14185 return
14926 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
14927 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
14928 )
14929
14930 for (var i = 0; i < m.length; i += 16) {
14931 processBlock(H, m, i)
14932 } 14186 }
14933 14187 var bs = n % self.DB
14934 // swap endian 14188 var cbs = self.DB - bs
14935 for (i = 0; i < 5; i++) { 14189 var bm = (1 << bs) - 1
14936 // shortcut 14190 r[0] = self[ds] >> bs
14937 var H_i = H[i] 14191 for (var i = ds + 1; i < self.t; ++i) {
14938 14192 r[i - ds - 1] |= (self[i] & bm) << cbs
14939 // Swap 14193 r[i - ds] = self[i] >> bs
14940 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
14941 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00)
14942 } 14194 }
14943 14195 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
14944 var digestbytes = wordsToBytes(H) 14196 r.t = self.t - ds
14945 return new Buffer(digestbytes) 14197 r.clamp()
14946}
14947
14948module.exports = ripemd160
14949
14950}).call(this,require("buffer").Buffer)
14951},{"buffer":7}],37:[function(require,module,exports){
14952(function (Buffer){
14953// prototype class for hash functions
14954function Hash (blockSize, finalSize) {
14955 this._block = new Buffer(blockSize)
14956 this._finalSize = finalSize
14957 this._blockSize = blockSize
14958 this._len = 0
14959 this._s = 0
14960} 14198}
14961 14199
14962Hash.prototype.update = function (data, enc) { 14200// (protected) r = this - a
14963 if (typeof data === 'string') { 14201function bnpSubTo(a, r) {
14964 enc = enc || 'utf8' 14202 var self = this
14965 data = new Buffer(data, enc) 14203 var i = 0,
14204 c = 0,
14205 m = Math.min(a.t, self.t)
14206 while (i < m) {
14207 c += self[i] - a[i]
14208 r[i++] = c & self.DM
14209 c >>= self.DB
14966 } 14210 }
14967 14211 if (a.t < self.t) {
14968 var l = this._len += data.length 14212 c -= a.s
14969 var s = this._s || 0 14213 while (i < self.t) {
14970 var f = 0 14214 c += self[i]
14971 var buffer = this._block 14215 r[i++] = c & self.DM
14972 14216 c >>= self.DB
14973 while (s < l) {
14974 var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
14975 var ch = (t - f)
14976
14977 for (var i = 0; i < ch; i++) {
14978 buffer[(s % this._blockSize) + i] = data[i + f]
14979 } 14217 }
14980 14218 c += self.s
14981 s += ch 14219 } else {
14982 f += ch 14220 c += self.s
14983 14221 while (i < a.t) {
14984 if ((s % this._blockSize) === 0) { 14222 c -= a[i]
14985 this._update(buffer) 14223 r[i++] = c & self.DM
14224 c >>= self.DB
14986 } 14225 }
14226 c -= a.s
14987 } 14227 }
14988 this._s = s 14228 r.s = (c < 0) ? -1 : 0
14989 14229 if (c < -1) r[i++] = self.DV + c
14990 return this 14230 else if (c > 0) r[i++] = c
14231 r.t = i
14232 r.clamp()
14991} 14233}
14992 14234
14993Hash.prototype.digest = function (enc) { 14235// (protected) r = this * a, r != this,a (HAC 14.12)
14994 // Suppose the length of the message M, in bits, is l 14236// "this" should be the larger one if appropriate.
14995 var l = this._len * 8 14237function bnpMultiplyTo(a, r) {
14996 14238 var x = this.abs(),
14997 // Append the bit 1 to the end of the message 14239 y = a.abs()
14998 this._block[this._len % this._blockSize] = 0x80 14240 var i = x.t
14999 14241 r.t = i + y.t
15000 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize 14242 while (--i >= 0) r[i] = 0
15001 this._block.fill(0, this._len % this._blockSize + 1) 14243 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
14244 r.s = 0
14245 r.clamp()
14246 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
14247}
15002 14248
15003 if (l % (this._blockSize * 8) >= this._finalSize * 8) { 14249// (protected) r = this^2, r != this (HAC 14.16)
15004 this._update(this._block) 14250function bnpSquareTo(r) {
15005 this._block.fill(0) 14251 var x = this.abs()
14252 var i = r.t = 2 * x.t
14253 while (--i >= 0) r[i] = 0
14254 for (i = 0; i < x.t - 1; ++i) {
14255 var c = x.am(i, x[i], r, 2 * i, 0, 1)
14256 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
14257 r[i + x.t] -= x.DV
14258 r[i + x.t + 1] = 1
14259 }
15006 } 14260 }
15007 14261 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
15008 // to this append the block which is equal to the number l written in binary 14262 r.s = 0
15009 // TODO: handle case where l is > Math.pow(2, 29) 14263 r.clamp()
15010 this._block.writeInt32BE(l, this._blockSize - 4)
15011
15012 var hash = this._update(this._block) || this._hash()
15013
15014 return enc ? hash.toString(enc) : hash
15015} 14264}
15016 14265
15017Hash.prototype._update = function () { 14266// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
15018 throw new Error('_update must be implemented by subclass') 14267// r != q, this != m. q or r may be null.
14268function bnpDivRemTo(m, q, r) {
14269 var self = this
14270 var pm = m.abs()
14271 if (pm.t <= 0) return
14272 var pt = self.abs()
14273 if (pt.t < pm.t) {
14274 if (q != null) q.fromInt(0)
14275 if (r != null) self.copyTo(r)
14276 return
14277 }
14278 if (r == null) r = new BigInteger()
14279 var y = new BigInteger(),
14280 ts = self.s,
14281 ms = m.s
14282 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
14283 if (nsh > 0) {
14284 pm.lShiftTo(nsh, y)
14285 pt.lShiftTo(nsh, r)
14286 } else {
14287 pm.copyTo(y)
14288 pt.copyTo(r)
14289 }
14290 var ys = y.t
14291 var y0 = y[ys - 1]
14292 if (y0 == 0) return
14293 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
14294 var d1 = self.FV / yt,
14295 d2 = (1 << self.F1) / yt,
14296 e = 1 << self.F2
14297 var i = r.t,
14298 j = i - ys,
14299 t = (q == null) ? new BigInteger() : q
14300 y.dlShiftTo(j, t)
14301 if (r.compareTo(t) >= 0) {
14302 r[r.t++] = 1
14303 r.subTo(t, r)
14304 }
14305 BigInteger.ONE.dlShiftTo(ys, t)
14306 t.subTo(y, y); // "negative" y so we can replace sub with am later
14307 while (y.t < ys) y[y.t++] = 0
14308 while (--j >= 0) {
14309 // Estimate quotient digit
14310 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
14311 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
14312 y.dlShiftTo(j, t)
14313 r.subTo(t, r)
14314 while (r[i] < --qd) r.subTo(t, r)
14315 }
14316 }
14317 if (q != null) {
14318 r.drShiftTo(ys, q)
14319 if (ts != ms) BigInteger.ZERO.subTo(q, q)
14320 }
14321 r.t = ys
14322 r.clamp()
14323 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
14324 if (ts < 0) BigInteger.ZERO.subTo(r, r)
15019} 14325}
15020 14326
15021module.exports = Hash 14327// (public) this mod a
15022 14328function bnMod(a) {
15023}).call(this,require("buffer").Buffer) 14329 var r = new BigInteger()
15024},{"buffer":7}],38:[function(require,module,exports){ 14330 this.abs()
15025var exports = module.exports = function SHA (algorithm) { 14331 .divRemTo(a, null, r)
15026 algorithm = algorithm.toLowerCase() 14332 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
15027 14333 return r
15028 var Algorithm = exports[algorithm]
15029 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
15030
15031 return new Algorithm()
15032} 14334}
15033 14335
15034exports.sha = require('./sha') 14336// Modular reduction using "classic" algorithm
15035exports.sha1 = require('./sha1') 14337function Classic(m) {
15036exports.sha224 = require('./sha224') 14338 this.m = m
15037exports.sha256 = require('./sha256')
15038exports.sha384 = require('./sha384')
15039exports.sha512 = require('./sha512')
15040
15041},{"./sha":39,"./sha1":40,"./sha224":41,"./sha256":42,"./sha384":43,"./sha512":44}],39:[function(require,module,exports){
15042(function (Buffer){
15043/*
15044 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
15045 * in FIPS PUB 180-1
15046 * This source code is derived from sha1.js of the same repository.
15047 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
15048 * operation was added.
15049 */
15050
15051var inherits = require('inherits')
15052var Hash = require('./hash')
15053
15054var W = new Array(80)
15055
15056function Sha () {
15057 this.init()
15058 this._w = W
15059
15060 Hash.call(this, 64, 56)
15061} 14339}
15062 14340
15063inherits(Sha, Hash) 14341function cConvert(x) {
15064 14342 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
15065Sha.prototype.init = function () { 14343 else return x
15066 this._a = 0x67452301 | 0
15067 this._b = 0xefcdab89 | 0
15068 this._c = 0x98badcfe | 0
15069 this._d = 0x10325476 | 0
15070 this._e = 0xc3d2e1f0 | 0
15071
15072 return this
15073} 14344}
15074 14345
15075/* 14346function cRevert(x) {
15076 * Bitwise rotate a 32-bit number to the left. 14347 return x
15077 */
15078function rol (num, cnt) {
15079 return (num << cnt) | (num >>> (32 - cnt))
15080} 14348}
15081 14349
15082Sha.prototype._update = function (M) { 14350function cReduce(x) {
15083 var W = this._w 14351 x.divRemTo(this.m, null, x)
15084
15085 var a = this._a
15086 var b = this._b
15087 var c = this._c
15088 var d = this._d
15089 var e = this._e
15090
15091 var j = 0, k
15092
15093 /*
15094 * SHA-1 has a bitwise rotate left operation. But, SHA is not
15095 * function calcW() { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) }
15096 */
15097 function calcW () { return W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16] }
15098 function loop (w, f) {
15099 W[j] = w
15100
15101 var t = rol(a, 5) + f + e + w + k
15102
15103 e = d
15104 d = c
15105 c = rol(b, 30)
15106 b = a
15107 a = t
15108 j++
15109 }
15110
15111 k = 1518500249
15112 while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d))
15113 while (j < 20) loop(calcW(), (b & c) | ((~b) & d))
15114 k = 1859775393
15115 while (j < 40) loop(calcW(), b ^ c ^ d)
15116 k = -1894007588
15117 while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d))
15118 k = -899497514
15119 while (j < 80) loop(calcW(), b ^ c ^ d)
15120
15121 this._a = (a + this._a) | 0
15122 this._b = (b + this._b) | 0
15123 this._c = (c + this._c) | 0
15124 this._d = (d + this._d) | 0
15125 this._e = (e + this._e) | 0
15126} 14352}
15127 14353
15128Sha.prototype._hash = function () { 14354function cMulTo(x, y, r) {
15129 var H = new Buffer(20) 14355 x.multiplyTo(y, r)
15130 14356 this.reduce(r)
15131 H.writeInt32BE(this._a | 0, 0)
15132 H.writeInt32BE(this._b | 0, 4)
15133 H.writeInt32BE(this._c | 0, 8)
15134 H.writeInt32BE(this._d | 0, 12)
15135 H.writeInt32BE(this._e | 0, 16)
15136
15137 return H
15138} 14357}
15139 14358
15140module.exports = Sha 14359function cSqrTo(x, r) {
15141 14360 x.squareTo(r)
15142 14361 this.reduce(r)
15143}).call(this,require("buffer").Buffer)
15144},{"./hash":37,"buffer":7,"inherits":35}],40:[function(require,module,exports){
15145(function (Buffer){
15146/*
15147 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
15148 * in FIPS PUB 180-1
15149 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
15150 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
15151 * Distributed under the BSD License
15152 * See http://pajhome.org.uk/crypt/md5 for details.
15153 */
15154
15155var inherits = require('inherits')
15156var Hash = require('./hash')
15157
15158var W = new Array(80)
15159
15160function Sha1 () {
15161 this.init()
15162 this._w = W
15163
15164 Hash.call(this, 64, 56)
15165} 14362}
15166 14363
15167inherits(Sha1, Hash) 14364Classic.prototype.convert = cConvert
15168 14365Classic.prototype.revert = cRevert
15169Sha1.prototype.init = function () { 14366Classic.prototype.reduce = cReduce
15170 this._a = 0x67452301 | 0 14367Classic.prototype.mulTo = cMulTo
15171 this._b = 0xefcdab89 | 0 14368Classic.prototype.sqrTo = cSqrTo
15172 this._c = 0x98badcfe | 0
15173 this._d = 0x10325476 | 0
15174 this._e = 0xc3d2e1f0 | 0
15175 14369
15176 return this 14370// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
14371// justification:
14372// xy == 1 (mod m)
14373// xy = 1+km
14374// xy(2-xy) = (1+km)(1-km)
14375// x[y(2-xy)] = 1-k^2m^2
14376// x[y(2-xy)] == 1 (mod m^2)
14377// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
14378// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
14379// JS multiply "overflows" differently from C/C++, so care is needed here.
14380function bnpInvDigit() {
14381 if (this.t < 1) return 0
14382 var x = this[0]
14383 if ((x & 1) == 0) return 0
14384 var y = x & 3; // y == 1/x mod 2^2
14385 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
14386 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
14387 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
14388 // last step - calculate inverse mod DV directly
14389 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
14390 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
14391 // we really want the negative inverse, and -DV < y < DV
14392 return (y > 0) ? this.DV - y : -y
15177} 14393}
15178 14394
15179/* 14395// Montgomery reduction
15180 * Bitwise rotate a 32-bit number to the left. 14396function Montgomery(m) {
15181 */ 14397 this.m = m
15182function rol (num, cnt) { 14398 this.mp = m.invDigit()
15183 return (num << cnt) | (num >>> (32 - cnt)) 14399 this.mpl = this.mp & 0x7fff
14400 this.mph = this.mp >> 15
14401 this.um = (1 << (m.DB - 15)) - 1
14402 this.mt2 = 2 * m.t
15184} 14403}
15185 14404
15186Sha1.prototype._update = function (M) { 14405// xR mod m
15187 var W = this._w 14406function montConvert(x) {
15188 14407 var r = new BigInteger()
15189 var a = this._a 14408 x.abs()
15190 var b = this._b 14409 .dlShiftTo(this.m.t, r)
15191 var c = this._c 14410 r.divRemTo(this.m, null, r)
15192 var d = this._d 14411 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
15193 var e = this._e 14412 return r
15194 14413}
15195 var j = 0, k
15196
15197 function calcW () { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) }
15198 function loop (w, f) {
15199 W[j] = w
15200 14414
15201 var t = rol(a, 5) + f + e + w + k 14415// x/R mod m
14416function montRevert(x) {
14417 var r = new BigInteger()
14418 x.copyTo(r)
14419 this.reduce(r)
14420 return r
14421}
15202 14422
15203 e = d 14423// x = x/R mod m (HAC 14.32)
15204 d = c 14424function montReduce(x) {
15205 c = rol(b, 30) 14425 while (x.t <= this.mt2) // pad x so am has enough room later
15206 b = a 14426 x[x.t++] = 0
15207 a = t 14427 for (var i = 0; i < this.m.t; ++i) {
15208 j++ 14428 // faster way of calculating u0 = x[i]*mp mod DV
14429 var j = x[i] & 0x7fff
14430 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
14431 // use am to combine the multiply-shift-add into one call
14432 j = i + this.m.t
14433 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
14434 // propagate carry
14435 while (x[j] >= x.DV) {
14436 x[j] -= x.DV
14437 x[++j]++
14438 }
15209 } 14439 }
15210 14440 x.clamp()
15211 k = 1518500249 14441 x.drShiftTo(this.m.t, x)
15212 while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d)) 14442 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
15213 while (j < 20) loop(calcW(), (b & c) | ((~b) & d))
15214 k = 1859775393
15215 while (j < 40) loop(calcW(), b ^ c ^ d)
15216 k = -1894007588
15217 while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d))
15218 k = -899497514
15219 while (j < 80) loop(calcW(), b ^ c ^ d)
15220
15221 this._a = (a + this._a) | 0
15222 this._b = (b + this._b) | 0
15223 this._c = (c + this._c) | 0
15224 this._d = (d + this._d) | 0
15225 this._e = (e + this._e) | 0
15226} 14443}
15227 14444
15228Sha1.prototype._hash = function () { 14445// r = "x^2/R mod m"; x != r
15229 var H = new Buffer(20) 14446function montSqrTo(x, r) {
15230 14447 x.squareTo(r)
15231 H.writeInt32BE(this._a | 0, 0) 14448 this.reduce(r)
15232 H.writeInt32BE(this._b | 0, 4)
15233 H.writeInt32BE(this._c | 0, 8)
15234 H.writeInt32BE(this._d | 0, 12)
15235 H.writeInt32BE(this._e | 0, 16)
15236
15237 return H
15238} 14449}
15239 14450
15240module.exports = Sha1 14451// r = "xy/R mod m"; x,y != r
15241 14452function montMulTo(x, y, r) {
15242}).call(this,require("buffer").Buffer) 14453 x.multiplyTo(y, r)
15243},{"./hash":37,"buffer":7,"inherits":35}],41:[function(require,module,exports){ 14454 this.reduce(r)
15244(function (Buffer){
15245/**
15246 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
15247 * in FIPS 180-2
15248 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
15249 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
15250 *
15251 */
15252
15253var inherits = require('inherits')
15254var Sha256 = require('./sha256')
15255var Hash = require('./hash')
15256
15257var W = new Array(64)
15258
15259function Sha224 () {
15260 this.init()
15261
15262 this._w = W // new Array(64)
15263
15264 Hash.call(this, 64, 56)
15265} 14455}
15266 14456
15267inherits(Sha224, Sha256) 14457Montgomery.prototype.convert = montConvert
15268 14458Montgomery.prototype.revert = montRevert
15269Sha224.prototype.init = function () { 14459Montgomery.prototype.reduce = montReduce
15270 this._a = 0xc1059ed8 | 0 14460Montgomery.prototype.mulTo = montMulTo
15271 this._b = 0x367cd507 | 0 14461Montgomery.prototype.sqrTo = montSqrTo
15272 this._c = 0x3070dd17 | 0
15273 this._d = 0xf70e5939 | 0
15274 this._e = 0xffc00b31 | 0
15275 this._f = 0x68581511 | 0
15276 this._g = 0x64f98fa7 | 0
15277 this._h = 0xbefa4fa4 | 0
15278 14462
15279 return this 14463// (protected) true iff this is even
14464function bnpIsEven() {
14465 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
15280} 14466}
15281 14467
15282Sha224.prototype._hash = function () { 14468// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
15283 var H = new Buffer(28) 14469function bnpExp(e, z) {
15284 14470 if (e > 0xffffffff || e < 1) return BigInteger.ONE
15285 H.writeInt32BE(this._a, 0) 14471 var r = new BigInteger(),
15286 H.writeInt32BE(this._b, 4) 14472 r2 = new BigInteger(),
15287 H.writeInt32BE(this._c, 8) 14473 g = z.convert(this),
15288 H.writeInt32BE(this._d, 12) 14474 i = nbits(e) - 1
15289 H.writeInt32BE(this._e, 16) 14475 g.copyTo(r)
15290 H.writeInt32BE(this._f, 20) 14476 while (--i >= 0) {
15291 H.writeInt32BE(this._g, 24) 14477 z.sqrTo(r, r2)
15292 14478 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
15293 return H 14479 else {
14480 var t = r
14481 r = r2
14482 r2 = t
14483 }
14484 }
14485 return z.revert(r)
15294} 14486}
15295 14487
15296module.exports = Sha224 14488// (public) this^e % m, 0 <= e < 2^32
15297 14489function bnModPowInt(e, m) {
15298}).call(this,require("buffer").Buffer) 14490 var z
15299},{"./hash":37,"./sha256":42,"buffer":7,"inherits":35}],42:[function(require,module,exports){ 14491 if (e < 256 || m.isEven()) z = new Classic(m)
15300(function (Buffer){ 14492 else z = new Montgomery(m)
15301/** 14493 return this.exp(e, z)
15302 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
15303 * in FIPS 180-2
15304 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
15305 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
15306 *
15307 */
15308
15309var inherits = require('inherits')
15310var Hash = require('./hash')
15311
15312var K = [
15313 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
15314 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
15315 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
15316 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
15317 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
15318 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
15319 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
15320 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
15321 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
15322 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
15323 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
15324 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
15325 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
15326 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
15327 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
15328 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
15329]
15330
15331var W = new Array(64)
15332
15333function Sha256 () {
15334 this.init()
15335
15336 this._w = W // new Array(64)
15337
15338 Hash.call(this, 64, 56)
15339} 14494}
15340 14495
15341inherits(Sha256, Hash) 14496// protected
14497proto.copyTo = bnpCopyTo
14498proto.fromInt = bnpFromInt
14499proto.fromString = bnpFromString
14500proto.clamp = bnpClamp
14501proto.dlShiftTo = bnpDLShiftTo
14502proto.drShiftTo = bnpDRShiftTo
14503proto.lShiftTo = bnpLShiftTo
14504proto.rShiftTo = bnpRShiftTo
14505proto.subTo = bnpSubTo
14506proto.multiplyTo = bnpMultiplyTo
14507proto.squareTo = bnpSquareTo
14508proto.divRemTo = bnpDivRemTo
14509proto.invDigit = bnpInvDigit
14510proto.isEven = bnpIsEven
14511proto.exp = bnpExp
15342 14512
15343Sha256.prototype.init = function () { 14513// public
15344 this._a = 0x6a09e667 | 0 14514proto.toString = bnToString
15345 this._b = 0xbb67ae85 | 0 14515proto.negate = bnNegate
15346 this._c = 0x3c6ef372 | 0 14516proto.abs = bnAbs
15347 this._d = 0xa54ff53a | 0 14517proto.compareTo = bnCompareTo
15348 this._e = 0x510e527f | 0 14518proto.bitLength = bnBitLength
15349 this._f = 0x9b05688c | 0 14519proto.byteLength = bnByteLength
15350 this._g = 0x1f83d9ab | 0 14520proto.mod = bnMod
15351 this._h = 0x5be0cd19 | 0 14521proto.modPowInt = bnModPowInt
15352 14522
15353 return this 14523// (public)
14524function bnClone() {
14525 var r = new BigInteger()
14526 this.copyTo(r)
14527 return r
15354} 14528}
15355 14529
15356function S (X, n) { 14530// (public) return value as integer
15357 return (X >>> n) | (X << (32 - n)) 14531function bnIntValue() {
14532 if (this.s < 0) {
14533 if (this.t == 1) return this[0] - this.DV
14534 else if (this.t == 0) return -1
14535 } else if (this.t == 1) return this[0]
14536 else if (this.t == 0) return 0
14537 // assumes 16 < DB < 32
14538 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
15358} 14539}
15359 14540
15360function R (X, n) { 14541// (public) return value as byte
15361 return (X >>> n) 14542function bnByteValue() {
14543 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
15362} 14544}
15363 14545
15364function Ch (x, y, z) { 14546// (public) return value as short (assumes DB>=16)
15365 return ((x & y) ^ ((~x) & z)) 14547function bnShortValue() {
14548 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
15366} 14549}
15367 14550
15368function Maj (x, y, z) { 14551// (protected) return x s.t. r^x < DV
15369 return ((x & y) ^ (x & z) ^ (y & z)) 14552function bnpChunkSize(r) {
14553 return Math.floor(Math.LN2 * this.DB / Math.log(r))
15370} 14554}
15371 14555
15372function Sigma0256 (x) { 14556// (public) 0 if this == 0, 1 if this > 0
15373 return (S(x, 2) ^ S(x, 13) ^ S(x, 22)) 14557function bnSigNum() {
14558 if (this.s < 0) return -1
14559 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
14560 else return 1
15374} 14561}
15375 14562
15376function Sigma1256 (x) { 14563// (protected) convert to radix string
15377 return (S(x, 6) ^ S(x, 11) ^ S(x, 25)) 14564function bnpToRadix(b) {
14565 if (b == null) b = 10
14566 if (this.signum() == 0 || b < 2 || b > 36) return "0"
14567 var cs = this.chunkSize(b)
14568 var a = Math.pow(b, cs)
14569 var d = nbv(a),
14570 y = new BigInteger(),
14571 z = new BigInteger(),
14572 r = ""
14573 this.divRemTo(d, y, z)
14574 while (y.signum() > 0) {
14575 r = (a + z.intValue())
14576 .toString(b)
14577 .substr(1) + r
14578 y.divRemTo(d, y, z)
14579 }
14580 return z.intValue()
14581 .toString(b) + r
15378} 14582}
15379 14583
15380function Gamma0256 (x) { 14584// (protected) convert from radix string
15381 return (S(x, 7) ^ S(x, 18) ^ R(x, 3)) 14585function bnpFromRadix(s, b) {
14586 var self = this
14587 self.fromInt(0)
14588 if (b == null) b = 10
14589 var cs = self.chunkSize(b)
14590 var d = Math.pow(b, cs),
14591 mi = false,
14592 j = 0,
14593 w = 0
14594 for (var i = 0; i < s.length; ++i) {
14595 var x = intAt(s, i)
14596 if (x < 0) {
14597 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
14598 continue
14599 }
14600 w = b * w + x
14601 if (++j >= cs) {
14602 self.dMultiply(d)
14603 self.dAddOffset(w, 0)
14604 j = 0
14605 w = 0
14606 }
14607 }
14608 if (j > 0) {
14609 self.dMultiply(Math.pow(b, j))
14610 self.dAddOffset(w, 0)
14611 }
14612 if (mi) BigInteger.ZERO.subTo(self, self)
15382} 14613}
15383 14614
15384function Gamma1256 (x) { 14615// (protected) alternate constructor
15385 return (S(x, 17) ^ S(x, 19) ^ R(x, 10)) 14616function bnpFromNumber(a, b, c) {
14617 var self = this
14618 if ("number" == typeof b) {
14619 // new BigInteger(int,int,RNG)
14620 if (a < 2) self.fromInt(1)
14621 else {
14622 self.fromNumber(a, c)
14623 if (!self.testBit(a - 1)) // force MSB set
14624 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
14625 if (self.isEven()) self.dAddOffset(1, 0); // force odd
14626 while (!self.isProbablePrime(b)) {
14627 self.dAddOffset(2, 0)
14628 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
14629 }
14630 }
14631 } else {
14632 // new BigInteger(int,RNG)
14633 var x = new Array(),
14634 t = a & 7
14635 x.length = (a >> 3) + 1
14636 b.nextBytes(x)
14637 if (t > 0) x[0] &= ((1 << t) - 1)
14638 else x[0] = 0
14639 self.fromString(x, 256)
14640 }
15386} 14641}
15387 14642
15388Sha256.prototype._update = function (M) { 14643// (public) convert to bigendian byte array
15389 var W = this._w 14644function bnToByteArray() {
15390 14645 var self = this
15391 var a = this._a | 0 14646 var i = self.t,
15392 var b = this._b | 0 14647 r = new Array()
15393 var c = this._c | 0 14648 r[0] = self.s
15394 var d = this._d | 0 14649 var p = self.DB - (i * self.DB) % 8,
15395 var e = this._e | 0 14650 d, k = 0
15396 var f = this._f | 0 14651 if (i-- > 0) {
15397 var g = this._g | 0 14652 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
15398 var h = this._h | 0 14653 r[k++] = d | (self.s << (self.DB - p))
15399 14654 while (i >= 0) {
15400 var j = 0 14655 if (p < 8) {
15401 14656 d = (self[i] & ((1 << p) - 1)) << (8 - p)
15402 function calcW () { return Gamma1256(W[j - 2]) + W[j - 7] + Gamma0256(W[j - 15]) + W[j - 16] } 14657 d |= self[--i] >> (p += self.DB - 8)
15403 function loop (w) { 14658 } else {
15404 W[j] = w 14659 d = (self[i] >> (p -= 8)) & 0xff
15405 14660 if (p <= 0) {
15406 var T1 = h + Sigma1256(e) + Ch(e, f, g) + K[j] + w 14661 p += self.DB
15407 var T2 = Sigma0256(a) + Maj(a, b, c) 14662 --i
15408 14663 }
15409 h = g 14664 }
15410 g = f 14665 if ((d & 0x80) != 0) d |= -256
15411 f = e 14666 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
15412 e = d + T1 14667 if (k > 0 || d != self.s) r[k++] = d
15413 d = c 14668 }
15414 c = b
15415 b = a
15416 a = T1 + T2
15417
15418 j++
15419 } 14669 }
15420 14670 return r
15421 while (j < 16) loop(M.readInt32BE(j * 4))
15422 while (j < 64) loop(calcW())
15423
15424 this._a = (a + this._a) | 0
15425 this._b = (b + this._b) | 0
15426 this._c = (c + this._c) | 0
15427 this._d = (d + this._d) | 0
15428 this._e = (e + this._e) | 0
15429 this._f = (f + this._f) | 0
15430 this._g = (g + this._g) | 0
15431 this._h = (h + this._h) | 0
15432} 14671}
15433 14672
15434Sha256.prototype._hash = function () { 14673function bnEquals(a) {
15435 var H = new Buffer(32) 14674 return (this.compareTo(a) == 0)
15436
15437 H.writeInt32BE(this._a, 0)
15438 H.writeInt32BE(this._b, 4)
15439 H.writeInt32BE(this._c, 8)
15440 H.writeInt32BE(this._d, 12)
15441 H.writeInt32BE(this._e, 16)
15442 H.writeInt32BE(this._f, 20)
15443 H.writeInt32BE(this._g, 24)
15444 H.writeInt32BE(this._h, 28)
15445
15446 return H
15447} 14675}
15448 14676
15449module.exports = Sha256 14677function bnMin(a) {
15450 14678 return (this.compareTo(a) < 0) ? this : a
15451}).call(this,require("buffer").Buffer)
15452},{"./hash":37,"buffer":7,"inherits":35}],43:[function(require,module,exports){
15453(function (Buffer){
15454var inherits = require('inherits')
15455var SHA512 = require('./sha512')
15456var Hash = require('./hash')
15457
15458var W = new Array(160)
15459
15460function Sha384 () {
15461 this.init()
15462 this._w = W
15463
15464 Hash.call(this, 128, 112)
15465} 14679}
15466 14680
15467inherits(Sha384, SHA512) 14681function bnMax(a) {
15468 14682 return (this.compareTo(a) > 0) ? this : a
15469Sha384.prototype.init = function () {
15470 this._a = 0xcbbb9d5d | 0
15471 this._b = 0x629a292a | 0
15472 this._c = 0x9159015a | 0
15473 this._d = 0x152fecd8 | 0
15474 this._e = 0x67332667 | 0
15475 this._f = 0x8eb44a87 | 0
15476 this._g = 0xdb0c2e0d | 0
15477 this._h = 0x47b5481d | 0
15478
15479 this._al = 0xc1059ed8 | 0
15480 this._bl = 0x367cd507 | 0
15481 this._cl = 0x3070dd17 | 0
15482 this._dl = 0xf70e5939 | 0
15483 this._el = 0xffc00b31 | 0
15484 this._fl = 0x68581511 | 0
15485 this._gl = 0x64f98fa7 | 0
15486 this._hl = 0xbefa4fa4 | 0
15487
15488 return this
15489} 14683}
15490 14684
15491Sha384.prototype._hash = function () { 14685// (protected) r = this op a (bitwise)
15492 var H = new Buffer(48) 14686function bnpBitwiseTo(a, op, r) {
15493 14687 var self = this
15494 function writeInt64BE (h, l, offset) { 14688 var i, f, m = Math.min(a.t, self.t)
15495 H.writeInt32BE(h, offset) 14689 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
15496 H.writeInt32BE(l, offset + 4) 14690 if (a.t < self.t) {
14691 f = a.s & self.DM
14692 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
14693 r.t = self.t
14694 } else {
14695 f = self.s & self.DM
14696 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
14697 r.t = a.t
15497 } 14698 }
15498 14699 r.s = op(self.s, a.s)
15499 writeInt64BE(this._a, this._al, 0) 14700 r.clamp()
15500 writeInt64BE(this._b, this._bl, 8)
15501 writeInt64BE(this._c, this._cl, 16)
15502 writeInt64BE(this._d, this._dl, 24)
15503 writeInt64BE(this._e, this._el, 32)
15504 writeInt64BE(this._f, this._fl, 40)
15505
15506 return H
15507} 14701}
15508 14702
15509module.exports = Sha384 14703// (public) this & a
15510 14704function op_and(x, y) {
15511}).call(this,require("buffer").Buffer) 14705 return x & y
15512},{"./hash":37,"./sha512":44,"buffer":7,"inherits":35}],44:[function(require,module,exports){
15513(function (Buffer){
15514var inherits = require('inherits')
15515var Hash = require('./hash')
15516
15517var K = [
15518 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
15519 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
15520 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
15521 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
15522 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
15523 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
15524 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
15525 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
15526 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
15527 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
15528 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
15529 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
15530 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
15531 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
15532 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
15533 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
15534 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
15535 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
15536 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
15537 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
15538 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
15539 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
15540 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
15541 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
15542 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
15543 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
15544 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
15545 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
15546 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
15547 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
15548 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
15549 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
15550 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
15551 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
15552 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
15553 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
15554 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
15555 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
15556 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
15557 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
15558]
15559
15560var W = new Array(160)
15561
15562function Sha512 () {
15563 this.init()
15564 this._w = W
15565
15566 Hash.call(this, 128, 112)
15567} 14706}
15568 14707
15569inherits(Sha512, Hash) 14708function bnAnd(a) {
15570 14709 var r = new BigInteger()
15571Sha512.prototype.init = function () { 14710 this.bitwiseTo(a, op_and, r)
15572 this._a = 0x6a09e667 | 0 14711 return r
15573 this._b = 0xbb67ae85 | 0
15574 this._c = 0x3c6ef372 | 0
15575 this._d = 0xa54ff53a | 0
15576 this._e = 0x510e527f | 0
15577 this._f = 0x9b05688c | 0
15578 this._g = 0x1f83d9ab | 0
15579 this._h = 0x5be0cd19 | 0
15580
15581 this._al = 0xf3bcc908 | 0
15582 this._bl = 0x84caa73b | 0
15583 this._cl = 0xfe94f82b | 0
15584 this._dl = 0x5f1d36f1 | 0
15585 this._el = 0xade682d1 | 0
15586 this._fl = 0x2b3e6c1f | 0
15587 this._gl = 0xfb41bd6b | 0
15588 this._hl = 0x137e2179 | 0
15589
15590 return this
15591} 14712}
15592 14713
15593function S (X, Xl, n) { 14714// (public) this | a
15594 return (X >>> n) | (Xl << (32 - n)) 14715function op_or(x, y) {
14716 return x | y
15595} 14717}
15596 14718
15597function Ch (x, y, z) { 14719function bnOr(a) {
15598 return ((x & y) ^ ((~x) & z)) 14720 var r = new BigInteger()
14721 this.bitwiseTo(a, op_or, r)
14722 return r
15599} 14723}
15600 14724
15601function Maj (x, y, z) { 14725// (public) this ^ a
15602 return ((x & y) ^ (x & z) ^ (y & z)) 14726function op_xor(x, y) {
14727 return x ^ y
15603} 14728}
15604 14729
15605Sha512.prototype._update = function (M) { 14730function bnXor(a) {
15606 var W = this._w 14731 var r = new BigInteger()
15607 14732 this.bitwiseTo(a, op_xor, r)
15608 var a = this._a | 0 14733 return r
15609 var b = this._b | 0 14734}
15610 var c = this._c | 0
15611 var d = this._d | 0
15612 var e = this._e | 0
15613 var f = this._f | 0
15614 var g = this._g | 0
15615 var h = this._h | 0
15616 14735
15617 var al = this._al | 0 14736// (public) this & ~a
15618 var bl = this._bl | 0 14737function op_andnot(x, y) {
15619 var cl = this._cl | 0 14738 return x & ~y
15620 var dl = this._dl | 0 14739}
15621 var el = this._el | 0
15622 var fl = this._fl | 0
15623 var gl = this._gl | 0
15624 var hl = this._hl | 0
15625 14740
15626 var i = 0, j = 0 14741function bnAndNot(a) {
15627 var Wi, Wil 14742 var r = new BigInteger()
15628 function calcW () { 14743 this.bitwiseTo(a, op_andnot, r)
15629 var x = W[j - 15 * 2] 14744 return r
15630 var xl = W[j - 15 * 2 + 1] 14745}
15631 var gamma0 = S(x, xl, 1) ^ S(x, xl, 8) ^ (x >>> 7)
15632 var gamma0l = S(xl, x, 1) ^ S(xl, x, 8) ^ S(xl, x, 7)
15633 14746
15634 x = W[j - 2 * 2] 14747// (public) ~this
15635 xl = W[j - 2 * 2 + 1] 14748function bnNot() {
15636 var gamma1 = S(x, xl, 19) ^ S(xl, x, 29) ^ (x >>> 6) 14749 var r = new BigInteger()
15637 var gamma1l = S(xl, x, 19) ^ S(x, xl, 29) ^ S(xl, x, 6) 14750 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
14751 r.t = this.t
14752 r.s = ~this.s
14753 return r
14754}
15638 14755
15639 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] 14756// (public) this << n
15640 var Wi7 = W[j - 7 * 2] 14757function bnShiftLeft(n) {
15641 var Wi7l = W[j - 7 * 2 + 1] 14758 var r = new BigInteger()
14759 if (n < 0) this.rShiftTo(-n, r)
14760 else this.lShiftTo(n, r)
14761 return r
14762}
15642 14763
15643 var Wi16 = W[j - 16 * 2] 14764// (public) this >> n
15644 var Wi16l = W[j - 16 * 2 + 1] 14765function bnShiftRight(n) {
14766 var r = new BigInteger()
14767 if (n < 0) this.lShiftTo(-n, r)
14768 else this.rShiftTo(n, r)
14769 return r
14770}
15645 14771
15646 Wil = gamma0l + Wi7l 14772// return index of lowest 1-bit in x, x < 2^31
15647 Wi = gamma0 + Wi7 + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0) 14773function lbit(x) {
15648 Wil = Wil + gamma1l 14774 if (x == 0) return -1
15649 Wi = Wi + gamma1 + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0) 14775 var r = 0
15650 Wil = Wil + Wi16l 14776 if ((x & 0xffff) == 0) {
15651 Wi = Wi + Wi16 + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0) 14777 x >>= 16
14778 r += 16
15652 } 14779 }
15653 14780 if ((x & 0xff) == 0) {
15654 function loop () { 14781 x >>= 8
15655 W[j] = Wi 14782 r += 8
15656 W[j + 1] = Wil
15657
15658 var maj = Maj(a, b, c)
15659 var majl = Maj(al, bl, cl)
15660
15661 var sigma0h = S(a, al, 28) ^ S(al, a, 2) ^ S(al, a, 7)
15662 var sigma0l = S(al, a, 28) ^ S(a, al, 2) ^ S(a, al, 7)
15663 var sigma1h = S(e, el, 14) ^ S(e, el, 18) ^ S(el, e, 9)
15664 var sigma1l = S(el, e, 14) ^ S(el, e, 18) ^ S(e, el, 9)
15665
15666 // t1 = h + sigma1 + ch + K[i] + W[i]
15667 var Ki = K[j]
15668 var Kil = K[j + 1]
15669
15670 var ch = Ch(e, f, g)
15671 var chl = Ch(el, fl, gl)
15672
15673 var t1l = hl + sigma1l
15674 var t1 = h + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0)
15675 t1l = t1l + chl
15676 t1 = t1 + ch + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0)
15677 t1l = t1l + Kil
15678 t1 = t1 + Ki + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0)
15679 t1l = t1l + Wil
15680 t1 = t1 + Wi + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0)
15681
15682 // t2 = sigma0 + maj
15683 var t2l = sigma0l + majl
15684 var t2 = sigma0h + maj + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0)
15685
15686 h = g
15687 hl = gl
15688 g = f
15689 gl = fl
15690 f = e
15691 fl = el
15692 el = (dl + t1l) | 0
15693 e = (d + t1 + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
15694 d = c
15695 dl = cl
15696 c = b
15697 cl = bl
15698 b = a
15699 bl = al
15700 al = (t1l + t2l) | 0
15701 a = (t1 + t2 + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0
15702
15703 i++
15704 j += 2
15705 } 14783 }
15706 14784 if ((x & 0xf) == 0) {
15707 while (i < 16) { 14785 x >>= 4
15708 Wi = M.readInt32BE(j * 4) 14786 r += 4
15709 Wil = M.readInt32BE(j * 4 + 4)
15710
15711 loop()
15712 } 14787 }
15713 14788 if ((x & 3) == 0) {
15714 while (i < 80) { 14789 x >>= 2
15715 calcW() 14790 r += 2
15716 loop()
15717 } 14791 }
15718 14792 if ((x & 1) == 0)++r
15719 this._al = (this._al + al) | 0 14793 return r
15720 this._bl = (this._bl + bl) | 0
15721 this._cl = (this._cl + cl) | 0
15722 this._dl = (this._dl + dl) | 0
15723 this._el = (this._el + el) | 0
15724 this._fl = (this._fl + fl) | 0
15725 this._gl = (this._gl + gl) | 0
15726 this._hl = (this._hl + hl) | 0
15727
15728 this._a = (this._a + a + ((this._al >>> 0) < (al >>> 0) ? 1 : 0)) | 0
15729 this._b = (this._b + b + ((this._bl >>> 0) < (bl >>> 0) ? 1 : 0)) | 0
15730 this._c = (this._c + c + ((this._cl >>> 0) < (cl >>> 0) ? 1 : 0)) | 0
15731 this._d = (this._d + d + ((this._dl >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
15732 this._e = (this._e + e + ((this._el >>> 0) < (el >>> 0) ? 1 : 0)) | 0
15733 this._f = (this._f + f + ((this._fl >>> 0) < (fl >>> 0) ? 1 : 0)) | 0
15734 this._g = (this._g + g + ((this._gl >>> 0) < (gl >>> 0) ? 1 : 0)) | 0
15735 this._h = (this._h + h + ((this._hl >>> 0) < (hl >>> 0) ? 1 : 0)) | 0
15736} 14794}
15737 14795
15738Sha512.prototype._hash = function () { 14796// (public) returns index of lowest 1-bit (or -1 if none)
15739 var H = new Buffer(64) 14797function bnGetLowestSetBit() {
14798 for (var i = 0; i < this.t; ++i)
14799 if (this[i] != 0) return i * this.DB + lbit(this[i])
14800 if (this.s < 0) return this.t * this.DB
14801 return -1
14802}
15740 14803
15741 function writeInt64BE (h, l, offset) { 14804// return number of 1 bits in x
15742 H.writeInt32BE(h, offset) 14805function cbit(x) {
15743 H.writeInt32BE(l, offset + 4) 14806 var r = 0
14807 while (x != 0) {
14808 x &= x - 1
14809 ++r
15744 } 14810 }
15745 14811 return r
15746 writeInt64BE(this._a, this._al, 0)
15747 writeInt64BE(this._b, this._bl, 8)
15748 writeInt64BE(this._c, this._cl, 16)
15749 writeInt64BE(this._d, this._dl, 24)
15750 writeInt64BE(this._e, this._el, 32)
15751 writeInt64BE(this._f, this._fl, 40)
15752 writeInt64BE(this._g, this._gl, 48)
15753 writeInt64BE(this._h, this._hl, 56)
15754
15755 return H
15756} 14812}
15757 14813
15758module.exports = Sha512 14814// (public) return number of set bits
15759 14815function bnBitCount() {
15760}).call(this,require("buffer").Buffer) 14816 var r = 0,
15761},{"./hash":37,"buffer":7,"inherits":35}],45:[function(require,module,exports){ 14817 x = this.s & this.DM
15762(function (Buffer){ 14818 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
15763'use strict'; 14819 return r
15764var createHash = require('create-hash/browser'); 14820}
15765var inherits = require('inherits')
15766
15767var Transform = require('stream').Transform
15768 14821
15769var ZEROS = new Buffer(128) 14822// (public) true iff nth bit is set
15770ZEROS.fill(0) 14823function bnTestBit(n) {
14824 var j = Math.floor(n / this.DB)
14825 if (j >= this.t) return (this.s != 0)
14826 return ((this[j] & (1 << (n % this.DB))) != 0)
14827}
15771 14828
15772function Hmac(alg, key) { 14829// (protected) this op (1<<n)
15773 Transform.call(this) 14830function bnpChangeBit(n, op) {
14831 var r = BigInteger.ONE.shiftLeft(n)
14832 this.bitwiseTo(r, op, r)
14833 return r
14834}
15774 14835
15775 if (typeof key === 'string') { 14836// (public) this | (1<<n)
15776 key = new Buffer(key) 14837function bnSetBit(n) {
15777 } 14838 return this.changeBit(n, op_or)
14839}
15778 14840
15779 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 14841// (public) this & ~(1<<n)
14842function bnClearBit(n) {
14843 return this.changeBit(n, op_andnot)
14844}
15780 14845
15781 this._alg = alg 14846// (public) this ^ (1<<n)
15782 this._key = key 14847function bnFlipBit(n) {
14848 return this.changeBit(n, op_xor)
14849}
15783 14850
15784 if (key.length > blocksize) { 14851// (protected) r = this + a
15785 key = createHash(alg).update(key).digest() 14852function bnpAddTo(a, r) {
14853 var self = this
15786 14854
15787 } else if (key.length < blocksize) { 14855 var i = 0,
15788 key = Buffer.concat([key, ZEROS], blocksize) 14856 c = 0,
14857 m = Math.min(a.t, self.t)
14858 while (i < m) {
14859 c += self[i] + a[i]
14860 r[i++] = c & self.DM
14861 c >>= self.DB
15789 } 14862 }
15790 14863 if (a.t < self.t) {
15791 var ipad = this._ipad = new Buffer(blocksize) 14864 c += a.s
15792 var opad = this._opad = new Buffer(blocksize) 14865 while (i < self.t) {
15793 14866 c += self[i]
15794 for (var i = 0; i < blocksize; i++) { 14867 r[i++] = c & self.DM
15795 ipad[i] = key[i] ^ 0x36 14868 c >>= self.DB
15796 opad[i] = key[i] ^ 0x5C 14869 }
14870 c += self.s
14871 } else {
14872 c += self.s
14873 while (i < a.t) {
14874 c += a[i]
14875 r[i++] = c & self.DM
14876 c >>= self.DB
14877 }
14878 c += a.s
15797 } 14879 }
15798 14880 r.s = (c < 0) ? -1 : 0
15799 this._hash = createHash(alg).update(ipad) 14881 if (c > 0) r[i++] = c
14882 else if (c < -1) r[i++] = self.DV + c
14883 r.t = i
14884 r.clamp()
15800} 14885}
15801 14886
15802inherits(Hmac, Transform) 14887// (public) this + a
15803 14888function bnAdd(a) {
15804Hmac.prototype.update = function (data, enc) { 14889 var r = new BigInteger()
15805 this._hash.update(data, enc) 14890 this.addTo(a, r)
15806 14891 return r
15807 return this
15808} 14892}
15809 14893
15810Hmac.prototype._transform = function (data, _, next) { 14894// (public) this - a
15811 this._hash.update(data) 14895function bnSubtract(a) {
15812 14896 var r = new BigInteger()
15813 next() 14897 this.subTo(a, r)
14898 return r
15814} 14899}
15815 14900
15816Hmac.prototype._flush = function (next) { 14901// (public) this * a
15817 this.push(this.digest()) 14902function bnMultiply(a) {
15818 14903 var r = new BigInteger()
15819 next() 14904 this.multiplyTo(a, r)
14905 return r
15820} 14906}
15821 14907
15822Hmac.prototype.digest = function (enc) { 14908// (public) this^2
15823 var h = this._hash.digest() 14909function bnSquare() {
15824 14910 var r = new BigInteger()
15825 return createHash(this._alg).update(this._opad).update(h).digest(enc) 14911 this.squareTo(r)
14912 return r
15826} 14913}
15827 14914
15828module.exports = function createHmac(alg, key) { 14915// (public) this / a
15829 return new Hmac(alg, key) 14916function bnDivide(a) {
14917 var r = new BigInteger()
14918 this.divRemTo(a, r, null)
14919 return r
15830} 14920}
15831 14921
15832}).call(this,require("buffer").Buffer) 14922// (public) this % a
15833},{"buffer":7,"create-hash/browser":32,"inherits":46,"stream":26}],46:[function(require,module,exports){ 14923function bnRemainder(a) {
15834arguments[4][12][0].apply(exports,arguments) 14924 var r = new BigInteger()
15835},{"dup":12}],47:[function(require,module,exports){ 14925 this.divRemTo(a, null, r)
15836var assert = require('assert') 14926 return r
15837var BigInteger = require('bigi') 14927}
15838
15839var Point = require('./point')
15840
15841function Curve(p, a, b, Gx, Gy, n, h) {
15842 this.p = p
15843 this.a = a
15844 this.b = b
15845 this.G = Point.fromAffine(this, Gx, Gy)
15846 this.n = n
15847 this.h = h
15848
15849 this.infinity = new Point(this, null, null, BigInteger.ZERO)
15850 14928
15851 // result caching 14929// (public) [this/a,this%a]
15852 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2) 14930function bnDivideAndRemainder(a) {
14931 var q = new BigInteger(),
14932 r = new BigInteger()
14933 this.divRemTo(a, q, r)
14934 return new Array(q, r)
15853} 14935}
15854 14936
15855Curve.prototype.pointFromX = function(isOdd, x) { 14937// (protected) this *= n, this >= 0, 1 < n < DV
15856 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p) 14938function bnpDMultiply(n) {
15857 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves 14939 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
14940 ++this.t
14941 this.clamp()
14942}
15858 14943
15859 var y = beta 14944// (protected) this += n << w words, this >= 0
15860 if (beta.isEven() ^ !isOdd) { 14945function bnpDAddOffset(n, w) {
15861 y = this.p.subtract(y) // -y % p 14946 if (n == 0) return
14947 while (this.t <= w) this[this.t++] = 0
14948 this[w] += n
14949 while (this[w] >= this.DV) {
14950 this[w] -= this.DV
14951 if (++w >= this.t) this[this.t++] = 0
14952 ++this[w]
15862 } 14953 }
15863
15864 return Point.fromAffine(this, x, y)
15865} 14954}
15866 14955
15867Curve.prototype.isInfinity = function(Q) { 14956// A "null" reducer
15868 if (Q === this.infinity) return true 14957function NullExp() {}
15869 14958
15870 return Q.z.signum() === 0 && Q.y.signum() !== 0 14959function nNop(x) {
14960 return x
15871} 14961}
15872 14962
15873Curve.prototype.isOnCurve = function(Q) { 14963function nMulTo(x, y, r) {
15874 if (this.isInfinity(Q)) return true 14964 x.multiplyTo(y, r)
15875
15876 var x = Q.affineX
15877 var y = Q.affineY
15878 var a = this.a
15879 var b = this.b
15880 var p = this.p
15881
15882 // Check that xQ and yQ are integers in the interval [0, p - 1]
15883 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
15884 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
15885
15886 // and check that y^2 = x^3 + ax + b (mod p)
15887 var lhs = y.square().mod(p)
15888 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
15889 return lhs.equals(rhs)
15890} 14965}
15891 14966
15892/** 14967function nSqrTo(x, r) {
15893 * Validate an elliptic curve point. 14968 x.squareTo(r)
15894 *
15895 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
15896 */
15897Curve.prototype.validate = function(Q) {
15898 // Check Q != O
15899 assert(!this.isInfinity(Q), 'Point is at infinity')
15900 assert(this.isOnCurve(Q), 'Point is not on the curve')
15901
15902 // Check nQ = O (where Q is a scalar multiple of G)
15903 var nQ = Q.multiply(this.n)
15904 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
15905
15906 return true
15907} 14969}
15908 14970
15909module.exports = Curve 14971NullExp.prototype.convert = nNop
14972NullExp.prototype.revert = nNop
14973NullExp.prototype.mulTo = nMulTo
14974NullExp.prototype.sqrTo = nSqrTo
15910 14975
15911},{"./point":51,"assert":5,"bigi":3}],48:[function(require,module,exports){ 14976// (public) this^e
15912module.exports={ 14977function bnPow(e) {
15913 "secp128r1": { 14978 return this.exp(e, new NullExp())
15914 "p": "fffffffdffffffffffffffffffffffff",
15915 "a": "fffffffdfffffffffffffffffffffffc",
15916 "b": "e87579c11079f43dd824993c2cee5ed3",
15917 "n": "fffffffe0000000075a30d1b9038a115",
15918 "h": "01",
15919 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
15920 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
15921 },
15922 "secp160k1": {
15923 "p": "fffffffffffffffffffffffffffffffeffffac73",
15924 "a": "00",
15925 "b": "07",
15926 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
15927 "h": "01",
15928 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
15929 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
15930 },
15931 "secp160r1": {
15932 "p": "ffffffffffffffffffffffffffffffff7fffffff",
15933 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
15934 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
15935 "n": "0100000000000000000001f4c8f927aed3ca752257",
15936 "h": "01",
15937 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
15938 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
15939 },
15940 "secp192k1": {
15941 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
15942 "a": "00",
15943 "b": "03",
15944 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
15945 "h": "01",
15946 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
15947 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
15948 },
15949 "secp192r1": {
15950 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
15951 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
15952 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
15953 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
15954 "h": "01",
15955 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
15956 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
15957 },
15958 "secp256k1": {
15959 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
15960 "a": "00",
15961 "b": "07",
15962 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
15963 "h": "01",
15964 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
15965 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
15966 },
15967 "secp256r1": {
15968 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
15969 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
15970 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
15971 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
15972 "h": "01",
15973 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
15974 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
15975 }
15976} 14979}
15977 14980
15978},{}],49:[function(require,module,exports){ 14981// (protected) r = lower n words of "this * a", a.t <= n
15979var Point = require('./point') 14982// "this" should be the larger one if appropriate.
15980var Curve = require('./curve') 14983function bnpMultiplyLowerTo(a, n, r) {
15981 14984 var i = Math.min(this.t + a.t, n)
15982var getCurveByName = require('./names') 14985 r.s = 0; // assumes a,this >= 0
15983 14986 r.t = i
15984module.exports = { 14987 while (i > 0) r[--i] = 0
15985 Curve: Curve, 14988 var j
15986 Point: Point, 14989 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
15987 getCurveByName: getCurveByName 14990 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
14991 r.clamp()
15988} 14992}
15989 14993
15990},{"./curve":47,"./names":50,"./point":51}],50:[function(require,module,exports){ 14994// (protected) r = "this * a" without lower n words, n > 0
15991var BigInteger = require('bigi') 14995// "this" should be the larger one if appropriate.
15992 14996function bnpMultiplyUpperTo(a, n, r) {
15993var curves = require('./curves') 14997 --n
15994var Curve = require('./curve') 14998 var i = r.t = this.t + a.t - n
15995 14999 r.s = 0; // assumes a,this >= 0
15996function getCurveByName(name) { 15000 while (--i >= 0) r[i] = 0
15997 var curve = curves[name] 15001 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
15998 if (!curve) return null 15002 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
15999 15003 r.clamp()
16000 var p = new BigInteger(curve.p, 16) 15004 r.drShiftTo(1, r)
16001 var a = new BigInteger(curve.a, 16)
16002 var b = new BigInteger(curve.b, 16)
16003 var n = new BigInteger(curve.n, 16)
16004 var h = new BigInteger(curve.h, 16)
16005 var Gx = new BigInteger(curve.Gx, 16)
16006 var Gy = new BigInteger(curve.Gy, 16)
16007
16008 return new Curve(p, a, b, Gx, Gy, n, h)
16009} 15005}
16010 15006
16011module.exports = getCurveByName 15007// Barrett modular reduction
16012 15008function Barrett(m) {
16013},{"./curve":47,"./curves":48,"bigi":3}],51:[function(require,module,exports){ 15009 // setup Barrett
16014(function (Buffer){ 15010 this.r2 = new BigInteger()
16015var assert = require('assert') 15011 this.q3 = new BigInteger()
16016var BigInteger = require('bigi') 15012 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
16017 15013 this.mu = this.r2.divide(m)
16018var THREE = BigInteger.valueOf(3) 15014 this.m = m
16019
16020function Point(curve, x, y, z) {
16021 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
16022
16023 this.curve = curve
16024 this.x = x
16025 this.y = y
16026 this.z = z
16027 this._zInv = null
16028
16029 this.compressed = true
16030} 15015}
16031 15016
16032Object.defineProperty(Point.prototype, 'zInv', { 15017function barrettConvert(x) {
16033 get: function() { 15018 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
16034 if (this._zInv === null) { 15019 else if (x.compareTo(this.m) < 0) return x
16035 this._zInv = this.z.modInverse(this.curve.p) 15020 else {
16036 } 15021 var r = new BigInteger()
16037 15022 x.copyTo(r)
16038 return this._zInv 15023 this.reduce(r)
15024 return r
16039 } 15025 }
16040}) 15026}
16041 15027
16042Object.defineProperty(Point.prototype, 'affineX', { 15028function barrettRevert(x) {
16043 get: function() { 15029 return x
16044 return this.x.multiply(this.zInv).mod(this.curve.p) 15030}
16045 }
16046})
16047 15031
16048Object.defineProperty(Point.prototype, 'affineY', { 15032// x = x mod m (HAC 14.42)
16049 get: function() { 15033function barrettReduce(x) {
16050 return this.y.multiply(this.zInv).mod(this.curve.p) 15034 var self = this
15035 x.drShiftTo(self.m.t - 1, self.r2)
15036 if (x.t > self.m.t + 1) {
15037 x.t = self.m.t + 1
15038 x.clamp()
16051 } 15039 }
16052}) 15040 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
16053 15041 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
16054Point.fromAffine = function(curve, x, y) { 15042 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
16055 return new Point(curve, x, y, BigInteger.ONE) 15043 x.subTo(self.r2, x)
15044 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
16056} 15045}
16057 15046
16058Point.prototype.equals = function(other) { 15047// r = x^2 mod m; x != r
16059 if (other === this) return true 15048function barrettSqrTo(x, r) {
16060 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other) 15049 x.squareTo(r)
16061 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this) 15050 this.reduce(r)
16062
16063 // u = Y2 * Z1 - Y1 * Z2
16064 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
16065
16066 if (u.signum() !== 0) return false
16067
16068 // v = X2 * Z1 - X1 * Z2
16069 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
16070
16071 return v.signum() === 0
16072} 15051}
16073 15052
16074Point.prototype.negate = function() { 15053// r = x*y mod m; x,y != r
16075 var y = this.curve.p.subtract(this.y) 15054function barrettMulTo(x, y, r) {
16076 15055 x.multiplyTo(y, r)
16077 return new Point(this.curve, this.x, y, this.z) 15056 this.reduce(r)
16078} 15057}
16079 15058
16080Point.prototype.add = function(b) { 15059Barrett.prototype.convert = barrettConvert
16081 if (this.curve.isInfinity(this)) return b 15060Barrett.prototype.revert = barrettRevert
16082 if (this.curve.isInfinity(b)) return this 15061Barrett.prototype.reduce = barrettReduce
16083 15062Barrett.prototype.mulTo = barrettMulTo
16084 var x1 = this.x 15063Barrett.prototype.sqrTo = barrettSqrTo
16085 var y1 = this.y
16086 var x2 = b.x
16087 var y2 = b.y
16088 15064
16089 // u = Y2 * Z1 - Y1 * Z2 15065// (public) this^e % m (HAC 14.85)
16090 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p) 15066function bnModPow(e, m) {
16091 // v = X2 * Z1 - X1 * Z2 15067 var i = e.bitLength(),
16092 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p) 15068 k, r = nbv(1),
15069 z
15070 if (i <= 0) return r
15071 else if (i < 18) k = 1
15072 else if (i < 48) k = 3
15073 else if (i < 144) k = 4
15074 else if (i < 768) k = 5
15075 else k = 6
15076 if (i < 8)
15077 z = new Classic(m)
15078 else if (m.isEven())
15079 z = new Barrett(m)
15080 else
15081 z = new Montgomery(m)
16093 15082
16094 if (v.signum() === 0) { 15083 // precomputation
16095 if (u.signum() === 0) { 15084 var g = new Array(),
16096 return this.twice() // this == b, so double 15085 n = 3,
15086 k1 = k - 1,
15087 km = (1 << k) - 1
15088 g[1] = z.convert(this)
15089 if (k > 1) {
15090 var g2 = new BigInteger()
15091 z.sqrTo(g[1], g2)
15092 while (n <= km) {
15093 g[n] = new BigInteger()
15094 z.mulTo(g2, g[n - 2], g[n])
15095 n += 2
16097 } 15096 }
16098
16099 return this.curve.infinity // this = -b, so infinity
16100 } 15097 }
16101 15098
16102 var v2 = v.square() 15099 var j = e.t - 1,
16103 var v3 = v2.multiply(v) 15100 w, is1 = true,
16104 var x1v2 = x1.multiply(v2) 15101 r2 = new BigInteger(),
16105 var zu2 = u.square().multiply(this.z) 15102 t
15103 i = nbits(e[j]) - 1
15104 while (j >= 0) {
15105 if (i >= k1) w = (e[j] >> (i - k1)) & km
15106 else {
15107 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
15108 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
15109 }
16106 15110
16107 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) 15111 n = k
16108 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p) 15112 while ((w & 1) == 0) {
16109 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 15113 w >>= 1
16110 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) 15114 --n
16111 // z3 = v^3 * z1 * z2 15115 }
16112 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p) 15116 if ((i -= n) < 0) {
15117 i += this.DB
15118 --j
15119 }
15120 if (is1) { // ret == 1, don't bother squaring or multiplying it
15121 g[w].copyTo(r)
15122 is1 = false
15123 } else {
15124 while (n > 1) {
15125 z.sqrTo(r, r2)
15126 z.sqrTo(r2, r)
15127 n -= 2
15128 }
15129 if (n > 0) z.sqrTo(r, r2)
15130 else {
15131 t = r
15132 r = r2
15133 r2 = t
15134 }
15135 z.mulTo(r2, g[w], r)
15136 }
16113 15137
16114 return new Point(this.curve, x3, y3, z3) 15138 while (j >= 0 && (e[j] & (1 << i)) == 0) {
15139 z.sqrTo(r, r2)
15140 t = r
15141 r = r2
15142 r2 = t
15143 if (--i < 0) {
15144 i = this.DB - 1
15145 --j
15146 }
15147 }
15148 }
15149 return z.revert(r)
16115} 15150}
16116 15151
16117Point.prototype.twice = function() { 15152// (public) gcd(this,a) (HAC 14.54)
16118 if (this.curve.isInfinity(this)) return this 15153function bnGCD(a) {
16119 if (this.y.signum() === 0) return this.curve.infinity 15154 var x = (this.s < 0) ? this.negate() : this.clone()
16120 15155 var y = (a.s < 0) ? a.negate() : a.clone()
16121 var x1 = this.x 15156 if (x.compareTo(y) < 0) {
16122 var y1 = this.y 15157 var t = x
16123 15158 x = y
16124 var y1z1 = y1.multiply(this.z) 15159 y = t
16125 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
16126 var a = this.curve.a
16127
16128 // w = 3 * x1^2 + a * z1^2
16129 var w = x1.square().multiply(THREE)
16130
16131 if (a.signum() !== 0) {
16132 w = w.add(this.z.square().multiply(a))
16133 } 15160 }
16134 15161 var i = x.getLowestSetBit(),
16135 w = w.mod(this.curve.p) 15162 g = y.getLowestSetBit()
16136 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) 15163 if (g < 0) return x
16137 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p) 15164 if (i < g) g = i
16138 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 15165 if (g > 0) {
16139 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p) 15166 x.rShiftTo(g, x)
16140 // z3 = 8 * (y1 * z1)^3 15167 y.rShiftTo(g, y)
16141 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p) 15168 }
16142 15169 while (x.signum() > 0) {
16143 return new Point(this.curve, x3, y3, z3) 15170 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
15171 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
15172 if (x.compareTo(y) >= 0) {
15173 x.subTo(y, x)
15174 x.rShiftTo(1, x)
15175 } else {
15176 y.subTo(x, y)
15177 y.rShiftTo(1, y)
15178 }
15179 }
15180 if (g > 0) y.lShiftTo(g, y)
15181 return y
16144} 15182}
16145 15183
16146// Simple NAF (Non-Adjacent Form) multiplication algorithm 15184// (protected) this % n, n < 2^26
16147// TODO: modularize the multiplication algorithm 15185function bnpModInt(n) {
16148Point.prototype.multiply = function(k) { 15186 if (n <= 0) return 0
16149 if (this.curve.isInfinity(this)) return this 15187 var d = this.DV % n,
16150 if (k.signum() === 0) return this.curve.infinity 15188 r = (this.s < 0) ? n - 1 : 0
16151 15189 if (this.t > 0)
16152 var e = k 15190 if (d == 0) r = this[0] % n
16153 var h = e.multiply(THREE) 15191 else
16154 15192 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
16155 var neg = this.negate() 15193 return r
16156 var R = this 15194}
16157
16158 for (var i = h.bitLength() - 2; i > 0; --i) {
16159 R = R.twice()
16160
16161 var hBit = h.testBit(i)
16162 var eBit = e.testBit(i)
16163 15195
16164 if (hBit != eBit) { 15196// (public) 1/this % m (HAC 14.61)
16165 R = R.add(hBit ? this : neg) 15197function bnModInverse(m) {
15198 var ac = m.isEven()
15199 if (this.signum() === 0) throw new Error('division by zero')
15200 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO
15201 var u = m.clone(),
15202 v = this.clone()
15203 var a = nbv(1),
15204 b = nbv(0),
15205 c = nbv(0),
15206 d = nbv(1)
15207 while (u.signum() != 0) {
15208 while (u.isEven()) {
15209 u.rShiftTo(1, u)
15210 if (ac) {
15211 if (!a.isEven() || !b.isEven()) {
15212 a.addTo(this, a)
15213 b.subTo(m, b)
15214 }
15215 a.rShiftTo(1, a)
15216 } else if (!b.isEven()) b.subTo(m, b)
15217 b.rShiftTo(1, b)
15218 }
15219 while (v.isEven()) {
15220 v.rShiftTo(1, v)
15221 if (ac) {
15222 if (!c.isEven() || !d.isEven()) {
15223 c.addTo(this, c)
15224 d.subTo(m, d)
15225 }
15226 c.rShiftTo(1, c)
15227 } else if (!d.isEven()) d.subTo(m, d)
15228 d.rShiftTo(1, d)
15229 }
15230 if (u.compareTo(v) >= 0) {
15231 u.subTo(v, u)
15232 if (ac) a.subTo(c, a)
15233 b.subTo(d, b)
15234 } else {
15235 v.subTo(u, v)
15236 if (ac) c.subTo(a, c)
15237 d.subTo(b, d)
16166 } 15238 }
16167 } 15239 }
16168 15240 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
16169 return R 15241 while (d.compareTo(m) >= 0) d.subTo(m, d)
15242 while (d.signum() < 0) d.addTo(m, d)
15243 return d
16170} 15244}
16171 15245
16172// Compute this*j + x*k (simultaneous multiplication) 15246var lowprimes = [
16173Point.prototype.multiplyTwo = function(j, x, k) { 15247 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
16174 var i 15248 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
16175 15249 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
16176 if (j.bitLength() > k.bitLength()) 15250 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
16177 i = j.bitLength() - 1 15251 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
16178 else 15252 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
16179 i = k.bitLength() - 1 15253 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
16180 15254 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
16181 var R = this.curve.infinity 15255 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
16182 var both = this.add(x) 15256 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
16183 15257 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
16184 while (i >= 0) { 15258]
16185 R = R.twice()
16186
16187 var jBit = j.testBit(i)
16188 var kBit = k.testBit(i)
16189 15259
16190 if (jBit) { 15260var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
16191 if (kBit) {
16192 R = R.add(both)
16193 15261
16194 } else { 15262// (public) test primality with certainty >= 1-.5^t
16195 R = R.add(this) 15263function bnIsProbablePrime(t) {
16196 } 15264 var i, x = this.abs()
15265 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
15266 for (i = 0; i < lowprimes.length; ++i)
15267 if (x[0] == lowprimes[i]) return true
15268 return false
15269 }
15270 if (x.isEven()) return false
15271 i = 1
15272 while (i < lowprimes.length) {
15273 var m = lowprimes[i],
15274 j = i + 1
15275 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
15276 m = x.modInt(m)
15277 while (i < j) if (m % lowprimes[i++] == 0) return false
15278 }
15279 return x.millerRabin(t)
15280}
16197 15281
16198 } else { 15282// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
16199 if (kBit) { 15283function bnpMillerRabin(t) {
16200 R = R.add(x) 15284 var n1 = this.subtract(BigInteger.ONE)
15285 var k = n1.getLowestSetBit()
15286 if (k <= 0) return false
15287 var r = n1.shiftRight(k)
15288 t = (t + 1) >> 1
15289 if (t > lowprimes.length) t = lowprimes.length
15290 var a = new BigInteger(null)
15291 var j, bases = []
15292 for (var i = 0; i < t; ++i) {
15293 for (;;) {
15294 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
15295 if (bases.indexOf(j) == -1) break
15296 }
15297 bases.push(j)
15298 a.fromInt(j)
15299 var y = a.modPow(r, this)
15300 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
15301 var j = 1
15302 while (j++ < k && y.compareTo(n1) != 0) {
15303 y = y.modPowInt(2, this)
15304 if (y.compareTo(BigInteger.ONE) == 0) return false
16201 } 15305 }
15306 if (y.compareTo(n1) != 0) return false
16202 } 15307 }
16203 --i
16204 } 15308 }
16205 15309 return true
16206 return R
16207} 15310}
16208 15311
16209Point.prototype.getEncoded = function(compressed) { 15312// protected
16210 if (compressed == undefined) compressed = this.compressed 15313proto.chunkSize = bnpChunkSize
16211 if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00' 15314proto.toRadix = bnpToRadix
15315proto.fromRadix = bnpFromRadix
15316proto.fromNumber = bnpFromNumber
15317proto.bitwiseTo = bnpBitwiseTo
15318proto.changeBit = bnpChangeBit
15319proto.addTo = bnpAddTo
15320proto.dMultiply = bnpDMultiply
15321proto.dAddOffset = bnpDAddOffset
15322proto.multiplyLowerTo = bnpMultiplyLowerTo
15323proto.multiplyUpperTo = bnpMultiplyUpperTo
15324proto.modInt = bnpModInt
15325proto.millerRabin = bnpMillerRabin
16212 15326
16213 var x = this.affineX 15327// public
16214 var y = this.affineY 15328proto.clone = bnClone
15329proto.intValue = bnIntValue
15330proto.byteValue = bnByteValue
15331proto.shortValue = bnShortValue
15332proto.signum = bnSigNum
15333proto.toByteArray = bnToByteArray
15334proto.equals = bnEquals
15335proto.min = bnMin
15336proto.max = bnMax
15337proto.and = bnAnd
15338proto.or = bnOr
15339proto.xor = bnXor
15340proto.andNot = bnAndNot
15341proto.not = bnNot
15342proto.shiftLeft = bnShiftLeft
15343proto.shiftRight = bnShiftRight
15344proto.getLowestSetBit = bnGetLowestSetBit
15345proto.bitCount = bnBitCount
15346proto.testBit = bnTestBit
15347proto.setBit = bnSetBit
15348proto.clearBit = bnClearBit
15349proto.flipBit = bnFlipBit
15350proto.add = bnAdd
15351proto.subtract = bnSubtract
15352proto.multiply = bnMultiply
15353proto.divide = bnDivide
15354proto.remainder = bnRemainder
15355proto.divideAndRemainder = bnDivideAndRemainder
15356proto.modPow = bnModPow
15357proto.modInverse = bnModInverse
15358proto.pow = bnPow
15359proto.gcd = bnGCD
15360proto.isProbablePrime = bnIsProbablePrime
16215 15361
16216 var buffer 15362// JSBN-specific extension
15363proto.square = bnSquare
16217 15364
16218 // Determine size of q in bytes 15365// constants
16219 var byteLength = Math.floor((this.curve.p.bitLength() + 7) / 8) 15366BigInteger.ZERO = nbv(0)
15367BigInteger.ONE = nbv(1)
15368BigInteger.valueOf = nbv
16220 15369
16221 // 0x02/0x03 | X 15370module.exports = BigInteger
16222 if (compressed) {
16223 buffer = new Buffer(1 + byteLength)
16224 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
16225 15371
16226 // 0x04 | X | Y 15372},{"../package.json":38}],36:[function(require,module,exports){
16227 } else { 15373(function (Buffer){
16228 buffer = new Buffer(1 + byteLength + byteLength) 15374// FIXME: Kind of a weird way to throw exceptions, consider removing
16229 buffer.writeUInt8(0x04, 0) 15375var assert = require('assert')
15376var BigInteger = require('./bigi')
16230 15377
16231 y.toBuffer(byteLength).copy(buffer, 1 + byteLength) 15378/**
15379 * Turns a byte array into a big integer.
15380 *
15381 * This function will interpret a byte array as a big integer in big
15382 * endian notation.
15383 */
15384BigInteger.fromByteArrayUnsigned = function(byteArray) {
15385 // BigInteger expects a DER integer conformant byte array
15386 if (byteArray[0] & 0x80) {
15387 return new BigInteger([0].concat(byteArray))
16232 } 15388 }
16233 15389
16234 x.toBuffer(byteLength).copy(buffer, 1) 15390 return new BigInteger(byteArray)
16235
16236 return buffer
16237} 15391}
16238 15392
16239Point.decodeFrom = function(curve, buffer) { 15393/**
16240 var type = buffer.readUInt8(0) 15394 * Returns a byte array representation of the big integer.
16241 var compressed = (type !== 4) 15395 *
16242 15396 * This returns the absolute of the contained value in big endian
16243 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8) 15397 * form. A value of zero results in an empty array.
16244 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength)) 15398 */
16245 15399BigInteger.prototype.toByteArrayUnsigned = function() {
16246 var Q 15400 var byteArray = this.toByteArray()
16247 if (compressed) { 15401 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
16248 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
16249 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
16250
16251 var isOdd = (type === 0x03)
16252 Q = curve.pointFromX(isOdd, x)
16253
16254 } else {
16255 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
16256
16257 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
16258 Q = Point.fromAffine(curve, x, y)
16259 }
16260
16261 Q.compressed = compressed
16262 return Q
16263} 15402}
16264 15403
16265Point.prototype.toString = function () { 15404BigInteger.fromDERInteger = function(byteArray) {
16266 if (this.curve.isInfinity(this)) return '(INFINITY)' 15405 return new BigInteger(byteArray)
16267
16268 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
16269} 15406}
16270 15407
16271module.exports = Point 15408/*
16272 15409 * Converts BigInteger to a DER integer representation.
16273}).call(this,require("buffer").Buffer) 15410 *
16274},{"assert":5,"bigi":3,"buffer":7}],52:[function(require,module,exports){ 15411 * The format for this value uses the most significant bit as a sign
16275(function (process,global,Buffer){ 15412 * bit. If the most significant bit is already set and the integer is
16276'use strict'; 15413 * positive, a 0x00 is prepended.
15414 *
15415 * Examples:
15416 *
15417 * 0 => 0x00
15418 * 1 => 0x01
15419 * -1 => 0xff
15420 * 127 => 0x7f
15421 * -127 => 0x81
15422 * 128 => 0x0080
15423 * -128 => 0x80
15424 * 255 => 0x00ff
15425 * -255 => 0xff01
15426 * 16300 => 0x3fac
15427 * -16300 => 0xc054
15428 * 62300 => 0x00f35c
15429 * -62300 => 0xff0ca4
15430*/
15431BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
16277 15432
16278var crypto = global.crypto || global.msCrypto 15433BigInteger.fromBuffer = function(buffer) {
16279if(crypto && crypto.getRandomValues) { 15434 // BigInteger expects a DER integer conformant byte array
16280 module.exports = randomBytes; 15435 if (buffer[0] & 0x80) {
16281} else { 15436 var byteArray = Array.prototype.slice.call(buffer)
16282 module.exports = oldBrowser;
16283}
16284function randomBytes(size, cb) {
16285 var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
16286 /* This will not work in older browsers.
16287 * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
16288 */
16289 15437
16290 crypto.getRandomValues(bytes); 15438 return new BigInteger([0].concat(byteArray))
16291 if (typeof cb === 'function') {
16292 return process.nextTick(function () {
16293 cb(null, bytes);
16294 });
16295 } 15439 }
16296 return bytes;
16297}
16298function oldBrowser() {
16299 throw new Error(
16300 'secure random number generation not supported by this browser\n'+
16301 'use chrome, FireFox or Internet Explorer 11'
16302 )
16303}
16304 15440
16305}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) 15441 return new BigInteger(buffer)
16306},{"_process":14,"buffer":7}],53:[function(require,module,exports){
16307(function (Buffer){
16308'use strict';
16309
16310function getFunctionName(fn) {
16311 return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1];
16312} 15442}
16313 15443
16314function getTypeTypeName(type) { 15444BigInteger.fromHex = function(hex) {
16315 if (nativeTypes.Function(type)) { 15445 if (hex === '') return BigInteger.ZERO
16316 type = type.toJSON ? type.toJSON() : getFunctionName(type);
16317 }
16318 if (nativeTypes.Object(type)) return JSON.stringify(type);
16319 15446
16320 return type; 15447 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
15448 assert.equal(hex.length % 2, 0, 'Incomplete hex')
15449 return new BigInteger(hex, 16)
16321} 15450}
16322 15451
16323function getValueTypeName(value) { 15452BigInteger.prototype.toBuffer = function(size) {
16324 if (nativeTypes.Null(value)) return ''; 15453 var byteArray = this.toByteArrayUnsigned()
16325 15454 var zeros = []
16326 return getFunctionName(value.constructor);
16327}
16328 15455
16329function tfErrorString(type, value) { 15456 var padding = size - byteArray.length
16330 var typeTypeName = getTypeTypeName(type); 15457 while (zeros.length < padding) zeros.push(0)
16331 var valueTypeName = getValueTypeName(value);
16332 15458
16333 return 'Expected ' + typeTypeName + ', got ' + (valueTypeName && valueTypeName + ' ') + JSON.stringify(value); 15459 return new Buffer(zeros.concat(byteArray))
16334} 15460}
16335 15461
16336function tfPropertyErrorString(type, name, value) { 15462BigInteger.prototype.toHex = function(size) {
16337 return tfErrorString('property \"' + name + '\" of type ' + getTypeTypeName(type), value); 15463 return this.toBuffer(size).toString('hex')
16338} 15464}
16339 15465
16340var nativeTypes = { 15466}).call(this,require("buffer").Buffer)
16341 Array: (function (_Array) { 15467},{"./bigi":35,"assert":1,"buffer":4}],37:[function(require,module,exports){
16342 function Array(_x) { 15468var BigInteger = require('./bigi')
16343 return _Array.apply(this, arguments);
16344 }
16345 15469
16346 Array.toString = function () { 15470//addons
16347 return _Array.toString(); 15471require('./convert')
16348 };
16349 15472
16350 return Array; 15473module.exports = BigInteger
16351 })(function (value) { 15474},{"./bigi":35,"./convert":36}],38:[function(require,module,exports){
16352 return value !== null && value !== undefined && value.constructor === Array; 15475module.exports={
16353 }), 15476 "_args": [
16354 Boolean: function Boolean(value) { 15477 [
16355 return typeof value === 'boolean'; 15478 "bigi",
15479 "/home/ian/git/bitcoin/bitcoinjs-lib-browser"
15480 ]
15481 ],
15482 "_from": "bigi@latest",
15483 "_id": "bigi@1.4.2",
15484 "_inCache": true,
15485 "_installable": true,
15486 "_location": "/bigi",
15487 "_nodeVersion": "6.1.0",
15488 "_npmOperationalInternal": {
15489 "host": "packages-12-west.internal.npmjs.com",
15490 "tmp": "tmp/bigi-1.4.2.tgz_1469584192413_0.6801238611806184"
16356 }, 15491 },
16357 Buffer: (function (_Buffer) { 15492 "_npmUser": {
16358 function Buffer(_x2) { 15493 "email": "jprichardson@gmail.com",
16359 return _Buffer.apply(this, arguments); 15494 "name": "jprichardson"
16360 }
16361
16362 Buffer.toString = function () {
16363 return _Buffer.toString();
16364 };
16365
16366 return Buffer;
16367 })(function (value) {
16368 return Buffer.isBuffer(value);
16369 }),
16370 Function: function Function(value) {
16371 return typeof value === 'function';
16372 }, 15495 },
16373 Null: function Null(value) { 15496 "_npmVersion": "3.8.6",
16374 return value === undefined || value === null; 15497 "_phantomChildren": {},
15498 "_requested": {
15499 "name": "bigi",
15500 "raw": "bigi",
15501 "rawSpec": "",
15502 "scope": null,
15503 "spec": "latest",
15504 "type": "tag"
16375 }, 15505 },
16376 Number: function Number(value) { 15506 "_requiredBy": [
16377 return typeof value === 'number'; 15507 "#USER",
15508 "/bitcoinjs-lib",
15509 "/ecurve"
15510 ],
15511 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz",
15512 "_shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
15513 "_shrinkwrap": null,
15514 "_spec": "bigi",
15515 "_where": "/home/ian/git/bitcoin/bitcoinjs-lib-browser",
15516 "bugs": {
15517 "url": "https://github.com/cryptocoinjs/bigi/issues"
16378 }, 15518 },
16379 Object: function Object(value) { 15519 "dependencies": {},
16380 return typeof value === 'object'; 15520 "description": "Big integers.",
15521 "devDependencies": {
15522 "coveralls": "^2.11.2",
15523 "istanbul": "^0.3.5",
15524 "jshint": "^2.5.1",
15525 "mocha": "^2.1.0",
15526 "mochify": "^2.1.0"
16381 }, 15527 },
16382 String: function String(value) { 15528 "directories": {},
16383 return typeof value === 'string'; 15529 "dist": {
15530 "shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
15531 "tarball": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz"
16384 }, 15532 },
16385 '': function _() { 15533 "gitHead": "c25308081c896ff84702303722bf5ecd8b3f78e3",
16386 return true; 15534 "homepage": "https://github.com/cryptocoinjs/bigi#readme",
16387 } 15535 "keywords": [
16388}; 15536 "cryptography",
16389 15537 "math",
16390function tJSON(type) { 15538 "bitcoin",
16391 return type && type.toJSON ? type.toJSON() : type; 15539 "arbitrary",
16392} 15540 "precision",
16393 15541 "arithmetic",
16394function sJSON(type) { 15542 "big",
16395 var json = tJSON(type); 15543 "integer",
16396 return nativeTypes.Object(json) ? JSON.stringify(json) : json; 15544 "int",
16397} 15545 "number",
16398 15546 "biginteger",
16399var otherTypes = { 15547 "bigint",
16400 arrayOf: function arrayOf(type) { 15548 "bignumber",
16401 function arrayOf(value, strict) { 15549 "decimal",
16402 try { 15550 "float"
16403 return nativeTypes.Array(value) && value.every(function (x) { 15551 ],
16404 return typeforce(type, x, strict); 15552 "main": "./lib/index.js",
16405 }); 15553 "maintainers": [
16406 } catch (e) { 15554 {
16407 return false; 15555 "email": "boydb@midnightdesign.ws",
16408 } 15556 "name": "midnightlightning"
15557 },
15558 {
15559 "email": "sidazhang89@gmail.com",
15560 "name": "sidazhang"
15561 },
15562 {
15563 "email": "npm@shesek.info",
15564 "name": "nadav"
15565 },
15566 {
15567 "email": "jprichardson@gmail.com",
15568 "name": "jprichardson"
16409 } 15569 }
16410 arrayOf.toJSON = function () { 15570 ],
16411 return [tJSON(type)]; 15571 "name": "bigi",
16412 }; 15572 "optionalDependencies": {},
16413 15573 "readme": "ERROR: No README data found!",
16414 return arrayOf; 15574 "repository": {
15575 "type": "git",
15576 "url": "git+https://github.com/cryptocoinjs/bigi.git"
16415 }, 15577 },
16416 15578 "scripts": {
16417 maybe: function maybe(type) { 15579 "browser-test": "mochify --wd -R spec",
16418 function maybe(value, strict) { 15580 "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
16419 return nativeTypes.Null(value) || typeforce(type, value, strict); 15581 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info",
16420 } 15582 "jshint": "jshint --config jshint.json lib/*.js ; true",
16421 maybe.toJSON = function () { 15583 "test": "_mocha -- test/*.js",
16422 return '?' + sJSON(type); 15584 "unit": "mocha"
16423 };
16424
16425 return maybe;
16426 }, 15585 },
16427 15586 "testling": {
16428 object: function object(type) { 15587 "browsers": [
16429 function object(value, strict) { 15588 "ie/9..latest",
16430 typeforce(nativeTypes.Object, value, strict); 15589 "firefox/latest",
16431 15590 "chrome/latest",
16432 var propertyName, propertyType, propertyValue; 15591 "safari/6.0..latest",
16433 15592 "iphone/6.0..latest",
16434 try { 15593 "android-browser/4.2..latest"
16435 for (propertyName in type) { 15594 ],
16436 propertyType = type[propertyName]; 15595 "files": "test/*.js",
16437 propertyValue = value[propertyName]; 15596 "harness": "mocha"
16438
16439 typeforce(propertyType, propertyValue, strict);
16440 }
16441 } catch (e) {
16442 throw new TypeError(tfPropertyErrorString(propertyType, propertyName, propertyValue));
16443 }
16444
16445 if (strict) {
16446 for (propertyName in value) {
16447 if (type[propertyName]) continue;
16448
16449 throw new TypeError('Unexpected property "' + propertyName + '"');
16450 }
16451 }
16452
16453 return true;
16454 }
16455 object.toJSON = function () {
16456 return type;
16457 };
16458
16459 return object;
16460 }, 15597 },
15598 "version": "1.4.2"
15599}
16461 15600
16462 oneOf: function oneOf() { 15601},{}],39:[function(require,module,exports){
16463 for (var _len = arguments.length, types = Array(_len), _key = 0; _key < _len; _key++) { 15602// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
16464 types[_key] = arguments[_key]; 15603// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
16465 } 15604// NOTE: SIGHASH byte ignored AND restricted, truncate before use
16466
16467 function oneOf(value, strict) {
16468 return types.some(function (type) {
16469 try {
16470 return typeforce(type, value, strict);
16471 } catch (e) {
16472 return false;
16473 }
16474 });
16475 }
16476 oneOf.toJSON = function () {
16477 return types.map(sJSON).join('|');
16478 };
16479
16480 return oneOf;
16481 },
16482 15605
16483 quacksLike: function quacksLike(type) { 15606var Buffer = require('safe-buffer').Buffer
16484 function quacksLike(value, strict) {
16485 return type === getValueTypeName(value);
16486 }
16487 quacksLike.toJSON = function () {
16488 return type;
16489 };
16490 15607
16491 return quacksLike; 15608function check (buffer) {
16492 }, 15609 if (buffer.length < 8) return false
15610 if (buffer.length > 72) return false
15611 if (buffer[0] !== 0x30) return false
15612 if (buffer[1] !== buffer.length - 2) return false
15613 if (buffer[2] !== 0x02) return false
16493 15614
16494 tuple: function tuple() { 15615 var lenR = buffer[3]
16495 for (var _len2 = arguments.length, types = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { 15616 if (lenR === 0) return false
16496 types[_key2] = arguments[_key2]; 15617 if (5 + lenR >= buffer.length) return false
16497 } 15618 if (buffer[4 + lenR] !== 0x02) return false
16498 15619
16499 function tuple(value, strict) { 15620 var lenS = buffer[5 + lenR]
16500 return types.every(function (type, i) { 15621 if (lenS === 0) return false
16501 return typeforce(type, value[i], strict); 15622 if ((6 + lenR + lenS) !== buffer.length) return false
16502 });
16503 }
16504 tuple.toJSON = function () {
16505 return '(' + types.map(sJSON).join(', ') + ')';
16506 };
16507 15623
16508 return tuple; 15624 if (buffer[4] & 0x80) return false
16509 }, 15625 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false
16510 15626
16511 value: function value(expected) { 15627 if (buffer[lenR + 6] & 0x80) return false
16512 function value(actual) { 15628 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false
16513 return actual === expected; 15629 return true
16514 } 15630}
16515 value.toJSON = function () {
16516 return expected;
16517 };
16518 15631
16519 return value; 15632function decode (buffer) {
16520 } 15633 if (buffer.length < 8) throw new Error('DER sequence length is too short')
16521}; 15634 if (buffer.length > 72) throw new Error('DER sequence length is too long')
15635 if (buffer[0] !== 0x30) throw new Error('Expected DER sequence')
15636 if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid')
15637 if (buffer[2] !== 0x02) throw new Error('Expected DER integer')
16522 15638
16523function compile(type) { 15639 var lenR = buffer[3]
16524 if (nativeTypes.String(type)) { 15640 if (lenR === 0) throw new Error('R length is zero')
16525 if (type[0] === '?') return otherTypes.maybe(compile(type.slice(1))); 15641 if (5 + lenR >= buffer.length) throw new Error('R length is too long')
15642 if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)')
16526 15643
16527 return nativeTypes[type] || otherTypes.quacksLike(type); 15644 var lenS = buffer[5 + lenR]
16528 } else if (type && nativeTypes.Object(type)) { 15645 if (lenS === 0) throw new Error('S length is zero')
16529 if (nativeTypes.Array(type)) return otherTypes.arrayOf(compile(type[0])); 15646 if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid')
16530 15647
16531 var compiled = {}; 15648 if (buffer[4] & 0x80) throw new Error('R value is negative')
15649 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded')
16532 15650
16533 for (var propertyName in type) { 15651 if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative')
16534 compiled[propertyName] = compile(type[propertyName]); 15652 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded')
16535 }
16536 15653
16537 return otherTypes.object(compiled); 15654 // non-BIP66 - extract R, S values
16538 } else if (nativeTypes.Function(type)) { 15655 return {
16539 return type; 15656 r: buffer.slice(4, 4 + lenR),
15657 s: buffer.slice(6 + lenR)
16540 } 15658 }
16541
16542 return otherTypes.value(type);
16543} 15659}
16544 15660
16545function typeforce(_x3, _x4, _x5) { 15661/*
16546 var _again = true; 15662 * Expects r and s to be positive DER integers.
16547 15663 *
16548 _function: while (_again) { 15664 * The DER format uses the most significant bit as a sign bit (& 0x80).
16549 var type = _x3, 15665 * If the significant bit is set AND the integer is positive, a 0x00 is prepended.
16550 value = _x4, 15666 *
16551 strict = _x5; 15667 * Examples:
16552 _again = false; 15668 *
15669 * 0 => 0x00
15670 * 1 => 0x01
15671 * -1 => 0xff
15672 * 127 => 0x7f
15673 * -127 => 0x81
15674 * 128 => 0x0080
15675 * -128 => 0x80
15676 * 255 => 0x00ff
15677 * -255 => 0xff01
15678 * 16300 => 0x3fac
15679 * -16300 => 0xc054
15680 * 62300 => 0x00f35c
15681 * -62300 => 0xff0ca4
15682*/
15683function encode (r, s) {
15684 var lenR = r.length
15685 var lenS = s.length
15686 if (lenR === 0) throw new Error('R length is zero')
15687 if (lenS === 0) throw new Error('S length is zero')
15688 if (lenR > 33) throw new Error('R length is too long')
15689 if (lenS > 33) throw new Error('S length is too long')
15690 if (r[0] & 0x80) throw new Error('R value is negative')
15691 if (s[0] & 0x80) throw new Error('S value is negative')
15692 if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded')
15693 if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded')
16553 15694
16554 if (nativeTypes.Function(type)) { 15695 var signature = Buffer.allocUnsafe(6 + lenR + lenS)
16555 if (type(value, strict)) return true;
16556 15696
16557 throw new TypeError(tfErrorString(type, value)); 15697 // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
16558 } 15698 signature[0] = 0x30
15699 signature[1] = signature.length - 2
15700 signature[2] = 0x02
15701 signature[3] = r.length
15702 r.copy(signature, 4)
15703 signature[4 + lenR] = 0x02
15704 signature[5 + lenR] = s.length
15705 s.copy(signature, 6 + lenR)
16559 15706
16560 // JIT 15707 return signature
16561 _x3 = compile(type);
16562 _x4 = value;
16563 _x5 = strict;
16564 _again = true;
16565 continue _function;
16566 }
16567} 15708}
16568 15709
16569// assign all types to typeforce function 15710module.exports = {
16570var typeName; 15711 check: check,
16571Object.keys(nativeTypes).forEach(function (typeName) { 15712 decode: decode,
16572 var nativeType = nativeTypes[typeName]; 15713 encode: encode
16573 nativeType.toJSON = function () {
16574 return typeName;
16575 };
16576
16577 typeforce[typeName] = nativeType;
16578});
16579
16580for (typeName in otherTypes) {
16581 typeforce[typeName] = otherTypes[typeName];
16582} 15714}
16583 15715
16584module.exports = typeforce; 15716},{"safe-buffer":98}],40:[function(require,module,exports){
16585module.exports.compile = compile; 15717module.exports={
16586}).call(this,require("buffer").Buffer) 15718 "OP_FALSE": 0,
16587},{"buffer":7}],54:[function(require,module,exports){ 15719 "OP_0": 0,
16588(function (Buffer){ 15720 "OP_PUSHDATA1": 76,
16589var assert = require('assert') 15721 "OP_PUSHDATA2": 77,
16590var base58check = require('bs58check') 15722 "OP_PUSHDATA4": 78,
16591var typeForce = require('typeforce') 15723 "OP_1NEGATE": 79,
15724 "OP_RESERVED": 80,
15725 "OP_1": 81,
15726 "OP_TRUE": 81,
15727 "OP_2": 82,
15728 "OP_3": 83,
15729 "OP_4": 84,
15730 "OP_5": 85,
15731 "OP_6": 86,
15732 "OP_7": 87,
15733 "OP_8": 88,
15734 "OP_9": 89,
15735 "OP_10": 90,
15736 "OP_11": 91,
15737 "OP_12": 92,
15738 "OP_13": 93,
15739 "OP_14": 94,
15740 "OP_15": 95,
15741 "OP_16": 96,
15742
15743 "OP_NOP": 97,
15744 "OP_VER": 98,
15745 "OP_IF": 99,
15746 "OP_NOTIF": 100,
15747 "OP_VERIF": 101,
15748 "OP_VERNOTIF": 102,
15749 "OP_ELSE": 103,
15750 "OP_ENDIF": 104,
15751 "OP_VERIFY": 105,
15752 "OP_RETURN": 106,
15753
15754 "OP_TOALTSTACK": 107,
15755 "OP_FROMALTSTACK": 108,
15756 "OP_2DROP": 109,
15757 "OP_2DUP": 110,
15758 "OP_3DUP": 111,
15759 "OP_2OVER": 112,
15760 "OP_2ROT": 113,
15761 "OP_2SWAP": 114,
15762 "OP_IFDUP": 115,
15763 "OP_DEPTH": 116,
15764 "OP_DROP": 117,
15765 "OP_DUP": 118,
15766 "OP_NIP": 119,
15767 "OP_OVER": 120,
15768 "OP_PICK": 121,
15769 "OP_ROLL": 122,
15770 "OP_ROT": 123,
15771 "OP_SWAP": 124,
15772 "OP_TUCK": 125,
15773
15774 "OP_CAT": 126,
15775 "OP_SUBSTR": 127,
15776 "OP_LEFT": 128,
15777 "OP_RIGHT": 129,
15778 "OP_SIZE": 130,
15779
15780 "OP_INVERT": 131,
15781 "OP_AND": 132,
15782 "OP_OR": 133,
15783 "OP_XOR": 134,
15784 "OP_EQUAL": 135,
15785 "OP_EQUALVERIFY": 136,
15786 "OP_RESERVED1": 137,
15787 "OP_RESERVED2": 138,
15788
15789 "OP_1ADD": 139,
15790 "OP_1SUB": 140,
15791 "OP_2MUL": 141,
15792 "OP_2DIV": 142,
15793 "OP_NEGATE": 143,
15794 "OP_ABS": 144,
15795 "OP_NOT": 145,
15796 "OP_0NOTEQUAL": 146,
15797 "OP_ADD": 147,
15798 "OP_SUB": 148,
15799 "OP_MUL": 149,
15800 "OP_DIV": 150,
15801 "OP_MOD": 151,
15802 "OP_LSHIFT": 152,
15803 "OP_RSHIFT": 153,
15804
15805 "OP_BOOLAND": 154,
15806 "OP_BOOLOR": 155,
15807 "OP_NUMEQUAL": 156,
15808 "OP_NUMEQUALVERIFY": 157,
15809 "OP_NUMNOTEQUAL": 158,
15810 "OP_LESSTHAN": 159,
15811 "OP_GREATERTHAN": 160,
15812 "OP_LESSTHANOREQUAL": 161,
15813 "OP_GREATERTHANOREQUAL": 162,
15814 "OP_MIN": 163,
15815 "OP_MAX": 164,
15816
15817 "OP_WITHIN": 165,
15818
15819 "OP_RIPEMD160": 166,
15820 "OP_SHA1": 167,
15821 "OP_SHA256": 168,
15822 "OP_HASH160": 169,
15823 "OP_HASH256": 170,
15824 "OP_CODESEPARATOR": 171,
15825 "OP_CHECKSIG": 172,
15826 "OP_CHECKSIGVERIFY": 173,
15827 "OP_CHECKMULTISIG": 174,
15828 "OP_CHECKMULTISIGVERIFY": 175,
15829
15830 "OP_NOP1": 176,
15831 "OP_NOP2": 177,
15832 "OP_CHECKLOCKTIMEVERIFY": 177,
15833
15834 "OP_NOP3": 178,
15835 "OP_NOP4": 179,
15836 "OP_NOP5": 180,
15837 "OP_NOP6": 181,
15838 "OP_NOP7": 182,
15839 "OP_NOP8": 183,
15840 "OP_NOP9": 184,
15841 "OP_NOP10": 185,
15842
15843 "OP_PUBKEYHASH": 253,
15844 "OP_PUBKEY": 254,
15845 "OP_INVALIDOPCODE": 255
15846}
15847
15848},{}],41:[function(require,module,exports){
15849var OPS = require('./index.json')
15850
15851var map = {}
15852for (var op in OPS) {
15853 var code = OPS[op]
15854 map[code] = op
15855}
15856
15857module.exports = map
15858
15859},{"./index.json":40}],42:[function(require,module,exports){
15860var Buffer = require('safe-buffer').Buffer
15861var bs58check = require('bs58check')
15862var bscript = require('./script')
16592var networks = require('./networks') 15863var networks = require('./networks')
16593var scripts = require('./scripts') 15864var typeforce = require('typeforce')
16594 15865var types = require('./types')
16595function findScriptTypeByVersion (version) {
16596 for (var networkName in networks) {
16597 var network = networks[networkName]
16598
16599 if (version === network.pubKeyHash) return 'pubkeyhash'
16600 if (version === network.scriptHash) return 'scripthash'
16601 }
16602}
16603
16604function Address (hash, version) {
16605 typeForce('Buffer', hash)
16606 15866
16607 assert.strictEqual(hash.length, 20, 'Invalid hash length') 15867function fromBase58Check (address) {
16608 assert.strictEqual(version & 0xff, version, 'Invalid version byte') 15868 var payload = bs58check.decode(address)
15869 if (payload.length < 21) throw new TypeError(address + ' is too short')
15870 if (payload.length > 21) throw new TypeError(address + ' is too long')
16609 15871
16610 this.hash = hash
16611 this.version = version
16612}
16613
16614Address.fromBase58Check = function (string) {
16615 var payload = base58check.decode(string)
16616 var version = payload.readUInt8(0) 15872 var version = payload.readUInt8(0)
16617 var hash = payload.slice(1) 15873 var hash = payload.slice(1)
16618 15874
16619 return new Address(hash, version) 15875 return { hash: hash, version: version }
16620} 15876}
16621 15877
16622Address.fromOutputScript = function (script, network) { 15878function toBase58Check (hash, version) {
16623 network = network || networks.bitcoin 15879 typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments)
16624 15880
16625 if (scripts.isPubKeyHashOutput(script)) return new Address(script.chunks[2], network.pubKeyHash) 15881 var payload = Buffer.allocUnsafe(21)
16626 if (scripts.isScriptHashOutput(script)) return new Address(script.chunks[1], network.scriptHash) 15882 payload.writeUInt8(version, 0)
15883 hash.copy(payload, 1)
16627 15884
16628 assert(false, script.toASM() + ' has no matching Address') 15885 return bs58check.encode(payload)
16629} 15886}
16630 15887
16631Address.prototype.toBase58Check = function () { 15888function fromOutputScript (outputScript, network) {
16632 var payload = new Buffer(21) 15889 network = network || networks.bitcoin
16633 payload.writeUInt8(this.version, 0)
16634 this.hash.copy(payload, 1)
16635
16636 return base58check.encode(payload)
16637}
16638
16639Address.prototype.toOutputScript = function () {
16640 var scriptType = findScriptTypeByVersion(this.version)
16641 15890
16642 if (scriptType === 'pubkeyhash') return scripts.pubKeyHashOutput(this.hash) 15891 if (bscript.pubKeyHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(3, 23), network.pubKeyHash)
16643 if (scriptType === 'scripthash') return scripts.scriptHashOutput(this.hash) 15892 if (bscript.scriptHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(2, 22), network.scriptHash)
16644 15893
16645 assert(false, this.toString() + ' has no matching Script') 15894 throw new Error(bscript.toASM(outputScript) + ' has no matching Address')
16646} 15895}
16647 15896
16648Address.prototype.toString = Address.prototype.toBase58Check 15897function toOutputScript (address, network) {
16649 15898 network = network || networks.bitcoin
16650module.exports = Address
16651
16652}).call(this,require("buffer").Buffer)
16653},{"./networks":66,"./scripts":69,"assert":5,"bs58check":31,"buffer":7,"typeforce":53}],55:[function(require,module,exports){
16654var bs58check = require('bs58check')
16655
16656function decode () {
16657 console.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.')
16658
16659 return bs58check.decode.apply(undefined, arguments)
16660}
16661 15899
16662function encode () { 15900 var decode = fromBase58Check(address)
16663 console.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.') 15901 if (decode.version === network.pubKeyHash) return bscript.pubKeyHash.output.encode(decode.hash)
15902 if (decode.version === network.scriptHash) return bscript.scriptHash.output.encode(decode.hash)
16664 15903
16665 return bs58check.encode.apply(undefined, arguments) 15904 throw new Error(address + ' has no matching Script')
16666} 15905}
16667 15906
16668module.exports = { 15907module.exports = {
16669 decode: decode, 15908 fromBase58Check: fromBase58Check,
16670 encode: encode 15909 fromOutputScript: fromOutputScript,
15910 toBase58Check: toBase58Check,
15911 toOutputScript: toOutputScript
16671} 15912}
16672 15913
16673},{"bs58check":31}],56:[function(require,module,exports){ 15914},{"./networks":51,"./script":52,"./types":78,"bs58check":80,"safe-buffer":98,"typeforce":109}],43:[function(require,module,exports){
16674(function (Buffer){ 15915var Buffer = require('safe-buffer').Buffer
16675var assert = require('assert') 15916var bcrypto = require('./crypto')
16676var bufferutils = require('./bufferutils') 15917var fastMerkleRoot = require('merkle-lib/fastRoot')
16677var crypto = require('./crypto') 15918var typeforce = require('typeforce')
15919var types = require('./types')
15920var varuint = require('varuint-bitcoin')
16678 15921
16679var Transaction = require('./transaction') 15922var Transaction = require('./transaction')
16680 15923
@@ -16688,7 +15931,7 @@ function Block () {
16688} 15931}
16689 15932
16690Block.fromBuffer = function (buffer) { 15933Block.fromBuffer = function (buffer) {
16691 assert(buffer.length >= 80, 'Buffer too small (< 80 bytes)') 15934 if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)')
16692 15935
16693 var offset = 0 15936 var offset = 0
16694 function readSlice (n) { 15937 function readSlice (n) {
@@ -16702,8 +15945,14 @@ Block.fromBuffer = function (buffer) {
16702 return i 15945 return i
16703 } 15946 }
16704 15947
15948 function readInt32 () {
15949 var i = buffer.readInt32LE(offset)
15950 offset += 4
15951 return i
15952 }
15953
16705 var block = new Block() 15954 var block = new Block()
16706 block.version = readUInt32() 15955 block.version = readInt32()
16707 block.prevHash = readSlice(32) 15956 block.prevHash = readSlice(32)
16708 block.merkleRoot = readSlice(32) 15957 block.merkleRoot = readSlice(32)
16709 block.timestamp = readUInt32() 15958 block.timestamp = readUInt32()
@@ -16713,16 +15962,14 @@ Block.fromBuffer = function (buffer) {
16713 if (buffer.length === 80) return block 15962 if (buffer.length === 80) return block
16714 15963
16715 function readVarInt () { 15964 function readVarInt () {
16716 var vi = bufferutils.readVarInt(buffer, offset) 15965 var vi = varuint.decode(buffer, offset)
16717 offset += vi.size 15966 offset += varuint.decode.bytes
16718 return vi.number 15967 return vi
16719 } 15968 }
16720 15969
16721 // FIXME: poor performance
16722 function readTransaction () { 15970 function readTransaction () {
16723 var tx = Transaction.fromBuffer(buffer.slice(offset), true) 15971 var tx = Transaction.fromBuffer(buffer.slice(offset), true)
16724 15972 offset += tx.byteLength()
16725 offset += tx.toBuffer().length
16726 return tx 15973 return tx
16727 } 15974 }
16728 15975
@@ -16737,16 +15984,24 @@ Block.fromBuffer = function (buffer) {
16737 return block 15984 return block
16738} 15985}
16739 15986
15987Block.prototype.byteLength = function (headersOnly) {
15988 if (headersOnly || !this.transactions) return 80
15989
15990 return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) {
15991 return a + x.byteLength()
15992 }, 0)
15993}
15994
16740Block.fromHex = function (hex) { 15995Block.fromHex = function (hex) {
16741 return Block.fromBuffer(new Buffer(hex, 'hex')) 15996 return Block.fromBuffer(Buffer.from(hex, 'hex'))
16742} 15997}
16743 15998
16744Block.prototype.getHash = function () { 15999Block.prototype.getHash = function () {
16745 return crypto.hash256(this.toBuffer(true)) 16000 return bcrypto.hash256(this.toBuffer(true))
16746} 16001}
16747 16002
16748Block.prototype.getId = function () { 16003Block.prototype.getId = function () {
16749 return bufferutils.reverse(this.getHash()).toString('hex') 16004 return this.getHash().reverse().toString('hex')
16750} 16005}
16751 16006
16752Block.prototype.getUTCDate = function () { 16007Block.prototype.getUTCDate = function () {
@@ -16756,8 +16011,9 @@ Block.prototype.getUTCDate = function () {
16756 return date 16011 return date
16757} 16012}
16758 16013
16014// TODO: buffer, offset compatibility
16759Block.prototype.toBuffer = function (headersOnly) { 16015Block.prototype.toBuffer = function (headersOnly) {
16760 var buffer = new Buffer(80) 16016 var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly))
16761 16017
16762 var offset = 0 16018 var offset = 0
16763 function writeSlice (slice) { 16019 function writeSlice (slice) {
@@ -16765,12 +16021,16 @@ Block.prototype.toBuffer = function (headersOnly) {
16765 offset += slice.length 16021 offset += slice.length
16766 } 16022 }
16767 16023
16024 function writeInt32 (i) {
16025 buffer.writeInt32LE(i, offset)
16026 offset += 4
16027 }
16768 function writeUInt32 (i) { 16028 function writeUInt32 (i) {
16769 buffer.writeUInt32LE(i, offset) 16029 buffer.writeUInt32LE(i, offset)
16770 offset += 4 16030 offset += 4
16771 } 16031 }
16772 16032
16773 writeUInt32(this.version) 16033 writeInt32(this.version)
16774 writeSlice(this.prevHash) 16034 writeSlice(this.prevHash)
16775 writeSlice(this.merkleRoot) 16035 writeSlice(this.merkleRoot)
16776 writeUInt32(this.timestamp) 16036 writeUInt32(this.timestamp)
@@ -16779,76 +16039,67 @@ Block.prototype.toBuffer = function (headersOnly) {
16779 16039
16780 if (headersOnly || !this.transactions) return buffer 16040 if (headersOnly || !this.transactions) return buffer
16781 16041
16782 var txLenBuffer = bufferutils.varIntBuffer(this.transactions.length) 16042 varuint.encode(this.transactions.length, buffer, offset)
16783 var txBuffers = this.transactions.map(function (tx) { 16043 offset += varuint.encode.bytes
16784 return tx.toBuffer() 16044
16045 this.transactions.forEach(function (tx) {
16046 var txSize = tx.byteLength() // TODO: extract from toBuffer?
16047 tx.toBuffer(buffer, offset)
16048 offset += txSize
16785 }) 16049 })
16786 16050
16787 return Buffer.concat([buffer, txLenBuffer].concat(txBuffers)) 16051 return buffer
16788} 16052}
16789 16053
16790Block.prototype.toHex = function (headersOnly) { 16054Block.prototype.toHex = function (headersOnly) {
16791 return this.toBuffer(headersOnly).toString('hex') 16055 return this.toBuffer(headersOnly).toString('hex')
16792} 16056}
16793 16057
16794module.exports = Block 16058Block.calculateTarget = function (bits) {
16059 var exponent = ((bits & 0xff000000) >> 24) - 3
16060 var mantissa = bits & 0x007fffff
16061 var target = Buffer.alloc(32, 0)
16062 target.writeUInt32BE(mantissa, 28 - exponent)
16063 return target
16064}
16795 16065
16796}).call(this,require("buffer").Buffer) 16066Block.calculateMerkleRoot = function (transactions) {
16797},{"./bufferutils":57,"./crypto":58,"./transaction":70,"assert":5,"buffer":7}],57:[function(require,module,exports){ 16067 typeforce([{ getHash: types.Function }], transactions)
16798(function (Buffer){ 16068 if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions')
16799var assert = require('assert')
16800var opcodes = require('./opcodes')
16801 16069
16802// https://github.com/feross/buffer/blob/master/index.js#L1127 16070 var hashes = transactions.map(function (transaction) {
16803function verifuint (value, max) { 16071 return transaction.getHash()
16804 assert(typeof value === 'number', 'cannot write a non-number as a number') 16072 })
16805 assert(value >= 0, 'specified a negative value for writing an unsigned value')
16806 assert(value <= max, 'value is larger than maximum value for type')
16807 assert(Math.floor(value) === value, 'value has a fractional component')
16808}
16809 16073
16810function pushDataSize (i) { 16074 return fastMerkleRoot(hashes, bcrypto.hash256)
16811 return i < opcodes.OP_PUSHDATA1 ? 1
16812 : i < 0xff ? 2
16813 : i < 0xffff ? 3
16814 : 5
16815} 16075}
16816 16076
16817function readPushDataInt (buffer, offset) { 16077Block.prototype.checkMerkleRoot = function () {
16818 var opcode = buffer.readUInt8(offset) 16078 if (!this.transactions) return false
16819 var number, size
16820 16079
16821 // ~6 bit 16080 var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions)
16822 if (opcode < opcodes.OP_PUSHDATA1) { 16081 return this.merkleRoot.compare(actualMerkleRoot) === 0
16823 number = opcode 16082}
16824 size = 1
16825 16083
16826 // 8 bit 16084Block.prototype.checkProofOfWork = function () {
16827 } else if (opcode === opcodes.OP_PUSHDATA1) { 16085 var hash = this.getHash().reverse()
16828 if (offset + 2 > buffer.length) return null 16086 var target = Block.calculateTarget(this.bits)
16829 number = buffer.readUInt8(offset + 1)
16830 size = 2
16831 16087
16832 // 16 bit 16088 return hash.compare(target) <= 0
16833 } else if (opcode === opcodes.OP_PUSHDATA2) { 16089}
16834 if (offset + 3 > buffer.length) return null
16835 number = buffer.readUInt16LE(offset + 1)
16836 size = 3
16837 16090
16838 // 32 bit 16091module.exports = Block
16839 } else {
16840 if (offset + 5 > buffer.length) return null
16841 assert.equal(opcode, opcodes.OP_PUSHDATA4, 'Unexpected opcode')
16842 16092
16843 number = buffer.readUInt32LE(offset + 1) 16093},{"./crypto":45,"./transaction":76,"./types":78,"merkle-lib/fastRoot":94,"safe-buffer":98,"typeforce":109,"varuint-bitcoin":111}],44:[function(require,module,exports){
16844 size = 5 16094var pushdata = require('pushdata-bitcoin')
16845 } 16095var varuint = require('varuint-bitcoin')
16846 16096
16847 return { 16097// https://github.com/feross/buffer/blob/master/index.js#L1127
16848 opcode: opcode, 16098function verifuint (value, max) {
16849 number: number, 16099 if (typeof value !== 'number') throw new Error('cannot write a non-number as a number')
16850 size: size 16100 if (value < 0) throw new Error('specified a negative value for writing an unsigned value')
16851 } 16101 if (value > max) throw new Error('RangeError: value out of range')
16102 if (Math.floor(value) !== value) throw new Error('value has a fractional component')
16852} 16103}
16853 16104
16854function readUInt64LE (buffer, offset) { 16105function readUInt64LE (buffer, offset) {
@@ -16861,142 +16112,45 @@ function readUInt64LE (buffer, offset) {
16861 return b + a 16112 return b + a
16862} 16113}
16863 16114
16864function readVarInt (buffer, offset) {
16865 var t = buffer.readUInt8(offset)
16866 var number, size
16867
16868 // 8 bit
16869 if (t < 253) {
16870 number = t
16871 size = 1
16872
16873 // 16 bit
16874 } else if (t < 254) {
16875 number = buffer.readUInt16LE(offset + 1)
16876 size = 3
16877
16878 // 32 bit
16879 } else if (t < 255) {
16880 number = buffer.readUInt32LE(offset + 1)
16881 size = 5
16882
16883 // 64 bit
16884 } else {
16885 number = readUInt64LE(buffer, offset + 1)
16886 size = 9
16887 }
16888
16889 return {
16890 number: number,
16891 size: size
16892 }
16893}
16894
16895function writePushDataInt (buffer, number, offset) {
16896 var size = pushDataSize(number)
16897
16898 // ~6 bit
16899 if (size === 1) {
16900 buffer.writeUInt8(number, offset)
16901
16902 // 8 bit
16903 } else if (size === 2) {
16904 buffer.writeUInt8(opcodes.OP_PUSHDATA1, offset)
16905 buffer.writeUInt8(number, offset + 1)
16906
16907 // 16 bit
16908 } else if (size === 3) {
16909 buffer.writeUInt8(opcodes.OP_PUSHDATA2, offset)
16910 buffer.writeUInt16LE(number, offset + 1)
16911
16912 // 32 bit
16913 } else {
16914 buffer.writeUInt8(opcodes.OP_PUSHDATA4, offset)
16915 buffer.writeUInt32LE(number, offset + 1)
16916 }
16917
16918 return size
16919}
16920
16921function writeUInt64LE (buffer, value, offset) { 16115function writeUInt64LE (buffer, value, offset) {
16922 verifuint(value, 0x001fffffffffffff) 16116 verifuint(value, 0x001fffffffffffff)
16923 16117
16924 buffer.writeInt32LE(value & -1, offset) 16118 buffer.writeInt32LE(value & -1, offset)
16925 buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4) 16119 buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4)
16120 return offset + 8
16926} 16121}
16927 16122
16928function varIntSize (i) { 16123// TODO: remove in 4.0.0?
16929 return i < 253 ? 1 16124function readVarInt (buffer, offset) {
16930 : i < 0x10000 ? 3 16125 var result = varuint.decode(buffer, offset)
16931 : i < 0x100000000 ? 5
16932 : 9
16933}
16934
16935function writeVarInt (buffer, number, offset) {
16936 var size = varIntSize(number)
16937
16938 // 8 bit
16939 if (size === 1) {
16940 buffer.writeUInt8(number, offset)
16941
16942 // 16 bit
16943 } else if (size === 3) {
16944 buffer.writeUInt8(253, offset)
16945 buffer.writeUInt16LE(number, offset + 1)
16946
16947 // 32 bit
16948 } else if (size === 5) {
16949 buffer.writeUInt8(254, offset)
16950 buffer.writeUInt32LE(number, offset + 1)
16951 16126
16952 // 64 bit 16127 return {
16953 } else { 16128 number: result,
16954 buffer.writeUInt8(255, offset) 16129 size: varuint.decode.bytes
16955 writeUInt64LE(buffer, number, offset + 1)
16956 } 16130 }
16957
16958 return size
16959}
16960
16961function varIntBuffer (i) {
16962 var size = varIntSize(i)
16963 var buffer = new Buffer(size)
16964 writeVarInt(buffer, i, 0)
16965
16966 return buffer
16967} 16131}
16968 16132
16969function reverse (buffer) { 16133// TODO: remove in 4.0.0?
16970 var buffer2 = new Buffer(buffer) 16134function writeVarInt (buffer, number, offset) {
16971 Array.prototype.reverse.call(buffer2) 16135 varuint.encode(number, buffer, offset)
16972 return buffer2 16136 return varuint.encode.bytes
16973} 16137}
16974 16138
16975module.exports = { 16139module.exports = {
16976 pushDataSize: pushDataSize, 16140 pushDataSize: pushdata.encodingLength,
16977 readPushDataInt: readPushDataInt, 16141 readPushDataInt: pushdata.decode,
16978 readUInt64LE: readUInt64LE, 16142 readUInt64LE: readUInt64LE,
16979 readVarInt: readVarInt, 16143 readVarInt: readVarInt,
16980 reverse: reverse, 16144 varIntBuffer: varuint.encode,
16981 varIntBuffer: varIntBuffer, 16145 varIntSize: varuint.encodingLength,
16982 varIntSize: varIntSize, 16146 writePushDataInt: pushdata.encode,
16983 writePushDataInt: writePushDataInt,
16984 writeUInt64LE: writeUInt64LE, 16147 writeUInt64LE: writeUInt64LE,
16985 writeVarInt: writeVarInt 16148 writeVarInt: writeVarInt
16986} 16149}
16987 16150
16988}).call(this,require("buffer").Buffer) 16151},{"pushdata-bitcoin":95,"varuint-bitcoin":111}],45:[function(require,module,exports){
16989},{"./opcodes":67,"assert":5,"buffer":7}],58:[function(require,module,exports){
16990var createHash = require('create-hash') 16152var createHash = require('create-hash')
16991 16153
16992function hash160 (buffer) {
16993 return ripemd160(sha256(buffer))
16994}
16995
16996function hash256 (buffer) {
16997 return sha256(sha256(buffer))
16998}
16999
17000function ripemd160 (buffer) { 16154function ripemd160 (buffer) {
17001 return createHash('rmd160').update(buffer).digest() 16155 return createHash('rmd160').update(buffer).digest()
17002} 16156}
@@ -17009,87 +16163,50 @@ function sha256 (buffer) {
17009 return createHash('sha256').update(buffer).digest() 16163 return createHash('sha256').update(buffer).digest()
17010} 16164}
17011 16165
17012// FIXME: Name not consistent with others 16166function hash160 (buffer) {
17013var createHmac = require('create-hmac') 16167 return ripemd160(sha256(buffer))
17014
17015function HmacSHA256 (buffer, secret) {
17016 console.warn('Hmac* functions are deprecated for removal in 2.0.0, use node crypto instead')
17017 return createHmac('sha256', secret).update(buffer).digest()
17018} 16168}
17019 16169
17020function HmacSHA512 (buffer, secret) { 16170function hash256 (buffer) {
17021 console.warn('Hmac* functions are deprecated for removal in 2.0.0, use node crypto instead') 16171 return sha256(sha256(buffer))
17022 return createHmac('sha512', secret).update(buffer).digest()
17023} 16172}
17024 16173
17025module.exports = { 16174module.exports = {
17026 ripemd160: ripemd160,
17027 sha1: sha1,
17028 sha256: sha256,
17029 hash160: hash160, 16175 hash160: hash160,
17030 hash256: hash256, 16176 hash256: hash256,
17031 HmacSHA256: HmacSHA256, 16177 ripemd160: ripemd160,
17032 HmacSHA512: HmacSHA512 16178 sha1: sha1,
16179 sha256: sha256
17033} 16180}
17034 16181
17035},{"create-hash":32,"create-hmac":45}],59:[function(require,module,exports){ 16182},{"create-hash":82}],46:[function(require,module,exports){
17036(function (Buffer){ 16183var Buffer = require('safe-buffer').Buffer
17037var assert = require('assert')
17038var createHmac = require('create-hmac') 16184var createHmac = require('create-hmac')
17039var typeForce = require('typeforce') 16185var typeforce = require('typeforce')
16186var types = require('./types')
17040 16187
17041var BigInteger = require('bigi') 16188var BigInteger = require('bigi')
17042var ECSignature = require('./ecsignature') 16189var ECSignature = require('./ecsignature')
17043 16190
17044var ZERO = new Buffer([0]) 16191var ZERO = Buffer.alloc(1, 0)
17045var ONE = new Buffer([1]) 16192var ONE = Buffer.alloc(1, 1)
17046
17047// https://tools.ietf.org/html/rfc6979#section-3.2
17048function deterministicGenerateK (curve, hash, d, checkSig) {
17049 typeForce('Buffer', hash)
17050 typeForce('BigInteger', d)
17051
17052 // FIXME: remove/uncomment for 2.0.0
17053 // typeForce('Function', checkSig)
17054
17055 if (typeof checkSig !== 'function') {
17056 console.warn('deterministicGenerateK requires a checkSig callback in 2.0.0, see #337 for more information')
17057
17058 checkSig = function (k) {
17059 var G = curve.G
17060 var n = curve.n
17061 var e = BigInteger.fromBuffer(hash)
17062
17063 var Q = G.multiply(k)
17064
17065 if (curve.isInfinity(Q))
17066 return false
17067
17068 var r = Q.affineX.mod(n)
17069 if (r.signum() === 0)
17070 return false
17071
17072 var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
17073 if (s.signum() === 0)
17074 return false
17075
17076 return true
17077 }
17078 }
17079 16193
17080 // sanity check 16194var ecurve = require('ecurve')
17081 assert.equal(hash.length, 32, 'Hash must be 256 bit') 16195var secp256k1 = ecurve.getCurveByName('secp256k1')
17082 16196
17083 var x = d.toBuffer(32) 16197// https://tools.ietf.org/html/rfc6979#section-3.2
17084 var k = new Buffer(32) 16198function deterministicGenerateK (hash, x, checkSig) {
17085 var v = new Buffer(32) 16199 typeforce(types.tuple(
16200 types.Hash256bit,
16201 types.Buffer256bit,
16202 types.Function
16203 ), arguments)
17086 16204
17087 // Step A, ignored as hash already provided 16205 // Step A, ignored as hash already provided
17088 // Step B 16206 // Step B
17089 v.fill(1)
17090
17091 // Step C 16207 // Step C
17092 k.fill(0) 16208 var k = Buffer.alloc(32, 0)
16209 var v = Buffer.alloc(32, 1)
17093 16210
17094 // Step D 16211 // Step D
17095 k = createHmac('sha256', k) 16212 k = createHmac('sha256', k)
@@ -17120,7 +16237,7 @@ function deterministicGenerateK (curve, hash, d, checkSig) {
17120 var T = BigInteger.fromBuffer(v) 16237 var T = BigInteger.fromBuffer(v)
17121 16238
17122 // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA 16239 // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA
17123 while ((T.signum() <= 0) || (T.compareTo(curve.n) >= 0) || !checkSig(T)) { 16240 while (T.signum() <= 0 || T.compareTo(secp256k1.n) >= 0 || !checkSig(T)) {
17124 k = createHmac('sha256', k) 16241 k = createHmac('sha256', k)
17125 .update(v) 16242 .update(v)
17126 .update(ZERO) 16243 .update(ZERO)
@@ -17137,32 +16254,31 @@ function deterministicGenerateK (curve, hash, d, checkSig) {
17137 return T 16254 return T
17138} 16255}
17139 16256
17140function sign (curve, hash, d) { 16257var N_OVER_TWO = secp256k1.n.shiftRight(1)
17141 var r, s 16258
16259function sign (hash, d) {
16260 typeforce(types.tuple(types.Hash256bit, types.BigInt), arguments)
17142 16261
16262 var x = d.toBuffer(32)
17143 var e = BigInteger.fromBuffer(hash) 16263 var e = BigInteger.fromBuffer(hash)
17144 var n = curve.n 16264 var n = secp256k1.n
17145 var G = curve.G 16265 var G = secp256k1.G
17146 16266
17147 deterministicGenerateK(curve, hash, d, function (k) { 16267 var r, s
16268 deterministicGenerateK(hash, x, function (k) {
17148 var Q = G.multiply(k) 16269 var Q = G.multiply(k)
17149 16270
17150 if (curve.isInfinity(Q)) 16271 if (secp256k1.isInfinity(Q)) return false
17151 return false
17152 16272
17153 r = Q.affineX.mod(n) 16273 r = Q.affineX.mod(n)
17154 if (r.signum() === 0) 16274 if (r.signum() === 0) return false
17155 return false
17156 16275
17157 s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n) 16276 s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
17158 if (s.signum() === 0) 16277 if (s.signum() === 0) return false
17159 return false
17160 16278
17161 return true 16279 return true
17162 }) 16280 })
17163 16281
17164 var N_OVER_TWO = n.shiftRight(1)
17165
17166 // enforce low S values, see bip62: 'low s values in signatures' 16282 // enforce low S values, see bip62: 'low s values in signatures'
17167 if (s.compareTo(N_OVER_TWO) > 0) { 16283 if (s.compareTo(N_OVER_TWO) > 0) {
17168 s = n.subtract(s) 16284 s = n.subtract(s)
@@ -17171,9 +16287,15 @@ function sign (curve, hash, d) {
17171 return new ECSignature(r, s) 16287 return new ECSignature(r, s)
17172} 16288}
17173 16289
17174function verifyRaw (curve, e, signature, Q) { 16290function verify (hash, signature, Q) {
17175 var n = curve.n 16291 typeforce(types.tuple(
17176 var G = curve.G 16292 types.Hash256bit,
16293 types.ECSignature,
16294 types.ECPoint
16295 ), arguments)
16296
16297 var n = secp256k1.n
16298 var G = secp256k1.G
17177 16299
17178 var r = signature.r 16300 var r = signature.r
17179 var s = signature.s 16301 var s = signature.s
@@ -17182,331 +16304,215 @@ function verifyRaw (curve, e, signature, Q) {
17182 if (r.signum() <= 0 || r.compareTo(n) >= 0) return false 16304 if (r.signum() <= 0 || r.compareTo(n) >= 0) return false
17183 if (s.signum() <= 0 || s.compareTo(n) >= 0) return false 16305 if (s.signum() <= 0 || s.compareTo(n) >= 0) return false
17184 16306
17185 // c = s^-1 mod n
17186 var c = s.modInverse(n)
17187
17188 // 1.4.4 Compute u1 = es^−1 mod n
17189 // u2 = rs^−1 mod n
17190 var u1 = e.multiply(c).mod(n)
17191 var u2 = r.multiply(c).mod(n)
17192
17193 // 1.4.5 Compute R = (xR, yR) = u1G + u2Q
17194 var R = G.multiplyTwo(u1, Q, u2)
17195 var v = R.affineX.mod(n)
17196
17197 // 1.4.5 (cont.) Enforce R is not at infinity
17198 if (curve.isInfinity(R)) return false
17199
17200 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
17201 return v.equals(r)
17202}
17203
17204function verify (curve, hash, signature, Q) {
17205 // 1.4.2 H = Hash(M), already done by the user 16307 // 1.4.2 H = Hash(M), already done by the user
17206 // 1.4.3 e = H 16308 // 1.4.3 e = H
17207 var e = BigInteger.fromBuffer(hash) 16309 var e = BigInteger.fromBuffer(hash)
17208 16310
17209 return verifyRaw(curve, e, signature, Q) 16311 // Compute s^-1
17210} 16312 var sInv = s.modInverse(n)
17211
17212/**
17213 * Recover a public key from a signature.
17214 *
17215 * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
17216 * Key Recovery Operation".
17217 *
17218 * http://www.secg.org/download/aid-780/sec1-v2.pdf
17219 */
17220function recoverPubKey (curve, e, signature, i) {
17221 assert.strictEqual(i & 3, i, 'Recovery param is more than two bits')
17222
17223 var n = curve.n
17224 var G = curve.G
17225
17226 var r = signature.r
17227 var s = signature.s
17228
17229 assert(r.signum() > 0 && r.compareTo(n) < 0, 'Invalid r value')
17230 assert(s.signum() > 0 && s.compareTo(n) < 0, 'Invalid s value')
17231
17232 // A set LSB signifies that the y-coordinate is odd
17233 var isYOdd = i & 1
17234
17235 // The more significant bit specifies whether we should use the
17236 // first or second candidate key.
17237 var isSecondKey = i >> 1
17238
17239 // 1.1 Let x = r + jn
17240 var x = isSecondKey ? r.add(n) : r
17241 var R = curve.pointFromX(isYOdd, x)
17242
17243 // 1.4 Check that nR is at infinity
17244 var nR = R.multiply(n)
17245 assert(curve.isInfinity(nR), 'nR is not a valid curve point')
17246
17247 // Compute -e from e
17248 var eNeg = e.negate().mod(n)
17249 16313
17250 // 1.6.1 Compute Q = r^-1 (sR - eG) 16314 // 1.4.4 Compute u1 = es^−1 mod n
17251 // Q = r^-1 (sR + -eG) 16315 // u2 = rs^−1 mod n
17252 var rInv = r.modInverse(n) 16316 var u1 = e.multiply(sInv).mod(n)
16317 var u2 = r.multiply(sInv).mod(n)
17253 16318
17254 var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv) 16319 // 1.4.5 Compute R = (xR, yR)
17255 curve.validate(Q) 16320 // R = u1G + u2Q
16321 var R = G.multiplyTwo(u1, Q, u2)
17256 16322
17257 return Q 16323 // 1.4.5 (cont.) Enforce R is not at infinity
17258} 16324 if (secp256k1.isInfinity(R)) return false
17259 16325
17260/** 16326 // 1.4.6 Convert the field element R.x to an integer
17261 * Calculate pubkey extraction parameter. 16327 var xR = R.affineX
17262 *
17263 * When extracting a pubkey from a signature, we have to
17264 * distinguish four different cases. Rather than putting this
17265 * burden on the verifier, Bitcoin includes a 2-bit value with the
17266 * signature.
17267 *
17268 * This function simply tries all four cases and returns the value
17269 * that resulted in a successful pubkey recovery.
17270 */
17271function calcPubKeyRecoveryParam (curve, e, signature, Q) {
17272 for (var i = 0; i < 4; i++) {
17273 var Qprime = recoverPubKey(curve, e, signature, i)
17274 16328
17275 // 1.6.2 Verify Q 16329 // 1.4.7 Set v = xR mod n
17276 if (Qprime.equals(Q)) { 16330 var v = xR.mod(n)
17277 return i
17278 }
17279 }
17280 16331
17281 throw new Error('Unable to find valid recovery factor') 16332 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
16333 return v.equals(r)
17282} 16334}
17283 16335
17284module.exports = { 16336module.exports = {
17285 calcPubKeyRecoveryParam: calcPubKeyRecoveryParam,
17286 deterministicGenerateK: deterministicGenerateK, 16337 deterministicGenerateK: deterministicGenerateK,
17287 recoverPubKey: recoverPubKey,
17288 sign: sign, 16338 sign: sign,
17289 verify: verify, 16339 verify: verify,
17290 verifyRaw: verifyRaw 16340
16341 // TODO: remove
16342 __curve: secp256k1
17291} 16343}
17292 16344
17293}).call(this,require("buffer").Buffer) 16345},{"./ecsignature":48,"./types":78,"bigi":37,"create-hmac":85,"ecurve":89,"safe-buffer":98,"typeforce":109}],47:[function(require,module,exports){
17294},{"./ecsignature":62,"assert":5,"bigi":3,"buffer":7,"create-hmac":45,"typeforce":53}],60:[function(require,module,exports){ 16346var baddress = require('./address')
17295(function (Buffer){ 16347var bcrypto = require('./crypto')
17296var assert = require('assert')
17297var base58check = require('bs58check')
17298var ecdsa = require('./ecdsa') 16348var ecdsa = require('./ecdsa')
17299var networks = require('./networks')
17300var randomBytes = require('randombytes') 16349var randomBytes = require('randombytes')
17301var typeForce = require('typeforce') 16350var typeforce = require('typeforce')
16351var types = require('./types')
16352var wif = require('wif')
17302 16353
16354var NETWORKS = require('./networks')
17303var BigInteger = require('bigi') 16355var BigInteger = require('bigi')
17304var ECPubKey = require('./ecpubkey')
17305 16356
17306var ecurve = require('ecurve') 16357var ecurve = require('ecurve')
17307var secp256k1 = ecurve.getCurveByName('secp256k1') 16358var secp256k1 = ecdsa.__curve
17308 16359
17309function ECKey (d, compressed) { 16360function ECPair (d, Q, options) {
17310 assert(d.signum() > 0, 'Private key must be greater than 0') 16361 if (options) {
17311 assert(d.compareTo(ECKey.curve.n) < 0, 'Private key must be less than the curve order') 16362 typeforce({
17312 16363 compressed: types.maybe(types.Boolean),
17313 var Q = ECKey.curve.G.multiply(d) 16364 network: types.maybe(types.Network)
17314 16365 }, options)
17315 this.d = d 16366 }
17316 this.pub = new ECPubKey(Q, compressed)
17317}
17318
17319// Constants
17320ECKey.curve = secp256k1
17321 16367
17322// Static constructors 16368 options = options || {}
17323ECKey.fromWIF = function (string) {
17324 var payload = base58check.decode(string)
17325 var compressed = false
17326 16369
17327 // Ignore the version byte 16370 if (d) {
17328 payload = payload.slice(1) 16371 if (d.signum() <= 0) throw new Error('Private key must be greater than 0')
16372 if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order')
16373 if (Q) throw new TypeError('Unexpected publicKey parameter')
17329 16374
17330 if (payload.length === 33) { 16375 this.d = d
17331 assert.strictEqual(payload[32], 0x01, 'Invalid compression flag') 16376 } else {
16377 typeforce(types.ECPoint, Q)
17332 16378
17333 // Truncate the compression flag 16379 this.__Q = Q
17334 payload = payload.slice(0, -1)
17335 compressed = true
17336 } 16380 }
17337 16381
17338 assert.equal(payload.length, 32, 'Invalid WIF payload length') 16382 this.compressed = options.compressed === undefined ? true : options.compressed
17339 16383 this.network = options.network || NETWORKS.bitcoin
17340 var d = BigInteger.fromBuffer(payload)
17341 return new ECKey(d, compressed)
17342} 16384}
17343 16385
17344ECKey.makeRandom = function (compressed, rng) { 16386Object.defineProperty(ECPair.prototype, 'Q', {
17345 rng = rng || randomBytes 16387 get: function () {
16388 if (!this.__Q && this.d) {
16389 this.__Q = secp256k1.G.multiply(this.d)
16390 }
17346 16391
17347 var buffer = rng(32) 16392 return this.__Q
17348 typeForce('Buffer', buffer) 16393 }
17349 assert.equal(buffer.length, 32, 'Expected 256-bit Buffer from RNG') 16394})
17350 16395
17351 var d = BigInteger.fromBuffer(buffer) 16396ECPair.fromPublicKeyBuffer = function (buffer, network) {
17352 d = d.mod(ECKey.curve.n) 16397 var Q = ecurve.Point.decodeFrom(secp256k1, buffer)
17353 16398
17354 return new ECKey(d, compressed) 16399 return new ECPair(null, Q, {
16400 compressed: Q.compressed,
16401 network: network
16402 })
17355} 16403}
17356 16404
17357// Export functions 16405ECPair.fromWIF = function (string, network) {
17358ECKey.prototype.toWIF = function (network) { 16406 var decoded = wif.decode(string)
17359 network = network || networks.bitcoin 16407 var version = decoded.version
16408
16409 // list of networks?
16410 if (types.Array(network)) {
16411 network = network.filter(function (x) {
16412 return version === x.wif
16413 }).pop()
17360 16414
17361 var bufferLen = this.pub.compressed ? 34 : 33 16415 if (!network) throw new Error('Unknown network version')
17362 var buffer = new Buffer(bufferLen)
17363 16416
17364 buffer.writeUInt8(network.wif, 0) 16417 // otherwise, assume a network object (or default to bitcoin)
17365 this.d.toBuffer(32).copy(buffer, 1) 16418 } else {
16419 network = network || NETWORKS.bitcoin
17366 16420
17367 if (this.pub.compressed) { 16421 if (version !== network.wif) throw new Error('Invalid network version')
17368 buffer.writeUInt8(0x01, 33)
17369 } 16422 }
17370 16423
17371 return base58check.encode(buffer) 16424 var d = BigInteger.fromBuffer(decoded.privateKey)
17372}
17373 16425
17374// Operations 16426 return new ECPair(d, null, {
17375ECKey.prototype.sign = function (hash) { 16427 compressed: decoded.compressed,
17376 return ecdsa.sign(ECKey.curve, hash, this.d) 16428 network: network
16429 })
17377} 16430}
17378 16431
17379module.exports = ECKey 16432ECPair.makeRandom = function (options) {
17380 16433 options = options || {}
17381}).call(this,require("buffer").Buffer)
17382},{"./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){
17383(function (Buffer){
17384var crypto = require('./crypto')
17385var ecdsa = require('./ecdsa')
17386var typeForce = require('typeforce')
17387var networks = require('./networks')
17388 16434
17389var Address = require('./address') 16435 var rng = options.rng || randomBytes
17390 16436
17391var ecurve = require('ecurve') 16437 var d
17392var secp256k1 = ecurve.getCurveByName('secp256k1') 16438 do {
17393 16439 var buffer = rng(32)
17394function ECPubKey (Q, compressed) { 16440 typeforce(types.Buffer256bit, buffer)
17395 if (compressed === undefined) {
17396 compressed = true
17397 }
17398 16441
17399 typeForce('Point', Q) 16442 d = BigInteger.fromBuffer(buffer)
17400 typeForce('Boolean', compressed) 16443 } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0)
17401 16444
17402 this.compressed = compressed 16445 return new ECPair(d, null, options)
17403 this.Q = Q
17404} 16446}
17405 16447
17406// Constants 16448ECPair.prototype.getAddress = function () {
17407ECPubKey.curve = secp256k1 16449 return baddress.toBase58Check(bcrypto.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash)
16450}
17408 16451
17409// Static constructors 16452ECPair.prototype.getNetwork = function () {
17410ECPubKey.fromBuffer = function (buffer) { 16453 return this.network
17411 var Q = ecurve.Point.decodeFrom(ECPubKey.curve, buffer)
17412 return new ECPubKey(Q, Q.compressed)
17413} 16454}
17414 16455
17415ECPubKey.fromHex = function (hex) { 16456ECPair.prototype.getPublicKeyBuffer = function () {
17416 return ECPubKey.fromBuffer(new Buffer(hex, 'hex')) 16457 return this.Q.getEncoded(this.compressed)
17417} 16458}
17418 16459
17419// Operations 16460ECPair.prototype.sign = function (hash) {
17420ECPubKey.prototype.getAddress = function (network) { 16461 if (!this.d) throw new Error('Missing private key')
17421 network = network || networks.bitcoin
17422 16462
17423 return new Address(crypto.hash160(this.toBuffer()), network.pubKeyHash) 16463 return ecdsa.sign(hash, this.d)
17424} 16464}
17425 16465
17426ECPubKey.prototype.verify = function (hash, signature) { 16466ECPair.prototype.toWIF = function () {
17427 return ecdsa.verify(ECPubKey.curve, hash, signature, this.Q) 16467 if (!this.d) throw new Error('Missing private key')
17428}
17429 16468
17430// Export functions 16469 return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed)
17431ECPubKey.prototype.toBuffer = function () {
17432 return this.Q.getEncoded(this.compressed)
17433} 16470}
17434 16471
17435ECPubKey.prototype.toHex = function () { 16472ECPair.prototype.verify = function (hash, signature) {
17436 return this.toBuffer().toString('hex') 16473 return ecdsa.verify(hash, signature, this.Q)
17437} 16474}
17438 16475
17439module.exports = ECPubKey 16476module.exports = ECPair
17440 16477
17441}).call(this,require("buffer").Buffer) 16478},{"./address":42,"./crypto":45,"./ecdsa":46,"./networks":51,"./types":78,"bigi":37,"ecurve":89,"randombytes":96,"typeforce":109,"wif":112}],48:[function(require,module,exports){
17442},{"./address":54,"./crypto":58,"./ecdsa":59,"./networks":66,"buffer":7,"ecurve":49,"typeforce":53}],62:[function(require,module,exports){
17443(function (Buffer){ 16479(function (Buffer){
17444var assert = require('assert') 16480var bip66 = require('bip66')
17445var typeForce = require('typeforce') 16481var typeforce = require('typeforce')
16482var types = require('./types')
17446 16483
17447var BigInteger = require('bigi') 16484var BigInteger = require('bigi')
17448 16485
17449function ECSignature (r, s) { 16486function ECSignature (r, s) {
17450 typeForce('BigInteger', r) 16487 typeforce(types.tuple(types.BigInt, types.BigInt), arguments)
17451 typeForce('BigInteger', s)
17452 16488
17453 this.r = r 16489 this.r = r
17454 this.s = s 16490 this.s = s
17455} 16491}
17456 16492
17457ECSignature.parseCompact = function (buffer) { 16493ECSignature.parseCompact = function (buffer) {
17458 assert.equal(buffer.length, 65, 'Invalid signature length') 16494 if (buffer.length !== 65) throw new Error('Invalid signature length')
17459 var i = buffer.readUInt8(0) - 27
17460 16495
17461 // At most 3 bits 16496 var flagByte = buffer.readUInt8(0) - 27
17462 assert.equal(i, i & 7, 'Invalid signature parameter') 16497 if (flagByte !== (flagByte & 7)) throw new Error('Invalid signature parameter')
17463 var compressed = !!(i & 4)
17464 16498
17465 // Recovery param only 16499 var compressed = !!(flagByte & 4)
17466 i = i & 3 16500 var recoveryParam = flagByte & 3
17467 16501
17468 var r = BigInteger.fromBuffer(buffer.slice(1, 33)) 16502 var r = BigInteger.fromBuffer(buffer.slice(1, 33))
17469 var s = BigInteger.fromBuffer(buffer.slice(33)) 16503 var s = BigInteger.fromBuffer(buffer.slice(33))
17470 16504
17471 return { 16505 return {
17472 compressed: compressed, 16506 compressed: compressed,
17473 i: i, 16507 i: recoveryParam,
17474 signature: new ECSignature(r, s) 16508 signature: new ECSignature(r, s)
17475 } 16509 }
17476} 16510}
17477 16511
17478ECSignature.fromDER = function (buffer) { 16512ECSignature.fromDER = function (buffer) {
17479 assert.equal(buffer.readUInt8(0), 0x30, 'Not a DER sequence') 16513 var decode = bip66.decode(buffer)
17480 assert.equal(buffer.readUInt8(1), buffer.length - 2, 'Invalid sequence length') 16514 var r = BigInteger.fromDERInteger(decode.r)
17481 assert.equal(buffer.readUInt8(2), 0x02, 'Expected a DER integer') 16515 var s = BigInteger.fromDERInteger(decode.s)
17482
17483 var rLen = buffer.readUInt8(3)
17484 assert(rLen > 0, 'R length is zero')
17485
17486 var offset = 4 + rLen
17487 assert.equal(buffer.readUInt8(offset), 0x02, 'Expected a DER integer (2)')
17488
17489 var sLen = buffer.readUInt8(offset + 1)
17490 assert(sLen > 0, 'S length is zero')
17491
17492 var rB = buffer.slice(4, offset)
17493 var sB = buffer.slice(offset + 2)
17494 offset += 2 + sLen
17495
17496 if (rLen > 1 && rB.readUInt8(0) === 0x00) {
17497 assert(rB.readUInt8(1) & 0x80, 'R value excessively padded')
17498 }
17499
17500 if (sLen > 1 && sB.readUInt8(0) === 0x00) {
17501 assert(sB.readUInt8(1) & 0x80, 'S value excessively padded')
17502 }
17503
17504 assert.equal(offset, buffer.length, 'Invalid DER encoding')
17505 var r = BigInteger.fromDERInteger(rB)
17506 var s = BigInteger.fromDERInteger(sB)
17507
17508 assert(r.signum() >= 0, 'R value is negative')
17509 assert(s.signum() >= 0, 'S value is negative')
17510 16516
17511 return new ECSignature(r, s) 16517 return new ECSignature(r, s)
17512} 16518}
@@ -17516,7 +16522,7 @@ ECSignature.parseScriptSignature = function (buffer) {
17516 var hashType = buffer.readUInt8(buffer.length - 1) 16522 var hashType = buffer.readUInt8(buffer.length - 1)
17517 var hashTypeMod = hashType & ~0x80 16523 var hashTypeMod = hashType & ~0x80
17518 16524
17519 assert(hashTypeMod > 0x00 && hashTypeMod < 0x04, 'Invalid hashType ' + hashType) 16525 if (hashTypeMod <= 0x00 || hashTypeMod >= 0x04) throw new Error('Invalid hashType ' + hashType)
17520 16526
17521 return { 16527 return {
17522 signature: ECSignature.fromDER(buffer.slice(0, -1)), 16528 signature: ECSignature.fromDER(buffer.slice(0, -1)),
@@ -17531,9 +16537,8 @@ ECSignature.prototype.toCompact = function (i, compressed) {
17531 16537
17532 i += 27 16538 i += 27
17533 16539
17534 var buffer = new Buffer(65) 16540 var buffer = Buffer.alloc(65)
17535 buffer.writeUInt8(i, 0) 16541 buffer.writeUInt8(i, 0)
17536
17537 this.r.toBuffer(32).copy(buffer, 1) 16542 this.r.toBuffer(32).copy(buffer, 1)
17538 this.s.toBuffer(32).copy(buffer, 33) 16543 this.s.toBuffer(32).copy(buffer, 33)
17539 16544
@@ -17541,30 +16546,17 @@ ECSignature.prototype.toCompact = function (i, compressed) {
17541} 16546}
17542 16547
17543ECSignature.prototype.toDER = function () { 16548ECSignature.prototype.toDER = function () {
17544 var rBa = this.r.toDERInteger() 16549 var r = Buffer.from(this.r.toDERInteger())
17545 var sBa = this.s.toDERInteger() 16550 var s = Buffer.from(this.s.toDERInteger())
17546 16551
17547 var sequence = [] 16552 return bip66.encode(r, s)
17548
17549 // INTEGER
17550 sequence.push(0x02, rBa.length)
17551 sequence = sequence.concat(rBa)
17552
17553 // INTEGER
17554 sequence.push(0x02, sBa.length)
17555 sequence = sequence.concat(sBa)
17556
17557 // SEQUENCE
17558 sequence.unshift(0x30, sequence.length)
17559
17560 return new Buffer(sequence)
17561} 16553}
17562 16554
17563ECSignature.prototype.toScriptSignature = function (hashType) { 16555ECSignature.prototype.toScriptSignature = function (hashType) {
17564 var hashTypeMod = hashType & ~0x80 16556 var hashTypeMod = hashType & ~0x80
17565 assert(hashTypeMod > 0x00 && hashTypeMod < 0x04, 'Invalid hashType ' + hashType) 16557 if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType)
17566 16558
17567 var hashTypeBuffer = new Buffer(1) 16559 var hashTypeBuffer = Buffer.alloc(1)
17568 hashTypeBuffer.writeUInt8(hashType, 0) 16560 hashTypeBuffer.writeUInt8(hashType, 0)
17569 16561
17570 return Buffer.concat([this.toDER(), hashTypeBuffer]) 16562 return Buffer.concat([this.toDER(), hashTypeBuffer])
@@ -17573,149 +16565,124 @@ ECSignature.prototype.toScriptSignature = function (hashType) {
17573module.exports = ECSignature 16565module.exports = ECSignature
17574 16566
17575}).call(this,require("buffer").Buffer) 16567}).call(this,require("buffer").Buffer)
17576},{"assert":5,"bigi":3,"buffer":7,"typeforce":53}],63:[function(require,module,exports){ 16568},{"./types":78,"bigi":37,"bip66":39,"buffer":4,"typeforce":109}],49:[function(require,module,exports){
17577(function (Buffer){ 16569var Buffer = require('safe-buffer').Buffer
17578var assert = require('assert')
17579var base58check = require('bs58check') 16570var base58check = require('bs58check')
17580var bcrypto = require('./crypto') 16571var bcrypto = require('./crypto')
17581var createHmac = require('create-hmac') 16572var createHmac = require('create-hmac')
17582var typeForce = require('typeforce') 16573var typeforce = require('typeforce')
17583var networks = require('./networks') 16574var types = require('./types')
16575var NETWORKS = require('./networks')
17584 16576
17585var BigInteger = require('bigi') 16577var BigInteger = require('bigi')
17586var ECKey = require('./eckey') 16578var ECPair = require('./ecpair')
17587var ECPubKey = require('./ecpubkey')
17588 16579
17589var ecurve = require('ecurve') 16580var ecurve = require('ecurve')
17590var curve = ecurve.getCurveByName('secp256k1') 16581var curve = ecurve.getCurveByName('secp256k1')
17591 16582
17592function findBIP32NetworkByVersion (version) { 16583function HDNode (keyPair, chainCode) {
17593 for (var name in networks) { 16584 typeforce(types.tuple('ECPair', types.Buffer256bit), arguments)
17594 var network = networks[name]
17595 16585
17596 if (version === network.bip32.private || version === network.bip32.public) { 16586 if (!keyPair.compressed) throw new TypeError('BIP32 only allows compressed keyPairs')
17597 return network
17598 }
17599 }
17600
17601 assert(false, 'Could not find network for ' + version.toString(16))
17602}
17603
17604function HDNode (K, chainCode, network) {
17605 network = network || networks.bitcoin
17606
17607 typeForce('Buffer', chainCode)
17608
17609 assert.equal(chainCode.length, 32, 'Expected chainCode length of 32, got ' + chainCode.length)
17610 assert(network.bip32, 'Unknown BIP32 constants for network')
17611 16587
16588 this.keyPair = keyPair
17612 this.chainCode = chainCode 16589 this.chainCode = chainCode
17613 this.depth = 0 16590 this.depth = 0
17614 this.index = 0 16591 this.index = 0
17615 this.parentFingerprint = 0x00000000 16592 this.parentFingerprint = 0x00000000
17616 this.network = network
17617
17618 if (K instanceof BigInteger) {
17619 this.privKey = new ECKey(K, true)
17620 this.pubKey = this.privKey.pub
17621 } else if (K instanceof ECKey) {
17622 assert(K.pub.compressed, 'ECKey must be compressed')
17623 this.privKey = K
17624 this.pubKey = K.pub
17625 } else if (K instanceof ECPubKey) {
17626 assert(K.compressed, 'ECPubKey must be compressed')
17627 this.pubKey = K
17628 } else {
17629 this.pubKey = new ECPubKey(K, true)
17630 }
17631} 16593}
17632 16594
17633HDNode.MASTER_SECRET = new Buffer('Bitcoin seed')
17634HDNode.HIGHEST_BIT = 0x80000000 16595HDNode.HIGHEST_BIT = 0x80000000
17635HDNode.LENGTH = 78 16596HDNode.LENGTH = 78
16597HDNode.MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8')
17636 16598
17637HDNode.fromSeedBuffer = function (seed, network) { 16599HDNode.fromSeedBuffer = function (seed, network) {
17638 typeForce('Buffer', seed) 16600 typeforce(types.tuple(types.Buffer, types.maybe(types.Network)), arguments)
17639 16601
17640 assert(seed.length >= 16, 'Seed should be at least 128 bits') 16602 if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits')
17641 assert(seed.length <= 64, 'Seed should be at most 512 bits') 16603 if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits')
17642 16604
17643 var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest() 16605 var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest()
17644 var IL = I.slice(0, 32) 16606 var IL = I.slice(0, 32)
17645 var IR = I.slice(32) 16607 var IR = I.slice(32)
17646 16608
17647 // In case IL is 0 or >= n, the master key is invalid 16609 // In case IL is 0 or >= n, the master key is invalid
17648 // This is handled by `new ECKey` in the HDNode constructor 16610 // This is handled by the ECPair constructor
17649 var pIL = BigInteger.fromBuffer(IL) 16611 var pIL = BigInteger.fromBuffer(IL)
16612 var keyPair = new ECPair(pIL, null, {
16613 network: network
16614 })
17650 16615
17651 return new HDNode(pIL, IR, network) 16616 return new HDNode(keyPair, IR)
17652} 16617}
17653 16618
17654HDNode.fromSeedHex = function (hex, network) { 16619HDNode.fromSeedHex = function (hex, network) {
17655 return HDNode.fromSeedBuffer(new Buffer(hex, 'hex'), network) 16620 return HDNode.fromSeedBuffer(Buffer.from(hex, 'hex'), network)
17656}
17657
17658HDNode.fromBase58 = function (string, network) {
17659 return HDNode.fromBuffer(base58check.decode(string), network, true)
17660} 16621}
17661 16622
17662// FIXME: remove in 2.x.y 16623HDNode.fromBase58 = function (string, networks) {
17663HDNode.fromBuffer = function (buffer, network, __ignoreDeprecation) { 16624 var buffer = base58check.decode(string)
17664 if (!__ignoreDeprecation) { 16625 if (buffer.length !== 78) throw new Error('Invalid buffer length')
17665 console.warn('HDNode.fromBuffer() is deprecated for removal in 2.x.y, use fromBase58 instead')
17666 }
17667
17668 assert.strictEqual(buffer.length, HDNode.LENGTH, 'Invalid buffer length')
17669 16626
17670 // 4 byte: version bytes 16627 // 4 bytes: version bytes
17671 var version = buffer.readUInt32BE(0) 16628 var version = buffer.readUInt32BE(0)
16629 var network
16630
16631 // list of networks?
16632 if (Array.isArray(networks)) {
16633 network = networks.filter(function (x) {
16634 return version === x.bip32.private ||
16635 version === x.bip32.public
16636 }).pop()
17672 16637
17673 if (network) { 16638 if (!network) throw new Error('Unknown network version')
17674 assert(version === network.bip32.private || version === network.bip32.public, "Network doesn't match")
17675 16639
17676 // auto-detect 16640 // otherwise, assume a network object (or default to bitcoin)
17677 } else { 16641 } else {
17678 network = findBIP32NetworkByVersion(version) 16642 network = networks || NETWORKS.bitcoin
17679 } 16643 }
17680 16644
16645 if (version !== network.bip32.private &&
16646 version !== network.bip32.public) throw new Error('Invalid network version')
16647
17681 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... 16648 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
17682 var depth = buffer.readUInt8(4) 16649 var depth = buffer[4]
17683 16650
17684 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) 16651 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
17685 var parentFingerprint = buffer.readUInt32BE(5) 16652 var parentFingerprint = buffer.readUInt32BE(5)
17686 if (depth === 0) { 16653 if (depth === 0) {
17687 assert.strictEqual(parentFingerprint, 0x00000000, 'Invalid parent fingerprint') 16654 if (parentFingerprint !== 0x00000000) throw new Error('Invalid parent fingerprint')
17688 } 16655 }
17689 16656
17690 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. 16657 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
17691 // This is encoded in MSB order. (0x00000000 if master key) 16658 // This is encoded in MSB order. (0x00000000 if master key)
17692 var index = buffer.readUInt32BE(9) 16659 var index = buffer.readUInt32BE(9)
17693 assert(depth > 0 || index === 0, 'Invalid index') 16660 if (depth === 0 && index !== 0) throw new Error('Invalid index')
17694 16661
17695 // 32 bytes: the chain code 16662 // 32 bytes: the chain code
17696 var chainCode = buffer.slice(13, 45) 16663 var chainCode = buffer.slice(13, 45)
17697 var data, hd 16664 var keyPair
17698 16665
17699 // 33 bytes: private key data (0x00 + k) 16666 // 33 bytes: private key data (0x00 + k)
17700 if (version === network.bip32.private) { 16667 if (version === network.bip32.private) {
17701 assert.strictEqual(buffer.readUInt8(45), 0x00, 'Invalid private key') 16668 if (buffer.readUInt8(45) !== 0x00) throw new Error('Invalid private key')
17702 data = buffer.slice(46, 78) 16669
17703 var d = BigInteger.fromBuffer(data) 16670 var d = BigInteger.fromBuffer(buffer.slice(46, 78))
17704 hd = new HDNode(d, chainCode, network) 16671 keyPair = new ECPair(d, null, { network: network })
17705 16672
17706 // 33 bytes: public key data (0x02 + X or 0x03 + X) 16673 // 33 bytes: public key data (0x02 + X or 0x03 + X)
17707 } else { 16674 } else {
17708 data = buffer.slice(45, 78) 16675 var Q = ecurve.Point.decodeFrom(curve, buffer.slice(45, 78))
17709 var Q = ecurve.Point.decodeFrom(curve, data) 16676 // Q.compressed is assumed, if somehow this assumption is broken, `new HDNode` will throw
17710 assert.equal(Q.compressed, true, 'Invalid public key')
17711 16677
17712 // Verify that the X coordinate in the public point corresponds to a point on the curve. 16678 // Verify that the X coordinate in the public point corresponds to a point on the curve.
17713 // If not, the extended public key is invalid. 16679 // If not, the extended public key is invalid.
17714 curve.validate(Q) 16680 curve.validate(Q)
17715 16681
17716 hd = new HDNode(Q, chainCode, network) 16682 keyPair = new ECPair(null, Q, { network: network })
17717 } 16683 }
17718 16684
16685 var hd = new HDNode(keyPair, chainCode)
17719 hd.depth = depth 16686 hd.depth = depth
17720 hd.index = index 16687 hd.index = index
17721 hd.parentFingerprint = parentFingerprint 16688 hd.parentFingerprint = parentFingerprint
@@ -17723,25 +16690,32 @@ HDNode.fromBuffer = function (buffer, network, __ignoreDeprecation) {
17723 return hd 16690 return hd
17724} 16691}
17725 16692
17726// FIXME: remove in 2.x.y 16693HDNode.prototype.getAddress = function () {
17727HDNode.fromHex = function (hex, network) { 16694 return this.keyPair.getAddress()
17728 return HDNode.fromBuffer(new Buffer(hex, 'hex'), network)
17729} 16695}
17730 16696
17731HDNode.prototype.getIdentifier = function () { 16697HDNode.prototype.getIdentifier = function () {
17732 return bcrypto.hash160(this.pubKey.toBuffer()) 16698 return bcrypto.hash160(this.keyPair.getPublicKeyBuffer())
17733} 16699}
17734 16700
17735HDNode.prototype.getFingerprint = function () { 16701HDNode.prototype.getFingerprint = function () {
17736 return this.getIdentifier().slice(0, 4) 16702 return this.getIdentifier().slice(0, 4)
17737} 16703}
17738 16704
17739HDNode.prototype.getAddress = function () { 16705HDNode.prototype.getNetwork = function () {
17740 return this.pubKey.getAddress(this.network) 16706 return this.keyPair.getNetwork()
16707}
16708
16709HDNode.prototype.getPublicKeyBuffer = function () {
16710 return this.keyPair.getPublicKeyBuffer()
17741} 16711}
17742 16712
17743HDNode.prototype.neutered = function () { 16713HDNode.prototype.neutered = function () {
17744 var neutered = new HDNode(this.pubKey.Q, this.chainCode, this.network) 16714 var neuteredKeyPair = new ECPair(null, this.keyPair.Q, {
16715 network: this.keyPair.network
16716 })
16717
16718 var neutered = new HDNode(neuteredKeyPair, this.chainCode)
17745 neutered.depth = this.depth 16719 neutered.depth = this.depth
17746 neutered.index = this.index 16720 neutered.index = this.index
17747 neutered.parentFingerprint = this.parentFingerprint 16721 neutered.parentFingerprint = this.parentFingerprint
@@ -17749,32 +16723,25 @@ HDNode.prototype.neutered = function () {
17749 return neutered 16723 return neutered
17750} 16724}
17751 16725
17752HDNode.prototype.toBase58 = function (isPrivate) { 16726HDNode.prototype.sign = function (hash) {
17753 return base58check.encode(this.toBuffer(isPrivate, true)) 16727 return this.keyPair.sign(hash)
17754} 16728}
17755 16729
17756// FIXME: remove in 2.x.y 16730HDNode.prototype.verify = function (hash, signature) {
17757HDNode.prototype.toBuffer = function (isPrivate, __ignoreDeprecation) { 16731 return this.keyPair.verify(hash, signature)
17758 if (isPrivate === undefined) { 16732}
17759 isPrivate = !!this.privKey
17760
17761 // FIXME: remove in 2.x.y
17762 } else {
17763 console.warn('isPrivate flag is deprecated, please use the .neutered() method instead')
17764 }
17765 16733
17766 if (!__ignoreDeprecation) { 16734HDNode.prototype.toBase58 = function (__isPrivate) {
17767 console.warn('HDNode.toBuffer() is deprecated for removal in 2.x.y, use toBase58 instead') 16735 if (__isPrivate !== undefined) throw new TypeError('Unsupported argument in 2.0.0')
17768 }
17769 16736
17770 // Version 16737 // Version
17771 var version = isPrivate ? this.network.bip32.private : this.network.bip32.public 16738 var network = this.keyPair.network
17772 var buffer = new Buffer(HDNode.LENGTH) 16739 var version = (!this.isNeutered()) ? network.bip32.private : network.bip32.public
16740 var buffer = Buffer.allocUnsafe(78)
17773 16741
17774 // 4 bytes: version bytes 16742 // 4 bytes: version bytes
17775 buffer.writeUInt32BE(version, 0) 16743 buffer.writeUInt32BE(version, 0)
17776 16744
17777 // Depth
17778 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... 16745 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
17779 buffer.writeUInt8(this.depth, 4) 16746 buffer.writeUInt8(this.depth, 4)
17780 16747
@@ -17782,59 +16749,49 @@ HDNode.prototype.toBuffer = function (isPrivate, __ignoreDeprecation) {
17782 buffer.writeUInt32BE(this.parentFingerprint, 5) 16749 buffer.writeUInt32BE(this.parentFingerprint, 5)
17783 16750
17784 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. 16751 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
17785 // This is encoded in Big endian. (0x00000000 if master key) 16752 // This is encoded in big endian. (0x00000000 if master key)
17786 buffer.writeUInt32BE(this.index, 9) 16753 buffer.writeUInt32BE(this.index, 9)
17787 16754
17788 // 32 bytes: the chain code 16755 // 32 bytes: the chain code
17789 this.chainCode.copy(buffer, 13) 16756 this.chainCode.copy(buffer, 13)
17790 16757
17791 // 33 bytes: the public key or private key data 16758 // 33 bytes: the public key or private key data
17792 if (isPrivate) { 16759 if (!this.isNeutered()) {
17793 // FIXME: remove in 2.x.y
17794 assert(this.privKey, 'Missing private key')
17795
17796 // 0x00 + k for private keys 16760 // 0x00 + k for private keys
17797 buffer.writeUInt8(0, 45) 16761 buffer.writeUInt8(0, 45)
17798 this.privKey.d.toBuffer(32).copy(buffer, 46) 16762 this.keyPair.d.toBuffer(32).copy(buffer, 46)
16763
16764 // 33 bytes: the public key
17799 } else { 16765 } else {
17800 // X9.62 encoding for public keys 16766 // X9.62 encoding for public keys
17801 this.pubKey.toBuffer().copy(buffer, 45) 16767 this.keyPair.getPublicKeyBuffer().copy(buffer, 45)
17802 } 16768 }
17803 16769
17804 return buffer 16770 return base58check.encode(buffer)
17805}
17806
17807// FIXME: remove in 2.x.y
17808HDNode.prototype.toHex = function (isPrivate) {
17809 return this.toBuffer(isPrivate).toString('hex')
17810} 16771}
17811 16772
17812// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions 16773// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
17813HDNode.prototype.derive = function (index) { 16774HDNode.prototype.derive = function (index) {
17814 var isHardened = index >= HDNode.HIGHEST_BIT 16775 typeforce(types.UInt32, index)
17815 var indexBuffer = new Buffer(4)
17816 indexBuffer.writeUInt32BE(index, 0)
17817 16776
17818 var data 16777 var isHardened = index >= HDNode.HIGHEST_BIT
16778 var data = Buffer.allocUnsafe(37)
17819 16779
17820 // Hardened child 16780 // Hardened child
17821 if (isHardened) { 16781 if (isHardened) {
17822 assert(this.privKey, 'Could not derive hardened child key') 16782 if (this.isNeutered()) throw new TypeError('Could not derive hardened child key')
17823 16783
17824 // data = 0x00 || ser256(kpar) || ser32(index) 16784 // data = 0x00 || ser256(kpar) || ser32(index)
17825 data = Buffer.concat([ 16785 data[0] = 0x00
17826 this.privKey.d.toBuffer(33), 16786 this.keyPair.d.toBuffer(32).copy(data, 1)
17827 indexBuffer 16787 data.writeUInt32BE(index, 33)
17828 ])
17829 16788
17830 // Normal child 16789 // Normal child
17831 } else { 16790 } else {
17832 // data = serP(point(kpar)) || ser32(index) 16791 // data = serP(point(kpar)) || ser32(index)
17833 // = serP(Kpar) || ser32(index) 16792 // = serP(Kpar) || ser32(index)
17834 data = Buffer.concat([ 16793 this.keyPair.getPublicKeyBuffer().copy(data, 0)
17835 this.pubKey.toBuffer(), 16794 data.writeUInt32BE(index, 33)
17836 indexBuffer
17837 ])
17838 } 16795 }
17839 16796
17840 var I = createHmac('sha512', this.chainCode).update(data).digest() 16797 var I = createHmac('sha512', this.chainCode).update(data).digest()
@@ -17849,32 +16806,37 @@ HDNode.prototype.derive = function (index) {
17849 } 16806 }
17850 16807
17851 // Private parent key -> private child key 16808 // Private parent key -> private child key
17852 var hd 16809 var derivedKeyPair
17853 if (this.privKey) { 16810 if (!this.isNeutered()) {
17854 // ki = parse256(IL) + kpar (mod n) 16811 // ki = parse256(IL) + kpar (mod n)
17855 var ki = pIL.add(this.privKey.d).mod(curve.n) 16812 var ki = pIL.add(this.keyPair.d).mod(curve.n)
17856 16813
17857 // In case ki == 0, proceed with the next value for i 16814 // In case ki == 0, proceed with the next value for i
17858 if (ki.signum() === 0) { 16815 if (ki.signum() === 0) {
17859 return this.derive(index + 1) 16816 return this.derive(index + 1)
17860 } 16817 }
17861 16818
17862 hd = new HDNode(ki, IR, this.network) 16819 derivedKeyPair = new ECPair(ki, null, {
16820 network: this.keyPair.network
16821 })
17863 16822
17864 // Public parent key -> public child key 16823 // Public parent key -> public child key
17865 } else { 16824 } else {
17866 // Ki = point(parse256(IL)) + Kpar 16825 // Ki = point(parse256(IL)) + Kpar
17867 // = G*IL + Kpar 16826 // = G*IL + Kpar
17868 var Ki = curve.G.multiply(pIL).add(this.pubKey.Q) 16827 var Ki = curve.G.multiply(pIL).add(this.keyPair.Q)
17869 16828
17870 // In case Ki is the point at infinity, proceed with the next value for i 16829 // In case Ki is the point at infinity, proceed with the next value for i
17871 if (curve.isInfinity(Ki)) { 16830 if (curve.isInfinity(Ki)) {
17872 return this.derive(index + 1) 16831 return this.derive(index + 1)
17873 } 16832 }
17874 16833
17875 hd = new HDNode(Ki, IR, this.network) 16834 derivedKeyPair = new ECPair(null, Ki, {
16835 network: this.keyPair.network
16836 })
17876 } 16837 }
17877 16838
16839 var hd = new HDNode(derivedKeyPair, IR)
17878 hd.depth = this.depth + 1 16840 hd.depth = this.depth + 1
17879 hd.index = index 16841 hd.index = index
17880 hd.parentFingerprint = this.getFingerprint().readUInt32BE(0) 16842 hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)
@@ -17883,435 +16845,204 @@ HDNode.prototype.derive = function (index) {
17883} 16845}
17884 16846
17885HDNode.prototype.deriveHardened = function (index) { 16847HDNode.prototype.deriveHardened = function (index) {
16848 typeforce(types.UInt31, index)
16849
17886 // Only derives hardened private keys by default 16850 // Only derives hardened private keys by default
17887 return this.derive(index + HDNode.HIGHEST_BIT) 16851 return this.derive(index + HDNode.HIGHEST_BIT)
17888} 16852}
17889 16853
17890HDNode.prototype.toString = HDNode.prototype.toBase58 16854// Private === not neutered
16855// Public === neutered
16856HDNode.prototype.isNeutered = function () {
16857 return !(this.keyPair.d)
16858}
16859
16860HDNode.prototype.derivePath = function (path) {
16861 typeforce(types.BIP32Path, path)
16862
16863 var splitPath = path.split('/')
16864 if (splitPath[0] === 'm') {
16865 if (this.parentFingerprint) {
16866 throw new Error('Not a master node')
16867 }
16868
16869 splitPath = splitPath.slice(1)
16870 }
16871
16872 return splitPath.reduce(function (prevHd, indexStr) {
16873 var index
16874 if (indexStr.slice(-1) === "'") {
16875 index = parseInt(indexStr.slice(0, -1), 10)
16876 return prevHd.deriveHardened(index)
16877 } else {
16878 index = parseInt(indexStr, 10)
16879 return prevHd.derive(index)
16880 }
16881 }, this)
16882}
17891 16883
17892module.exports = HDNode 16884module.exports = HDNode
17893 16885
17894}).call(this,require("buffer").Buffer) 16886},{"./crypto":45,"./ecpair":47,"./networks":51,"./types":78,"bigi":37,"bs58check":80,"create-hmac":85,"ecurve":89,"safe-buffer":98,"typeforce":109}],50:[function(require,module,exports){
17895},{"./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){
17896module.exports = { 16887module.exports = {
17897 Address: require('./address'),
17898 base58check: require('./base58check'),
17899 Block: require('./block'), 16888 Block: require('./block'),
17900 bufferutils: require('./bufferutils'), 16889 ECPair: require('./ecpair'),
17901 crypto: require('./crypto'),
17902 ecdsa: require('./ecdsa'),
17903 ECKey: require('./eckey'),
17904 ECPubKey: require('./ecpubkey'),
17905 ECSignature: require('./ecsignature'), 16890 ECSignature: require('./ecsignature'),
17906 Message: require('./message'),
17907 opcodes: require('./opcodes'),
17908 HDNode: require('./hdnode'), 16891 HDNode: require('./hdnode'),
17909 Script: require('./script'),
17910 scripts: require('./scripts'),
17911 Transaction: require('./transaction'), 16892 Transaction: require('./transaction'),
17912 TransactionBuilder: require('./transaction_builder'), 16893 TransactionBuilder: require('./transaction_builder'),
17913 networks: require('./networks'),
17914 Wallet: require('./wallet')
17915}
17916
17917},{"./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){
17918(function (Buffer){
17919var bufferutils = require('./bufferutils')
17920var crypto = require('./crypto')
17921var ecdsa = require('./ecdsa')
17922var networks = require('./networks')
17923
17924var BigInteger = require('bigi')
17925var ECPubKey = require('./ecpubkey')
17926var ECSignature = require('./ecsignature')
17927 16894
17928var ecurve = require('ecurve') 16895 address: require('./address'),
17929var ecparams = ecurve.getCurveByName('secp256k1') 16896 bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0
17930 16897 crypto: require('./crypto'),
17931function magicHash (message, network) { 16898 networks: require('./networks'),
17932 var magicPrefix = new Buffer(network.magicPrefix) 16899 opcodes: require('bitcoin-ops'),
17933 var messageBuffer = new Buffer(message) 16900 script: require('./script')
17934 var lengthBuffer = bufferutils.varIntBuffer(messageBuffer.length)
17935
17936 var buffer = Buffer.concat([magicPrefix, lengthBuffer, messageBuffer])
17937 return crypto.hash256(buffer)
17938}
17939
17940function sign (privKey, message, network) {
17941 network = network || networks.bitcoin
17942
17943 var hash = magicHash(message, network)
17944 var signature = privKey.sign(hash)
17945 var e = BigInteger.fromBuffer(hash)
17946 var i = ecdsa.calcPubKeyRecoveryParam(ecparams, e, signature, privKey.pub.Q)
17947
17948 return signature.toCompact(i, privKey.pub.compressed)
17949}
17950
17951// TODO: network could be implied from address
17952function verify (address, signature, message, network) {
17953 if (!Buffer.isBuffer(signature)) {
17954 signature = new Buffer(signature, 'base64')
17955 }
17956
17957 network = network || networks.bitcoin
17958
17959 var hash = magicHash(message, network)
17960 var parsed = ECSignature.parseCompact(signature)
17961 var e = BigInteger.fromBuffer(hash)
17962 var Q = ecdsa.recoverPubKey(ecparams, e, parsed.signature, parsed.i)
17963
17964 var pubKey = new ECPubKey(Q, parsed.compressed)
17965 return pubKey.getAddress(network).toString() === address.toString()
17966}
17967
17968module.exports = {
17969 magicHash: magicHash,
17970 sign: sign,
17971 verify: verify
17972} 16901}
17973 16902
17974}).call(this,require("buffer").Buffer) 16903},{"./address":42,"./block":43,"./bufferutils":44,"./crypto":45,"./ecpair":47,"./ecsignature":48,"./hdnode":49,"./networks":51,"./script":52,"./transaction":76,"./transaction_builder":77,"bitcoin-ops":40}],51:[function(require,module,exports){
17975},{"./bufferutils":57,"./crypto":58,"./ecdsa":59,"./ecpubkey":61,"./ecsignature":62,"./networks":66,"bigi":3,"buffer":7,"ecurve":49}],66:[function(require,module,exports){
17976// https://en.bitcoin.it/wiki/List_of_address_prefixes 16904// https://en.bitcoin.it/wiki/List_of_address_prefixes
17977// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 16905// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
17978 16906
17979var networks = { 16907module.exports = {
17980 bitcoin: { 16908 bitcoin: {
17981 magicPrefix: '\x18Bitcoin Signed Message:\n', 16909 messagePrefix: '\x18Bitcoin Signed Message:\n',
17982 bip32: { 16910 bip32: {
17983 public: 0x0488b21e, 16911 public: 0x0488b21e,
17984 private: 0x0488ade4 16912 private: 0x0488ade4
17985 }, 16913 },
17986 pubKeyHash: 0x00, 16914 pubKeyHash: 0x00,
17987 scriptHash: 0x05, 16915 scriptHash: 0x05,
17988 wif: 0x80, 16916 wif: 0x80
17989 dustThreshold: 546, // https://github.com/bitcoin/bitcoin/blob/v0.9.2/src/core.h#L151-L162
17990 feePerKb: 10000, // https://github.com/bitcoin/bitcoin/blob/v0.9.2/src/main.cpp#L53
17991 estimateFee: estimateFee('bitcoin')
17992 }, 16917 },
17993 testnet: { 16918 testnet: {
17994 magicPrefix: '\x18Bitcoin Signed Message:\n', 16919 messagePrefix: '\x18Bitcoin Signed Message:\n',
17995 bip32: { 16920 bip32: {
17996 public: 0x043587cf, 16921 public: 0x043587cf,
17997 private: 0x04358394 16922 private: 0x04358394
17998 }, 16923 },
17999 pubKeyHash: 0x6f, 16924 pubKeyHash: 0x6f,
18000 scriptHash: 0xc4, 16925 scriptHash: 0xc4,
18001 wif: 0xef, 16926 wif: 0xef
18002 dustThreshold: 546,
18003 feePerKb: 10000,
18004 estimateFee: estimateFee('testnet')
18005 }, 16927 },
18006 litecoin: { 16928 litecoin: {
18007 magicPrefix: '\x19Litecoin Signed Message:\n', 16929 messagePrefix: '\x19Litecoin Signed Message:\n',
18008 bip32: { 16930 bip32: {
18009 public: 0x019da462, 16931 public: 0x019da462,
18010 private: 0x019d9cfe 16932 private: 0x019d9cfe
18011 }, 16933 },
18012 pubKeyHash: 0x30, 16934 pubKeyHash: 0x30,
18013 scriptHash: 0x05, 16935 scriptHash: 0x32,
18014 wif: 0xb0, 16936 wif: 0xb0
18015 dustThreshold: 0, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.cpp#L360-L365
18016 dustSoftThreshold: 100000, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.h#L53
18017 feePerKb: 100000, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.cpp#L56
18018 estimateFee: estimateFee('litecoin')
18019 },
18020 dogecoin: {
18021 magicPrefix: '\x19Dogecoin Signed Message:\n',
18022 bip32: {
18023 public: 0x02facafd,
18024 private: 0x02fac398
18025 },
18026 pubKeyHash: 0x1e,
18027 scriptHash: 0x16,
18028 wif: 0x9e,
18029 dustThreshold: 0, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/core.h#L155-L160
18030 dustSoftThreshold: 100000000, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/main.h#L62
18031 feePerKb: 100000000, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/main.cpp#L58
18032 estimateFee: estimateFee('dogecoin')
18033 },
18034 viacoin: {
18035 magicPrefix: '\x18Viacoin Signed Message:\n',
18036 bip32: {
18037 public: 0x0488b21e,
18038 private: 0x0488ade4
18039 },
18040 pubKeyHash: 0x47,
18041 scriptHash: 0x21,
18042 wif: 0xc7,
18043 dustThreshold: 560,
18044 dustSoftThreshold: 100000,
18045 feePerKb: 100000, //
18046 estimateFee: estimateFee('viacoin')
18047 },
18048 viacointestnet: {
18049 magicPrefix: '\x18Viacoin Signed Message:\n',
18050 bip32: {
18051 public: 0x043587cf,
18052 private: 0x04358394
18053 },
18054 pubKeyHash: 0x7f,
18055 scriptHash: 0xc4,
18056 wif: 0xff,
18057 dustThreshold: 560,
18058 dustSoftThreshold: 100000,
18059 feePerKb: 100000,
18060 estimateFee: estimateFee('viacointestnet')
18061 },
18062 gamerscoin: {
18063 magicPrefix: '\x19Gamerscoin Signed Message:\n',
18064 bip32: {
18065 public: 0x019da462,
18066 private: 0x019d9cfe
18067 },
18068 pubKeyHash: 0x26,
18069 scriptHash: 0x05,
18070 wif: 0xA6,
18071 dustThreshold: 0, // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L358-L363
18072 dustSoftThreshold: 100000, // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L51
18073 feePerKb: 100000, // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L54
18074 estimateFee: estimateFee('gamerscoin')
18075 },
18076 jumbucks: {
18077 magicPrefix: '\x19Jumbucks Signed Message:\n',
18078 bip32: {
18079 public: 0x037a689a,
18080 private: 0x037a6460
18081 },
18082 pubKeyHash: 0x2b,
18083 scriptHash: 0x05,
18084 wif: 0xab,
18085 dustThreshold: 0,
18086 dustSoftThreshold: 10000,
18087 feePerKb: 10000,
18088 estimateFee: estimateFee('jumbucks')
18089 },
18090 zetacoin: {
18091 magicPrefix: '\x18Zetacoin Signed Message:\n',
18092 bip32: {
18093 public: 0x0488b21e,
18094 private: 0x0488ade4
18095 },
18096 pubKeyHash: 0x50,
18097 scriptHash: 0x09,
18098 wif: 0xe0,
18099 dustThreshold: 546, // https://github.com/zetacoin/zetacoin/blob/master/src/core.h#L159
18100 feePerKb: 10000, // https://github.com/zetacoin/zetacoin/blob/master/src/main.cpp#L54
18101 estimateFee: estimateFee('zetacoin')
18102 } 16937 }
18103} 16938}
18104 16939
18105function estimateFee (type) { 16940},{}],52:[function(require,module,exports){
18106 return function (tx) { 16941var Buffer = require('safe-buffer').Buffer
18107 var network = networks[type] 16942var bip66 = require('bip66')
18108 var baseFee = network.feePerKb 16943var pushdata = require('pushdata-bitcoin')
18109 var byteSize = tx.toBuffer().length 16944var typeforce = require('typeforce')
16945var types = require('./types')
16946var scriptNumber = require('./script_number')
18110 16947
18111 var fee = baseFee * Math.ceil(byteSize / 1000) 16948var OPS = require('bitcoin-ops')
18112 if (network.dustSoftThreshold === undefined) return fee 16949var REVERSE_OPS = require('bitcoin-ops/map')
16950var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
18113 16951
18114 tx.outs.forEach(function (e) { 16952function isOPInt (value) {
18115 if (e.value < network.dustSoftThreshold) { 16953 return types.Number(value) &&
18116 fee += baseFee 16954 ((value === OPS.OP_0) ||
18117 } 16955 (value >= OPS.OP_1 && value <= OPS.OP_16) ||
18118 }) 16956 (value === OPS.OP_1NEGATE))
16957}
18119 16958
18120 return fee 16959function isPushOnlyChunk (value) {
18121 } 16960 return types.Buffer(value) || isOPInt(value)
16961}
16962
16963function isPushOnly (value) {
16964 return types.Array(value) && value.every(isPushOnlyChunk)
18122} 16965}
18123 16966
18124module.exports = networks 16967function compile (chunks) {
16968 // TODO: remove me
16969 if (Buffer.isBuffer(chunks)) return chunks
18125 16970
18126},{}],67:[function(require,module,exports){ 16971 typeforce(types.Array, chunks)
18127module.exports = {
18128 // push value
18129 OP_FALSE: 0,
18130 OP_0: 0,
18131 OP_PUSHDATA1: 76,
18132 OP_PUSHDATA2: 77,
18133 OP_PUSHDATA4: 78,
18134 OP_1NEGATE: 79,
18135 OP_RESERVED: 80,
18136 OP_1: 81,
18137 OP_TRUE: 81,
18138 OP_2: 82,
18139 OP_3: 83,
18140 OP_4: 84,
18141 OP_5: 85,
18142 OP_6: 86,
18143 OP_7: 87,
18144 OP_8: 88,
18145 OP_9: 89,
18146 OP_10: 90,
18147 OP_11: 91,
18148 OP_12: 92,
18149 OP_13: 93,
18150 OP_14: 94,
18151 OP_15: 95,
18152 OP_16: 96,
18153
18154 // control
18155 OP_NOP: 97,
18156 OP_VER: 98,
18157 OP_IF: 99,
18158 OP_NOTIF: 100,
18159 OP_VERIF: 101,
18160 OP_VERNOTIF: 102,
18161 OP_ELSE: 103,
18162 OP_ENDIF: 104,
18163 OP_VERIFY: 105,
18164 OP_RETURN: 106,
18165
18166 // stack ops
18167 OP_TOALTSTACK: 107,
18168 OP_FROMALTSTACK: 108,
18169 OP_2DROP: 109,
18170 OP_2DUP: 110,
18171 OP_3DUP: 111,
18172 OP_2OVER: 112,
18173 OP_2ROT: 113,
18174 OP_2SWAP: 114,
18175 OP_IFDUP: 115,
18176 OP_DEPTH: 116,
18177 OP_DROP: 117,
18178 OP_DUP: 118,
18179 OP_NIP: 119,
18180 OP_OVER: 120,
18181 OP_PICK: 121,
18182 OP_ROLL: 122,
18183 OP_ROT: 123,
18184 OP_SWAP: 124,
18185 OP_TUCK: 125,
18186
18187 // splice ops
18188 OP_CAT: 126,
18189 OP_SUBSTR: 127,
18190 OP_LEFT: 128,
18191 OP_RIGHT: 129,
18192 OP_SIZE: 130,
18193
18194 // bit logic
18195 OP_INVERT: 131,
18196 OP_AND: 132,
18197 OP_OR: 133,
18198 OP_XOR: 134,
18199 OP_EQUAL: 135,
18200 OP_EQUALVERIFY: 136,
18201 OP_RESERVED1: 137,
18202 OP_RESERVED2: 138,
18203
18204 // numeric
18205 OP_1ADD: 139,
18206 OP_1SUB: 140,
18207 OP_2MUL: 141,
18208 OP_2DIV: 142,
18209 OP_NEGATE: 143,
18210 OP_ABS: 144,
18211 OP_NOT: 145,
18212 OP_0NOTEQUAL: 146,
18213
18214 OP_ADD: 147,
18215 OP_SUB: 148,
18216 OP_MUL: 149,
18217 OP_DIV: 150,
18218 OP_MOD: 151,
18219 OP_LSHIFT: 152,
18220 OP_RSHIFT: 153,
18221
18222 OP_BOOLAND: 154,
18223 OP_BOOLOR: 155,
18224 OP_NUMEQUAL: 156,
18225 OP_NUMEQUALVERIFY: 157,
18226 OP_NUMNOTEQUAL: 158,
18227 OP_LESSTHAN: 159,
18228 OP_GREATERTHAN: 160,
18229 OP_LESSTHANOREQUAL: 161,
18230 OP_GREATERTHANOREQUAL: 162,
18231 OP_MIN: 163,
18232 OP_MAX: 164,
18233
18234 OP_WITHIN: 165,
18235
18236 // crypto
18237 OP_RIPEMD160: 166,
18238 OP_SHA1: 167,
18239 OP_SHA256: 168,
18240 OP_HASH160: 169,
18241 OP_HASH256: 170,
18242 OP_CODESEPARATOR: 171,
18243 OP_CHECKSIG: 172,
18244 OP_CHECKSIGVERIFY: 173,
18245 OP_CHECKMULTISIG: 174,
18246 OP_CHECKMULTISIGVERIFY: 175,
18247
18248 // expansion
18249 OP_NOP1: 176,
18250 OP_NOP2: 177,
18251 OP_NOP3: 178,
18252 OP_NOP4: 179,
18253 OP_NOP5: 180,
18254 OP_NOP6: 181,
18255 OP_NOP7: 182,
18256 OP_NOP8: 183,
18257 OP_NOP9: 184,
18258 OP_NOP10: 185,
18259
18260 // template matching params
18261 OP_PUBKEYHASH: 253,
18262 OP_PUBKEY: 254,
18263 OP_INVALIDOPCODE: 255
18264}
18265
18266},{}],68:[function(require,module,exports){
18267(function (Buffer){
18268var assert = require('assert')
18269var bufferutils = require('./bufferutils')
18270var crypto = require('./crypto')
18271var typeForce = require('typeforce')
18272var opcodes = require('./opcodes')
18273 16972
18274function Script (buffer, chunks) { 16973 var bufferSize = chunks.reduce(function (accum, chunk) {
18275 typeForce('Buffer', buffer) 16974 // data chunk
18276 typeForce('Array', chunks) 16975 if (Buffer.isBuffer(chunk)) {
16976 // adhere to BIP62.3, minimal push policy
16977 if (chunk.length === 1 && (chunk[0] === 0x81 || (chunk[0] >= 1 && chunk[0] <= 16))) {
16978 return accum + 1
16979 }
18277 16980
18278 this.buffer = buffer 16981 return accum + pushdata.encodingLength(chunk.length) + chunk.length
18279 this.chunks = chunks 16982 }
18280}
18281 16983
18282Script.fromASM = function (asm) {
18283 var strChunks = asm.split(' ')
18284 var chunks = strChunks.map(function (strChunk) {
18285 // opcode 16984 // opcode
18286 if (strChunk in opcodes) { 16985 return accum + 1
18287 return opcodes[strChunk] 16986 }, 0.0)
18288 16987
16988 var buffer = Buffer.allocUnsafe(bufferSize)
16989 var offset = 0
16990
16991 chunks.forEach(function (chunk) {
18289 // data chunk 16992 // data chunk
16993 if (Buffer.isBuffer(chunk)) {
16994 // adhere to BIP62.3, minimal push policy
16995 if (chunk.length === 1 && chunk[0] >= 1 && chunk[0] <= 16) {
16996 var opcode = OP_INT_BASE + chunk[0]
16997 buffer.writeUInt8(opcode, offset)
16998 offset += 1
16999 return
17000 }
17001
17002 if (chunk.length === 1 && chunk[0] === 0x81) {
17003 buffer.writeUInt8(OPS.OP_1NEGATE, offset)
17004 offset += 1
17005 return
17006 }
17007
17008 offset += pushdata.encode(buffer, chunk.length, offset)
17009
17010 chunk.copy(buffer, offset)
17011 offset += chunk.length
17012
17013 // opcode
18290 } else { 17014 } else {
18291 return new Buffer(strChunk, 'hex') 17015 buffer.writeUInt8(chunk, offset)
17016 offset += 1
18292 } 17017 }
18293 }) 17018 })
18294 17019
18295 return Script.fromChunks(chunks) 17020 if (offset !== buffer.length) throw new Error('Could not decode chunks')
17021 return buffer
18296} 17022}
18297 17023
18298Script.fromBuffer = function (buffer) { 17024function decompile (buffer) {
17025 // TODO: remove me
17026 if (types.Array(buffer)) return buffer
17027
17028 typeforce(types.Buffer, buffer)
17029
18299 var chunks = [] 17030 var chunks = []
18300 var i = 0 17031 var i = 0
18301 17032
18302 while (i < buffer.length) { 17033 while (i < buffer.length) {
18303 var opcode = buffer.readUInt8(i) 17034 var opcode = buffer[i]
18304 17035
18305 // data chunk 17036 // data chunk
18306 if ((opcode > opcodes.OP_0) && (opcode <= opcodes.OP_PUSHDATA4)) { 17037 if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) {
18307 var d = bufferutils.readPushDataInt(buffer, i) 17038 var d = pushdata.decode(buffer, i)
18308 17039
18309 // did reading a pushDataInt fail? return non-chunked script 17040 // did reading a pushDataInt fail? empty script
18310 if (d === null) return new Script(buffer, []) 17041 if (d === null) return []
18311 i += d.size 17042 i += d.size
18312 17043
18313 // attempt to read too much data? 17044 // attempt to read too much data? empty script
18314 if (i + d.number > buffer.length) return new Script(buffer, []) 17045 if (i + d.number > buffer.length) return []
18315 17046
18316 var data = buffer.slice(i, i + d.number) 17047 var data = buffer.slice(i, i + d.number)
18317 i += d.number 17048 i += d.number
@@ -18326,398 +17057,870 @@ Script.fromBuffer = function (buffer) {
18326 } 17057 }
18327 } 17058 }
18328 17059
18329 return new Script(buffer, chunks) 17060 return chunks
18330} 17061}
18331 17062
18332Script.fromChunks = function (chunks) { 17063function toASM (chunks) {
18333 typeForce('Array', chunks) 17064 if (Buffer.isBuffer(chunks)) {
17065 chunks = decompile(chunks)
17066 }
18334 17067
18335 var bufferSize = chunks.reduce(function (accum, chunk) { 17068 return chunks.map(function (chunk) {
18336 // data chunk 17069 // data?
18337 if (Buffer.isBuffer(chunk)) { 17070 if (Buffer.isBuffer(chunk)) return chunk.toString('hex')
18338 return accum + bufferutils.pushDataSize(chunk.length) + chunk.length
18339 }
18340 17071
18341 // opcode 17072 // opcode!
18342 return accum + 1 17073 return REVERSE_OPS[chunk]
18343 }, 0.0) 17074 }).join(' ')
17075}
18344 17076
18345 var buffer = new Buffer(bufferSize) 17077function fromASM (asm) {
18346 var offset = 0 17078 typeforce(types.String, asm)
18347 17079
18348 chunks.forEach(function (chunk) { 17080 return compile(asm.split(' ').map(function (chunkStr) {
18349 // data chunk 17081 // opcode?
18350 if (Buffer.isBuffer(chunk)) { 17082 if (OPS[chunkStr] !== undefined) return OPS[chunkStr]
18351 offset += bufferutils.writePushDataInt(buffer, chunk.length, offset) 17083 typeforce(types.Hex, chunkStr)
18352 17084
18353 chunk.copy(buffer, offset) 17085 // data!
18354 offset += chunk.length 17086 return Buffer.from(chunkStr, 'hex')
17087 }))
17088}
18355 17089
18356 // opcode 17090function toStack (chunks) {
18357 } else { 17091 chunks = decompile(chunks)
18358 buffer.writeUInt8(chunk, offset) 17092 typeforce(isPushOnly, chunks)
18359 offset += 1 17093
18360 } 17094 return chunks.map(function (op) {
17095 if (Buffer.isBuffer(op)) return op
17096 if (op === OPS.OP_0) return Buffer.allocUnsafe(0)
17097
17098 return scriptNumber.encode(op - OP_INT_BASE)
18361 }) 17099 })
17100}
17101
17102function isCanonicalPubKey (buffer) {
17103 if (!Buffer.isBuffer(buffer)) return false
17104 if (buffer.length < 33) return false
18362 17105
18363 assert.equal(offset, buffer.length, 'Could not decode chunks') 17106 switch (buffer[0]) {
18364 return new Script(buffer, chunks) 17107 case 0x02:
17108 case 0x03:
17109 return buffer.length === 33
17110 case 0x04:
17111 return buffer.length === 65
17112 }
17113
17114 return false
18365} 17115}
18366 17116
18367Script.fromHex = function (hex) { 17117function isDefinedHashType (hashType) {
18368 return Script.fromBuffer(new Buffer(hex, 'hex')) 17118 var hashTypeMod = hashType & ~0x80
17119
17120// return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE
17121 return hashTypeMod > 0x00 && hashTypeMod < 0x04
18369} 17122}
18370 17123
18371Script.EMPTY = Script.fromChunks([]) 17124function isCanonicalSignature (buffer) {
17125 if (!Buffer.isBuffer(buffer)) return false
17126 if (!isDefinedHashType(buffer[buffer.length - 1])) return false
18372 17127
18373Script.prototype.getHash = function () { 17128 return bip66.check(buffer.slice(0, -1))
18374 return crypto.hash160(this.buffer)
18375} 17129}
18376 17130
18377// FIXME: doesn't work for data chunks, maybe time to use buffertools.compare... 17131module.exports = {
18378Script.prototype.without = function (needle) { 17132 compile: compile,
18379 return Script.fromChunks(this.chunks.filter(function (op) { 17133 decompile: decompile,
18380 return op !== needle 17134 fromASM: fromASM,
18381 })) 17135 toASM: toASM,
17136 toStack: toStack,
17137
17138 number: require('./script_number'),
17139
17140 isCanonicalPubKey: isCanonicalPubKey,
17141 isCanonicalSignature: isCanonicalSignature,
17142 isPushOnly: isPushOnly,
17143 isDefinedHashType: isDefinedHashType
18382} 17144}
18383 17145
18384var reverseOps = [] 17146var templates = require('./templates')
18385for (var op in opcodes) { 17147for (var key in templates) {
18386 var code = opcodes[op] 17148 module.exports[key] = templates[key]
18387 reverseOps[code] = op
18388} 17149}
18389 17150
18390Script.prototype.toASM = function () { 17151},{"./script_number":53,"./templates":54,"./types":78,"bip66":39,"bitcoin-ops":40,"bitcoin-ops/map":41,"pushdata-bitcoin":95,"safe-buffer":98,"typeforce":109}],53:[function(require,module,exports){
18391 return this.chunks.map(function (chunk) { 17152var Buffer = require('safe-buffer').Buffer
18392 // data chunk
18393 if (Buffer.isBuffer(chunk)) {
18394 return chunk.toString('hex')
18395 17153
18396 // opcode 17154function decode (buffer, maxLength, minimal) {
18397 } else { 17155 maxLength = maxLength || 4
18398 return reverseOps[chunk] 17156 minimal = minimal === undefined ? true : minimal
17157
17158 var length = buffer.length
17159 if (length === 0) return 0
17160 if (length > maxLength) throw new TypeError('Script number overflow')
17161 if (minimal) {
17162 if ((buffer[length - 1] & 0x7f) === 0) {
17163 if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number')
18399 } 17164 }
18400 }).join(' ') 17165 }
17166
17167 // 40-bit
17168 if (length === 5) {
17169 var a = buffer.readUInt32LE(0)
17170 var b = buffer.readUInt8(4)
17171
17172 if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a)
17173 return (b * 0x100000000) + a
17174 }
17175
17176 var result = 0
17177
17178 // 32-bit / 24-bit / 16-bit / 8-bit
17179 for (var i = 0; i < length; ++i) {
17180 result |= buffer[i] << (8 * i)
17181 }
17182
17183 if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1))))
17184 return result
18401} 17185}
18402 17186
18403Script.prototype.toBuffer = function () { 17187function scriptNumSize (i) {
18404 return this.buffer 17188 return i > 0x7fffffff ? 5
17189 : i > 0x7fffff ? 4
17190 : i > 0x7fff ? 3
17191 : i > 0x7f ? 2
17192 : i > 0x00 ? 1
17193 : 0
18405} 17194}
18406 17195
18407Script.prototype.toHex = function () { 17196function encode (number) {
18408 return this.toBuffer().toString('hex') 17197 var value = Math.abs(number)
17198 var size = scriptNumSize(value)
17199 var buffer = Buffer.allocUnsafe(size)
17200 var negative = number < 0
17201
17202 for (var i = 0; i < size; ++i) {
17203 buffer.writeUInt8(value & 0xff, i)
17204 value >>= 8
17205 }
17206
17207 if (buffer[size - 1] & 0x80) {
17208 buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1)
17209 } else if (negative) {
17210 buffer[size - 1] |= 0x80
17211 }
17212
17213 return buffer
18409} 17214}
18410 17215
18411module.exports = Script 17216module.exports = {
17217 decode: decode,
17218 encode: encode
17219}
18412 17220
18413}).call(this,require("buffer").Buffer) 17221},{"safe-buffer":98}],54:[function(require,module,exports){
18414},{"./bufferutils":57,"./crypto":58,"./opcodes":67,"assert":5,"buffer":7,"typeforce":53}],69:[function(require,module,exports){ 17222var decompile = require('../script').decompile
18415(function (Buffer){ 17223var multisig = require('./multisig')
18416var assert = require('assert') 17224var nullData = require('./nulldata')
18417var ops = require('./opcodes') 17225var pubKey = require('./pubkey')
18418var typeForce = require('typeforce') 17226var pubKeyHash = require('./pubkeyhash')
17227var scriptHash = require('./scripthash')
17228var witnessPubKeyHash = require('./witnesspubkeyhash')
17229var witnessScriptHash = require('./witnessscripthash')
17230var witnessCommitment = require('./witnesscommitment')
17231
17232var types = {
17233 MULTISIG: 'multisig',
17234 NONSTANDARD: 'nonstandard',
17235 NULLDATA: 'nulldata',
17236 P2PK: 'pubkey',
17237 P2PKH: 'pubkeyhash',
17238 P2SH: 'scripthash',
17239 P2WPKH: 'witnesspubkeyhash',
17240 P2WSH: 'witnessscripthash',
17241 WITNESS_COMMITMENT: 'witnesscommitment'
17242}
18419 17243
18420var ecurve = require('ecurve') 17244function classifyOutput (script) {
18421var curve = ecurve.getCurveByName('secp256k1') 17245 if (witnessPubKeyHash.output.check(script)) return types.P2WPKH
17246 if (witnessScriptHash.output.check(script)) return types.P2WSH
17247 if (pubKeyHash.output.check(script)) return types.P2PKH
17248 if (scriptHash.output.check(script)) return types.P2SH
18422 17249
18423var ECSignature = require('./ecsignature') 17250 // XXX: optimization, below functions .decompile before use
18424var Script = require('./script') 17251 var chunks = decompile(script)
17252 if (multisig.output.check(chunks)) return types.MULTISIG
17253 if (pubKey.output.check(chunks)) return types.P2PK
17254 if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT
17255 if (nullData.output.check(chunks)) return types.NULLDATA
18425 17256
18426function isCanonicalPubKey (buffer) { 17257 return types.NONSTANDARD
18427 if (!Buffer.isBuffer(buffer)) return false 17258}
18428 17259
18429 try { 17260function classifyInput (script, allowIncomplete) {
18430 ecurve.Point.decodeFrom(curve, buffer) 17261 // XXX: optimization, below functions .decompile before use
18431 } catch (e) { 17262 var chunks = decompile(script)
18432 if (!(e.message.match(/Invalid sequence (length|tag)/)))
18433 throw e
18434 17263
18435 return false 17264 if (pubKeyHash.input.check(chunks)) return types.P2PKH
17265 if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH
17266 if (multisig.input.check(chunks, allowIncomplete)) return types.MULTISIG
17267 if (pubKey.input.check(chunks)) return types.P2PK
17268
17269 return types.NONSTANDARD
17270}
17271
17272function classifyWitness (script, allowIncomplete) {
17273 // XXX: optimization, below functions .decompile before use
17274 var chunks = decompile(script)
17275
17276 if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH
17277 if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH
17278
17279 return types.NONSTANDARD
17280}
17281
17282module.exports = {
17283 classifyInput: classifyInput,
17284 classifyOutput: classifyOutput,
17285 classifyWitness: classifyWitness,
17286 multisig: multisig,
17287 nullData: nullData,
17288 pubKey: pubKey,
17289 pubKeyHash: pubKeyHash,
17290 scriptHash: scriptHash,
17291 witnessPubKeyHash: witnessPubKeyHash,
17292 witnessScriptHash: witnessScriptHash,
17293 witnessCommitment: witnessCommitment,
17294 types: types
17295}
17296
17297},{"../script":52,"./multisig":55,"./nulldata":58,"./pubkey":59,"./pubkeyhash":62,"./scripthash":65,"./witnesscommitment":68,"./witnesspubkeyhash":70,"./witnessscripthash":73}],55:[function(require,module,exports){
17298module.exports = {
17299 input: require('./input'),
17300 output: require('./output')
17301}
17302
17303},{"./input":56,"./output":57}],56:[function(require,module,exports){
17304// OP_0 [signatures ...]
17305
17306var Buffer = require('safe-buffer').Buffer
17307var bscript = require('../../script')
17308var typeforce = require('typeforce')
17309var OPS = require('bitcoin-ops')
17310
17311function partialSignature (value) {
17312 return value === OPS.OP_0 || bscript.isCanonicalSignature(value)
17313}
17314
17315function check (script, allowIncomplete) {
17316 var chunks = bscript.decompile(script)
17317 if (chunks.length < 2) return false
17318 if (chunks[0] !== OPS.OP_0) return false
17319
17320 if (allowIncomplete) {
17321 return chunks.slice(1).every(partialSignature)
18436 } 17322 }
18437 17323
18438 return true 17324 return chunks.slice(1).every(bscript.isCanonicalSignature)
18439} 17325}
17326check.toJSON = function () { return 'multisig input' }
18440 17327
18441function isCanonicalSignature (buffer) { 17328var EMPTY_BUFFER = Buffer.allocUnsafe(0)
18442 if (!Buffer.isBuffer(buffer)) return false
18443 17329
18444 try { 17330function encodeStack (signatures, scriptPubKey) {
18445 ECSignature.parseScriptSignature(buffer) 17331 typeforce([partialSignature], signatures)
18446 } catch (e) { 17332
18447 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/))) { 17333 if (scriptPubKey) {
18448 throw e 17334 var scriptData = bscript.multisig.output.decode(scriptPubKey)
17335
17336 if (signatures.length < scriptData.m) {
17337 throw new TypeError('Not enough signatures provided')
18449 } 17338 }
18450 17339
18451 return false 17340 if (signatures.length > scriptData.pubKeys.length) {
17341 throw new TypeError('Too many signatures provided')
17342 }
18452 } 17343 }
18453 17344
18454 return true 17345 return [].concat(EMPTY_BUFFER, signatures)
18455} 17346}
18456 17347
18457function isPubKeyHashInput (script) { 17348function encode (signatures, scriptPubKey) {
18458 return script.chunks.length === 2 && 17349 return bscript.compile(encodeStack(signatures, scriptPubKey))
18459 isCanonicalSignature(script.chunks[0]) &&
18460 isCanonicalPubKey(script.chunks[1])
18461} 17350}
18462 17351
18463function isPubKeyHashOutput (script) { 17352function decodeStack (stack, allowIncomplete) {
18464 return script.chunks.length === 5 && 17353 typeforce(check, stack, allowIncomplete)
18465 script.chunks[0] === ops.OP_DUP && 17354 return stack.slice(1)
18466 script.chunks[1] === ops.OP_HASH160 &&
18467 Buffer.isBuffer(script.chunks[2]) &&
18468 script.chunks[2].length === 20 &&
18469 script.chunks[3] === ops.OP_EQUALVERIFY &&
18470 script.chunks[4] === ops.OP_CHECKSIG
18471} 17355}
18472 17356
18473function isPubKeyInput (script) { 17357function decode (buffer, allowIncomplete) {
18474 return script.chunks.length === 1 && 17358 var stack = bscript.decompile(buffer)
18475 isCanonicalSignature(script.chunks[0]) 17359 return decodeStack(stack, allowIncomplete)
18476} 17360}
18477 17361
18478function isPubKeyOutput (script) { 17362module.exports = {
18479 return script.chunks.length === 2 && 17363 check: check,
18480 isCanonicalPubKey(script.chunks[0]) && 17364 decode: decode,
18481 script.chunks[1] === ops.OP_CHECKSIG 17365 decodeStack: decodeStack,
17366 encode: encode,
17367 encodeStack: encodeStack
18482} 17368}
18483 17369
18484function isScriptHashInput (script, allowIncomplete) { 17370},{"../../script":52,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],57:[function(require,module,exports){
18485 if (script.chunks.length < 2) return false 17371// m [pubKeys ...] n OP_CHECKMULTISIG
18486 17372
18487 var lastChunk = script.chunks[script.chunks.length - 1] 17373var bscript = require('../../script')
18488 if (!Buffer.isBuffer(lastChunk)) return false 17374var types = require('../../types')
17375var typeforce = require('typeforce')
17376var OPS = require('bitcoin-ops')
17377var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
17378
17379function check (script, allowIncomplete) {
17380 var chunks = bscript.decompile(script)
17381
17382 if (chunks.length < 4) return false
17383 if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) return false
17384 if (!types.Number(chunks[0])) return false
17385 if (!types.Number(chunks[chunks.length - 2])) return false
17386 var m = chunks[0] - OP_INT_BASE
17387 var n = chunks[chunks.length - 2] - OP_INT_BASE
17388
17389 if (m <= 0) return false
17390 if (n > 16) return false
17391 if (m > n) return false
17392 if (n !== chunks.length - 3) return false
17393 if (allowIncomplete) return true
17394
17395 var keys = chunks.slice(1, -2)
17396 return keys.every(bscript.isCanonicalPubKey)
17397}
17398check.toJSON = function () { return 'multi-sig output' }
17399
17400function encode (m, pubKeys) {
17401 typeforce({
17402 m: types.Number,
17403 pubKeys: [bscript.isCanonicalPubKey]
17404 }, {
17405 m: m,
17406 pubKeys: pubKeys
17407 })
18489 17408
18490 var scriptSig = Script.fromChunks(script.chunks.slice(0, -1)) 17409 var n = pubKeys.length
18491 var redeemScript = Script.fromBuffer(lastChunk) 17410 if (n < m) throw new TypeError('Not enough pubKeys provided')
18492 17411
18493 // is redeemScript a valid script? 17412 return bscript.compile([].concat(
18494 if (redeemScript.chunks.length === 0) return false 17413 OP_INT_BASE + m,
17414 pubKeys,
17415 OP_INT_BASE + n,
17416 OPS.OP_CHECKMULTISIG
17417 ))
17418}
17419
17420function decode (buffer, allowIncomplete) {
17421 var chunks = bscript.decompile(buffer)
17422 typeforce(check, chunks, allowIncomplete)
17423
17424 return {
17425 m: chunks[0] - OP_INT_BASE,
17426 pubKeys: chunks.slice(1, -2)
17427 }
17428}
17429
17430module.exports = {
17431 check: check,
17432 decode: decode,
17433 encode: encode
17434}
17435
17436},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],58:[function(require,module,exports){
17437// OP_RETURN {data}
18495 17438
18496 return classifyInput(scriptSig, allowIncomplete) === classifyOutput(redeemScript) 17439var bscript = require('../script')
17440var types = require('../types')
17441var typeforce = require('typeforce')
17442var OPS = require('bitcoin-ops')
17443
17444function check (script) {
17445 var buffer = bscript.compile(script)
17446
17447 return buffer.length > 1 &&
17448 buffer[0] === OPS.OP_RETURN
18497} 17449}
17450check.toJSON = function () { return 'null data output' }
17451
17452function encode (data) {
17453 typeforce(types.Buffer, data)
18498 17454
18499function isScriptHashOutput (script) { 17455 return bscript.compile([OPS.OP_RETURN, data])
18500 return script.chunks.length === 3 &&
18501 script.chunks[0] === ops.OP_HASH160 &&
18502 Buffer.isBuffer(script.chunks[1]) &&
18503 script.chunks[1].length === 20 &&
18504 script.chunks[2] === ops.OP_EQUAL
18505} 17456}
18506 17457
18507// allowIncomplete is to account for combining signatures 17458function decode (buffer) {
18508// See https://github.com/bitcoin/bitcoin/blob/f425050546644a36b0b8e0eb2f6934a3e0f6f80f/src/script/sign.cpp#L195-L197 17459 typeforce(check, buffer)
18509function isMultisigInput (script, allowIncomplete) {
18510 if (script.chunks.length < 2) return false
18511 if (script.chunks[0] !== ops.OP_0) return false
18512 17460
18513 if (allowIncomplete) { 17461 return buffer.slice(2)
18514 return script.chunks.slice(1).every(function (chunk) { 17462}
18515 return chunk === ops.OP_0 || isCanonicalSignature(chunk) 17463
18516 }) 17464module.exports = {
17465 output: {
17466 check: check,
17467 decode: decode,
17468 encode: encode
18517 } 17469 }
17470}
18518 17471
18519 return script.chunks.slice(1).every(isCanonicalSignature) 17472},{"../script":52,"../types":78,"bitcoin-ops":40,"typeforce":109}],59:[function(require,module,exports){
17473arguments[4][55][0].apply(exports,arguments)
17474},{"./input":60,"./output":61,"dup":55}],60:[function(require,module,exports){
17475// {signature}
17476
17477var bscript = require('../../script')
17478var types = require('../../types')
17479var typeforce = require('typeforce')
17480
17481function check (script) {
17482 var chunks = bscript.decompile(script)
17483
17484 return chunks.length === 1 &&
17485 bscript.isCanonicalSignature(chunks[0])
18520} 17486}
17487check.toJSON = function () { return 'pubKey input' }
18521 17488
18522function isMultisigOutput (script) { 17489function encodeStack (signature) {
18523 if (script.chunks.length < 4) return false 17490 typeforce(types.Buffer, signature)
18524 if (script.chunks[script.chunks.length - 1] !== ops.OP_CHECKMULTISIG) return false 17491 return [signature]
17492}
18525 17493
18526 var mOp = script.chunks[0] 17494function encode (signature) {
18527 if (mOp === ops.OP_0) return false 17495 return bscript.compile(encodeStack(signature))
18528 if (mOp < ops.OP_1) return false 17496}
18529 if (mOp > ops.OP_16) return false
18530 17497
18531 var nOp = script.chunks[script.chunks.length - 2] 17498function decodeStack (stack) {
18532 if (nOp === ops.OP_0) return false 17499 typeforce(check, stack)
18533 if (nOp < ops.OP_1) return false 17500 return stack[0]
18534 if (nOp > ops.OP_16) return false 17501}
18535 17502
18536 var m = mOp - (ops.OP_1 - 1) 17503function decode (buffer) {
18537 var n = nOp - (ops.OP_1 - 1) 17504 var stack = bscript.decompile(buffer)
18538 if (n < m) return false 17505 return decodeStack(stack)
17506}
18539 17507
18540 var pubKeys = script.chunks.slice(1, -2) 17508module.exports = {
18541 if (n < pubKeys.length) return false 17509 check: check,
17510 decode: decode,
17511 decodeStack: decodeStack,
17512 encode: encode,
17513 encodeStack: encodeStack
17514}
17515
17516},{"../../script":52,"../../types":78,"typeforce":109}],61:[function(require,module,exports){
17517// {pubKey} OP_CHECKSIG
18542 17518
18543 return pubKeys.every(isCanonicalPubKey) 17519var bscript = require('../../script')
17520var typeforce = require('typeforce')
17521var OPS = require('bitcoin-ops')
17522
17523function check (script) {
17524 var chunks = bscript.decompile(script)
17525
17526 return chunks.length === 2 &&
17527 bscript.isCanonicalPubKey(chunks[0]) &&
17528 chunks[1] === OPS.OP_CHECKSIG
18544} 17529}
17530check.toJSON = function () { return 'pubKey output' }
17531
17532function encode (pubKey) {
17533 typeforce(bscript.isCanonicalPubKey, pubKey)
18545 17534
18546function isNullDataOutput (script) { 17535 return bscript.compile([pubKey, OPS.OP_CHECKSIG])
18547 return script.chunks[0] === ops.OP_RETURN
18548} 17536}
18549 17537
18550function classifyOutput (script) { 17538function decode (buffer) {
18551 typeForce('Script', script) 17539 var chunks = bscript.decompile(buffer)
17540 typeforce(check, chunks)
18552 17541
18553 if (isPubKeyHashOutput(script)) { 17542 return chunks[0]
18554 return 'pubkeyhash' 17543}
18555 } else if (isScriptHashOutput(script)) {
18556 return 'scripthash'
18557 } else if (isMultisigOutput(script)) {
18558 return 'multisig'
18559 } else if (isPubKeyOutput(script)) {
18560 return 'pubkey'
18561 } else if (isNullDataOutput(script)) {
18562 return 'nulldata'
18563 }
18564 17544
18565 return 'nonstandard' 17545module.exports = {
17546 check: check,
17547 decode: decode,
17548 encode: encode
18566} 17549}
18567 17550
18568function classifyInput (script, allowIncomplete) { 17551},{"../../script":52,"bitcoin-ops":40,"typeforce":109}],62:[function(require,module,exports){
18569 typeForce('Script', script) 17552arguments[4][55][0].apply(exports,arguments)
17553},{"./input":63,"./output":64,"dup":55}],63:[function(require,module,exports){
17554// {signature} {pubKey}
17555
17556var bscript = require('../../script')
17557var types = require('../../types')
17558var typeforce = require('typeforce')
17559
17560function check (script) {
17561 var chunks = bscript.decompile(script)
17562
17563 return chunks.length === 2 &&
17564 bscript.isCanonicalSignature(chunks[0]) &&
17565 bscript.isCanonicalPubKey(chunks[1])
17566}
17567check.toJSON = function () { return 'pubKeyHash input' }
17568
17569function encodeStack (signature, pubKey) {
17570 typeforce({
17571 signature: types.Buffer, pubKey: types.Buffer
17572 }, {
17573 signature: signature, pubKey: pubKey
17574 })
17575
17576 return [signature, pubKey]
17577}
17578
17579function encode (signature, pubKey) {
17580 return bscript.compile(encodeStack(signature, pubKey))
17581}
18570 17582
18571 if (isPubKeyHashInput(script)) { 17583function decodeStack (stack) {
18572 return 'pubkeyhash' 17584 typeforce(check, stack)
18573 } else if (isMultisigInput(script, allowIncomplete)) { 17585
18574 return 'multisig' 17586 return {
18575 } else if (isScriptHashInput(script, allowIncomplete)) { 17587 signature: stack[0],
18576 return 'scripthash' 17588 pubKey: stack[1]
18577 } else if (isPubKeyInput(script)) {
18578 return 'pubkey'
18579 } 17589 }
17590}
18580 17591
18581 return 'nonstandard' 17592function decode (buffer) {
17593 var stack = bscript.decompile(buffer)
17594 return decodeStack(stack)
18582} 17595}
18583 17596
18584// Standard Script Templates 17597module.exports = {
18585// {pubKey} OP_CHECKSIG 17598 check: check,
18586function pubKeyOutput (pubKey) { 17599 decode: decode,
18587 return Script.fromChunks([ 17600 decodeStack: decodeStack,
18588 pubKey.toBuffer(), 17601 encode: encode,
18589 ops.OP_CHECKSIG 17602 encodeStack: encodeStack
18590 ])
18591} 17603}
18592 17604
17605},{"../../script":52,"../../types":78,"typeforce":109}],64:[function(require,module,exports){
18593// OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG 17606// OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
18594function pubKeyHashOutput (hash) { 17607
18595 typeForce('Buffer', hash) 17608var bscript = require('../../script')
18596 17609var types = require('../../types')
18597 return Script.fromChunks([ 17610var typeforce = require('typeforce')
18598 ops.OP_DUP, 17611var OPS = require('bitcoin-ops')
18599 ops.OP_HASH160, 17612
18600 hash, 17613function check (script) {
18601 ops.OP_EQUALVERIFY, 17614 var buffer = bscript.compile(script)
18602 ops.OP_CHECKSIG 17615
17616 return buffer.length === 25 &&
17617 buffer[0] === OPS.OP_DUP &&
17618 buffer[1] === OPS.OP_HASH160 &&
17619 buffer[2] === 0x14 &&
17620 buffer[23] === OPS.OP_EQUALVERIFY &&
17621 buffer[24] === OPS.OP_CHECKSIG
17622}
17623check.toJSON = function () { return 'pubKeyHash output' }
17624
17625function encode (pubKeyHash) {
17626 typeforce(types.Hash160bit, pubKeyHash)
17627
17628 return bscript.compile([
17629 OPS.OP_DUP,
17630 OPS.OP_HASH160,
17631 pubKeyHash,
17632 OPS.OP_EQUALVERIFY,
17633 OPS.OP_CHECKSIG
18603 ]) 17634 ])
18604} 17635}
18605 17636
17637function decode (buffer) {
17638 typeforce(check, buffer)
17639
17640 return buffer.slice(3, 23)
17641}
17642
17643module.exports = {
17644 check: check,
17645 decode: decode,
17646 encode: encode
17647}
17648
17649},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],65:[function(require,module,exports){
17650arguments[4][55][0].apply(exports,arguments)
17651},{"./input":66,"./output":67,"dup":55}],66:[function(require,module,exports){
17652// <scriptSig> {serialized scriptPubKey script}
17653
17654var Buffer = require('safe-buffer').Buffer
17655var bscript = require('../../script')
17656var typeforce = require('typeforce')
17657
17658function check (script, allowIncomplete) {
17659 var chunks = bscript.decompile(script)
17660 if (chunks.length < 1) return false
17661
17662 var lastChunk = chunks[chunks.length - 1]
17663 if (!Buffer.isBuffer(lastChunk)) return false
17664
17665 var scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1)))
17666 var redeemScriptChunks = bscript.decompile(lastChunk)
17667
17668 // is redeemScript a valid script?
17669 if (redeemScriptChunks.length === 0) return false
17670
17671 // is redeemScriptSig push only?
17672 if (!bscript.isPushOnly(scriptSigChunks)) return false
17673
17674 var inputType = bscript.classifyInput(scriptSigChunks, allowIncomplete)
17675 var outputType = bscript.classifyOutput(redeemScriptChunks)
17676 if (chunks.length === 1) {
17677 return outputType === bscript.types.P2WSH || outputType === bscript.types.P2WPKH
17678 }
17679 return inputType === outputType
17680}
17681check.toJSON = function () { return 'scriptHash input' }
17682
17683function encodeStack (redeemScriptStack, redeemScript) {
17684 var serializedScriptPubKey = bscript.compile(redeemScript)
17685
17686 return [].concat(redeemScriptStack, serializedScriptPubKey)
17687}
17688
17689function encode (redeemScriptSig, redeemScript) {
17690 var redeemScriptStack = bscript.decompile(redeemScriptSig)
17691
17692 return bscript.compile(encodeStack(redeemScriptStack, redeemScript))
17693}
17694
17695function decodeStack (stack) {
17696 typeforce(check, stack)
17697
17698 return {
17699 redeemScriptStack: stack.slice(0, -1),
17700 redeemScript: stack[stack.length - 1]
17701 }
17702}
17703
17704function decode (buffer) {
17705 var stack = bscript.decompile(buffer)
17706 var result = decodeStack(stack)
17707 result.redeemScriptSig = bscript.compile(result.redeemScriptStack)
17708 delete result.redeemScriptStack
17709 return result
17710}
17711
17712module.exports = {
17713 check: check,
17714 decode: decode,
17715 decodeStack: decodeStack,
17716 encode: encode,
17717 encodeStack: encodeStack
17718}
17719
17720},{"../../script":52,"safe-buffer":98,"typeforce":109}],67:[function(require,module,exports){
18606// OP_HASH160 {scriptHash} OP_EQUAL 17721// OP_HASH160 {scriptHash} OP_EQUAL
18607function scriptHashOutput (hash) {
18608 typeForce('Buffer', hash)
18609 17722
18610 return Script.fromChunks([ 17723var bscript = require('../../script')
18611 ops.OP_HASH160, 17724var types = require('../../types')
18612 hash, 17725var typeforce = require('typeforce')
18613 ops.OP_EQUAL 17726var OPS = require('bitcoin-ops')
18614 ]) 17727
17728function check (script) {
17729 var buffer = bscript.compile(script)
17730
17731 return buffer.length === 23 &&
17732 buffer[0] === OPS.OP_HASH160 &&
17733 buffer[1] === 0x14 &&
17734 buffer[22] === OPS.OP_EQUAL
18615} 17735}
17736check.toJSON = function () { return 'scriptHash output' }
18616 17737
18617// m [pubKeys ...] n OP_CHECKMULTISIG 17738function encode (scriptHash) {
18618function multisigOutput (m, pubKeys) { 17739 typeforce(types.Hash160bit, scriptHash)
18619 typeForce(['ECPubKey'], pubKeys)
18620 17740
18621 assert(pubKeys.length >= m, 'Not enough pubKeys provided') 17741 return bscript.compile([OPS.OP_HASH160, scriptHash, OPS.OP_EQUAL])
17742}
18622 17743
18623 var pubKeyBuffers = pubKeys.map(function (pubKey) { 17744function decode (buffer) {
18624 return pubKey.toBuffer() 17745 typeforce(check, buffer)
18625 })
18626 var n = pubKeys.length
18627 17746
18628 return Script.fromChunks([].concat( 17747 return buffer.slice(2, 22)
18629 (ops.OP_1 - 1) + m,
18630 pubKeyBuffers,
18631 (ops.OP_1 - 1) + n,
18632 ops.OP_CHECKMULTISIG
18633 ))
18634} 17748}
18635 17749
18636// {signature} 17750module.exports = {
18637function pubKeyInput (signature) { 17751 check: check,
18638 typeForce('Buffer', signature) 17752 decode: decode,
17753 encode: encode
17754}
17755
17756},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],68:[function(require,module,exports){
17757module.exports = {
17758 output: require('./output')
17759}
17760
17761},{"./output":69}],69:[function(require,module,exports){
17762// OP_RETURN {aa21a9ed} {commitment}
17763
17764var Buffer = require('safe-buffer').Buffer
17765var bscript = require('../../script')
17766var types = require('../../types')
17767var typeforce = require('typeforce')
17768var OPS = require('bitcoin-ops')
17769
17770var HEADER = Buffer.from('aa21a9ed', 'hex')
17771
17772function check (script) {
17773 var buffer = bscript.compile(script)
17774
17775 return buffer.length > 37 &&
17776 buffer[0] === OPS.OP_RETURN &&
17777 buffer[1] === 0x24 &&
17778 buffer.slice(2, 6).equals(HEADER)
17779}
17780
17781check.toJSON = function () { return 'Witness commitment output' }
17782
17783function encode (commitment) {
17784 typeforce(types.Hash256bit, commitment)
17785
17786 var buffer = Buffer.allocUnsafe(36)
17787 HEADER.copy(buffer, 0)
17788 commitment.copy(buffer, 4)
17789
17790 return bscript.compile([OPS.OP_RETURN, buffer])
17791}
17792
17793function decode (buffer) {
17794 typeforce(check, buffer)
18639 17795
18640 return Script.fromChunks([signature]) 17796 return bscript.decompile(buffer)[1].slice(4, 36)
18641} 17797}
18642 17798
17799module.exports = {
17800 check: check,
17801 decode: decode,
17802 encode: encode
17803}
17804
17805},{"../../script":52,"../../types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],70:[function(require,module,exports){
17806arguments[4][55][0].apply(exports,arguments)
17807},{"./input":71,"./output":72,"dup":55}],71:[function(require,module,exports){
18643// {signature} {pubKey} 17808// {signature} {pubKey}
18644function pubKeyHashInput (signature, pubKey) {
18645 typeForce('Buffer', signature)
18646 17809
18647 return Script.fromChunks([signature, pubKey.toBuffer()]) 17810var pkh = require('../pubkeyhash/input')
17811
17812module.exports = {
17813 check: pkh.check,
17814 decodeStack: pkh.decodeStack,
17815 encodeStack: pkh.encodeStack
18648} 17816}
18649 17817
18650// <scriptSig> {serialized scriptPubKey script} 17818},{"../pubkeyhash/input":63}],72:[function(require,module,exports){
18651function scriptHashInput (scriptSig, scriptPubKey) { 17819// OP_0 {pubKeyHash}
18652 return Script.fromChunks([].concat( 17820
18653 scriptSig.chunks, 17821var bscript = require('../../script')
18654 scriptPubKey.toBuffer() 17822var types = require('../../types')
18655 )) 17823var typeforce = require('typeforce')
17824var OPS = require('bitcoin-ops')
17825
17826function check (script) {
17827 var buffer = bscript.compile(script)
17828
17829 return buffer.length === 22 &&
17830 buffer[0] === OPS.OP_0 &&
17831 buffer[1] === 0x14
18656} 17832}
17833check.toJSON = function () { return 'Witness pubKeyHash output' }
18657 17834
18658// OP_0 [signatures ...] 17835function encode (pubKeyHash) {
18659function multisigInput (signatures, scriptPubKey) { 17836 typeforce(types.Hash160bit, pubKeyHash)
18660 if (scriptPubKey) {
18661 assert(isMultisigOutput(scriptPubKey))
18662 17837
18663 var mOp = scriptPubKey.chunks[0] 17838 return bscript.compile([OPS.OP_0, pubKeyHash])
18664 var nOp = scriptPubKey.chunks[scriptPubKey.chunks.length - 2] 17839}
18665 var m = mOp - (ops.OP_1 - 1)
18666 var n = nOp - (ops.OP_1 - 1)
18667 17840
18668 assert(signatures.length >= m, 'Not enough signatures provided') 17841function decode (buffer) {
18669 assert(signatures.length <= n, 'Too many signatures provided') 17842 typeforce(check, buffer)
18670 }
18671 17843
18672 return Script.fromChunks([].concat(ops.OP_0, signatures)) 17844 return buffer.slice(2)
18673} 17845}
18674 17846
18675function nullDataOutput (data) { 17847module.exports = {
18676 return Script.fromChunks([ops.OP_RETURN, data]) 17848 check: check,
17849 decode: decode,
17850 encode: encode
18677} 17851}
18678 17852
17853},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],73:[function(require,module,exports){
17854arguments[4][55][0].apply(exports,arguments)
17855},{"./input":74,"./output":75,"dup":55}],74:[function(require,module,exports){
17856// {signature} {pubKey}
17857
17858var p2sh = require('../scripthash/input')
17859
18679module.exports = { 17860module.exports = {
18680 isCanonicalPubKey: isCanonicalPubKey, 17861 check: p2sh.check,
18681 isCanonicalSignature: isCanonicalSignature, 17862 decodeStack: p2sh.decodeStack,
18682 isPubKeyHashInput: isPubKeyHashInput, 17863 encodeStack: p2sh.encodeStack
18683 isPubKeyHashOutput: isPubKeyHashOutput,
18684 isPubKeyInput: isPubKeyInput,
18685 isPubKeyOutput: isPubKeyOutput,
18686 isScriptHashInput: isScriptHashInput,
18687 isScriptHashOutput: isScriptHashOutput,
18688 isMultisigInput: isMultisigInput,
18689 isMultisigOutput: isMultisigOutput,
18690 isNullDataOutput: isNullDataOutput,
18691 classifyOutput: classifyOutput,
18692 classifyInput: classifyInput,
18693 pubKeyOutput: pubKeyOutput,
18694 pubKeyHashOutput: pubKeyHashOutput,
18695 scriptHashOutput: scriptHashOutput,
18696 multisigOutput: multisigOutput,
18697 pubKeyInput: pubKeyInput,
18698 pubKeyHashInput: pubKeyHashInput,
18699 scriptHashInput: scriptHashInput,
18700 multisigInput: multisigInput,
18701 dataOutput: function (data) {
18702 console.warn('dataOutput is deprecated, use nullDataOutput by 2.0.0')
18703 return nullDataOutput(data)
18704 },
18705 nullDataOutput: nullDataOutput
18706} 17864}
18707 17865
18708}).call(this,require("buffer").Buffer) 17866},{"../scripthash/input":66}],75:[function(require,module,exports){
18709},{"./ecsignature":62,"./opcodes":67,"./script":68,"assert":5,"buffer":7,"ecurve":49,"typeforce":53}],70:[function(require,module,exports){ 17867// OP_0 {scriptHash}
18710(function (Buffer){ 17868
18711var assert = require('assert') 17869var bscript = require('../../script')
17870var types = require('../../types')
17871var typeforce = require('typeforce')
17872var OPS = require('bitcoin-ops')
17873
17874function check (script) {
17875 var buffer = bscript.compile(script)
17876
17877 return buffer.length === 34 &&
17878 buffer[0] === OPS.OP_0 &&
17879 buffer[1] === 0x20
17880}
17881check.toJSON = function () { return 'Witness scriptHash output' }
17882
17883function encode (scriptHash) {
17884 typeforce(types.Hash256bit, scriptHash)
17885
17886 return bscript.compile([OPS.OP_0, scriptHash])
17887}
17888
17889function decode (buffer) {
17890 typeforce(check, buffer)
17891
17892 return buffer.slice(2)
17893}
17894
17895module.exports = {
17896 check: check,
17897 decode: decode,
17898 encode: encode
17899}
17900
17901},{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],76:[function(require,module,exports){
17902var Buffer = require('safe-buffer').Buffer
17903var bcrypto = require('./crypto')
17904var bscript = require('./script')
18712var bufferutils = require('./bufferutils') 17905var bufferutils = require('./bufferutils')
18713var crypto = require('./crypto') 17906var opcodes = require('bitcoin-ops')
18714var typeForce = require('typeforce') 17907var typeforce = require('typeforce')
18715var opcodes = require('./opcodes') 17908var types = require('./types')
18716var scripts = require('./scripts') 17909var varuint = require('varuint-bitcoin')
18717 17910
18718var Address = require('./address') 17911function varSliceSize (someScript) {
18719var ECSignature = require('./ecsignature') 17912 var length = someScript.length
18720var Script = require('./script') 17913
17914 return varuint.encodingLength(length) + length
17915}
17916
17917function vectorSize (someVector) {
17918 var length = someVector.length
17919
17920 return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) {
17921 return sum + varSliceSize(witness)
17922 }, 0)
17923}
18721 17924
18722function Transaction () { 17925function Transaction () {
18723 this.version = 1 17926 this.version = 1
@@ -18731,8 +17934,20 @@ Transaction.SIGHASH_ALL = 0x01
18731Transaction.SIGHASH_NONE = 0x02 17934Transaction.SIGHASH_NONE = 0x02
18732Transaction.SIGHASH_SINGLE = 0x03 17935Transaction.SIGHASH_SINGLE = 0x03
18733Transaction.SIGHASH_ANYONECANPAY = 0x80 17936Transaction.SIGHASH_ANYONECANPAY = 0x80
17937Transaction.ADVANCED_TRANSACTION_MARKER = 0x00
17938Transaction.ADVANCED_TRANSACTION_FLAG = 0x01
18734 17939
18735Transaction.fromBuffer = function (buffer, __disableAssert) { 17940var EMPTY_SCRIPT = Buffer.allocUnsafe(0)
17941var EMPTY_WITNESS = []
17942var ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
17943var ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex')
17944var VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex')
17945var BLANK_OUTPUT = {
17946 script: EMPTY_SCRIPT,
17947 valueBuffer: VALUE_UINT64_MAX
17948}
17949
17950Transaction.fromBuffer = function (buffer, __noStrict) {
18736 var offset = 0 17951 var offset = 0
18737 function readSlice (n) { 17952 function readSlice (n) {
18738 offset += n 17953 offset += n
@@ -18745,6 +17960,12 @@ Transaction.fromBuffer = function (buffer, __disableAssert) {
18745 return i 17960 return i
18746 } 17961 }
18747 17962
17963 function readInt32 () {
17964 var i = buffer.readInt32LE(offset)
17965 offset += 4
17966 return i
17967 }
17968
18748 function readUInt64 () { 17969 function readUInt64 () {
18749 var i = bufferutils.readUInt64LE(buffer, offset) 17970 var i = bufferutils.readUInt64LE(buffer, offset)
18750 offset += 8 17971 offset += 8
@@ -18752,132 +17973,111 @@ Transaction.fromBuffer = function (buffer, __disableAssert) {
18752 } 17973 }
18753 17974
18754 function readVarInt () { 17975 function readVarInt () {
18755 var vi = bufferutils.readVarInt(buffer, offset) 17976 var vi = varuint.decode(buffer, offset)
18756 offset += vi.size 17977 offset += varuint.decode.bytes
18757 return vi.number 17978 return vi
18758 } 17979 }
18759 17980
18760 function readScript () { 17981 function readVarSlice () {
18761 return Script.fromBuffer(readSlice(readVarInt())) 17982 return readSlice(readVarInt())
18762 } 17983 }
18763 17984
18764 function readGenerationScript () { 17985 function readVector () {
18765 return new Script(readSlice(readVarInt()), []) 17986 var count = readVarInt()
17987 var vector = []
17988 for (var i = 0; i < count; i++) vector.push(readVarSlice())
17989 return vector
18766 } 17990 }
18767 17991
18768 var tx = new Transaction() 17992 var tx = new Transaction()
18769 tx.version = readUInt32() 17993 tx.version = readInt32()
17994
17995 var marker = buffer.readUInt8(offset)
17996 var flag = buffer.readUInt8(offset + 1)
17997
17998 var hasWitnesses = false
17999 if (marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
18000 flag === Transaction.ADVANCED_TRANSACTION_FLAG) {
18001 offset += 2
18002 hasWitnesses = true
18003 }
18770 18004
18771 var vinLen = readVarInt() 18005 var vinLen = readVarInt()
18772 for (var i = 0; i < vinLen; ++i) { 18006 for (var i = 0; i < vinLen; ++i) {
18773 var hash = readSlice(32) 18007 tx.ins.push({
18774 18008 hash: readSlice(32),
18775 if (Transaction.isCoinbaseHash(hash)) { 18009 index: readUInt32(),
18776 tx.ins.push({ 18010 script: readVarSlice(),
18777 hash: hash, 18011 sequence: readUInt32(),
18778 index: readUInt32(), 18012 witness: EMPTY_WITNESS
18779 script: readGenerationScript(), 18013 })
18780 sequence: readUInt32()
18781 })
18782 } else {
18783 tx.ins.push({
18784 hash: hash,
18785 index: readUInt32(),
18786 script: readScript(),
18787 sequence: readUInt32()
18788 })
18789 }
18790 } 18014 }
18791 18015
18792 var voutLen = readVarInt() 18016 var voutLen = readVarInt()
18793 for (i = 0; i < voutLen; ++i) { 18017 for (i = 0; i < voutLen; ++i) {
18794 tx.outs.push({ 18018 tx.outs.push({
18795 value: readUInt64(), 18019 value: readUInt64(),
18796 script: readScript() 18020 script: readVarSlice()
18797 }) 18021 })
18798 } 18022 }
18799 18023
18800 tx.locktime = readUInt32() 18024 if (hasWitnesses) {
18025 for (i = 0; i < vinLen; ++i) {
18026 tx.ins[i].witness = readVector()
18027 }
18801 18028
18802 if (!__disableAssert) { 18029 // was this pointless?
18803 assert.equal(offset, buffer.length, 'Transaction has unexpected data') 18030 if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
18804 } 18031 }
18805 18032
18033 tx.locktime = readUInt32()
18034
18035 if (__noStrict) return tx
18036 if (offset !== buffer.length) throw new Error('Transaction has unexpected data')
18037
18806 return tx 18038 return tx
18807} 18039}
18808 18040
18809Transaction.fromHex = function (hex) { 18041Transaction.fromHex = function (hex) {
18810 return Transaction.fromBuffer(new Buffer(hex, 'hex')) 18042 return Transaction.fromBuffer(Buffer.from(hex, 'hex'))
18811} 18043}
18812 18044
18813Transaction.isCoinbaseHash = function (buffer) { 18045Transaction.isCoinbaseHash = function (buffer) {
18814 return Array.prototype.every.call(buffer, function (x) { 18046 typeforce(types.Hash256bit, buffer)
18815 return x === 0 18047 for (var i = 0; i < 32; ++i) {
18816 }) 18048 if (buffer[i] !== 0) return false
18049 }
18050 return true
18817} 18051}
18818 18052
18819/** 18053Transaction.prototype.isCoinbase = function () {
18820 * Create a new txIn. 18054 return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
18821 * 18055}
18822 * Can be called with any of:
18823 *
18824 * - A transaction and an index
18825 * - A transaction hash and an index
18826 *
18827 * Note that this method does not sign the created input.
18828 */
18829Transaction.prototype.addInput = function (hash, index, sequence, script) {
18830 if (sequence === undefined || sequence === null) {
18831 sequence = Transaction.DEFAULT_SEQUENCE
18832 }
18833 18056
18834 script = script || Script.EMPTY 18057Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) {
18058 typeforce(types.tuple(
18059 types.Hash256bit,
18060 types.UInt32,
18061 types.maybe(types.UInt32),
18062 types.maybe(types.Buffer)
18063 ), arguments)
18835 18064
18836 if (typeof hash === 'string') { 18065 if (types.Null(sequence)) {
18837 // TxId hex is big-endian, we need little-endian 18066 sequence = Transaction.DEFAULT_SEQUENCE
18838 hash = bufferutils.reverse(new Buffer(hash, 'hex'))
18839 } else if (hash instanceof Transaction) {
18840 hash = hash.getHash()
18841 } 18067 }
18842 18068
18843 typeForce('Buffer', hash)
18844 typeForce('Number', index)
18845 typeForce('Number', sequence)
18846 typeForce('Script', script)
18847
18848 assert.equal(hash.length, 32, 'Expected hash length of 32, got ' + hash.length)
18849
18850 // Add the input and return the input's index 18069 // Add the input and return the input's index
18851 return (this.ins.push({ 18070 return (this.ins.push({
18852 hash: hash, 18071 hash: hash,
18853 index: index, 18072 index: index,
18854 script: script, 18073 script: scriptSig || EMPTY_SCRIPT,
18855 sequence: sequence 18074 sequence: sequence,
18075 witness: EMPTY_WITNESS
18856 }) - 1) 18076 }) - 1)
18857} 18077}
18858 18078
18859/**
18860 * Create a new txOut.
18861 *
18862 * Can be called with:
18863 *
18864 * - A base58 address string and a value
18865 * - An Address object and a value
18866 * - A scriptPubKey Script and a value
18867 */
18868Transaction.prototype.addOutput = function (scriptPubKey, value) { 18079Transaction.prototype.addOutput = function (scriptPubKey, value) {
18869 // Attempt to get a valid address if it's a base58 address string 18080 typeforce(types.tuple(types.Buffer, types.Satoshi), arguments)
18870 if (typeof scriptPubKey === 'string') {
18871 scriptPubKey = Address.fromBase58Check(scriptPubKey)
18872 }
18873
18874 // Attempt to get a valid script if it's an Address object
18875 if (scriptPubKey instanceof Address) {
18876 scriptPubKey = scriptPubKey.toOutputScript()
18877 }
18878
18879 typeForce('Script', scriptPubKey)
18880 typeForce('Number', value)
18881 18081
18882 // Add the output and return the output's index 18082 // Add the output and return the output's index
18883 return (this.outs.push({ 18083 return (this.outs.push({
@@ -18886,6 +18086,39 @@ Transaction.prototype.addOutput = function (scriptPubKey, value) {
18886 }) - 1) 18086 }) - 1)
18887} 18087}
18888 18088
18089Transaction.prototype.hasWitnesses = function () {
18090 return this.ins.some(function (x) {
18091 return x.witness.length !== 0
18092 })
18093}
18094
18095Transaction.prototype.weight = function () {
18096 var base = this.__byteLength(false)
18097 var total = this.__byteLength(true)
18098 return base * 3 + total
18099}
18100
18101Transaction.prototype.virtualSize = function () {
18102 return Math.ceil(this.weight() / 4)
18103}
18104
18105Transaction.prototype.byteLength = function () {
18106 return this.__byteLength(true)
18107}
18108
18109Transaction.prototype.__byteLength = function (__allowWitness) {
18110 var hasWitnesses = __allowWitness && this.hasWitnesses()
18111
18112 return (
18113 (hasWitnesses ? 10 : 8) +
18114 varuint.encodingLength(this.ins.length) +
18115 varuint.encodingLength(this.outs.length) +
18116 this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) +
18117 this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) +
18118 (hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0)
18119 )
18120}
18121
18889Transaction.prototype.clone = function () { 18122Transaction.prototype.clone = function () {
18890 var newTx = new Transaction() 18123 var newTx = new Transaction()
18891 newTx.version = this.version 18124 newTx.version = this.version
@@ -18896,7 +18129,8 @@ Transaction.prototype.clone = function () {
18896 hash: txIn.hash, 18129 hash: txIn.hash,
18897 index: txIn.index, 18130 index: txIn.index,
18898 script: txIn.script, 18131 script: txIn.script,
18899 sequence: txIn.sequence 18132 sequence: txIn.sequence,
18133 witness: txIn.witness
18900 } 18134 }
18901 }) 18135 })
18902 18136
@@ -18913,122 +18147,230 @@ Transaction.prototype.clone = function () {
18913/** 18147/**
18914 * Hash transaction for signing a specific input. 18148 * Hash transaction for signing a specific input.
18915 * 18149 *
18916 * Bitcoin uses a different hash for each signed transaction input. This 18150 * Bitcoin uses a different hash for each signed transaction input.
18917 * method copies the transaction, makes the necessary changes based on the 18151 * This method copies the transaction, makes the necessary changes based on the
18918 * hashType, serializes and finally hashes the result. This hash can then be 18152 * hashType, and then hashes the result.
18919 * used to sign the transaction input in question. 18153 * This hash can then be used to sign the provided transaction input.
18920 */ 18154 */
18921Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) { 18155Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
18922 // FIXME: remove in 2.x.y 18156 typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments)
18923 if (arguments[0] instanceof Script) {
18924 console.warn('hashForSignature(prevOutScript, inIndex, ...) has been deprecated. Use hashForSignature(inIndex, prevOutScript, ...)')
18925 18157
18926 // swap the arguments (must be stored in tmp, arguments is special) 18158 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
18927 var tmp = arguments[0] 18159 if (inIndex >= this.ins.length) return ONE
18928 inIndex = arguments[1]
18929 prevOutScript = tmp
18930 }
18931 18160
18932 typeForce('Number', inIndex) 18161 // ignore OP_CODESEPARATOR
18933 typeForce('Script', prevOutScript) 18162 var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) {
18934 typeForce('Number', hashType) 18163 return x !== opcodes.OP_CODESEPARATOR
18935 18164 }))
18936 assert(inIndex >= 0, 'Invalid vin index')
18937 assert(inIndex < this.ins.length, 'Invalid vin index')
18938 18165
18939 var txTmp = this.clone() 18166 var txTmp = this.clone()
18940 var hashScript = prevOutScript.without(opcodes.OP_CODESEPARATOR)
18941 18167
18942 // Blank out other inputs' signatures 18168 // SIGHASH_NONE: ignore all outputs? (wildcard payee)
18943 txTmp.ins.forEach(function (txIn) { 18169 if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
18944 txIn.script = Script.EMPTY 18170 txTmp.outs = []
18945 }) 18171
18946 txTmp.ins[inIndex].script = hashScript 18172 // ignore sequence numbers (except at inIndex)
18173 txTmp.ins.forEach(function (input, i) {
18174 if (i === inIndex) return
18175
18176 input.sequence = 0
18177 })
18178
18179 // SIGHASH_SINGLE: ignore all outputs, except at the same index?
18180 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
18181 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
18182 if (inIndex >= this.outs.length) return ONE
18947 18183
18948 var hashTypeModifier = hashType & 0x1f 18184 // truncate outputs after
18185 txTmp.outs.length = inIndex + 1
18949 18186
18950 if (hashTypeModifier === Transaction.SIGHASH_NONE) { 18187 // "blank" outputs before
18951 assert(false, 'SIGHASH_NONE not yet supported') 18188 for (var i = 0; i < inIndex; i++) {
18952 } else if (hashTypeModifier === Transaction.SIGHASH_SINGLE) { 18189 txTmp.outs[i] = BLANK_OUTPUT
18953 assert(false, 'SIGHASH_SINGLE not yet supported') 18190 }
18191
18192 // ignore sequence numbers (except at inIndex)
18193 txTmp.ins.forEach(function (input, y) {
18194 if (y === inIndex) return
18195
18196 input.sequence = 0
18197 })
18954 } 18198 }
18955 18199
18200 // SIGHASH_ANYONECANPAY: ignore inputs entirely?
18956 if (hashType & Transaction.SIGHASH_ANYONECANPAY) { 18201 if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
18957 assert(false, 'SIGHASH_ANYONECANPAY not yet supported') 18202 txTmp.ins = [txTmp.ins[inIndex]]
18203 txTmp.ins[0].script = ourScript
18204
18205 // SIGHASH_ALL: only ignore input scripts
18206 } else {
18207 // "blank" others input scripts
18208 txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT })
18209 txTmp.ins[inIndex].script = ourScript
18958 } 18210 }
18959 18211
18960 var hashTypeBuffer = new Buffer(4) 18212 // serialize and hash
18961 hashTypeBuffer.writeInt32LE(hashType, 0) 18213 var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4)
18214 buffer.writeInt32LE(hashType, buffer.length - 4)
18215 txTmp.__toBuffer(buffer, 0, false)
18962 18216
18963 var buffer = Buffer.concat([txTmp.toBuffer(), hashTypeBuffer]) 18217 return bcrypto.hash256(buffer)
18964 return crypto.hash256(buffer)
18965} 18218}
18966 18219
18967Transaction.prototype.getHash = function () { 18220Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) {
18968 return crypto.hash256(this.toBuffer()) 18221 typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments)
18969}
18970 18222
18971Transaction.prototype.getId = function () { 18223 var tbuffer, toffset
18972 // TxHash is little-endian, we need big-endian 18224 function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) }
18973 return bufferutils.reverse(this.getHash()).toString('hex') 18225 function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) }
18974} 18226 function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) }
18227 function writeVarInt (i) {
18228 varuint.encode(i, tbuffer, toffset)
18229 toffset += varuint.encode.bytes
18230 }
18231 function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
18975 18232
18976Transaction.prototype.toBuffer = function () { 18233 var hashOutputs = ZERO
18977 function scriptSize (script) { 18234 var hashPrevouts = ZERO
18978 var length = script.buffer.length 18235 var hashSequence = ZERO
18979 18236
18980 return bufferutils.varIntSize(length) + length 18237 if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) {
18981 } 18238 tbuffer = Buffer.allocUnsafe(36 * this.ins.length)
18239 toffset = 0
18982 18240
18983 var buffer = new Buffer( 18241 this.ins.forEach(function (txIn) {
18984 8 + 18242 writeSlice(txIn.hash)
18985 bufferutils.varIntSize(this.ins.length) + 18243 writeUInt32(txIn.index)
18986 bufferutils.varIntSize(this.outs.length) + 18244 })
18987 this.ins.reduce(function (sum, input) { return sum + 40 + scriptSize(input.script) }, 0) +
18988 this.outs.reduce(function (sum, output) { return sum + 8 + scriptSize(output.script) }, 0)
18989 )
18990 18245
18991 var offset = 0 18246 hashPrevouts = bcrypto.hash256(tbuffer)
18992 function writeSlice (slice) {
18993 slice.copy(buffer, offset)
18994 offset += slice.length
18995 } 18247 }
18996 18248
18997 function writeUInt32 (i) { 18249 if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) &&
18998 buffer.writeUInt32LE(i, offset) 18250 (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
18999 offset += 4 18251 (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
18252 tbuffer = Buffer.allocUnsafe(4 * this.ins.length)
18253 toffset = 0
18254
18255 this.ins.forEach(function (txIn) {
18256 writeUInt32(txIn.sequence)
18257 })
18258
18259 hashSequence = bcrypto.hash256(tbuffer)
19000 } 18260 }
19001 18261
19002 function writeUInt64 (i) { 18262 if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
19003 bufferutils.writeUInt64LE(buffer, i, offset) 18263 (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
19004 offset += 8 18264 var txOutsSize = this.outs.reduce(function (sum, output) {
18265 return sum + 8 + varSliceSize(output.script)
18266 }, 0)
18267
18268 tbuffer = Buffer.allocUnsafe(txOutsSize)
18269 toffset = 0
18270
18271 this.outs.forEach(function (out) {
18272 writeUInt64(out.value)
18273 writeVarSlice(out.script)
18274 })
18275
18276 hashOutputs = bcrypto.hash256(tbuffer)
18277 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) {
18278 var output = this.outs[inIndex]
18279
18280 tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script))
18281 toffset = 0
18282 writeUInt64(output.value)
18283 writeVarSlice(output.script)
18284
18285 hashOutputs = bcrypto.hash256(tbuffer)
19005 } 18286 }
19006 18287
18288 tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript))
18289 toffset = 0
18290
18291 var input = this.ins[inIndex]
18292 writeUInt32(this.version)
18293 writeSlice(hashPrevouts)
18294 writeSlice(hashSequence)
18295 writeSlice(input.hash)
18296 writeUInt32(input.index)
18297 writeVarSlice(prevOutScript)
18298 writeUInt64(value)
18299 writeUInt32(input.sequence)
18300 writeSlice(hashOutputs)
18301 writeUInt32(this.locktime)
18302 writeUInt32(hashType)
18303 return bcrypto.hash256(tbuffer)
18304}
18305
18306Transaction.prototype.getHash = function () {
18307 return bcrypto.hash256(this.__toBuffer(undefined, undefined, false))
18308}
18309
18310Transaction.prototype.getId = function () {
18311 // transaction hash's are displayed in reverse order
18312 return this.getHash().reverse().toString('hex')
18313}
18314
18315Transaction.prototype.toBuffer = function (buffer, initialOffset) {
18316 return this.__toBuffer(buffer, initialOffset, true)
18317}
18318
18319Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) {
18320 if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness))
18321
18322 var offset = initialOffset || 0
18323 function writeSlice (slice) { offset += slice.copy(buffer, offset) }
18324 function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) }
18325 function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) }
18326 function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) }
18327 function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) }
19007 function writeVarInt (i) { 18328 function writeVarInt (i) {
19008 var n = bufferutils.writeVarInt(buffer, i, offset) 18329 varuint.encode(i, buffer, offset)
19009 offset += n 18330 offset += varuint.encode.bytes
18331 }
18332 function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
18333 function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) }
18334
18335 writeInt32(this.version)
18336
18337 var hasWitnesses = __allowWitness && this.hasWitnesses()
18338
18339 if (hasWitnesses) {
18340 writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER)
18341 writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG)
19010 } 18342 }
19011 18343
19012 writeUInt32(this.version)
19013 writeVarInt(this.ins.length) 18344 writeVarInt(this.ins.length)
19014 18345
19015 this.ins.forEach(function (txIn) { 18346 this.ins.forEach(function (txIn) {
19016 writeSlice(txIn.hash) 18347 writeSlice(txIn.hash)
19017 writeUInt32(txIn.index) 18348 writeUInt32(txIn.index)
19018 writeVarInt(txIn.script.buffer.length) 18349 writeVarSlice(txIn.script)
19019 writeSlice(txIn.script.buffer)
19020 writeUInt32(txIn.sequence) 18350 writeUInt32(txIn.sequence)
19021 }) 18351 })
19022 18352
19023 writeVarInt(this.outs.length) 18353 writeVarInt(this.outs.length)
19024 this.outs.forEach(function (txOut) { 18354 this.outs.forEach(function (txOut) {
19025 writeUInt64(txOut.value) 18355 if (!txOut.valueBuffer) {
19026 writeVarInt(txOut.script.buffer.length) 18356 writeUInt64(txOut.value)
19027 writeSlice(txOut.script.buffer) 18357 } else {
18358 writeSlice(txOut.valueBuffer)
18359 }
18360
18361 writeVarSlice(txOut.script)
19028 }) 18362 })
19029 18363
18364 if (hasWitnesses) {
18365 this.ins.forEach(function (input) {
18366 writeVector(input.witness)
18367 })
18368 }
18369
19030 writeUInt32(this.locktime) 18370 writeUInt32(this.locktime)
19031 18371
18372 // avoid slicing unless necessary
18373 if (initialOffset !== undefined) return buffer.slice(initialOffset, offset)
19032 return buffer 18374 return buffer
19033} 18375}
19034 18376
@@ -19036,240 +18378,614 @@ Transaction.prototype.toHex = function () {
19036 return this.toBuffer().toString('hex') 18378 return this.toBuffer().toString('hex')
19037} 18379}
19038 18380
19039Transaction.prototype.setInputScript = function (index, script) { 18381Transaction.prototype.setInputScript = function (index, scriptSig) {
19040 typeForce('Number', index) 18382 typeforce(types.tuple(types.Number, types.Buffer), arguments)
19041 typeForce('Script', script)
19042 18383
19043 this.ins[index].script = script 18384 this.ins[index].script = scriptSig
19044} 18385}
19045 18386
19046// FIXME: remove in 2.x.y 18387Transaction.prototype.setWitness = function (index, witness) {
19047Transaction.prototype.sign = function (index, privKey, hashType) { 18388 typeforce(types.tuple(types.Number, [types.Buffer]), arguments)
19048 console.warn('Transaction.prototype.sign is deprecated. Use TransactionBuilder instead.')
19049
19050 var prevOutScript = privKey.pub.getAddress().toOutputScript()
19051 var signature = this.signInput(index, prevOutScript, privKey, hashType)
19052 18389
19053 var scriptSig = scripts.pubKeyHashInput(signature, privKey.pub) 18390 this.ins[index].witness = witness
19054 this.setInputScript(index, scriptSig)
19055} 18391}
19056 18392
19057// FIXME: remove in 2.x.y 18393module.exports = Transaction
19058Transaction.prototype.signInput = function (index, prevOutScript, privKey, hashType) {
19059 console.warn('Transaction.prototype.signInput is deprecated. Use TransactionBuilder instead.')
19060 18394
19061 hashType = hashType || Transaction.SIGHASH_ALL 18395},{"./bufferutils":44,"./crypto":45,"./script":52,"./types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109,"varuint-bitcoin":111}],77:[function(require,module,exports){
18396var Buffer = require('safe-buffer').Buffer
18397var baddress = require('./address')
18398var bcrypto = require('./crypto')
18399var bscript = require('./script')
18400var networks = require('./networks')
18401var ops = require('bitcoin-ops')
18402var typeforce = require('typeforce')
18403var types = require('./types')
18404var scriptTypes = bscript.types
18405var SIGNABLE = [bscript.types.P2PKH, bscript.types.P2PK, bscript.types.MULTISIG]
18406var P2SH = SIGNABLE.concat([bscript.types.P2WPKH, bscript.types.P2WSH])
18407
18408var ECPair = require('./ecpair')
18409var ECSignature = require('./ecsignature')
18410var Transaction = require('./transaction')
19062 18411
19063 var hash = this.hashForSignature(index, prevOutScript, hashType) 18412function extractChunks (type, chunks, script) {
19064 var signature = privKey.sign(hash) 18413 var pubKeys = []
18414 var signatures = []
18415 switch (type) {
18416 case scriptTypes.P2PKH:
18417 // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)')
18418 pubKeys = chunks.slice(1)
18419 signatures = chunks.slice(0, 1)
18420 break
19065 18421
19066 return signature.toScriptSignature(hashType) 18422 case scriptTypes.P2PK:
18423 pubKeys[0] = script ? bscript.pubKey.output.decode(script) : undefined
18424 signatures = chunks.slice(0, 1)
18425 break
18426
18427 case scriptTypes.MULTISIG:
18428 if (script) {
18429 var multisig = bscript.multisig.output.decode(script)
18430 pubKeys = multisig.pubKeys
18431 }
18432
18433 signatures = chunks.slice(1).map(function (chunk) {
18434 return chunk.length === 0 ? undefined : chunk
18435 })
18436 break
18437 }
18438
18439 return {
18440 pubKeys: pubKeys,
18441 signatures: signatures
18442 }
19067} 18443}
18444function expandInput (scriptSig, witnessStack) {
18445 if (scriptSig.length === 0 && witnessStack.length === 0) return {}
19068 18446
19069// FIXME: remove in 2.x.y 18447 var prevOutScript
19070Transaction.prototype.validateInput = function (index, prevOutScript, pubKey, buffer) { 18448 var prevOutType
19071 console.warn('Transaction.prototype.validateInput is deprecated. Use TransactionBuilder instead.') 18449 var scriptType
18450 var script
18451 var redeemScript
18452 var witnessScript
18453 var witnessScriptType
18454 var redeemScriptType
18455 var witness = false
18456 var p2wsh = false
18457 var p2sh = false
18458 var witnessProgram
18459 var chunks
18460
18461 var scriptSigChunks = bscript.decompile(scriptSig)
18462 var sigType = bscript.classifyInput(scriptSigChunks, true)
18463 if (sigType === scriptTypes.P2SH) {
18464 p2sh = true
18465 redeemScript = scriptSigChunks[scriptSigChunks.length - 1]
18466 redeemScriptType = bscript.classifyOutput(redeemScript)
18467 prevOutScript = bscript.scriptHash.output.encode(bcrypto.hash160(redeemScript))
18468 prevOutType = scriptTypes.P2SH
18469 script = redeemScript
18470 }
18471
18472 var classifyWitness = bscript.classifyWitness(witnessStack)
18473 if (classifyWitness === scriptTypes.P2WSH) {
18474 witnessScript = witnessStack[witnessStack.length - 1]
18475 witnessScriptType = bscript.classifyOutput(witnessScript)
18476 p2wsh = true
18477 if (scriptSig.length === 0) {
18478 prevOutScript = bscript.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
18479 prevOutType = scriptTypes.P2WSH
18480 if (typeof redeemScript !== 'undefined') {
18481 throw new Error('Redeem script given when unnecessary')
18482 }
18483 // bare witness
18484 } else {
18485 if (!redeemScript) {
18486 throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty')
18487 }
18488 witnessProgram = bscript.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
18489 if (!redeemScript.equals(witnessProgram)) {
18490 throw new Error('Redeem script didn\'t match witnessScript')
18491 }
18492 }
19072 18493
19073 var parsed = ECSignature.parseScriptSignature(buffer) 18494 if (SIGNABLE.indexOf(bscript.classifyOutput(witnessScript)) === -1) {
19074 var hash = this.hashForSignature(index, prevOutScript, parsed.hashType) 18495 throw new Error('unsupported witness script')
18496 }
18497 script = witnessScript
18498 scriptType = witnessScriptType
18499 chunks = witnessStack.slice(0, -1)
18500 } else if (classifyWitness === scriptTypes.P2WPKH) {
18501 var key = witnessStack[witnessStack.length - 1]
18502 var keyHash = bcrypto.hash160(key)
18503 if (scriptSig.length === 0) {
18504 prevOutScript = bscript.witnessPubKeyHash.output.encode(keyHash)
18505 prevOutType = scriptTypes.P2WPKH
18506 if (typeof redeemScript !== 'undefined') {
18507 throw new Error('Redeem script given when unnecessary')
18508 }
18509 } else {
18510 if (!redeemScript) {
18511 throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty')
18512 }
18513 witnessProgram = bscript.witnessPubKeyHash.output.encode(keyHash)
18514 if (!redeemScript.equals(witnessProgram)) {
18515 throw new Error('Redeem script did not have the right witness program')
18516 }
18517 }
18518
18519 scriptType = scriptTypes.P2PKH
18520 chunks = witnessStack
18521 } else if (redeemScript) {
18522 if (P2SH.indexOf(redeemScriptType) === -1) {
18523 throw new Error('Bad redeemscript!')
18524 }
18525
18526 script = redeemScript
18527 scriptType = redeemScriptType
18528 chunks = scriptSigChunks.slice(0, -1)
18529 } else {
18530 prevOutType = scriptType = bscript.classifyInput(scriptSig)
18531 chunks = scriptSigChunks
18532 }
18533
18534 var expanded = extractChunks(scriptType, chunks, script)
18535
18536 var result = {
18537 pubKeys: expanded.pubKeys,
18538 signatures: expanded.signatures,
18539 prevOutScript: prevOutScript,
18540 prevOutType: prevOutType,
18541 signType: scriptType,
18542 signScript: script,
18543 witness: Boolean(witness)
18544 }
18545
18546 if (p2sh) {
18547 result.redeemScript = redeemScript
18548 result.redeemScriptType = redeemScriptType
18549 }
19075 18550
19076 return pubKey.verify(hash, parsed.signature) 18551 if (p2wsh) {
18552 result.witnessScript = witnessScript
18553 result.witnessScriptType = witnessScriptType
18554 }
18555
18556 return result
19077} 18557}
19078 18558
19079module.exports = Transaction 18559// could be done in expandInput, but requires the original Transaction for hashForSignature
18560function fixMultisigOrder (input, transaction, vin) {
18561 if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return
18562 if (input.pubKeys.length === input.signatures.length) return
19080 18563
19081}).call(this,require("buffer").Buffer) 18564 var unmatched = input.signatures.concat()
19082},{"./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){
19083(function (Buffer){
19084var assert = require('assert')
19085var ops = require('./opcodes')
19086var scripts = require('./scripts')
19087 18565
19088var ECPubKey = require('./ecpubkey') 18566 input.signatures = input.pubKeys.map(function (pubKey) {
19089var ECSignature = require('./ecsignature') 18567 var keyPair = ECPair.fromPublicKeyBuffer(pubKey)
19090var Script = require('./script') 18568 var match
19091var Transaction = require('./transaction')
19092 18569
19093function extractInput (txIn) { 18570 // check for a signature
19094 var redeemScript 18571 unmatched.some(function (signature, i) {
19095 var scriptSig = txIn.script 18572 // skip if undefined || OP_0
19096 var prevOutScript 18573 if (!signature) return false
19097 var prevOutType = scripts.classifyInput(scriptSig, true)
19098 var scriptType
19099 18574
19100 // Re-classify if scriptHash 18575 // TODO: avoid O(n) hashForSignature
19101 if (prevOutType === 'scripthash') { 18576 var parsed = ECSignature.parseScriptSignature(signature)
19102 redeemScript = Script.fromBuffer(scriptSig.chunks.slice(-1)[0]) 18577 var hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType)
19103 prevOutScript = scripts.scriptHashOutput(redeemScript.getHash())
19104 18578
19105 scriptSig = Script.fromChunks(scriptSig.chunks.slice(0, -1)) 18579 // skip if signature does not match pubKey
19106 scriptType = scripts.classifyInput(scriptSig, true) 18580 if (!keyPair.verify(hash, parsed.signature)) return false
19107 } else { 18581
19108 scriptType = prevOutType 18582 // remove matched signature from unmatched
18583 unmatched[i] = undefined
18584 match = signature
18585
18586 return true
18587 })
18588
18589 return match
18590 })
18591}
18592
18593function expandOutput (script, scriptType, ourPubKey) {
18594 typeforce(types.Buffer, script)
18595
18596 var scriptChunks = bscript.decompile(script)
18597 if (!scriptType) {
18598 scriptType = bscript.classifyOutput(script)
19109 } 18599 }
19110 18600
19111 // Extract hashType, pubKeys and signatures 18601 var pubKeys = []
19112 var hashType, parsed, pubKeys, signatures
19113 18602
19114 switch (scriptType) { 18603 switch (scriptType) {
19115 case 'pubkeyhash': { 18604 // does our hash160(pubKey) match the output scripts?
19116 parsed = ECSignature.parseScriptSignature(scriptSig.chunks[0]) 18605 case scriptTypes.P2PKH:
19117 hashType = parsed.hashType 18606 if (!ourPubKey) break
19118 pubKeys = [ECPubKey.fromBuffer(scriptSig.chunks[1])]
19119 signatures = [parsed.signature]
19120 prevOutScript = pubKeys[0].getAddress().toOutputScript()
19121 18607
18608 var pkh1 = scriptChunks[2]
18609 var pkh2 = bcrypto.hash160(ourPubKey)
18610 if (pkh1.equals(pkh2)) pubKeys = [ourPubKey]
19122 break 18611 break
19123 }
19124 18612
19125 case 'pubkey': { 18613 // does our hash160(pubKey) match the output scripts?
19126 parsed = ECSignature.parseScriptSignature(scriptSig.chunks[0]) 18614 case scriptTypes.P2WPKH:
19127 hashType = parsed.hashType 18615 if (!ourPubKey) break
19128 signatures = [parsed.signature]
19129 18616
19130 if (redeemScript) { 18617 var wpkh1 = scriptChunks[1]
19131 pubKeys = [ECPubKey.fromBuffer(redeemScript.chunks[0])] 18618 var wpkh2 = bcrypto.hash160(ourPubKey)
19132 } 18619 if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey]
18620 break
19133 18621
18622 case scriptTypes.P2PK:
18623 pubKeys = scriptChunks.slice(0, 1)
19134 break 18624 break
19135 }
19136 18625
19137 case 'multisig': { 18626 case scriptTypes.MULTISIG:
19138 signatures = scriptSig.chunks.slice(1).map(function (chunk) { 18627 pubKeys = scriptChunks.slice(1, -2)
19139 if (chunk === ops.OP_0) return chunk 18628 break
19140 18629
19141 var parsed = ECSignature.parseScriptSignature(chunk) 18630 default: return { scriptType: scriptType }
19142 hashType = parsed.hashType 18631 }
19143 18632
19144 return parsed.signature 18633 return {
19145 }) 18634 pubKeys: pubKeys,
18635 scriptType: scriptType,
18636 signatures: pubKeys.map(function () { return undefined })
18637 }
18638}
18639
18640function checkP2shInput (input, redeemScriptHash) {
18641 if (input.prevOutType) {
18642 if (input.prevOutType !== scriptTypes.P2SH) throw new Error('PrevOutScript must be P2SH')
18643
18644 var prevOutScriptScriptHash = bscript.decompile(input.prevOutScript)[1]
18645 if (!prevOutScriptScriptHash.equals(redeemScriptHash)) throw new Error('Inconsistent hash160(RedeemScript)')
18646 }
18647}
18648
18649function checkP2WSHInput (input, witnessScriptHash) {
18650 if (input.prevOutType) {
18651 if (input.prevOutType !== scriptTypes.P2WSH) throw new Error('PrevOutScript must be P2WSH')
18652
18653 var scriptHash = bscript.decompile(input.prevOutScript)[1]
18654 if (!scriptHash.equals(witnessScriptHash)) throw new Error('Inconsistent sha25(WitnessScript)')
18655 }
18656}
18657
18658function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) {
18659 var expanded
18660 var prevOutType
18661 var prevOutScript
18662
18663 var p2sh = false
18664 var p2shType
18665 var redeemScriptHash
18666
18667 var witness = false
18668 var p2wsh = false
18669 var witnessType
18670 var witnessScriptHash
18671
18672 var signType
18673 var signScript
18674
18675 if (redeemScript && witnessScript) {
18676 redeemScriptHash = bcrypto.hash160(redeemScript)
18677 witnessScriptHash = bcrypto.sha256(witnessScript)
18678 checkP2shInput(input, redeemScriptHash)
18679
18680 if (!redeemScript.equals(bscript.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script')
18681
18682 expanded = expandOutput(witnessScript, undefined, kpPubKey)
18683 if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
18684 prevOutType = bscript.types.P2SH
18685 prevOutScript = bscript.scriptHash.output.encode(redeemScriptHash)
18686 p2sh = witness = p2wsh = true
18687 p2shType = bscript.types.P2WSH
18688 signType = witnessType = expanded.scriptType
18689 signScript = witnessScript
18690 } else if (redeemScript) {
18691 redeemScriptHash = bcrypto.hash160(redeemScript)
18692 checkP2shInput(input, redeemScriptHash)
18693
18694 expanded = expandOutput(redeemScript, undefined, kpPubKey)
18695 if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bscript.toASM(redeemScript) + '"')
18696
18697 prevOutType = bscript.types.P2SH
18698 prevOutScript = bscript.scriptHash.output.encode(redeemScriptHash)
18699 p2sh = true
18700 signType = p2shType = expanded.scriptType
18701 signScript = redeemScript
18702 witness = signType === bscript.types.P2WPKH
18703 } else if (witnessScript) {
18704 witnessScriptHash = bcrypto.sha256(witnessScript)
18705 checkP2WSHInput(input, witnessScriptHash)
18706
18707 expanded = expandOutput(witnessScript, undefined, kpPubKey)
18708 if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
18709
18710 prevOutType = bscript.types.P2WSH
18711 prevOutScript = bscript.witnessScriptHash.output.encode(witnessScriptHash)
18712 witness = p2wsh = true
18713 signType = witnessType = expanded.scriptType
18714 signScript = witnessScript
18715 } else if (input.prevOutType) {
18716 // embedded scripts are not possible without a redeemScript
18717 if (input.prevOutType === scriptTypes.P2SH ||
18718 input.prevOutType === scriptTypes.P2WSH) {
18719 throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript')
18720 }
18721
18722 prevOutType = input.prevOutType
18723 prevOutScript = input.prevOutScript
18724 expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey)
18725 if (!expanded.pubKeys) return
18726
18727 witness = (input.prevOutType === scriptTypes.P2WPKH)
18728 signType = prevOutType
18729 signScript = prevOutScript
18730 } else {
18731 prevOutScript = bscript.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey))
18732 expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey)
18733 prevOutType = scriptTypes.P2PKH
18734 witness = false
18735 signType = prevOutType
18736 signScript = prevOutScript
18737 }
19146 18738
19147 if (redeemScript) { 18739 if (witness && !types.Satoshi(witnessValue)) {
19148 pubKeys = redeemScript.chunks.slice(1, -2).map(ECPubKey.fromBuffer) 18740 throw new Error('Input was witness but not given witness value')
18741 }
18742
18743 if (signType === scriptTypes.P2WPKH) {
18744 signScript = bscript.pubKeyHash.output.encode(bscript.witnessPubKeyHash.output.decode(signScript))
18745 }
18746
18747 if (p2sh) {
18748 input.redeemScript = redeemScript
18749 input.redeemScriptType = p2shType
18750 }
18751
18752 if (p2wsh) {
18753 input.witnessScript = witnessScript
18754 input.witnessScriptType = witnessType
18755 }
18756
18757 input.pubKeys = expanded.pubKeys
18758 input.signatures = expanded.signatures
18759 input.signScript = signScript
18760 input.signType = signType
18761 input.prevOutScript = prevOutScript
18762 input.prevOutType = prevOutType
18763 input.witness = witness
18764}
18765
18766function buildStack (type, signatures, pubKeys, allowIncomplete) {
18767 if (type === scriptTypes.P2PKH) {
18768 if (signatures.length === 1 && Buffer.isBuffer(signatures[0]) && pubKeys.length === 1) return bscript.pubKeyHash.input.encodeStack(signatures[0], pubKeys[0])
18769 } else if (type === scriptTypes.P2PK) {
18770 if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return bscript.pubKey.input.encodeStack(signatures[0])
18771 } else if (type === scriptTypes.MULTISIG) {
18772 if (signatures.length > 0) {
18773 signatures = signatures.map(function (signature) {
18774 return signature || ops.OP_0
18775 })
18776 if (!allowIncomplete) {
18777 // remove blank signatures
18778 signatures = signatures.filter(function (x) { return x !== ops.OP_0 })
19149 } 18779 }
19150 18780
19151 break 18781 return bscript.multisig.input.encodeStack(signatures /* see if it's necessary first */)
19152 } 18782 }
18783 } else {
18784 throw new Error('Not yet supported')
18785 }
18786
18787 if (!allowIncomplete) throw new Error('Not enough signatures provided')
18788
18789 return []
18790}
18791
18792function buildInput (input, allowIncomplete) {
18793 var scriptType = input.prevOutType
18794 var sig = []
18795 var witness = []
18796 if (SIGNABLE.indexOf(scriptType) !== -1) {
18797 sig = buildStack(scriptType, input.signatures, input.pubKeys, allowIncomplete)
18798 }
18799
18800 var p2sh = false
18801 if (scriptType === bscript.types.P2SH) {
18802 // We can remove this error later when we have a guarantee prepareInput
18803 // rejects unsignable scripts - it MUST be signable at this point.
18804 if (P2SH.indexOf(input.redeemScriptType) === -1) {
18805 throw new Error('Impossible to sign this type')
18806 }
18807 p2sh = true
18808 if (SIGNABLE.indexOf(input.redeemScriptType) !== -1) {
18809 sig = buildStack(input.redeemScriptType, input.signatures, input.pubKeys, allowIncomplete)
18810 }
18811 // If it wasn't SIGNABLE, it's witness, defer to that
18812 scriptType = input.redeemScriptType
18813 }
18814
18815 if (scriptType === bscript.types.P2WPKH) {
18816 // P2WPKH is a special case of P2PKH
18817 witness = buildStack(bscript.types.P2PKH, input.signatures, input.pubKeys, allowIncomplete)
18818 } else if (scriptType === bscript.types.P2WSH) {
18819 // We can remove this check later
18820 if (SIGNABLE.indexOf(input.witnessScriptType) !== -1) {
18821 witness = buildStack(input.witnessScriptType, input.signatures, input.pubKeys, allowIncomplete)
18822 witness.push(input.witnessScript)
18823 } else {
18824 // We can remove this error later when we have a guarantee prepareInput
18825 // rejects unsignble scripts - it MUST be signable at this point.
18826 throw new Error()
18827 }
18828
18829 scriptType = input.witnessScriptType
18830 }
18831
18832 // append redeemScript if necessary
18833 if (p2sh) {
18834 sig.push(input.redeemScript)
19153 } 18835 }
19154 18836
19155 return { 18837 return {
19156 hashType: hashType, 18838 type: scriptType,
19157 prevOutScript: prevOutScript, 18839 script: bscript.compile(sig),
19158 prevOutType: prevOutType, 18840 witness: witness
19159 pubKeys: pubKeys,
19160 redeemScript: redeemScript,
19161 scriptType: scriptType,
19162 signatures: signatures
19163 } 18841 }
19164} 18842}
19165 18843
19166function TransactionBuilder () { 18844function TransactionBuilder (network, maximumFeeRate) {
19167 this.prevTxMap = {} 18845 this.prevTxMap = {}
19168 this.prevOutScripts = {} 18846 this.network = network || networks.bitcoin
19169 this.prevOutTypes = {} 18847
18848 // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth)
18849 this.maximumFeeRate = maximumFeeRate || 1000
19170 18850
19171 this.inputs = [] 18851 this.inputs = []
19172 this.tx = new Transaction() 18852 this.tx = new Transaction()
19173} 18853}
19174 18854
19175TransactionBuilder.fromTransaction = function (transaction) { 18855TransactionBuilder.prototype.setLockTime = function (locktime) {
19176 var txb = new TransactionBuilder() 18856 typeforce(types.UInt32, locktime)
19177 18857
19178 // Copy other transaction fields 18858 // if any signatures exist, throw
19179 txb.tx.version = transaction.version 18859 if (this.inputs.some(function (input) {
19180 txb.tx.locktime = transaction.locktime 18860 if (!input.signatures) return false
19181 18861
19182 // Extract/add inputs 18862 return input.signatures.some(function (s) { return s })
19183 transaction.ins.forEach(function (txIn) { 18863 })) {
19184 txb.addInput(txIn.hash, txIn.index, txIn.sequence) 18864 throw new Error('No, this would invalidate signatures')
19185 }) 18865 }
18866
18867 this.tx.locktime = locktime
18868}
18869
18870TransactionBuilder.prototype.setVersion = function (version) {
18871 typeforce(types.UInt32, version)
19186 18872
19187 // Extract/add outputs 18873 // XXX: this might eventually become more complex depending on what the versions represent
18874 this.tx.version = version
18875}
18876
18877TransactionBuilder.fromTransaction = function (transaction, network) {
18878 var txb = new TransactionBuilder(network)
18879
18880 // Copy transaction fields
18881 txb.setVersion(transaction.version)
18882 txb.setLockTime(transaction.locktime)
18883
18884 // Copy outputs (done first to avoid signature invalidation)
19188 transaction.outs.forEach(function (txOut) { 18885 transaction.outs.forEach(function (txOut) {
19189 txb.addOutput(txOut.script, txOut.value) 18886 txb.addOutput(txOut.script, txOut.value)
19190 }) 18887 })
19191 18888
19192 // Extract/add signatures 18889 // Copy inputs
19193 txb.inputs = transaction.ins.map(function (txIn) { 18890 transaction.ins.forEach(function (txIn) {
19194 // TODO: remove me after testcase added 18891 txb.__addInputUnsafe(txIn.hash, txIn.index, {
19195 assert(!Transaction.isCoinbaseHash(txIn.hash), 'coinbase inputs not supported') 18892 sequence: txIn.sequence,
19196 18893 script: txIn.script,
19197 // Ignore empty scripts 18894 witness: txIn.witness
19198 if (txIn.script.buffer.length === 0) return {} 18895 })
18896 })
19199 18897
19200 return extractInput(txIn) 18898 // fix some things not possible through the public API
18899 txb.inputs.forEach(function (input, i) {
18900 fixMultisigOrder(input, transaction, i)
19201 }) 18901 })
19202 18902
19203 return txb 18903 return txb
19204} 18904}
19205 18905
19206TransactionBuilder.prototype.addInput = function (prevTx, index, sequence, prevOutScript) { 18906TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) {
19207 var prevOutHash 18907 if (!this.__canModifyInputs()) {
18908 throw new Error('No, this would invalidate signatures')
18909 }
19208 18910
19209 // txId 18911 var value
19210 if (typeof prevTx === 'string') {
19211 prevOutHash = new Buffer(prevTx, 'hex')
19212 18912
19213 // TxId hex is big-endian, we want little-endian hash 18913 // is it a hex string?
19214 Array.prototype.reverse.call(prevOutHash) 18914 if (typeof txHash === 'string') {
18915 // transaction hashs's are displayed in reverse order, un-reverse it
18916 txHash = Buffer.from(txHash, 'hex').reverse()
19215 18917
19216 // Transaction 18918 // is it a Transaction object?
19217 } else if (prevTx instanceof Transaction) { 18919 } else if (txHash instanceof Transaction) {
19218 prevOutHash = prevTx.getHash() 18920 var txOut = txHash.outs[vout]
19219 prevOutScript = prevTx.outs[index].script 18921 prevOutScript = txOut.script
18922 value = txOut.value
19220 18923
19221 // txHash 18924 txHash = txHash.getHash()
19222 } else {
19223 prevOutHash = prevTx
19224 } 18925 }
19225 18926
19226 var input = {} 18927 return this.__addInputUnsafe(txHash, vout, {
19227 if (prevOutScript) { 18928 sequence: sequence,
19228 var prevOutType = scripts.classifyOutput(prevOutScript) 18929 prevOutScript: prevOutScript,
18930 value: value
18931 })
18932}
19229 18933
19230 // if we can, extract pubKey information 18934TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) {
19231 switch (prevOutType) { 18935 if (Transaction.isCoinbaseHash(txHash)) {
19232 case 'multisig': { 18936 throw new Error('coinbase inputs not supported')
19233 input.pubKeys = prevOutScript.chunks.slice(1, -2).map(ECPubKey.fromBuffer) 18937 }
19234 break
19235 }
19236 18938
19237 case 'pubkey': { 18939 var prevTxOut = txHash.toString('hex') + ':' + vout
19238 input.pubKeys = prevOutScript.chunks.slice(0, 1).map(ECPubKey.fromBuffer) 18940 if (this.prevTxMap[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut)
19239 break
19240 }
19241 }
19242 18941
19243 if (prevOutType !== 'scripthash') { 18942 var input = {}
19244 input.scriptType = prevOutType
19245 }
19246 18943
19247 input.prevOutScript = prevOutScript 18944 // derive what we can from the scriptSig
19248 input.prevOutType = prevOutType 18945 if (options.script !== undefined) {
18946 input = expandInput(options.script, options.witness || [])
19249 } 18947 }
19250 18948
19251 assert(this.inputs.every(function (input2) { 18949 // if an input value was given, retain it
19252 if (input2.hashType === undefined) return true 18950 if (options.value !== undefined) {
18951 input.value = options.value
18952 }
19253 18953
19254 return input2.hashType & Transaction.SIGHASH_ANYONECANPAY 18954 // derive what we can from the previous transactions output script
19255 }), 'No, this would invalidate signatures') 18955 if (!input.prevOutScript && options.prevOutScript) {
18956 var prevOutType
19256 18957
19257 var prevOut = prevOutHash.toString('hex') + ':' + index 18958 if (!input.pubKeys && !input.signatures) {
19258 assert(!(prevOut in this.prevTxMap), 'Transaction is already an input') 18959 var expanded = expandOutput(options.prevOutScript)
19259 18960
19260 var vin = this.tx.addInput(prevOutHash, index, sequence) 18961 if (expanded.pubKeys) {
18962 input.pubKeys = expanded.pubKeys
18963 input.signatures = expanded.signatures
18964 }
18965
18966 prevOutType = expanded.scriptType
18967 }
18968
18969 input.prevOutScript = options.prevOutScript
18970 input.prevOutType = prevOutType || bscript.classifyOutput(options.prevOutScript)
18971 }
18972
18973 var vin = this.tx.addInput(txHash, vout, options.sequence, options.scriptSig)
19261 this.inputs[vin] = input 18974 this.inputs[vin] = input
19262 this.prevTxMap[prevOut] = vin 18975 this.prevTxMap[prevTxOut] = vin
19263 18976
19264 return vin 18977 return vin
19265} 18978}
19266 18979
19267TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) { 18980TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) {
19268 assert(this.inputs.every(function (input) { 18981 if (!this.__canModifyOutputs()) {
19269 if (input.hashType === undefined) return true 18982 throw new Error('No, this would invalidate signatures')
18983 }
19270 18984
19271 return (input.hashType & 0x1f) === Transaction.SIGHASH_SINGLE 18985 // Attempt to get a script if it's a base58 address string
19272 }), 'No, this would invalidate signatures') 18986 if (typeof scriptPubKey === 'string') {
18987 scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network)
18988 }
19273 18989
19274 return this.tx.addOutput(scriptPubKey, value) 18990 return this.tx.addOutput(scriptPubKey, value)
19275} 18991}
@@ -19281,592 +18997,3116 @@ TransactionBuilder.prototype.buildIncomplete = function () {
19281 return this.__build(true) 18997 return this.__build(true)
19282} 18998}
19283 18999
19284var canSignTypes = {
19285 'pubkeyhash': true,
19286 'multisig': true,
19287 'pubkey': true
19288}
19289
19290TransactionBuilder.prototype.__build = function (allowIncomplete) { 19000TransactionBuilder.prototype.__build = function (allowIncomplete) {
19291 if (!allowIncomplete) { 19001 if (!allowIncomplete) {
19292 assert(this.tx.ins.length > 0, 'Transaction has no inputs') 19002 if (!this.tx.ins.length) throw new Error('Transaction has no inputs')
19293 assert(this.tx.outs.length > 0, 'Transaction has no outputs') 19003 if (!this.tx.outs.length) throw new Error('Transaction has no outputs')
19294 } 19004 }
19295 19005
19296 var tx = this.tx.clone() 19006 var tx = this.tx.clone()
19007 // Create script signatures from inputs
19008 this.inputs.forEach(function (input, i) {
19009 var scriptType = input.witnessScriptType || input.redeemScriptType || input.prevOutType
19010 if (!scriptType && !allowIncomplete) throw new Error('Transaction is not complete')
19011 var result = buildInput(input, allowIncomplete)
19297 19012
19298 // Create script signatures from signature meta-data 19013 // skip if no result
19299 this.inputs.forEach(function (input, index) {
19300 var scriptType = input.scriptType
19301 var scriptSig
19302
19303 if (!allowIncomplete) { 19014 if (!allowIncomplete) {
19304 assert(!!scriptType, 'Transaction is not complete') 19015 if (SIGNABLE.indexOf(result.type) === -1 && result.type !== bscript.types.P2WPKH) {
19305 assert(scriptType in canSignTypes, scriptType + ' not supported') 19016 throw new Error(result.type + ' not supported')
19306 assert(input.signatures, 'Transaction is missing signatures') 19017 }
19307 } 19018 }
19308 19019
19309 if (input.signatures) { 19020 tx.setInputScript(i, result.script)
19310 switch (scriptType) { 19021 tx.setWitness(i, result.witness)
19311 case 'pubkeyhash': { 19022 })
19312 var pkhSignature = input.signatures[0].toScriptSignature(input.hashType)
19313 scriptSig = scripts.pubKeyHashInput(pkhSignature, input.pubKeys[0])
19314 break
19315 }
19316 19023
19317 case 'multisig': { 19024 if (!allowIncomplete) {
19318 // Array.prototype.map is sparse-compatible 19025 // do not rely on this, its merely a last resort
19319 var msSignatures = input.signatures.map(function (signature) { 19026 if (this.__overMaximumFees(tx.byteLength())) {
19320 return signature && signature.toScriptSignature(input.hashType) 19027 throw new Error('Transaction has absurd fees')
19321 }) 19028 }
19029 }
19322 19030
19323 // fill in blanks with OP_0 19031 return tx
19324 if (allowIncomplete) { 19032}
19325 for (var i = 0; i < msSignatures.length; ++i) {
19326 if (msSignatures[i]) continue
19327 19033
19328 msSignatures[i] = ops.OP_0 19034function canSign (input) {
19329 } 19035 return input.prevOutScript !== undefined &&
19330 } else { 19036 input.signScript !== undefined &&
19331 // Array.prototype.filter returns non-sparse array 19037 input.pubKeys !== undefined &&
19332 msSignatures = msSignatures.filter(function (x) { return x }) 19038 input.signatures !== undefined &&
19333 } 19039 input.signatures.length === input.pubKeys.length &&
19040 input.pubKeys.length > 0 &&
19041 input.witness !== undefined
19042}
19334 19043
19335 var redeemScript = allowIncomplete ? undefined : input.redeemScript 19044TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) {
19336 scriptSig = scripts.multisigInput(msSignatures, redeemScript) 19045 if (keyPair.network !== this.network) throw new Error('Inconsistent network')
19337 break 19046 if (!this.inputs[vin]) throw new Error('No input at index: ' + vin)
19338 } 19047 hashType = hashType || Transaction.SIGHASH_ALL
19339 19048
19340 case 'pubkey': { 19049 var input = this.inputs[vin]
19341 var pkSignature = input.signatures[0].toScriptSignature(input.hashType) 19050
19342 scriptSig = scripts.pubKeyInput(pkSignature) 19051 // if redeemScript was previously provided, enforce consistency
19343 break 19052 if (input.redeemScript !== undefined &&
19344 } 19053 redeemScript &&
19054 !input.redeemScript.equals(redeemScript)) {
19055 throw new Error('Inconsistent redeemScript')
19056 }
19057
19058 var kpPubKey = keyPair.getPublicKeyBuffer()
19059 if (!canSign(input)) {
19060 prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript)
19061 if (!canSign(input)) throw Error(input.prevOutType + ' not supported')
19062 }
19063
19064 // ready to sign
19065 var signatureHash
19066 if (input.witness) {
19067 signatureHash = this.tx.hashForWitnessV0(vin, input.signScript, witnessValue, hashType)
19068 } else {
19069 signatureHash = this.tx.hashForSignature(vin, input.signScript, hashType)
19070 }
19071 // enforce in order signing of public keys
19072 var signed = input.pubKeys.some(function (pubKey, i) {
19073 if (!kpPubKey.equals(pubKey)) return false
19074 if (input.signatures[i]) throw new Error('Signature already exists')
19075
19076 input.signatures[i] = keyPair.sign(signatureHash).toScriptSignature(hashType)
19077 return true
19078 })
19079
19080 if (!signed) throw new Error('Key pair cannot sign for this input')
19081}
19082
19083function signatureHashType (buffer) {
19084 return buffer.readUInt8(buffer.length - 1)
19085}
19086
19087TransactionBuilder.prototype.__canModifyInputs = function () {
19088 return this.inputs.every(function (input) {
19089 // any signatures?
19090 if (input.signatures === undefined) return true
19091
19092 return input.signatures.every(function (signature) {
19093 if (!signature) return true
19094 var hashType = signatureHashType(signature)
19095
19096 // if SIGHASH_ANYONECANPAY is set, signatures would not
19097 // be invalidated by more inputs
19098 return hashType & Transaction.SIGHASH_ANYONECANPAY
19099 })
19100 })
19101}
19102
19103TransactionBuilder.prototype.__canModifyOutputs = function () {
19104 var nInputs = this.tx.ins.length
19105 var nOutputs = this.tx.outs.length
19106
19107 return this.inputs.every(function (input) {
19108 if (input.signatures === undefined) return true
19109
19110 return input.signatures.every(function (signature) {
19111 if (!signature) return true
19112 var hashType = signatureHashType(signature)
19113
19114 var hashTypeMod = hashType & 0x1f
19115 if (hashTypeMod === Transaction.SIGHASH_NONE) return true
19116 if (hashTypeMod === Transaction.SIGHASH_SINGLE) {
19117 // if SIGHASH_SINGLE is set, and nInputs > nOutputs
19118 // some signatures would be invalidated by the addition
19119 // of more outputs
19120 return nInputs <= nOutputs
19345 } 19121 }
19122 })
19123 })
19124}
19125
19126TransactionBuilder.prototype.__overMaximumFees = function (bytes) {
19127 // not all inputs will have .value defined
19128 var incoming = this.inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0)
19129
19130 // but all outputs do, and if we have any input value
19131 // we can immediately determine if the outputs are too small
19132 var outgoing = this.tx.outs.reduce(function (a, x) { return a + x.value }, 0)
19133 var fee = incoming - outgoing
19134 var feeRate = fee / bytes
19135
19136 return feeRate > this.maximumFeeRate
19137}
19138
19139module.exports = TransactionBuilder
19140
19141},{"./address":42,"./crypto":45,"./ecpair":47,"./ecsignature":48,"./networks":51,"./script":52,"./transaction":76,"./types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],78:[function(require,module,exports){
19142var typeforce = require('typeforce')
19143
19144var UINT31_MAX = Math.pow(2, 31) - 1
19145function UInt31 (value) {
19146 return typeforce.UInt32(value) && value <= UINT31_MAX
19147}
19148
19149function BIP32Path (value) {
19150 return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/)
19151}
19152BIP32Path.toJSON = function () { return 'BIP32 derivation path' }
19153
19154var SATOSHI_MAX = 21 * 1e14
19155function Satoshi (value) {
19156 return typeforce.UInt53(value) && value <= SATOSHI_MAX
19157}
19158
19159// external dependent types
19160var BigInt = typeforce.quacksLike('BigInteger')
19161var ECPoint = typeforce.quacksLike('Point')
19162
19163// exposed, external API
19164var ECSignature = typeforce.compile({ r: BigInt, s: BigInt })
19165var Network = typeforce.compile({
19166 messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String),
19167 bip32: {
19168 public: typeforce.UInt32,
19169 private: typeforce.UInt32
19170 },
19171 pubKeyHash: typeforce.UInt8,
19172 scriptHash: typeforce.UInt8,
19173 wif: typeforce.UInt8
19174})
19175
19176// extend typeforce types with ours
19177var types = {
19178 BigInt: BigInt,
19179 BIP32Path: BIP32Path,
19180 Buffer256bit: typeforce.BufferN(32),
19181 ECPoint: ECPoint,
19182 ECSignature: ECSignature,
19183 Hash160bit: typeforce.BufferN(20),
19184 Hash256bit: typeforce.BufferN(32),
19185 Network: Network,
19186 Satoshi: Satoshi,
19187 UInt31: UInt31
19188}
19189
19190for (var typeName in typeforce) {
19191 types[typeName] = typeforce[typeName]
19192}
19193
19194module.exports = types
19195
19196},{"typeforce":109}],79:[function(require,module,exports){
19197var basex = require('base-x')
19198var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
19199
19200module.exports = basex(ALPHABET)
19201
19202},{"base-x":34}],80:[function(require,module,exports){
19203(function (Buffer){
19204'use strict'
19205
19206var base58 = require('bs58')
19207var createHash = require('create-hash')
19208
19209// SHA256(SHA256(buffer))
19210function sha256x2 (buffer) {
19211 var tmp = createHash('sha256').update(buffer).digest()
19212 return createHash('sha256').update(tmp).digest()
19213}
19214
19215// Encode a buffer as a base58-check encoded string
19216function encode (payload) {
19217 var checksum = sha256x2(payload)
19218
19219 return base58.encode(Buffer.concat([
19220 payload,
19221 checksum
19222 ], payload.length + 4))
19223}
19224
19225function decodeRaw (buffer) {
19226 var payload = buffer.slice(0, -4)
19227 var checksum = buffer.slice(-4)
19228 var newChecksum = sha256x2(payload)
19229
19230 if (checksum[0] ^ newChecksum[0] |
19231 checksum[1] ^ newChecksum[1] |
19232 checksum[2] ^ newChecksum[2] |
19233 checksum[3] ^ newChecksum[3]) return
19234
19235 return payload
19236}
19237
19238// Decode a base58-check encoded string to a buffer, no result if checksum is wrong
19239function decodeUnsafe (string) {
19240 var buffer = base58.decodeUnsafe(string)
19241 if (!buffer) return
19242
19243 return decodeRaw(buffer)
19244}
19245
19246function decode (string) {
19247 var buffer = base58.decode(string)
19248 var payload = decodeRaw(buffer)
19249 if (!payload) throw new Error('Invalid checksum')
19250 return payload
19251}
19252
19253module.exports = {
19254 encode: encode,
19255 decode: decode,
19256 decodeUnsafe: decodeUnsafe
19257}
19258
19259}).call(this,require("buffer").Buffer)
19260},{"bs58":79,"buffer":4,"create-hash":82}],81:[function(require,module,exports){
19261var Buffer = require('safe-buffer').Buffer
19262var Transform = require('stream').Transform
19263var StringDecoder = require('string_decoder').StringDecoder
19264var inherits = require('inherits')
19265
19266function CipherBase (hashMode) {
19267 Transform.call(this)
19268 this.hashMode = typeof hashMode === 'string'
19269 if (this.hashMode) {
19270 this[hashMode] = this._finalOrDigest
19271 } else {
19272 this.final = this._finalOrDigest
19273 }
19274 if (this._final) {
19275 this.__final = this._final
19276 this._final = null
19277 }
19278 this._decoder = null
19279 this._encoding = null
19280}
19281inherits(CipherBase, Transform)
19282
19283CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
19284 if (typeof data === 'string') {
19285 data = Buffer.from(data, inputEnc)
19286 }
19287
19288 var outData = this._update(data)
19289 if (this.hashMode) return this
19290
19291 if (outputEnc) {
19292 outData = this._toString(outData, outputEnc)
19293 }
19294
19295 return outData
19296}
19297
19298CipherBase.prototype.setAutoPadding = function () {}
19299CipherBase.prototype.getAuthTag = function () {
19300 throw new Error('trying to get auth tag in unsupported state')
19301}
19302
19303CipherBase.prototype.setAuthTag = function () {
19304 throw new Error('trying to set auth tag in unsupported state')
19305}
19306
19307CipherBase.prototype.setAAD = function () {
19308 throw new Error('trying to set aad in unsupported state')
19309}
19310
19311CipherBase.prototype._transform = function (data, _, next) {
19312 var err
19313 try {
19314 if (this.hashMode) {
19315 this._update(data)
19316 } else {
19317 this.push(this._update(data))
19346 } 19318 }
19319 } catch (e) {
19320 err = e
19321 } finally {
19322 next(err)
19323 }
19324}
19325CipherBase.prototype._flush = function (done) {
19326 var err
19327 try {
19328 this.push(this.__final())
19329 } catch (e) {
19330 err = e
19331 }
19347 19332
19348 // did we build a scriptSig? 19333 done(err)
19349 if (scriptSig) { 19334}
19350 // wrap as scriptHash if necessary 19335CipherBase.prototype._finalOrDigest = function (outputEnc) {
19351 if (input.prevOutType === 'scripthash') { 19336 var outData = this.__final() || Buffer.alloc(0)
19352 scriptSig = scripts.scriptHashInput(scriptSig, input.redeemScript) 19337 if (outputEnc) {
19353 } 19338 outData = this._toString(outData, outputEnc, true)
19339 }
19340 return outData
19341}
19342
19343CipherBase.prototype._toString = function (value, enc, fin) {
19344 if (!this._decoder) {
19345 this._decoder = new StringDecoder(enc)
19346 this._encoding = enc
19347 }
19348
19349 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
19350
19351 var out = this._decoder.write(value)
19352 if (fin) {
19353 out += this._decoder.end()
19354 }
19355
19356 return out
19357}
19358
19359module.exports = CipherBase
19360
19361},{"inherits":93,"safe-buffer":98,"stream":27,"string_decoder":28}],82:[function(require,module,exports){
19362(function (Buffer){
19363'use strict'
19364var inherits = require('inherits')
19365var md5 = require('./md5')
19366var RIPEMD160 = require('ripemd160')
19367var sha = require('sha.js')
19368
19369var Base = require('cipher-base')
19370
19371function HashNoConstructor (hash) {
19372 Base.call(this, 'digest')
19373
19374 this._hash = hash
19375 this.buffers = []
19376}
19377
19378inherits(HashNoConstructor, Base)
19379
19380HashNoConstructor.prototype._update = function (data) {
19381 this.buffers.push(data)
19382}
19383
19384HashNoConstructor.prototype._final = function () {
19385 var buf = Buffer.concat(this.buffers)
19386 var r = this._hash(buf)
19387 this.buffers = null
19388
19389 return r
19390}
19391
19392function Hash (hash) {
19393 Base.call(this, 'digest')
19394
19395 this._hash = hash
19396}
19397
19398inherits(Hash, Base)
19399
19400Hash.prototype._update = function (data) {
19401 this._hash.update(data)
19402}
19403
19404Hash.prototype._final = function () {
19405 return this._hash.digest()
19406}
19407
19408module.exports = function createHash (alg) {
19409 alg = alg.toLowerCase()
19410 if (alg === 'md5') return new HashNoConstructor(md5)
19411 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
19412
19413 return new Hash(sha(alg))
19414}
19415
19416}).call(this,require("buffer").Buffer)
19417},{"./md5":84,"buffer":4,"cipher-base":81,"inherits":93,"ripemd160":97,"sha.js":100}],83:[function(require,module,exports){
19418(function (Buffer){
19419'use strict'
19420var intSize = 4
19421var zeroBuffer = new Buffer(intSize)
19422zeroBuffer.fill(0)
19423
19424var charSize = 8
19425var hashSize = 16
19426
19427function toArray (buf) {
19428 if ((buf.length % intSize) !== 0) {
19429 var len = buf.length + (intSize - (buf.length % intSize))
19430 buf = Buffer.concat([buf, zeroBuffer], len)
19431 }
19354 19432
19355 tx.setInputScript(index, scriptSig) 19433 var arr = new Array(buf.length >>> 2)
19434 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
19435 arr[j] = buf.readInt32LE(i)
19436 }
19437
19438 return arr
19439}
19440
19441module.exports = function hash (buf, fn) {
19442 var arr = fn(toArray(buf), buf.length * charSize)
19443 buf = new Buffer(hashSize)
19444 for (var i = 0; i < arr.length; i++) {
19445 buf.writeInt32LE(arr[i], i << 2, true)
19446 }
19447 return buf
19448}
19449
19450}).call(this,require("buffer").Buffer)
19451},{"buffer":4}],84:[function(require,module,exports){
19452'use strict'
19453/*
19454 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
19455 * Digest Algorithm, as defined in RFC 1321.
19456 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
19457 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
19458 * Distributed under the BSD License
19459 * See http://pajhome.org.uk/crypt/md5 for more info.
19460 */
19461
19462var makeHash = require('./make-hash')
19463
19464/*
19465 * Calculate the MD5 of an array of little-endian words, and a bit length
19466 */
19467function core_md5 (x, len) {
19468 /* append padding */
19469 x[len >> 5] |= 0x80 << ((len) % 32)
19470 x[(((len + 64) >>> 9) << 4) + 14] = len
19471
19472 var a = 1732584193
19473 var b = -271733879
19474 var c = -1732584194
19475 var d = 271733878
19476
19477 for (var i = 0; i < x.length; i += 16) {
19478 var olda = a
19479 var oldb = b
19480 var oldc = c
19481 var oldd = d
19482
19483 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
19484 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
19485 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
19486 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
19487 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
19488 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
19489 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
19490 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
19491 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
19492 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
19493 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
19494 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
19495 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
19496 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
19497 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
19498 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
19499
19500 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
19501 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
19502 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
19503 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
19504 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
19505 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
19506 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
19507 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
19508 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
19509 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
19510 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
19511 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
19512 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
19513 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
19514 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
19515 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
19516
19517 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
19518 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
19519 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
19520 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
19521 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
19522 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
19523 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
19524 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
19525 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
19526 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
19527 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
19528 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
19529 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
19530 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
19531 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
19532 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
19533
19534 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
19535 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
19536 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
19537 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
19538 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
19539 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
19540 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
19541 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
19542 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
19543 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
19544 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
19545 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
19546 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
19547 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
19548 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
19549 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
19550
19551 a = safe_add(a, olda)
19552 b = safe_add(b, oldb)
19553 c = safe_add(c, oldc)
19554 d = safe_add(d, oldd)
19555 }
19556
19557 return [a, b, c, d]
19558}
19559
19560/*
19561 * These functions implement the four basic operations the algorithm uses.
19562 */
19563function md5_cmn (q, a, b, x, s, t) {
19564 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
19565}
19566
19567function md5_ff (a, b, c, d, x, s, t) {
19568 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
19569}
19570
19571function md5_gg (a, b, c, d, x, s, t) {
19572 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
19573}
19574
19575function md5_hh (a, b, c, d, x, s, t) {
19576 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
19577}
19578
19579function md5_ii (a, b, c, d, x, s, t) {
19580 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
19581}
19582
19583/*
19584 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
19585 * to work around bugs in some JS interpreters.
19586 */
19587function safe_add (x, y) {
19588 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
19589 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
19590 return (msw << 16) | (lsw & 0xFFFF)
19591}
19592
19593/*
19594 * Bitwise rotate a 32-bit number to the left.
19595 */
19596function bit_rol (num, cnt) {
19597 return (num << cnt) | (num >>> (32 - cnt))
19598}
19599
19600module.exports = function md5 (buf) {
19601 return makeHash(buf, core_md5)
19602}
19603
19604},{"./make-hash":83}],85:[function(require,module,exports){
19605'use strict'
19606var inherits = require('inherits')
19607var Legacy = require('./legacy')
19608var Base = require('cipher-base')
19609var Buffer = require('safe-buffer').Buffer
19610var md5 = require('create-hash/md5')
19611var RIPEMD160 = require('ripemd160')
19612
19613var sha = require('sha.js')
19614
19615var ZEROS = Buffer.alloc(128)
19616
19617function Hmac (alg, key) {
19618 Base.call(this, 'digest')
19619 if (typeof key === 'string') {
19620 key = Buffer.from(key)
19621 }
19622
19623 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
19624
19625 this._alg = alg
19626 this._key = key
19627 if (key.length > blocksize) {
19628 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
19629 key = hash.update(key).digest()
19630 } else if (key.length < blocksize) {
19631 key = Buffer.concat([key, ZEROS], blocksize)
19632 }
19633
19634 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
19635 var opad = this._opad = Buffer.allocUnsafe(blocksize)
19636
19637 for (var i = 0; i < blocksize; i++) {
19638 ipad[i] = key[i] ^ 0x36
19639 opad[i] = key[i] ^ 0x5C
19640 }
19641 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
19642 this._hash.update(ipad)
19643}
19644
19645inherits(Hmac, Base)
19646
19647Hmac.prototype._update = function (data) {
19648 this._hash.update(data)
19649}
19650
19651Hmac.prototype._final = function () {
19652 var h = this._hash.digest()
19653 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
19654 return hash.update(this._opad).update(h).digest()
19655}
19656
19657module.exports = function createHmac (alg, key) {
19658 alg = alg.toLowerCase()
19659 if (alg === 'rmd160' || alg === 'ripemd160') {
19660 return new Hmac('rmd160', key)
19661 }
19662 if (alg === 'md5') {
19663 return new Legacy(md5, key)
19664 }
19665 return new Hmac(alg, key)
19666}
19667
19668},{"./legacy":86,"cipher-base":81,"create-hash/md5":84,"inherits":93,"ripemd160":97,"safe-buffer":98,"sha.js":100}],86:[function(require,module,exports){
19669'use strict'
19670var inherits = require('inherits')
19671var Buffer = require('safe-buffer').Buffer
19672
19673var Base = require('cipher-base')
19674
19675var ZEROS = Buffer.alloc(128)
19676var blocksize = 64
19677
19678function Hmac (alg, key) {
19679 Base.call(this, 'digest')
19680 if (typeof key === 'string') {
19681 key = Buffer.from(key)
19682 }
19683
19684 this._alg = alg
19685 this._key = key
19686
19687 if (key.length > blocksize) {
19688 key = alg(key)
19689 } else if (key.length < blocksize) {
19690 key = Buffer.concat([key, ZEROS], blocksize)
19691 }
19692
19693 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
19694 var opad = this._opad = Buffer.allocUnsafe(blocksize)
19695
19696 for (var i = 0; i < blocksize; i++) {
19697 ipad[i] = key[i] ^ 0x36
19698 opad[i] = key[i] ^ 0x5C
19699 }
19700
19701 this._hash = [ipad]
19702}
19703
19704inherits(Hmac, Base)
19705
19706Hmac.prototype._update = function (data) {
19707 this._hash.push(data)
19708}
19709
19710Hmac.prototype._final = function () {
19711 var h = this._alg(Buffer.concat(this._hash))
19712 return this._alg(Buffer.concat([this._opad, h]))
19713}
19714module.exports = Hmac
19715
19716},{"cipher-base":81,"inherits":93,"safe-buffer":98}],87:[function(require,module,exports){
19717var assert = require('assert')
19718var BigInteger = require('bigi')
19719
19720var Point = require('./point')
19721
19722function Curve (p, a, b, Gx, Gy, n, h) {
19723 this.p = p
19724 this.a = a
19725 this.b = b
19726 this.G = Point.fromAffine(this, Gx, Gy)
19727 this.n = n
19728 this.h = h
19729
19730 this.infinity = new Point(this, null, null, BigInteger.ZERO)
19731
19732 // result caching
19733 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
19734
19735 // determine size of p in bytes
19736 this.pLength = Math.floor((this.p.bitLength() + 7) / 8)
19737}
19738
19739Curve.prototype.pointFromX = function (isOdd, x) {
19740 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
19741 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves
19742
19743 var y = beta
19744 if (beta.isEven() ^ !isOdd) {
19745 y = this.p.subtract(y) // -y % p
19746 }
19747
19748 return Point.fromAffine(this, x, y)
19749}
19750
19751Curve.prototype.isInfinity = function (Q) {
19752 if (Q === this.infinity) return true
19753
19754 return Q.z.signum() === 0 && Q.y.signum() !== 0
19755}
19756
19757Curve.prototype.isOnCurve = function (Q) {
19758 if (this.isInfinity(Q)) return true
19759
19760 var x = Q.affineX
19761 var y = Q.affineY
19762 var a = this.a
19763 var b = this.b
19764 var p = this.p
19765
19766 // Check that xQ and yQ are integers in the interval [0, p - 1]
19767 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
19768 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
19769
19770 // and check that y^2 = x^3 + ax + b (mod p)
19771 var lhs = y.square().mod(p)
19772 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
19773 return lhs.equals(rhs)
19774}
19775
19776/**
19777 * Validate an elliptic curve point.
19778 *
19779 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
19780 */
19781Curve.prototype.validate = function (Q) {
19782 // Check Q != O
19783 assert(!this.isInfinity(Q), 'Point is at infinity')
19784 assert(this.isOnCurve(Q), 'Point is not on the curve')
19785
19786 // Check nQ = O (where Q is a scalar multiple of G)
19787 var nQ = Q.multiply(this.n)
19788 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
19789
19790 return true
19791}
19792
19793module.exports = Curve
19794
19795},{"./point":91,"assert":1,"bigi":37}],88:[function(require,module,exports){
19796module.exports={
19797 "secp128r1": {
19798 "p": "fffffffdffffffffffffffffffffffff",
19799 "a": "fffffffdfffffffffffffffffffffffc",
19800 "b": "e87579c11079f43dd824993c2cee5ed3",
19801 "n": "fffffffe0000000075a30d1b9038a115",
19802 "h": "01",
19803 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
19804 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
19805 },
19806 "secp160k1": {
19807 "p": "fffffffffffffffffffffffffffffffeffffac73",
19808 "a": "00",
19809 "b": "07",
19810 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
19811 "h": "01",
19812 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
19813 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
19814 },
19815 "secp160r1": {
19816 "p": "ffffffffffffffffffffffffffffffff7fffffff",
19817 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
19818 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
19819 "n": "0100000000000000000001f4c8f927aed3ca752257",
19820 "h": "01",
19821 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
19822 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
19823 },
19824 "secp192k1": {
19825 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
19826 "a": "00",
19827 "b": "03",
19828 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
19829 "h": "01",
19830 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
19831 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
19832 },
19833 "secp192r1": {
19834 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
19835 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
19836 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
19837 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
19838 "h": "01",
19839 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
19840 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
19841 },
19842 "secp256k1": {
19843 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
19844 "a": "00",
19845 "b": "07",
19846 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
19847 "h": "01",
19848 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
19849 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
19850 },
19851 "secp256r1": {
19852 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
19853 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
19854 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
19855 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
19856 "h": "01",
19857 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
19858 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
19859 }
19860}
19861
19862},{}],89:[function(require,module,exports){
19863var Point = require('./point')
19864var Curve = require('./curve')
19865
19866var getCurveByName = require('./names')
19867
19868module.exports = {
19869 Curve: Curve,
19870 Point: Point,
19871 getCurveByName: getCurveByName
19872}
19873
19874},{"./curve":87,"./names":90,"./point":91}],90:[function(require,module,exports){
19875var BigInteger = require('bigi')
19876
19877var curves = require('./curves.json')
19878var Curve = require('./curve')
19879
19880function getCurveByName (name) {
19881 var curve = curves[name]
19882 if (!curve) return null
19883
19884 var p = new BigInteger(curve.p, 16)
19885 var a = new BigInteger(curve.a, 16)
19886 var b = new BigInteger(curve.b, 16)
19887 var n = new BigInteger(curve.n, 16)
19888 var h = new BigInteger(curve.h, 16)
19889 var Gx = new BigInteger(curve.Gx, 16)
19890 var Gy = new BigInteger(curve.Gy, 16)
19891
19892 return new Curve(p, a, b, Gx, Gy, n, h)
19893}
19894
19895module.exports = getCurveByName
19896
19897},{"./curve":87,"./curves.json":88,"bigi":37}],91:[function(require,module,exports){
19898(function (Buffer){
19899var assert = require('assert')
19900var BigInteger = require('bigi')
19901
19902var THREE = BigInteger.valueOf(3)
19903
19904function Point (curve, x, y, z) {
19905 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
19906
19907 this.curve = curve
19908 this.x = x
19909 this.y = y
19910 this.z = z
19911 this._zInv = null
19912
19913 this.compressed = true
19914}
19915
19916Object.defineProperty(Point.prototype, 'zInv', {
19917 get: function () {
19918 if (this._zInv === null) {
19919 this._zInv = this.z.modInverse(this.curve.p)
19356 } 19920 }
19357 })
19358 19921
19359 return tx 19922 return this._zInv
19923 }
19924})
19925
19926Object.defineProperty(Point.prototype, 'affineX', {
19927 get: function () {
19928 return this.x.multiply(this.zInv).mod(this.curve.p)
19929 }
19930})
19931
19932Object.defineProperty(Point.prototype, 'affineY', {
19933 get: function () {
19934 return this.y.multiply(this.zInv).mod(this.curve.p)
19935 }
19936})
19937
19938Point.fromAffine = function (curve, x, y) {
19939 return new Point(curve, x, y, BigInteger.ONE)
19360} 19940}
19361 19941
19362TransactionBuilder.prototype.sign = function (index, privKey, redeemScript, hashType) { 19942Point.prototype.equals = function (other) {
19363 assert(index in this.inputs, 'No input at index: ' + index) 19943 if (other === this) return true
19364 hashType = hashType || Transaction.SIGHASH_ALL 19944 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
19945 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
19365 19946
19366 var input = this.inputs[index] 19947 // u = Y2 * Z1 - Y1 * Z2
19367 var canSign = input.hashType && 19948 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
19368 input.prevOutScript && 19949
19369 input.prevOutType && 19950 if (u.signum() !== 0) return false
19370 input.pubKeys && 19951
19371 input.scriptType && 19952 // v = X2 * Z1 - X1 * Z2
19372 input.signatures 19953 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
19373 19954
19374 // are we almost ready to sign? 19955 return v.signum() === 0
19375 if (canSign) { 19956}
19376 // if redeemScript was provided, enforce consistency 19957
19377 if (redeemScript) { 19958Point.prototype.negate = function () {
19378 assert.deepEqual(input.redeemScript, redeemScript, 'Inconsistent redeemScript') 19959 var y = this.curve.p.subtract(this.y)
19960
19961 return new Point(this.curve, this.x, y, this.z)
19962}
19963
19964Point.prototype.add = function (b) {
19965 if (this.curve.isInfinity(this)) return b
19966 if (this.curve.isInfinity(b)) return this
19967
19968 var x1 = this.x
19969 var y1 = this.y
19970 var x2 = b.x
19971 var y2 = b.y
19972
19973 // u = Y2 * Z1 - Y1 * Z2
19974 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
19975 // v = X2 * Z1 - X1 * Z2
19976 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
19977
19978 if (v.signum() === 0) {
19979 if (u.signum() === 0) {
19980 return this.twice() // this == b, so double
19379 } 19981 }
19380 19982
19381 assert.equal(input.hashType, hashType, 'Inconsistent hashType') 19983 return this.curve.infinity // this = -b, so infinity
19984 }
19382 19985
19383 // no? prepare 19986 var v2 = v.square()
19384 } else { 19987 var v3 = v2.multiply(v)
19385 // must be pay-to-scriptHash? 19988 var x1v2 = x1.multiply(v2)
19386 if (redeemScript) { 19989 var zu2 = u.square().multiply(this.z)
19387 // if we have a prevOutScript, enforce scriptHash equality to the redeemScript
19388 if (input.prevOutScript) {
19389 assert.equal(input.prevOutType, 'scripthash', 'PrevOutScript must be P2SH')
19390 19990
19391 var scriptHash = input.prevOutScript.chunks[1] 19991 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
19392 assert.deepEqual(scriptHash, redeemScript.getHash(), 'RedeemScript does not match ' + scriptHash.toString('hex')) 19992 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
19393 } 19993 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
19994 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)
19995 // z3 = v^3 * z1 * z2
19996 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
19997
19998 return new Point(this.curve, x3, y3, z3)
19999}
19394 20000
19395 var scriptType = scripts.classifyOutput(redeemScript) 20001Point.prototype.twice = function () {
19396 assert(scriptType in canSignTypes, 'RedeemScript not supported (' + scriptType + ')') 20002 if (this.curve.isInfinity(this)) return this
20003 if (this.y.signum() === 0) return this.curve.infinity
19397 20004
19398 var pubKeys = [] 20005 var x1 = this.x
19399 switch (scriptType) { 20006 var y1 = this.y
19400 case 'multisig': {
19401 pubKeys = redeemScript.chunks.slice(1, -2).map(ECPubKey.fromBuffer)
19402 break
19403 }
19404 20007
19405 case 'pubkeyhash': { 20008 var y1z1 = y1.multiply(this.z).mod(this.curve.p)
19406 var pkh1 = redeemScript.chunks[2] 20009 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
19407 var pkh2 = privKey.pub.getAddress().hash 20010 var a = this.curve.a
19408 20011
19409 assert.deepEqual(pkh1, pkh2, 'privateKey cannot sign for this input') 20012 // w = 3 * x1^2 + a * z1^2
19410 pubKeys = [privKey.pub] 20013 var w = x1.square().multiply(THREE)
19411 break
19412 }
19413 20014
19414 case 'pubkey': { 20015 if (a.signum() !== 0) {
19415 pubKeys = redeemScript.chunks.slice(0, 1).map(ECPubKey.fromBuffer) 20016 w = w.add(this.z.square().multiply(a))
19416 break 20017 }
19417 }
19418 }
19419 20018
19420 if (!input.prevOutScript) { 20019 w = w.mod(this.curve.p)
19421 input.prevOutScript = scripts.scriptHashOutput(redeemScript.getHash()) 20020 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
19422 input.prevOutType = 'scripthash' 20021 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
19423 } 20022 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
20023 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
20024 // z3 = 8 * (y1 * z1)^3
20025 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
19424 20026
19425 input.pubKeys = pubKeys 20027 return new Point(this.curve, x3, y3, z3)
19426 input.redeemScript = redeemScript 20028}
19427 input.scriptType = scriptType
19428 20029
19429 // cannot be pay-to-scriptHash 20030// Simple NAF (Non-Adjacent Form) multiplication algorithm
19430 } else { 20031// TODO: modularize the multiplication algorithm
19431 assert.notEqual(input.prevOutType, 'scripthash', 'PrevOutScript is P2SH, missing redeemScript') 20032Point.prototype.multiply = function (k) {
20033 if (this.curve.isInfinity(this)) return this
20034 if (k.signum() === 0) return this.curve.infinity
20035
20036 var e = k
20037 var h = e.multiply(THREE)
20038
20039 var neg = this.negate()
20040 var R = this
20041
20042 for (var i = h.bitLength() - 2; i > 0; --i) {
20043 var hBit = h.testBit(i)
20044 var eBit = e.testBit(i)
20045
20046 R = R.twice()
20047
20048 if (hBit !== eBit) {
20049 R = R.add(hBit ? this : neg)
20050 }
20051 }
19432 20052
19433 // can we otherwise sign this? 20053 return R
19434 if (input.scriptType) { 20054}
19435 assert(input.pubKeys, input.scriptType + ' not supported')
19436 20055
19437 // we know nothin' Jon Snow, assume pubKeyHash 20056// Compute this*j + x*k (simultaneous multiplication)
20057Point.prototype.multiplyTwo = function (j, x, k) {
20058 var i = Math.max(j.bitLength(), k.bitLength()) - 1
20059 var R = this.curve.infinity
20060 var both = this.add(x)
20061
20062 while (i >= 0) {
20063 var jBit = j.testBit(i)
20064 var kBit = k.testBit(i)
20065
20066 R = R.twice()
20067
20068 if (jBit) {
20069 if (kBit) {
20070 R = R.add(both)
19438 } else { 20071 } else {
19439 input.prevOutScript = privKey.pub.getAddress().toOutputScript() 20072 R = R.add(this)
19440 input.prevOutType = 'pubkeyhash'
19441 input.pubKeys = [privKey.pub]
19442 input.scriptType = input.prevOutType
19443 } 20073 }
20074 } else if (kBit) {
20075 R = R.add(x)
19444 } 20076 }
20077 --i
20078 }
19445 20079
19446 input.hashType = hashType 20080 return R
19447 input.signatures = input.signatures || [] 20081}
20082
20083Point.prototype.getEncoded = function (compressed) {
20084 if (compressed == null) compressed = this.compressed
20085 if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00'
20086
20087 var x = this.affineX
20088 var y = this.affineY
20089 var byteLength = this.curve.pLength
20090 var buffer
20091
20092 // 0x02/0x03 | X
20093 if (compressed) {
20094 buffer = new Buffer(1 + byteLength)
20095 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
20096
20097 // 0x04 | X | Y
20098 } else {
20099 buffer = new Buffer(1 + byteLength + byteLength)
20100 buffer.writeUInt8(0x04, 0)
20101
20102 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
19448 } 20103 }
19449 20104
19450 var signatureScript = input.redeemScript || input.prevOutScript 20105 x.toBuffer(byteLength).copy(buffer, 1)
19451 var signatureHash = this.tx.hashForSignature(index, signatureScript, hashType)
19452 20106
19453 // enforce signature order matches public keys 20107 return buffer
19454 if (input.scriptType === 'multisig' && input.redeemScript && input.signatures.length !== input.pubKeys.length) { 20108}
19455 // maintain a local copy of unmatched signatures
19456 var unmatched = input.signatures.slice()
19457 20109
19458 input.signatures = input.pubKeys.map(function (pubKey) { 20110Point.decodeFrom = function (curve, buffer) {
19459 var match 20111 var type = buffer.readUInt8(0)
20112 var compressed = (type !== 4)
19460 20113
19461 // check for any matching signatures 20114 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
19462 unmatched.some(function (signature, i) { 20115 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength))
19463 if (!pubKey.verify(signatureHash, signature)) return false
19464 match = signature
19465 20116
19466 // remove matched signature from unmatched 20117 var Q
19467 unmatched.splice(i, 1) 20118 if (compressed) {
20119 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
20120 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
19468 20121
19469 return true 20122 var isOdd = (type === 0x03)
19470 }) 20123 Q = curve.pointFromX(isOdd, x)
20124 } else {
20125 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
19471 20126
19472 return match || undefined 20127 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
19473 }) 20128 Q = Point.fromAffine(curve, x, y)
19474 } 20129 }
19475 20130
19476 // enforce in order signing of public keys 20131 Q.compressed = compressed
19477 assert(input.pubKeys.some(function (pubKey, i) { 20132 return Q
19478 if (!privKey.pub.Q.equals(pubKey.Q)) return false 20133}
19479 20134
19480 assert(!input.signatures[i], 'Signature already exists') 20135Point.prototype.toString = function () {
19481 var signature = privKey.sign(signatureHash) 20136 if (this.curve.isInfinity(this)) return '(INFINITY)'
19482 input.signatures[i] = signature
19483 20137
19484 return true 20138 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
19485 }, this), 'privateKey cannot sign for this input')
19486} 20139}
19487 20140
19488module.exports = TransactionBuilder 20141module.exports = Point
19489 20142
19490}).call(this,require("buffer").Buffer) 20143}).call(this,require("buffer").Buffer)
19491},{"./ecpubkey":61,"./ecsignature":62,"./opcodes":67,"./script":68,"./scripts":69,"./transaction":70,"assert":5,"buffer":7}],72:[function(require,module,exports){ 20144},{"assert":1,"bigi":37,"buffer":4}],92:[function(require,module,exports){
19492(function (Buffer){ 20145(function (Buffer){
19493var assert = require('assert') 20146'use strict'
19494var bufferutils = require('./bufferutils') 20147var Transform = require('stream').Transform
19495var typeForce = require('typeforce') 20148var inherits = require('inherits')
19496var networks = require('./networks')
19497var randomBytes = require('randombytes')
19498 20149
19499var Address = require('./address') 20150function HashBase (blockSize) {
19500var HDNode = require('./hdnode') 20151 Transform.call(this)
19501var TransactionBuilder = require('./transaction_builder')
19502var Script = require('./script')
19503 20152
19504function Wallet (seed, network) { 20153 this._block = new Buffer(blockSize)
19505 console.warn('Wallet is deprecated and will be removed in 2.0.0, see #296') 20154 this._blockSize = blockSize
20155 this._blockOffset = 0
20156 this._length = [0, 0, 0, 0]
19506 20157
19507 seed = seed || randomBytes(32) 20158 this._finalized = false
19508 network = network || networks.bitcoin 20159}
19509 20160
19510 // Stored in a closure to make accidental serialization less likely 20161inherits(HashBase, Transform)
19511 var masterKey = HDNode.fromSeedBuffer(seed, network)
19512 20162
19513 // HD first-level child derivation method should be hardened 20163HashBase.prototype._transform = function (chunk, encoding, callback) {
19514 // See https://bitcointalk.org/index.php?topic=405179.msg4415254#msg4415254 20164 var error = null
19515 var accountZero = masterKey.deriveHardened(0) 20165 try {
19516 var externalAccount = accountZero.derive(0) 20166 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
19517 var internalAccount = accountZero.derive(1) 20167 this.update(chunk)
20168 } catch (err) {
20169 error = err
20170 }
19518 20171
19519 this.addresses = [] 20172 callback(error)
19520 this.changeAddresses = [] 20173}
19521 this.network = network
19522 this.unspents = []
19523 20174
19524 // FIXME: remove in 2.0.0 20175HashBase.prototype._flush = function (callback) {
19525 this.unspentMap = {} 20176 var error = null
20177 try {
20178 this.push(this._digest())
20179 } catch (err) {
20180 error = err
20181 }
19526 20182
19527 // FIXME: remove in 2.0.0 20183 callback(error)
19528 var me = this 20184}
19529 this.newMasterKey = function (seed) {
19530 console.warn('newMasterKey is deprecated, please make a new Wallet instance instead')
19531 20185
19532 seed = seed || randomBytes(32) 20186HashBase.prototype.update = function (data, encoding) {
19533 masterKey = HDNode.fromSeedBuffer(seed, network) 20187 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
20188 if (this._finalized) throw new Error('Digest already called')
20189 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
19534 20190
19535 accountZero = masterKey.deriveHardened(0) 20191 // consume data
19536 externalAccount = accountZero.derive(0) 20192 var block = this._block
19537 internalAccount = accountZero.derive(1) 20193 var offset = 0
20194 while (this._blockOffset + data.length - offset >= this._blockSize) {
20195 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
20196 this._update()
20197 this._blockOffset = 0
20198 }
20199 while (offset < data.length) block[this._blockOffset++] = data[offset++]
19538 20200
19539 me.addresses = [] 20201 // update length
19540 me.changeAddresses = [] 20202 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
20203 this._length[j] += carry
20204 carry = (this._length[j] / 0x0100000000) | 0
20205 if (carry > 0) this._length[j] -= 0x0100000000 * carry
20206 }
19541 20207
19542 me.unspents = [] 20208 return this
19543 me.unspentMap = {} 20209}
20210
20211HashBase.prototype._update = function (data) {
20212 throw new Error('_update is not implemented')
20213}
20214
20215HashBase.prototype.digest = function (encoding) {
20216 if (this._finalized) throw new Error('Digest already called')
20217 this._finalized = true
20218
20219 var digest = this._digest()
20220 if (encoding !== undefined) digest = digest.toString(encoding)
20221 return digest
20222}
20223
20224HashBase.prototype._digest = function () {
20225 throw new Error('_digest is not implemented')
20226}
20227
20228module.exports = HashBase
20229
20230}).call(this,require("buffer").Buffer)
20231},{"buffer":4,"inherits":93,"stream":27}],93:[function(require,module,exports){
20232arguments[4][8][0].apply(exports,arguments)
20233},{"dup":8}],94:[function(require,module,exports){
20234(function (Buffer){
20235// constant-space merkle root calculation algorithm
20236module.exports = function fastRoot (values, digestFn) {
20237 if (!Array.isArray(values)) throw TypeError('Expected values Array')
20238 if (typeof digestFn !== 'function') throw TypeError('Expected digest Function')
20239
20240 var length = values.length
20241 var results = values.concat()
20242
20243 while (length > 1) {
20244 var j = 0
20245
20246 for (var i = 0; i < length; i += 2, ++j) {
20247 var left = results[i]
20248 var right = i + 1 === length ? left : results[i + 1]
20249 var data = Buffer.concat([left, right])
20250
20251 results[j] = digestFn(data)
20252 }
20253
20254 length = j
19544 } 20255 }
19545 20256
19546 this.getMasterKey = function () { 20257 return results[0]
19547 return masterKey 20258}
20259
20260}).call(this,require("buffer").Buffer)
20261},{"buffer":4}],95:[function(require,module,exports){
20262var OPS = require('bitcoin-ops')
20263
20264function encodingLength (i) {
20265 return i < OPS.OP_PUSHDATA1 ? 1
20266 : i <= 0xff ? 2
20267 : i <= 0xffff ? 3
20268 : 5
20269}
20270
20271function encode (buffer, number, offset) {
20272 var size = encodingLength(number)
20273
20274 // ~6 bit
20275 if (size === 1) {
20276 buffer.writeUInt8(number, offset)
20277
20278 // 8 bit
20279 } else if (size === 2) {
20280 buffer.writeUInt8(OPS.OP_PUSHDATA1, offset)
20281 buffer.writeUInt8(number, offset + 1)
20282
20283 // 16 bit
20284 } else if (size === 3) {
20285 buffer.writeUInt8(OPS.OP_PUSHDATA2, offset)
20286 buffer.writeUInt16LE(number, offset + 1)
20287
20288 // 32 bit
20289 } else {
20290 buffer.writeUInt8(OPS.OP_PUSHDATA4, offset)
20291 buffer.writeUInt32LE(number, offset + 1)
19548 } 20292 }
19549 this.getAccountZero = function () { 20293
19550 return accountZero 20294 return size
20295}
20296
20297function decode (buffer, offset) {
20298 var opcode = buffer.readUInt8(offset)
20299 var number, size
20300
20301 // ~6 bit
20302 if (opcode < OPS.OP_PUSHDATA1) {
20303 number = opcode
20304 size = 1
20305
20306 // 8 bit
20307 } else if (opcode === OPS.OP_PUSHDATA1) {
20308 if (offset + 2 > buffer.length) return null
20309 number = buffer.readUInt8(offset + 1)
20310 size = 2
20311
20312 // 16 bit
20313 } else if (opcode === OPS.OP_PUSHDATA2) {
20314 if (offset + 3 > buffer.length) return null
20315 number = buffer.readUInt16LE(offset + 1)
20316 size = 3
20317
20318 // 32 bit
20319 } else {
20320 if (offset + 5 > buffer.length) return null
20321 if (opcode !== OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode')
20322
20323 number = buffer.readUInt32LE(offset + 1)
20324 size = 5
19551 } 20325 }
19552 this.getExternalAccount = function () { 20326
19553 return externalAccount 20327 return {
20328 opcode: opcode,
20329 number: number,
20330 size: size
19554 } 20331 }
19555 this.getInternalAccount = function () { 20332}
19556 return internalAccount 20333
20334module.exports = {
20335 encodingLength: encodingLength,
20336 encode: encode,
20337 decode: decode
20338}
20339
20340},{"bitcoin-ops":40}],96:[function(require,module,exports){
20341(function (process,global){
20342'use strict'
20343
20344function oldBrowser () {
20345 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
20346}
20347
20348var Buffer = require('safe-buffer').Buffer
20349var crypto = global.crypto || global.msCrypto
20350
20351if (crypto && crypto.getRandomValues) {
20352 module.exports = randomBytes
20353} else {
20354 module.exports = oldBrowser
20355}
20356
20357function randomBytes (size, cb) {
20358 // phantomjs needs to throw
20359 if (size > 65536) throw new Error('requested too many random bytes')
20360 // in case browserify isn't using the Uint8Array version
20361 var rawBytes = new global.Uint8Array(size)
20362
20363 // This will not work in older browsers.
20364 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
20365 if (size > 0) { // getRandomValues fails on IE if size == 0
20366 crypto.getRandomValues(rawBytes)
19557 } 20367 }
20368
20369 // XXX: phantomjs doesn't like a buffer being passed here
20370 var bytes = Buffer.from(rawBytes.buffer)
20371
20372 if (typeof cb === 'function') {
20373 return process.nextTick(function () {
20374 cb(null, bytes)
20375 })
20376 }
20377
20378 return bytes
19558} 20379}
19559 20380
19560Wallet.prototype.createTransaction = function (to, value, options) { 20381}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
19561 // FIXME: remove in 2.0.0 20382},{"_process":12,"safe-buffer":98}],97:[function(require,module,exports){
19562 if (typeof options !== 'object') { 20383(function (Buffer){
19563 if (options !== undefined) { 20384'use strict'
19564 console.warn('Non options object parameters are deprecated, use options object instead') 20385var inherits = require('inherits')
20386var HashBase = require('hash-base')
20387
20388function RIPEMD160 () {
20389 HashBase.call(this, 64)
19565 20390
19566 options = { 20391 // state
19567 fixedFee: arguments[2], 20392 this._a = 0x67452301
19568 changeAddress: arguments[3] 20393 this._b = 0xefcdab89
19569 } 20394 this._c = 0x98badcfe
20395 this._d = 0x10325476
20396 this._e = 0xc3d2e1f0
20397}
20398
20399inherits(RIPEMD160, HashBase)
20400
20401RIPEMD160.prototype._update = function () {
20402 var m = new Array(16)
20403 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
20404
20405 var al = this._a
20406 var bl = this._b
20407 var cl = this._c
20408 var dl = this._d
20409 var el = this._e
20410
20411 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
20412 // K = 0x00000000
20413 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
20414 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
20415 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
20416 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
20417 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
20418 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
20419 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
20420 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
20421 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
20422 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
20423 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
20424 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
20425 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
20426 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
20427 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
20428 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
20429 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
20430
20431 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
20432 // K = 0x5a827999
20433 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
20434 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
20435 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
20436 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
20437 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
20438 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
20439 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
20440 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
20441 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
20442 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
20443 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
20444 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
20445 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
20446 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
20447 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
20448 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
20449 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
20450
20451 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
20452 // K = 0x6ed9eba1
20453 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
20454 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
20455 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
20456 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
20457 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
20458 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
20459 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
20460 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
20461 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
20462 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
20463 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
20464 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
20465 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
20466 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
20467 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
20468 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
20469 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
20470
20471 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
20472 // K = 0x8f1bbcdc
20473 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
20474 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
20475 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
20476 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
20477 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
20478 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
20479 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
20480 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
20481 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
20482 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
20483 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
20484 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
20485 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
20486 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
20487 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
20488 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
20489 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
20490
20491 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
20492 // K = 0xa953fd4e
20493 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
20494 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
20495 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
20496 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
20497 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
20498 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
20499 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
20500 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
20501 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
20502 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
20503 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
20504 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
20505 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
20506 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
20507 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
20508 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
20509 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
20510
20511 var ar = this._a
20512 var br = this._b
20513 var cr = this._c
20514 var dr = this._d
20515 var er = this._e
20516
20517 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
20518 // K' = 0x50a28be6
20519 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
20520 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
20521 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
20522 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
20523 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
20524 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
20525 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
20526 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
20527 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
20528 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
20529 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
20530 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
20531 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
20532 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
20533 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
20534 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
20535 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
20536
20537 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
20538 // K' = 0x5c4dd124
20539 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
20540 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
20541 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
20542 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
20543 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
20544 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
20545 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
20546 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
20547 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
20548 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
20549 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
20550 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
20551 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
20552 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
20553 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
20554 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
20555 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
20556
20557 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
20558 // K' = 0x6d703ef3
20559 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
20560 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
20561 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
20562 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
20563 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
20564 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
20565 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
20566 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
20567 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
20568 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
20569 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
20570 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
20571 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
20572 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
20573 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
20574 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
20575 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
20576
20577 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
20578 // K' = 0x7a6d76e9
20579 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
20580 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
20581 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
20582 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
20583 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
20584 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
20585 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
20586 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
20587 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
20588 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
20589 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
20590 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
20591 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
20592 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
20593 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
20594 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
20595 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
20596
20597 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
20598 // K' = 0x00000000
20599 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
20600 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
20601 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
20602 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
20603 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
20604 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
20605 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
20606 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
20607 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
20608 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
20609 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
20610 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
20611 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
20612 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
20613 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
20614 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
20615 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
20616
20617 // change state
20618 var t = (this._b + cl + dr) | 0
20619 this._b = (this._c + dl + er) | 0
20620 this._c = (this._d + el + ar) | 0
20621 this._d = (this._e + al + br) | 0
20622 this._e = (this._a + bl + cr) | 0
20623 this._a = t
20624}
20625
20626RIPEMD160.prototype._digest = function () {
20627 // create padding and handle blocks
20628 this._block[this._blockOffset++] = 0x80
20629 if (this._blockOffset > 56) {
20630 this._block.fill(0, this._blockOffset, 64)
20631 this._update()
20632 this._blockOffset = 0
20633 }
20634
20635 this._block.fill(0, this._blockOffset, 56)
20636 this._block.writeUInt32LE(this._length[0], 56)
20637 this._block.writeUInt32LE(this._length[1], 60)
20638 this._update()
20639
20640 // produce result
20641 var buffer = new Buffer(20)
20642 buffer.writeInt32LE(this._a, 0)
20643 buffer.writeInt32LE(this._b, 4)
20644 buffer.writeInt32LE(this._c, 8)
20645 buffer.writeInt32LE(this._d, 12)
20646 buffer.writeInt32LE(this._e, 16)
20647 return buffer
20648}
20649
20650function rotl (x, n) {
20651 return (x << n) | (x >>> (32 - n))
20652}
20653
20654function fn1 (a, b, c, d, e, m, k, s) {
20655 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
20656}
20657
20658function fn2 (a, b, c, d, e, m, k, s) {
20659 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
20660}
20661
20662function fn3 (a, b, c, d, e, m, k, s) {
20663 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
20664}
20665
20666function fn4 (a, b, c, d, e, m, k, s) {
20667 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
20668}
20669
20670function fn5 (a, b, c, d, e, m, k, s) {
20671 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
20672}
20673
20674module.exports = RIPEMD160
20675
20676}).call(this,require("buffer").Buffer)
20677},{"buffer":4,"hash-base":92,"inherits":93}],98:[function(require,module,exports){
20678arguments[4][26][0].apply(exports,arguments)
20679},{"buffer":4,"dup":26}],99:[function(require,module,exports){
20680(function (Buffer){
20681// prototype class for hash functions
20682function Hash (blockSize, finalSize) {
20683 this._block = new Buffer(blockSize)
20684 this._finalSize = finalSize
20685 this._blockSize = blockSize
20686 this._len = 0
20687 this._s = 0
20688}
20689
20690Hash.prototype.update = function (data, enc) {
20691 if (typeof data === 'string') {
20692 enc = enc || 'utf8'
20693 data = new Buffer(data, enc)
20694 }
20695
20696 var l = this._len += data.length
20697 var s = this._s || 0
20698 var f = 0
20699 var buffer = this._block
20700
20701 while (s < l) {
20702 var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
20703 var ch = (t - f)
20704
20705 for (var i = 0; i < ch; i++) {
20706 buffer[(s % this._blockSize) + i] = data[i + f]
20707 }
20708
20709 s += ch
20710 f += ch
20711
20712 if ((s % this._blockSize) === 0) {
20713 this._update(buffer)
19570 } 20714 }
19571 } 20715 }
20716 this._s = s
19572 20717
19573 options = options || {} 20718 return this
20719}
19574 20720
19575 assert(value > this.network.dustThreshold, value + ' must be above dust threshold (' + this.network.dustThreshold + ' Satoshis)') 20721Hash.prototype.digest = function (enc) {
20722 // Suppose the length of the message M, in bits, is l
20723 var l = this._len * 8
19576 20724
19577 var changeAddress = options.changeAddress 20725 // Append the bit 1 to the end of the message
19578 var fixedFee = options.fixedFee 20726 this._block[this._len % this._blockSize] = 0x80
19579 var minConf = options.minConf === undefined ? 0 : options.minConf // FIXME: change minConf:1 by default in 2.0.0
19580 20727
19581 // filter by minConf, then pending and sort by descending value 20728 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
19582 var unspents = this.unspents.filter(function (unspent) { 20729 this._block.fill(0, this._len % this._blockSize + 1)
19583 return unspent.confirmations >= minConf
19584 }).filter(function (unspent) {
19585 return !unspent.pending
19586 }).sort(function (o1, o2) {
19587 return o2.value - o1.value
19588 })
19589 20730
19590 var accum = 0 20731 if (l % (this._blockSize * 8) >= this._finalSize * 8) {
19591 var addresses = [] 20732 this._update(this._block)
19592 var subTotal = value 20733 this._block.fill(0)
20734 }
19593 20735
19594 var txb = new TransactionBuilder() 20736 // to this append the block which is equal to the number l written in binary
19595 txb.addOutput(to, value) 20737 // TODO: handle case where l is > Math.pow(2, 29)
20738 this._block.writeInt32BE(l, this._blockSize - 4)
19596 20739
19597 for (var i = 0; i < unspents.length; ++i) { 20740 var hash = this._update(this._block) || this._hash()
19598 var unspent = unspents[i]
19599 addresses.push(unspent.address)
19600 20741
19601 txb.addInput(unspent.txHash, unspent.index) 20742 return enc ? hash.toString(enc) : hash
20743}
19602 20744
19603 var fee = fixedFee === undefined ? estimatePaddedFee(txb.buildIncomplete(), this.network) : fixedFee 20745Hash.prototype._update = function () {
20746 throw new Error('_update must be implemented by subclass')
20747}
19604 20748
19605 accum += unspent.value 20749module.exports = Hash
19606 subTotal = value + fee
19607 20750
19608 if (accum >= subTotal) { 20751}).call(this,require("buffer").Buffer)
19609 var change = accum - subTotal 20752},{"buffer":4}],100:[function(require,module,exports){
20753var exports = module.exports = function SHA (algorithm) {
20754 algorithm = algorithm.toLowerCase()
19610 20755
19611 if (change > this.network.dustThreshold) { 20756 var Algorithm = exports[algorithm]
19612 txb.addOutput(changeAddress || this.getChangeAddress(), change) 20757 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
19613 }
19614 20758
19615 break 20759 return new Algorithm()
19616 } 20760}
20761
20762exports.sha = require('./sha')
20763exports.sha1 = require('./sha1')
20764exports.sha224 = require('./sha224')
20765exports.sha256 = require('./sha256')
20766exports.sha384 = require('./sha384')
20767exports.sha512 = require('./sha512')
20768
20769},{"./sha":101,"./sha1":102,"./sha224":103,"./sha256":104,"./sha384":105,"./sha512":106}],101:[function(require,module,exports){
20770(function (Buffer){
20771/*
20772 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
20773 * in FIPS PUB 180-1
20774 * This source code is derived from sha1.js of the same repository.
20775 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
20776 * operation was added.
20777 */
20778
20779var inherits = require('inherits')
20780var Hash = require('./hash')
20781
20782var K = [
20783 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
20784]
20785
20786var W = new Array(80)
20787
20788function Sha () {
20789 this.init()
20790 this._w = W
20791
20792 Hash.call(this, 64, 56)
20793}
20794
20795inherits(Sha, Hash)
20796
20797Sha.prototype.init = function () {
20798 this._a = 0x67452301
20799 this._b = 0xefcdab89
20800 this._c = 0x98badcfe
20801 this._d = 0x10325476
20802 this._e = 0xc3d2e1f0
20803
20804 return this
20805}
20806
20807function rotl5 (num) {
20808 return (num << 5) | (num >>> 27)
20809}
20810
20811function rotl30 (num) {
20812 return (num << 30) | (num >>> 2)
20813}
20814
20815function ft (s, b, c, d) {
20816 if (s === 0) return (b & c) | ((~b) & d)
20817 if (s === 2) return (b & c) | (b & d) | (c & d)
20818 return b ^ c ^ d
20819}
20820
20821Sha.prototype._update = function (M) {
20822 var W = this._w
20823
20824 var a = this._a | 0
20825 var b = this._b | 0
20826 var c = this._c | 0
20827 var d = this._d | 0
20828 var e = this._e | 0
20829
20830 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
20831 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
20832
20833 for (var j = 0; j < 80; ++j) {
20834 var s = ~~(j / 20)
20835 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
20836
20837 e = d
20838 d = c
20839 c = rotl30(b)
20840 b = a
20841 a = t
19617 } 20842 }
19618 20843
19619 assert(accum >= subTotal, 'Not enough funds (incl. fee): ' + accum + ' < ' + subTotal) 20844 this._a = (a + this._a) | 0
20845 this._b = (b + this._b) | 0
20846 this._c = (c + this._c) | 0
20847 this._d = (d + this._d) | 0
20848 this._e = (e + this._e) | 0
20849}
19620 20850
19621 return this.signWith(txb, addresses).build() 20851Sha.prototype._hash = function () {
20852 var H = new Buffer(20)
20853
20854 H.writeInt32BE(this._a | 0, 0)
20855 H.writeInt32BE(this._b | 0, 4)
20856 H.writeInt32BE(this._c | 0, 8)
20857 H.writeInt32BE(this._d | 0, 12)
20858 H.writeInt32BE(this._e | 0, 16)
20859
20860 return H
19622} 20861}
19623 20862
19624// FIXME: remove in 2.0.0 20863module.exports = Sha
19625Wallet.prototype.processPendingTx = function (tx) { 20864
19626 this.__processTx(tx, true) 20865}).call(this,require("buffer").Buffer)
20866},{"./hash":99,"buffer":4,"inherits":93}],102:[function(require,module,exports){
20867(function (Buffer){
20868/*
20869 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
20870 * in FIPS PUB 180-1
20871 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
20872 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
20873 * Distributed under the BSD License
20874 * See http://pajhome.org.uk/crypt/md5 for details.
20875 */
20876
20877var inherits = require('inherits')
20878var Hash = require('./hash')
20879
20880var K = [
20881 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
20882]
20883
20884var W = new Array(80)
20885
20886function Sha1 () {
20887 this.init()
20888 this._w = W
20889
20890 Hash.call(this, 64, 56)
19627} 20891}
19628 20892
19629// FIXME: remove in 2.0.0 20893inherits(Sha1, Hash)
19630Wallet.prototype.processConfirmedTx = function (tx) { 20894
19631 this.__processTx(tx, false) 20895Sha1.prototype.init = function () {
20896 this._a = 0x67452301
20897 this._b = 0xefcdab89
20898 this._c = 0x98badcfe
20899 this._d = 0x10325476
20900 this._e = 0xc3d2e1f0
20901
20902 return this
19632} 20903}
19633 20904
19634// FIXME: remove in 2.0.0 20905function rotl1 (num) {
19635Wallet.prototype.__processTx = function (tx, isPending) { 20906 return (num << 1) | (num >>> 31)
19636 console.warn('processTransaction is considered harmful, see issue #260 for more information') 20907}
19637 20908
19638 var txId = tx.getId() 20909function rotl5 (num) {
19639 var txHash = tx.getHash() 20910 return (num << 5) | (num >>> 27)
20911}
19640 20912
19641 tx.outs.forEach(function (txOut, i) { 20913function rotl30 (num) {
19642 var address 20914 return (num << 30) | (num >>> 2)
20915}
19643 20916
19644 try { 20917function ft (s, b, c, d) {
19645 address = Address.fromOutputScript(txOut.script, this.network).toString() 20918 if (s === 0) return (b & c) | ((~b) & d)
19646 } catch (e) { 20919 if (s === 2) return (b & c) | (b & d) | (c & d)
19647 if (!(e.message.match(/has no matching Address/))) 20920 return b ^ c ^ d
19648 throw e 20921}
19649 }
19650 20922
19651 var myAddresses = this.addresses.concat(this.changeAddresses) 20923Sha1.prototype._update = function (M) {
19652 if (myAddresses.indexOf(address) > -1) { 20924 var W = this._w
19653 var lookup = txId + ':' + i
19654 if (lookup in this.unspentMap) return
19655 20925
19656 // its unique, add it 20926 var a = this._a | 0
19657 var unspent = { 20927 var b = this._b | 0
19658 address: address, 20928 var c = this._c | 0
19659 confirmations: 0, // no way to determine this without more information 20929 var d = this._d | 0
19660 index: i, 20930 var e = this._e | 0
19661 txHash: txHash,
19662 txId: txId,
19663 value: txOut.value,
19664 pending: isPending
19665 }
19666 20931
19667 this.unspentMap[lookup] = unspent 20932 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
19668 this.unspents.push(unspent) 20933 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
19669 }
19670 }, this)
19671 20934
19672 tx.ins.forEach(function (txIn) { 20935 for (var j = 0; j < 80; ++j) {
19673 // copy and convert to big-endian hex 20936 var s = ~~(j / 20)
19674 var txInId = bufferutils.reverse(txIn.hash).toString('hex') 20937 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
19675 20938
19676 var lookup = txInId + ':' + txIn.index 20939 e = d
19677 if (!(lookup in this.unspentMap)) return 20940 d = c
20941 c = rotl30(b)
20942 b = a
20943 a = t
20944 }
19678 20945
19679 var unspent = this.unspentMap[lookup] 20946 this._a = (a + this._a) | 0
20947 this._b = (b + this._b) | 0
20948 this._c = (c + this._c) | 0
20949 this._d = (d + this._d) | 0
20950 this._e = (e + this._e) | 0
20951}
19680 20952
19681 if (isPending) { 20953Sha1.prototype._hash = function () {
19682 unspent.pending = true 20954 var H = new Buffer(20)
19683 unspent.spent = true
19684 } else {
19685 delete this.unspentMap[lookup]
19686 20955
19687 this.unspents = this.unspents.filter(function (unspent2) { 20956 H.writeInt32BE(this._a | 0, 0)
19688 return unspent !== unspent2 20957 H.writeInt32BE(this._b | 0, 4)
19689 }) 20958 H.writeInt32BE(this._c | 0, 8)
19690 } 20959 H.writeInt32BE(this._d | 0, 12)
19691 }, this) 20960 H.writeInt32BE(this._e | 0, 16)
20961
20962 return H
20963}
20964
20965module.exports = Sha1
20966
20967}).call(this,require("buffer").Buffer)
20968},{"./hash":99,"buffer":4,"inherits":93}],103:[function(require,module,exports){
20969(function (Buffer){
20970/**
20971 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
20972 * in FIPS 180-2
20973 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
20974 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
20975 *
20976 */
20977
20978var inherits = require('inherits')
20979var Sha256 = require('./sha256')
20980var Hash = require('./hash')
20981
20982var W = new Array(64)
20983
20984function Sha224 () {
20985 this.init()
20986
20987 this._w = W // new Array(64)
20988
20989 Hash.call(this, 64, 56)
20990}
20991
20992inherits(Sha224, Sha256)
20993
20994Sha224.prototype.init = function () {
20995 this._a = 0xc1059ed8
20996 this._b = 0x367cd507
20997 this._c = 0x3070dd17
20998 this._d = 0xf70e5939
20999 this._e = 0xffc00b31
21000 this._f = 0x68581511
21001 this._g = 0x64f98fa7
21002 this._h = 0xbefa4fa4
21003
21004 return this
21005}
21006
21007Sha224.prototype._hash = function () {
21008 var H = new Buffer(28)
21009
21010 H.writeInt32BE(this._a, 0)
21011 H.writeInt32BE(this._b, 4)
21012 H.writeInt32BE(this._c, 8)
21013 H.writeInt32BE(this._d, 12)
21014 H.writeInt32BE(this._e, 16)
21015 H.writeInt32BE(this._f, 20)
21016 H.writeInt32BE(this._g, 24)
21017
21018 return H
19692} 21019}
19693 21020
19694Wallet.prototype.generateAddress = function () { 21021module.exports = Sha224
19695 var k = this.addresses.length 21022
19696 var address = this.getExternalAccount().derive(k).getAddress() 21023}).call(this,require("buffer").Buffer)
21024},{"./hash":99,"./sha256":104,"buffer":4,"inherits":93}],104:[function(require,module,exports){
21025(function (Buffer){
21026/**
21027 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
21028 * in FIPS 180-2
21029 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
21030 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
21031 *
21032 */
21033
21034var inherits = require('inherits')
21035var Hash = require('./hash')
21036
21037var K = [
21038 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
21039 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
21040 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
21041 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
21042 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
21043 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
21044 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
21045 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
21046 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
21047 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
21048 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
21049 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
21050 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
21051 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
21052 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
21053 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
21054]
21055
21056var W = new Array(64)
21057
21058function Sha256 () {
21059 this.init()
19697 21060
19698 this.addresses.push(address.toString()) 21061 this._w = W // new Array(64)
19699 21062
19700 return this.getReceiveAddress() 21063 Hash.call(this, 64, 56)
19701} 21064}
19702 21065
19703Wallet.prototype.generateChangeAddress = function () { 21066inherits(Sha256, Hash)
19704 var k = this.changeAddresses.length
19705 var address = this.getInternalAccount().derive(k).getAddress()
19706 21067
19707 this.changeAddresses.push(address.toString()) 21068Sha256.prototype.init = function () {
21069 this._a = 0x6a09e667
21070 this._b = 0xbb67ae85
21071 this._c = 0x3c6ef372
21072 this._d = 0xa54ff53a
21073 this._e = 0x510e527f
21074 this._f = 0x9b05688c
21075 this._g = 0x1f83d9ab
21076 this._h = 0x5be0cd19
21077
21078 return this
21079}
19708 21080
19709 return this.getChangeAddress() 21081function ch (x, y, z) {
21082 return z ^ (x & (y ^ z))
21083}
21084
21085function maj (x, y, z) {
21086 return (x & y) | (z & (x | y))
21087}
21088
21089function sigma0 (x) {
21090 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
19710} 21091}
19711 21092
19712Wallet.prototype.getAddress = function () { 21093function sigma1 (x) {
19713 if (this.addresses.length === 0) { 21094 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
19714 this.generateAddress() 21095}
21096
21097function gamma0 (x) {
21098 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
21099}
21100
21101function gamma1 (x) {
21102 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
21103}
21104
21105Sha256.prototype._update = function (M) {
21106 var W = this._w
21107
21108 var a = this._a | 0
21109 var b = this._b | 0
21110 var c = this._c | 0
21111 var d = this._d | 0
21112 var e = this._e | 0
21113 var f = this._f | 0
21114 var g = this._g | 0
21115 var h = this._h | 0
21116
21117 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
21118 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
21119
21120 for (var j = 0; j < 64; ++j) {
21121 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
21122 var T2 = (sigma0(a) + maj(a, b, c)) | 0
21123
21124 h = g
21125 g = f
21126 f = e
21127 e = (d + T1) | 0
21128 d = c
21129 c = b
21130 b = a
21131 a = (T1 + T2) | 0
19715 } 21132 }
19716 21133
19717 return this.addresses[this.addresses.length - 1] 21134 this._a = (a + this._a) | 0
21135 this._b = (b + this._b) | 0
21136 this._c = (c + this._c) | 0
21137 this._d = (d + this._d) | 0
21138 this._e = (e + this._e) | 0
21139 this._f = (f + this._f) | 0
21140 this._g = (g + this._g) | 0
21141 this._h = (h + this._h) | 0
19718} 21142}
19719 21143
19720Wallet.prototype.getBalance = function (minConf) { 21144Sha256.prototype._hash = function () {
19721 minConf = minConf || 0 21145 var H = new Buffer(32)
19722 21146
19723 return this.unspents.filter(function (unspent) { 21147 H.writeInt32BE(this._a, 0)
19724 return unspent.confirmations >= minConf 21148 H.writeInt32BE(this._b, 4)
21149 H.writeInt32BE(this._c, 8)
21150 H.writeInt32BE(this._d, 12)
21151 H.writeInt32BE(this._e, 16)
21152 H.writeInt32BE(this._f, 20)
21153 H.writeInt32BE(this._g, 24)
21154 H.writeInt32BE(this._h, 28)
19725 21155
19726 // FIXME: remove spent filter in 2.0.0 21156 return H
19727 }).filter(function (unspent) { 21157}
19728 return !unspent.spent 21158
19729 }).reduce(function (accum, unspent) { 21159module.exports = Sha256
19730 return accum + unspent.value 21160
19731 }, 0) 21161}).call(this,require("buffer").Buffer)
21162},{"./hash":99,"buffer":4,"inherits":93}],105:[function(require,module,exports){
21163(function (Buffer){
21164var inherits = require('inherits')
21165var SHA512 = require('./sha512')
21166var Hash = require('./hash')
21167
21168var W = new Array(160)
21169
21170function Sha384 () {
21171 this.init()
21172 this._w = W
21173
21174 Hash.call(this, 128, 112)
21175}
21176
21177inherits(Sha384, SHA512)
21178
21179Sha384.prototype.init = function () {
21180 this._ah = 0xcbbb9d5d
21181 this._bh = 0x629a292a
21182 this._ch = 0x9159015a
21183 this._dh = 0x152fecd8
21184 this._eh = 0x67332667
21185 this._fh = 0x8eb44a87
21186 this._gh = 0xdb0c2e0d
21187 this._hh = 0x47b5481d
21188
21189 this._al = 0xc1059ed8
21190 this._bl = 0x367cd507
21191 this._cl = 0x3070dd17
21192 this._dl = 0xf70e5939
21193 this._el = 0xffc00b31
21194 this._fl = 0x68581511
21195 this._gl = 0x64f98fa7
21196 this._hl = 0xbefa4fa4
21197
21198 return this
19732} 21199}
19733 21200
19734Wallet.prototype.getChangeAddress = function () { 21201Sha384.prototype._hash = function () {
19735 if (this.changeAddresses.length === 0) { 21202 var H = new Buffer(48)
19736 this.generateChangeAddress() 21203
21204 function writeInt64BE (h, l, offset) {
21205 H.writeInt32BE(h, offset)
21206 H.writeInt32BE(l, offset + 4)
19737 } 21207 }
19738 21208
19739 return this.changeAddresses[this.changeAddresses.length - 1] 21209 writeInt64BE(this._ah, this._al, 0)
21210 writeInt64BE(this._bh, this._bl, 8)
21211 writeInt64BE(this._ch, this._cl, 16)
21212 writeInt64BE(this._dh, this._dl, 24)
21213 writeInt64BE(this._eh, this._el, 32)
21214 writeInt64BE(this._fh, this._fl, 40)
21215
21216 return H
19740} 21217}
19741 21218
19742Wallet.prototype.getInternalPrivateKey = function (index) { 21219module.exports = Sha384
19743 return this.getInternalAccount().derive(index).privKey 21220
21221}).call(this,require("buffer").Buffer)
21222},{"./hash":99,"./sha512":106,"buffer":4,"inherits":93}],106:[function(require,module,exports){
21223(function (Buffer){
21224var inherits = require('inherits')
21225var Hash = require('./hash')
21226
21227var K = [
21228 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
21229 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
21230 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
21231 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
21232 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
21233 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
21234 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
21235 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
21236 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
21237 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
21238 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
21239 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
21240 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
21241 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
21242 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
21243 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
21244 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
21245 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
21246 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
21247 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
21248 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
21249 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
21250 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
21251 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
21252 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
21253 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
21254 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
21255 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
21256 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
21257 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
21258 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
21259 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
21260 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
21261 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
21262 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
21263 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
21264 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
21265 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
21266 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
21267 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
21268]
21269
21270var W = new Array(160)
21271
21272function Sha512 () {
21273 this.init()
21274 this._w = W
21275
21276 Hash.call(this, 128, 112)
19744} 21277}
19745 21278
19746Wallet.prototype.getPrivateKey = function (index) { 21279inherits(Sha512, Hash)
19747 return this.getExternalAccount().derive(index).privKey 21280
21281Sha512.prototype.init = function () {
21282 this._ah = 0x6a09e667
21283 this._bh = 0xbb67ae85
21284 this._ch = 0x3c6ef372
21285 this._dh = 0xa54ff53a
21286 this._eh = 0x510e527f
21287 this._fh = 0x9b05688c
21288 this._gh = 0x1f83d9ab
21289 this._hh = 0x5be0cd19
21290
21291 this._al = 0xf3bcc908
21292 this._bl = 0x84caa73b
21293 this._cl = 0xfe94f82b
21294 this._dl = 0x5f1d36f1
21295 this._el = 0xade682d1
21296 this._fl = 0x2b3e6c1f
21297 this._gl = 0xfb41bd6b
21298 this._hl = 0x137e2179
21299
21300 return this
21301}
21302
21303function Ch (x, y, z) {
21304 return z ^ (x & (y ^ z))
21305}
21306
21307function maj (x, y, z) {
21308 return (x & y) | (z & (x | y))
21309}
21310
21311function sigma0 (x, xl) {
21312 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
21313}
21314
21315function sigma1 (x, xl) {
21316 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
21317}
21318
21319function Gamma0 (x, xl) {
21320 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
21321}
21322
21323function Gamma0l (x, xl) {
21324 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
21325}
21326
21327function Gamma1 (x, xl) {
21328 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
21329}
21330
21331function Gamma1l (x, xl) {
21332 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
21333}
21334
21335function getCarry (a, b) {
21336 return (a >>> 0) < (b >>> 0) ? 1 : 0
19748} 21337}
19749 21338
19750Wallet.prototype.getPrivateKeyForAddress = function (address) { 21339Sha512.prototype._update = function (M) {
19751 var index 21340 var W = this._w
21341
21342 var ah = this._ah | 0
21343 var bh = this._bh | 0
21344 var ch = this._ch | 0
21345 var dh = this._dh | 0
21346 var eh = this._eh | 0
21347 var fh = this._fh | 0
21348 var gh = this._gh | 0
21349 var hh = this._hh | 0
21350
21351 var al = this._al | 0
21352 var bl = this._bl | 0
21353 var cl = this._cl | 0
21354 var dl = this._dl | 0
21355 var el = this._el | 0
21356 var fl = this._fl | 0
21357 var gl = this._gl | 0
21358 var hl = this._hl | 0
21359
21360 for (var i = 0; i < 32; i += 2) {
21361 W[i] = M.readInt32BE(i * 4)
21362 W[i + 1] = M.readInt32BE(i * 4 + 4)
21363 }
21364 for (; i < 160; i += 2) {
21365 var xh = W[i - 15 * 2]
21366 var xl = W[i - 15 * 2 + 1]
21367 var gamma0 = Gamma0(xh, xl)
21368 var gamma0l = Gamma0l(xl, xh)
21369
21370 xh = W[i - 2 * 2]
21371 xl = W[i - 2 * 2 + 1]
21372 var gamma1 = Gamma1(xh, xl)
21373 var gamma1l = Gamma1l(xl, xh)
21374
21375 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
21376 var Wi7h = W[i - 7 * 2]
21377 var Wi7l = W[i - 7 * 2 + 1]
21378
21379 var Wi16h = W[i - 16 * 2]
21380 var Wi16l = W[i - 16 * 2 + 1]
21381
21382 var Wil = (gamma0l + Wi7l) | 0
21383 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
21384 Wil = (Wil + gamma1l) | 0
21385 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
21386 Wil = (Wil + Wi16l) | 0
21387 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
19752 21388
19753 if ((index = this.addresses.indexOf(address)) > -1) { 21389 W[i] = Wih
19754 return this.getPrivateKey(index) 21390 W[i + 1] = Wil
19755 } 21391 }
19756 21392
19757 if ((index = this.changeAddresses.indexOf(address)) > -1) { 21393 for (var j = 0; j < 160; j += 2) {
19758 return this.getInternalPrivateKey(index) 21394 Wih = W[j]
21395 Wil = W[j + 1]
21396
21397 var majh = maj(ah, bh, ch)
21398 var majl = maj(al, bl, cl)
21399
21400 var sigma0h = sigma0(ah, al)
21401 var sigma0l = sigma0(al, ah)
21402 var sigma1h = sigma1(eh, el)
21403 var sigma1l = sigma1(el, eh)
21404
21405 // t1 = h + sigma1 + ch + K[j] + W[j]
21406 var Kih = K[j]
21407 var Kil = K[j + 1]
21408
21409 var chh = Ch(eh, fh, gh)
21410 var chl = Ch(el, fl, gl)
21411
21412 var t1l = (hl + sigma1l) | 0
21413 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
21414 t1l = (t1l + chl) | 0
21415 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
21416 t1l = (t1l + Kil) | 0
21417 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
21418 t1l = (t1l + Wil) | 0
21419 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
21420
21421 // t2 = sigma0 + maj
21422 var t2l = (sigma0l + majl) | 0
21423 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
21424
21425 hh = gh
21426 hl = gl
21427 gh = fh
21428 gl = fl
21429 fh = eh
21430 fl = el
21431 el = (dl + t1l) | 0
21432 eh = (dh + t1h + getCarry(el, dl)) | 0
21433 dh = ch
21434 dl = cl
21435 ch = bh
21436 cl = bl
21437 bh = ah
21438 bl = al
21439 al = (t1l + t2l) | 0
21440 ah = (t1h + t2h + getCarry(al, t1l)) | 0
19759 } 21441 }
19760 21442
19761 assert(false, 'Unknown address. Make sure the address is from the keychain and has been generated') 21443 this._al = (this._al + al) | 0
21444 this._bl = (this._bl + bl) | 0
21445 this._cl = (this._cl + cl) | 0
21446 this._dl = (this._dl + dl) | 0
21447 this._el = (this._el + el) | 0
21448 this._fl = (this._fl + fl) | 0
21449 this._gl = (this._gl + gl) | 0
21450 this._hl = (this._hl + hl) | 0
21451
21452 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
21453 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
21454 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
21455 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
21456 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
21457 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
21458 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
21459 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
19762} 21460}
19763 21461
19764Wallet.prototype.getUnspentOutputs = function (minConf) { 21462Sha512.prototype._hash = function () {
19765 minConf = minConf || 0 21463 var H = new Buffer(64)
19766 21464
19767 return this.unspents.filter(function (unspent) { 21465 function writeInt64BE (h, l, offset) {
19768 return unspent.confirmations >= minConf 21466 H.writeInt32BE(h, offset)
21467 H.writeInt32BE(l, offset + 4)
21468 }
19769 21469
19770 // FIXME: remove spent filter in 2.0.0 21470 writeInt64BE(this._ah, this._al, 0)
19771 }).filter(function (unspent) { 21471 writeInt64BE(this._bh, this._bl, 8)
19772 return !unspent.spent 21472 writeInt64BE(this._ch, this._cl, 16)
19773 }).map(function (unspent) { 21473 writeInt64BE(this._dh, this._dl, 24)
19774 return { 21474 writeInt64BE(this._eh, this._el, 32)
19775 address: unspent.address, 21475 writeInt64BE(this._fh, this._fl, 40)
19776 confirmations: unspent.confirmations, 21476 writeInt64BE(this._gh, this._gl, 48)
19777 index: unspent.index, 21477 writeInt64BE(this._hh, this._hl, 56)
19778 txId: unspent.txId, 21478
19779 value: unspent.value, 21479 return H
21480}
21481
21482module.exports = Sha512
21483
21484}).call(this,require("buffer").Buffer)
21485},{"./hash":99,"buffer":4,"inherits":93}],107:[function(require,module,exports){
21486var inherits = require('inherits')
21487var native = require('./native')
21488
21489function TfTypeError (type, value, valueTypeName) {
21490 this.__error = Error.call(this)
21491 this.__type = type
21492 this.__value = value
21493 this.__valueTypeName = valueTypeName
21494
21495 var message
21496 Object.defineProperty(this, 'message', {
21497 enumerable: true,
21498 get: function () {
21499 if (message) return message
21500
21501 valueTypeName = valueTypeName || getValueTypeName(value)
21502 message = tfErrorString(type, value, valueTypeName)
21503
21504 return message
21505 }
21506 })
21507}
21508
21509function TfPropertyTypeError (type, property, label, value, error, valueTypeName) {
21510 this.__error = error || Error.call(this)
21511 this.__label = label
21512 this.__property = property
21513 this.__type = type
21514 this.__value = value
21515 this.__valueTypeName = valueTypeName
19780 21516
19781 // FIXME: remove in 2.0.0 21517 var message
19782 hash: unspent.txId, 21518 Object.defineProperty(this, 'message', {
19783 pending: unspent.pending 21519 enumerable: true,
21520 get: function () {
21521 if (message) return message
21522 if (type) {
21523 valueTypeName = valueTypeName || getValueTypeName(value)
21524 message = tfPropertyErrorString(type, label, property, value, valueTypeName)
21525 } else {
21526 message = 'Unexpected property "' + property + '"'
21527 }
21528
21529 return message
19784 } 21530 }
19785 }) 21531 })
19786} 21532}
19787 21533
19788Wallet.prototype.setUnspentOutputs = function (unspents) { 21534// inherit from Error, assign stack
19789 this.unspentMap = {} 21535[TfTypeError, TfPropertyTypeError].forEach(function (tfErrorType) {
19790 this.unspents = unspents.map(function (unspent) { 21536 inherits(tfErrorType, Error)
19791 // FIXME: remove unspent.hash in 2.0.0 21537 Object.defineProperty(tfErrorType, 'stack', {
19792 var txId = unspent.txId || unspent.hash 21538 get: function () { return this.__error.stack }
19793 var index = unspent.index 21539 })
21540})
21541
21542function tfCustomError (expected, actual) {
21543 return new TfTypeError(expected, {}, actual)
21544}
21545
21546function tfSubError (e, property, label) {
21547 // sub child?
21548 if (e instanceof TfPropertyTypeError) {
21549 property = property + '.' + e.__property
21550 label = e.__label
21551
21552 return new TfPropertyTypeError(
21553 e.__type, property, label, e.__value, e.__error, e.__valueTypeName
21554 )
21555 }
21556
21557 // child?
21558 if (e instanceof TfTypeError) {
21559 return new TfPropertyTypeError(
21560 e.__type, property, label, e.__value, e.__error, e.__valueTypeName
21561 )
21562 }
21563
21564 return e
21565}
21566
21567function getTypeName (fn) {
21568 return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1]
21569}
21570
21571function getValueTypeName (value) {
21572 return native.Nil(value) ? '' : getTypeName(value.constructor)
21573}
21574
21575function getValue (value) {
21576 if (native.Function(value)) return ''
21577 if (native.String(value)) return JSON.stringify(value)
21578 if (value && native.Object(value)) return ''
21579 return value
21580}
21581
21582function tfJSON (type) {
21583 if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type)
21584 if (native.Array(type)) return 'Array'
21585 if (type && native.Object(type)) return 'Object'
21586
21587 return type !== undefined ? type : ''
21588}
21589
21590function tfErrorString (type, value, valueTypeName) {
21591 var valueJson = getValue(value)
21592
21593 return 'Expected ' + tfJSON(type) + ', got' +
21594 (valueTypeName !== '' ? ' ' + valueTypeName : '') +
21595 (valueJson !== '' ? ' ' + valueJson : '')
21596}
21597
21598function tfPropertyErrorString (type, label, name, value, valueTypeName) {
21599 var description = '" of type '
21600 if (label === 'key') description = '" with key type '
21601
21602 return tfErrorString('property "' + tfJSON(name) + description + tfJSON(type), value, valueTypeName)
21603}
21604
21605module.exports = {
21606 TfTypeError: TfTypeError,
21607 TfPropertyTypeError: TfPropertyTypeError,
21608 tfCustomError: tfCustomError,
21609 tfSubError: tfSubError,
21610 tfJSON: tfJSON,
21611 getValueTypeName: getValueTypeName
21612}
21613
21614},{"./native":110,"inherits":93}],108:[function(require,module,exports){
21615(function (Buffer){
21616var NATIVE = require('./native')
21617var ERRORS = require('./errors')
21618
21619function _Buffer (value) {
21620 return Buffer.isBuffer(value)
21621}
21622
21623function Hex (value) {
21624 return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value)
21625}
21626
21627function _LengthN (type, length) {
21628 var name = type.toJSON()
21629
21630 function Length (value) {
21631 if (!type(value)) return false
21632 if (value.length === length) return true
21633
21634 throw ERRORS.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')')
21635 }
21636 Length.toJSON = function () { return name }
21637
21638 return Length
21639}
21640
21641var _ArrayN = _LengthN.bind(null, NATIVE.Array)
21642var _BufferN = _LengthN.bind(null, _Buffer)
21643var _HexN = _LengthN.bind(null, Hex)
21644
21645var UINT53_MAX = Math.pow(2, 53) - 1
21646
21647function Finite (value) {
21648 return typeof value === 'number' && isFinite(value)
21649}
21650function Int8 (value) { return ((value << 24) >> 24) === value }
21651function Int16 (value) { return ((value << 16) >> 16) === value }
21652function Int32 (value) { return (value | 0) === value }
21653function UInt8 (value) { return (value & 0xff) === value }
21654function UInt16 (value) { return (value & 0xffff) === value }
21655function UInt32 (value) { return (value >>> 0) === value }
21656function UInt53 (value) {
21657 return typeof value === 'number' &&
21658 value >= 0 &&
21659 value <= UINT53_MAX &&
21660 Math.floor(value) === value
21661}
21662
21663var types = {
21664 ArrayN: _ArrayN,
21665 Buffer: _Buffer,
21666 BufferN: _BufferN,
21667 Finite: Finite,
21668 Hex: Hex,
21669 HexN: _HexN,
21670 Int8: Int8,
21671 Int16: Int16,
21672 Int32: Int32,
21673 UInt8: UInt8,
21674 UInt16: UInt16,
21675 UInt32: UInt32,
21676 UInt53: UInt53
21677}
21678
21679for (var typeName in types) {
21680 types[typeName].toJSON = function (t) {
21681 return t
21682 }.bind(null, typeName)
21683}
21684
21685module.exports = types
21686
21687}).call(this,{"isBuffer":require("../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
21688},{"../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js":9,"./errors":107,"./native":110}],109:[function(require,module,exports){
21689var ERRORS = require('./errors')
21690var NATIVE = require('./native')
19794 21691
19795 // FIXME: remove in 2.0.0 21692// short-hand
19796 if (unspent.hash !== undefined) { 21693var tfJSON = ERRORS.tfJSON
19797 console.warn('unspent.hash is deprecated, use unspent.txId instead') 21694var TfTypeError = ERRORS.TfTypeError
21695var TfPropertyTypeError = ERRORS.TfPropertyTypeError
21696var tfSubError = ERRORS.tfSubError
21697var getValueTypeName = ERRORS.getValueTypeName
21698
21699var TYPES = {
21700 arrayOf: function arrayOf (type) {
21701 type = compile(type)
21702
21703 function _arrayOf (array, strict) {
21704 if (!NATIVE.Array(array)) return false
21705
21706 return array.every(function (value, i) {
21707 try {
21708 return typeforce(type, value, strict)
21709 } catch (e) {
21710 throw tfSubError(e, i)
21711 }
21712 })
19798 } 21713 }
21714 _arrayOf.toJSON = function () { return '[' + tfJSON(type) + ']' }
21715
21716 return _arrayOf
21717 },
19799 21718
19800 // FIXME: remove in 2.0.0 21719 maybe: function maybe (type) {
19801 if (index === undefined) { 21720 type = compile(type)
19802 console.warn('unspent.outputIndex is deprecated, use unspent.index instead') 21721
19803 index = unspent.outputIndex 21722 function _maybe (value, strict) {
21723 return NATIVE.Nil(value) || type(value, strict, maybe)
19804 } 21724 }
21725 _maybe.toJSON = function () { return '?' + tfJSON(type) }
19805 21726
19806 typeForce('String', txId) 21727 return _maybe
19807 typeForce('Number', index) 21728 },
19808 typeForce('Number', unspent.value) 21729
21730 map: function map (propertyType, propertyKeyType) {
21731 propertyType = compile(propertyType)
21732 if (propertyKeyType) propertyKeyType = compile(propertyKeyType)
21733
21734 function _map (value, strict) {
21735 if (!NATIVE.Object(value, strict)) return false
21736 if (NATIVE.Nil(value, strict)) return false
21737
21738 for (var propertyName in value) {
21739 try {
21740 if (propertyKeyType) {
21741 typeforce(propertyKeyType, propertyName, strict)
21742 }
21743 } catch (e) {
21744 throw tfSubError(e, propertyName, 'key')
21745 }
21746
21747 try {
21748 var propertyValue = value[propertyName]
21749 typeforce(propertyType, propertyValue, strict)
21750 } catch (e) {
21751 throw tfSubError(e, propertyName)
21752 }
21753 }
19809 21754
19810 assert.equal(txId.length, 64, 'Expected valid txId, got ' + txId) 21755 return true
19811 assert.doesNotThrow(function () { 21756 }
19812 Address.fromBase58Check(unspent.address)
19813 }, 'Expected Base58 Address, got ' + unspent.address)
19814 assert(isFinite(index), 'Expected finite index, got ' + index)
19815 21757
19816 // FIXME: remove branch in 2.0.0 21758 if (propertyKeyType) {
19817 if (unspent.confirmations !== undefined) { 21759 _map.toJSON = function () {
19818 typeForce('Number', unspent.confirmations) 21760 return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}'
21761 }
21762 } else {
21763 _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }
19819 } 21764 }
19820 21765
19821 var txHash = bufferutils.reverse(new Buffer(txId, 'hex')) 21766 return _map
21767 },
19822 21768
19823 unspent = { 21769 object: function object (uncompiled) {
19824 address: unspent.address, 21770 var type = {}
19825 confirmations: unspent.confirmations || 0,
19826 index: index,
19827 txHash: txHash,
19828 txId: txId,
19829 value: unspent.value,
19830 21771
19831 // FIXME: remove in 2.0.0 21772 for (var typePropertyName in uncompiled) {
19832 pending: unspent.pending || false 21773 type[typePropertyName] = compile(uncompiled[typePropertyName])
19833 } 21774 }
19834 21775
19835 // FIXME: remove in 2.0.0 21776 function _object (value, strict) {
19836 this.unspentMap[txId + ':' + index] = unspent 21777 if (!NATIVE.Object(value)) return false
21778 if (NATIVE.Nil(value)) return false
19837 21779
19838 return unspent 21780 var propertyName
19839 }, this) 21781
21782 try {
21783 for (propertyName in type) {
21784 var propertyType = type[propertyName]
21785 var propertyValue = value[propertyName]
21786
21787 typeforce(propertyType, propertyValue, strict)
21788 }
21789 } catch (e) {
21790 throw tfSubError(e, propertyName)
21791 }
21792
21793 if (strict) {
21794 for (propertyName in value) {
21795 if (type[propertyName]) continue
21796
21797 throw new TfPropertyTypeError(undefined, propertyName)
21798 }
21799 }
21800
21801 return true
21802 }
21803 _object.toJSON = function () { return tfJSON(type) }
21804
21805 return _object
21806 },
21807
21808 oneOf: function oneOf () {
21809 var types = [].slice.call(arguments).map(compile)
21810
21811 function _oneOf (value, strict) {
21812 return types.some(function (type) {
21813 try {
21814 return typeforce(type, value, strict)
21815 } catch (e) {
21816 return false
21817 }
21818 })
21819 }
21820 _oneOf.toJSON = function () { return types.map(tfJSON).join('|') }
21821
21822 return _oneOf
21823 },
21824
21825 quacksLike: function quacksLike (type) {
21826 function _quacksLike (value) {
21827 return type === getValueTypeName(value)
21828 }
21829 _quacksLike.toJSON = function () { return type }
21830
21831 return _quacksLike
21832 },
21833
21834 tuple: function tuple () {
21835 var types = [].slice.call(arguments).map(compile)
21836
21837 function _tuple (values, strict) {
21838 return types.every(function (type, i) {
21839 try {
21840 return typeforce(type, values[i], strict)
21841 } catch (e) {
21842 throw tfSubError(e, i)
21843 }
21844 }) && (!strict || values.length === arguments.length)
21845 }
21846 _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }
21847
21848 return _tuple
21849 },
21850
21851 value: function value (expected) {
21852 function _value (actual) {
21853 return actual === expected
21854 }
21855 _value.toJSON = function () { return expected }
21856
21857 return _value
21858 }
19840} 21859}
19841 21860
19842Wallet.prototype.signWith = function (tx, addresses) { 21861function compile (type) {
19843 addresses.forEach(function (address, i) { 21862 if (NATIVE.String(type)) {
19844 var privKey = this.getPrivateKeyForAddress(address) 21863 if (type[0] === '?') return TYPES.maybe(compile(type.slice(1)))
19845 21864
19846 tx.sign(i, privKey) 21865 return NATIVE[type] || TYPES.quacksLike(type)
19847 }, this) 21866 } else if (type && NATIVE.Object(type)) {
21867 if (NATIVE.Array(type)) return TYPES.arrayOf(compile(type[0]))
19848 21868
19849 return tx 21869 return TYPES.object(type)
21870 } else if (NATIVE.Function(type)) {
21871 return type
21872 }
21873
21874 return TYPES.value(type)
21875}
21876
21877function typeforce (type, value, strict, surrogate) {
21878 if (NATIVE.Function(type)) {
21879 if (type(value, strict)) return true
21880
21881 throw new TfTypeError(surrogate || type, value)
21882 }
21883
21884 // JIT
21885 return typeforce(compile(type), value, strict)
19850} 21886}
19851 21887
19852function estimatePaddedFee (tx, network) { 21888// assign types to typeforce function
19853 var tmpTx = tx.clone() 21889for (var typeName in NATIVE) {
19854 tmpTx.addOutput(Script.EMPTY, network.dustSoftThreshold || 0) 21890 typeforce[typeName] = NATIVE[typeName]
21891}
21892
21893for (typeName in TYPES) {
21894 typeforce[typeName] = TYPES[typeName]
21895}
21896
21897var EXTRA = require('./extra')
21898for (typeName in EXTRA) {
21899 typeforce[typeName] = EXTRA[typeName]
21900}
21901
21902// async wrapper
21903function __async (type, value, strict, callback) {
21904 // default to falsy strict if using shorthand overload
21905 if (typeof strict === 'function') return __async(type, value, false, strict)
21906
21907 try {
21908 typeforce(type, value, strict)
21909 } catch (e) {
21910 return callback(e)
21911 }
21912
21913 callback()
21914}
21915
21916typeforce.async = __async
21917typeforce.compile = compile
21918typeforce.TfTypeError = TfTypeError
21919typeforce.TfPropertyTypeError = TfPropertyTypeError
21920
21921module.exports = typeforce
21922
21923},{"./errors":107,"./extra":108,"./native":110}],110:[function(require,module,exports){
21924var types = {
21925 Array: function (value) { return value !== null && value !== undefined && value.constructor === Array },
21926 Boolean: function (value) { return typeof value === 'boolean' },
21927 Function: function (value) { return typeof value === 'function' },
21928 Nil: function (value) { return value === undefined || value === null },
21929 Number: function (value) { return typeof value === 'number' },
21930 Object: function (value) { return typeof value === 'object' },
21931 String: function (value) { return typeof value === 'string' },
21932 '': function () { return true }
21933}
21934
21935// TODO: deprecate
21936types.Null = types.Nil
21937
21938for (var typeName in types) {
21939 types[typeName].toJSON = function (t) {
21940 return t
21941 }.bind(null, typeName)
21942}
21943
21944module.exports = types
21945
21946},{}],111:[function(require,module,exports){
21947(function (Buffer){
21948'use strict'
21949
21950// Number.MAX_SAFE_INTEGER
21951var MAX_SAFE_INTEGER = 9007199254740991
21952
21953function checkUInt53 (n) {
21954 if (n < 0 || n > MAX_SAFE_INTEGER || n % 1 !== 0) throw new RangeError('value out of range')
21955}
21956
21957function encode (number, buffer, offset) {
21958 checkUInt53(number)
21959
21960 if (!buffer) buffer = new Buffer(encodingLength(number))
21961 if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance')
21962 if (!offset) offset = 0
21963
21964 // 8 bit
21965 if (number < 0xfd) {
21966 buffer.writeUInt8(number, offset)
21967 encode.bytes = 1
21968
21969 // 16 bit
21970 } else if (number <= 0xffff) {
21971 buffer.writeUInt8(0xfd, offset)
21972 buffer.writeUInt16LE(number, offset + 1)
21973 encode.bytes = 3
21974
21975 // 32 bit
21976 } else if (number <= 0xffffffff) {
21977 buffer.writeUInt8(0xfe, offset)
21978 buffer.writeUInt32LE(number, offset + 1)
21979 encode.bytes = 5
21980
21981 // 64 bit
21982 } else {
21983 buffer.writeUInt8(0xff, offset)
21984 buffer.writeUInt32LE(number >>> 0, offset + 1)
21985 buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5)
21986 encode.bytes = 9
21987 }
21988
21989 return buffer
21990}
21991
21992function decode (buffer, offset) {
21993 if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance')
21994 if (!offset) offset = 0
21995
21996 var first = buffer.readUInt8(offset)
21997
21998 // 8 bit
21999 if (first < 0xfd) {
22000 decode.bytes = 1
22001 return first
22002
22003 // 16 bit
22004 } else if (first === 0xfd) {
22005 decode.bytes = 3
22006 return buffer.readUInt16LE(offset + 1)
22007
22008 // 32 bit
22009 } else if (first === 0xfe) {
22010 decode.bytes = 5
22011 return buffer.readUInt32LE(offset + 1)
22012
22013 // 64 bit
22014 } else {
22015 decode.bytes = 9
22016 var lo = buffer.readUInt32LE(offset + 1)
22017 var hi = buffer.readUInt32LE(offset + 5)
22018 var number = hi * 0x0100000000 + lo
22019 checkUInt53(number)
22020
22021 return number
22022 }
22023}
22024
22025function encodingLength (number) {
22026 checkUInt53(number)
22027
22028 return (
22029 number < 0xfd ? 1
22030 : number <= 0xffff ? 3
22031 : number <= 0xffffffff ? 5
22032 : 9
22033 )
22034}
22035
22036module.exports = { encode: encode, decode: decode, encodingLength: encodingLength }
22037
22038}).call(this,require("buffer").Buffer)
22039},{"buffer":4}],112:[function(require,module,exports){
22040(function (Buffer){
22041var bs58check = require('bs58check')
22042
22043function decodeRaw (buffer, version) {
22044 // check version only if defined
22045 if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version')
22046
22047 // uncompressed
22048 if (buffer.length === 33) {
22049 return {
22050 version: buffer[0],
22051 privateKey: buffer.slice(1, 33),
22052 compressed: false
22053 }
22054 }
22055
22056 // invalid length
22057 if (buffer.length !== 34) throw new Error('Invalid WIF length')
22058
22059 // invalid compression flag
22060 if (buffer[33] !== 0x01) throw new Error('Invalid compression flag')
22061
22062 return {
22063 version: buffer[0],
22064 privateKey: buffer.slice(1, 33),
22065 compressed: true
22066 }
22067}
22068
22069function encodeRaw (version, privateKey, compressed) {
22070 var result = new Buffer(compressed ? 34 : 33)
22071
22072 result.writeUInt8(version, 0)
22073 privateKey.copy(result, 1)
22074
22075 if (compressed) {
22076 result[33] = 0x01
22077 }
19855 22078
19856 return network.estimateFee(tmpTx) 22079 return result
19857} 22080}
19858 22081
19859// FIXME: 1.0.0 shims, remove in 2.0.0 22082function decode (string, version) {
19860Wallet.prototype.getReceiveAddress = Wallet.prototype.getAddress 22083 return decodeRaw(bs58check.decode(string), version)
19861Wallet.prototype.createTx = Wallet.prototype.createTransaction 22084}
19862 22085
19863module.exports = Wallet 22086function encode (version, privateKey, compressed) {
22087 if (typeof version === 'number') return bs58check.encode(encodeRaw(version, privateKey, compressed))
22088
22089 return bs58check.encode(
22090 encodeRaw(
22091 version.version,
22092 version.privateKey,
22093 version.compressed
22094 )
22095 )
22096}
22097
22098module.exports = {
22099 decode: decode,
22100 decodeRaw: decodeRaw,
22101 encode: encode,
22102 encodeRaw: encodeRaw
22103}
19864 22104
19865}).call(this,require("buffer").Buffer) 22105}).call(this,require("buffer").Buffer)
19866},{"./address":54,"./bufferutils":57,"./hdnode":63,"./networks":66,"./script":68,"./transaction_builder":71,"assert":5,"buffer":7,"randombytes":52,"typeforce":53}]},{},[64])(64) 22106},{"bs58check":80,"buffer":4}]},{},[33])(33)
19867});</script> 22107});</script>
19868 <script>bitcoin.networks.shadow = { 22108 <script>bitcoinjs.bitcoin.networks.shadow = {
19869 magicPrefix: '\x19ShadowCash Signed Message:\n', 22109 messagePrefix: "unused",
19870 bip32: { 22110 bip32: {
19871 public: 0xEE80286A, 22111 public: 0xEE80286A,
19872 private: 0xEE8031E8 22112 private: 0xEE8031E8
@@ -19874,13 +22114,10 @@ module.exports = Wallet
19874 pubKeyHash: 0x3f, 22114 pubKeyHash: 0x3f,
19875 scriptHash: 0x7d, 22115 scriptHash: 0x7d,
19876 wif: 0xbf, 22116 wif: 0xbf,
19877 dustThreshold: 0,
19878 feePerKb: 1000,
19879 estimateFee: function() { return "unused in this app" },
19880}; 22117};
19881 22118
19882bitcoin.networks.shadowtn = { 22119bitcoinjs.bitcoin.networks.shadowtn = {
19883 magicPrefix: '\x19ShadowCash Signed Message:\n', 22120 messagePrefix: "unused",
19884 bip32: { 22121 bip32: {
19885 public: 0x76C0FDFB, 22122 public: 0x76C0FDFB,
19886 private: 0x76C1077A 22123 private: 0x76C1077A
@@ -19888,21 +22125,21 @@ bitcoin.networks.shadowtn = {
19888 pubKeyHash: 0x7f, 22125 pubKeyHash: 0x7f,
19889 scriptHash: 0xc4, 22126 scriptHash: 0xc4,
19890 wif: 0xff, 22127 wif: 0xff,
19891 dustThreshold: 0,
19892 feePerKb: 1000,
19893 estimateFee: function() { return "unused in this app" },
19894}; 22128};
19895 22129
19896bitcoin.networks.clam = { 22130bitcoinjs.bitcoin.networks.clam = {
22131 messagePrefix: "unused",
19897 bip32: { 22132 bip32: {
19898 public: 0xa8c26d64, 22133 public: 0xa8c26d64,
19899 private: 0xa8c17826 22134 private: 0xa8c17826
19900 }, 22135 },
19901 pubKeyHash: 0x89, 22136 pubKeyHash: 0x89,
22137 scriptHash: 0x00, // TODO set this correctly
19902 wif: 0x85, 22138 wif: 0x85,
19903}; 22139};
19904 22140
19905bitcoin.networks.crown = { 22141bitcoinjs.bitcoin.networks.crown = {
22142 messagePrefix: "unused",
19906 bip32: { 22143 bip32: {
19907 public: 0x0488b21e, 22144 public: 0x0488b21e,
19908 private: 0x0488ade4 22145 private: 0x0488ade4
@@ -19912,7 +22149,8 @@ bitcoin.networks.crown = {
19912 wif: 0x80, 22149 wif: 0x80,
19913}; 22150};
19914 22151
19915bitcoin.networks.dash = { 22152bitcoinjs.bitcoin.networks.dash = {
22153 messagePrefix: "unused",
19916 bip32: { 22154 bip32: {
19917 public: 0x0488b21e, 22155 public: 0x0488b21e,
19918 private: 0x0488ade4 22156 private: 0x0488ade4
@@ -19922,7 +22160,8 @@ bitcoin.networks.dash = {
19922 wif: 0xcc, 22160 wif: 0xcc,
19923}; 22161};
19924 22162
19925bitcoin.networks.dashtn = { 22163bitcoinjs.bitcoin.networks.dashtn = {
22164 messagePrefix: "unused",
19926 bip32: { 22165 bip32: {
19927 public: 0x043587cf, 22166 public: 0x043587cf,
19928 private: 0x04358394 22167 private: 0x04358394
@@ -19932,7 +22171,8 @@ bitcoin.networks.dashtn = {
19932 wif: 0xef, 22171 wif: 0xef,
19933}; 22172};
19934 22173
19935bitcoin.networks.game = { 22174bitcoinjs.bitcoin.networks.game = {
22175 messagePrefix: "unused",
19936 bip32: { 22176 bip32: {
19937 public: 0x0488b21e, 22177 public: 0x0488b21e,
19938 private: 0x0488ade4 22178 private: 0x0488ade4
@@ -19942,27 +22182,30 @@ bitcoin.networks.game = {
19942 wif: 0xa6, 22182 wif: 0xa6,
19943}; 22183};
19944 22184
19945bitcoin.networks.namecoin = { 22185bitcoinjs.bitcoin.networks.namecoin = {
22186 messagePrefix: "unused",
19946 bip32: { 22187 bip32: {
19947 public: 0x0488b21e, 22188 public: 0x0488b21e,
19948 private: 0x0488ade4 22189 private: 0x0488ade4
19949 }, 22190 },
19950 pubKeyHash: 0x34, 22191 pubKeyHash: 0x34,
19951 //scriptHash: 0x10, 22192 scriptHash: 0x00, // TODO set this correctly
19952 wif: 0x80, 22193 wif: 0x80,
19953}; 22194};
19954 22195
19955bitcoin.networks.peercoin = { 22196bitcoinjs.bitcoin.networks.peercoin = {
22197 messagePrefix: "unused",
19956 bip32: { 22198 bip32: {
19957 public: 0x0488b21e, 22199 public: 0x0488b21e,
19958 private: 0x0488ade4 22200 private: 0x0488ade4
19959 }, 22201 },
19960 pubKeyHash: 0x37, 22202 pubKeyHash: 0x37,
19961 //scriptHash: 0x10, 22203 scriptHash: 0x00, // TODO set this correctly
19962 wif: 0xb7, 22204 wif: 0xb7,
19963}; 22205};
19964 22206
19965bitcoin.networks.slimcoin = { 22207bitcoinjs.bitcoin.networks.slimcoin = {
22208 messagePrefix: "unused",
19966 bip32: { 22209 bip32: {
19967 public: 0xef6adf10, 22210 public: 0xef6adf10,
19968 private: 0xef69ea80 22211 private: 0xef69ea80
@@ -19972,7 +22215,8 @@ bitcoin.networks.slimcoin = {
19972 wif: 0x46, 22215 wif: 0x46,
19973}; 22216};
19974 22217
19975bitcoin.networks.slimcointn = { 22218bitcoinjs.bitcoin.networks.slimcointn = {
22219 messagePrefix: "unused",
19976 bip32: { 22220 bip32: {
19977 public: 0x043587CF, 22221 public: 0x043587CF,
19978 private: 0x04358394 22222 private: 0x04358394
@@ -19982,6 +22226,71 @@ bitcoin.networks.slimcointn = {
19982 wif: 0x57, 22226 wif: 0x57,
19983}; 22227};
19984 22228
22229bitcoinjs.bitcoin.networks.dogecoin = {
22230 messagePrefix: '\x19Dogecoin Signed Message:\n',
22231 bip32: {
22232 public: 0x02facafd,
22233 private: 0x02fac398
22234 },
22235 pubKeyHash: 0x1e,
22236 scriptHash: 0x16,
22237 wif: 0x9e,
22238},
22239
22240bitcoinjs.bitcoin.networks.viacoin = {
22241 messagePrefix: '\x18Viacoin Signed Message:\n',
22242 bip32: {
22243 public: 0x0488b21e,
22244 private: 0x0488ade4
22245 },
22246 pubKeyHash: 0x47,
22247 scriptHash: 0x21,
22248 wif: 0xc7,
22249},
22250
22251bitcoinjs.bitcoin.networks.viacointestnet = {
22252 messagePrefix: '\x18Viacoin Signed Message:\n',
22253 bip32: {
22254 public: 0x043587cf,
22255 private: 0x04358394
22256 },
22257 pubKeyHash: 0x7f,
22258 scriptHash: 0xc4,
22259 wif: 0xff,
22260},
22261
22262bitcoinjs.bitcoin.networks.gamerscoin = {
22263 messagePrefix: '\x19Gamerscoin Signed Message:\n',
22264 bip32: {
22265 public: 0x019da462,
22266 private: 0x019d9cfe
22267 },
22268 pubKeyHash: 0x26,
22269 scriptHash: 0x05,
22270 wif: 0xA6,
22271},
22272
22273bitcoinjs.bitcoin.networks.jumbucks = {
22274 messagePrefix: '\x19Jumbucks Signed Message:\n',
22275 bip32: {
22276 public: 0x037a689a,
22277 private: 0x037a6460
22278 },
22279 pubKeyHash: 0x2b,
22280 scriptHash: 0x05,
22281 wif: 0xab,
22282},
22283
22284bitcoinjs.bitcoin.networks.zetacoin = {
22285 messagePrefix: '\x18Zetacoin Signed Message:\n',
22286 bip32: {
22287 public: 0x0488b21e,
22288 private: 0x0488ade4
22289 },
22290 pubKeyHash: 0x50,
22291 scriptHash: 0x09,
22292 wif: 0xe0,
22293}
19985</script> 22294</script>
19986 <script>(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.ethUtil = 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){ 22295 <script>(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.ethUtil = 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){
19987(function (global){ 22296(function (global){
@@ -43750,7 +46059,7 @@ window.Entropy = new (function() {
43750 var seed = null; 46059 var seed = null;
43751 var bip32RootKey = null; 46060 var bip32RootKey = null;
43752 var bip32ExtendedKey = null; 46061 var bip32ExtendedKey = null;
43753 var network = bitcoin.networks.bitcoin; 46062 var network = bitcoinjs.bitcoin.networks.bitcoin;
43754 var addressRowTemplate = $("#address-row-template"); 46063 var addressRowTemplate = $("#address-row-template");
43755 46064
43756 var showIndex = true; 46065 var showIndex = true;
@@ -43791,8 +46100,10 @@ window.Entropy = new (function() {
43791 DOM.extendedPubKey = $(".extended-pub-key"); 46100 DOM.extendedPubKey = $(".extended-pub-key");
43792 DOM.bip32tab = $("#bip32-tab"); 46101 DOM.bip32tab = $("#bip32-tab");
43793 DOM.bip44tab = $("#bip44-tab"); 46102 DOM.bip44tab = $("#bip44-tab");
46103 DOM.bip49tab = $("#bip49-tab");
43794 DOM.bip32panel = $("#bip32"); 46104 DOM.bip32panel = $("#bip32");
43795 DOM.bip44panel = $("#bip44"); 46105 DOM.bip44panel = $("#bip44");
46106 DOM.bip49panel = $("#bip49");
43796 DOM.bip32path = $("#bip32-path"); 46107 DOM.bip32path = $("#bip32-path");
43797 DOM.bip44path = $("#bip44-path"); 46108 DOM.bip44path = $("#bip44-path");
43798 DOM.bip44purpose = $("#bip44 .purpose"); 46109 DOM.bip44purpose = $("#bip44 .purpose");
@@ -43801,6 +46112,15 @@ window.Entropy = new (function() {
43801 DOM.bip44accountXprv = $("#bip44 .account-xprv"); 46112 DOM.bip44accountXprv = $("#bip44 .account-xprv");
43802 DOM.bip44accountXpub = $("#bip44 .account-xpub"); 46113 DOM.bip44accountXpub = $("#bip44 .account-xpub");
43803 DOM.bip44change = $("#bip44 .change"); 46114 DOM.bip44change = $("#bip44 .change");
46115 DOM.bip49unavailable = $("#bip49 .unavailable");
46116 DOM.bip49available = $("#bip49 .available");
46117 DOM.bip49path = $("#bip49-path");
46118 DOM.bip49purpose = $("#bip49 .purpose");
46119 DOM.bip49coin = $("#bip49 .coin");
46120 DOM.bip49account = $("#bip49 .account");
46121 DOM.bip49accountXprv = $("#bip49 .account-xprv");
46122 DOM.bip49accountXpub = $("#bip49 .account-xpub");
46123 DOM.bip49change = $("#bip49 .change");
43804 DOM.generatedStrength = $(".generate-container .strength"); 46124 DOM.generatedStrength = $(".generate-container .strength");
43805 DOM.hardenedAddresses = $(".hardened-addresses"); 46125 DOM.hardenedAddresses = $(".hardened-addresses");
43806 DOM.addresses = $(".addresses"); 46126 DOM.addresses = $(".addresses");
@@ -43832,10 +46152,10 @@ window.Entropy = new (function() {
43832 DOM.more.on("click", showMore); 46152 DOM.more.on("click", showMore);
43833 DOM.rootKey.on("input", delayedRootKeyChanged); 46153 DOM.rootKey.on("input", delayedRootKeyChanged);
43834 DOM.bip32path.on("input", calcForDerivationPath); 46154 DOM.bip32path.on("input", calcForDerivationPath);
43835 DOM.bip44purpose.on("input", calcForDerivationPath);
43836 DOM.bip44coin.on("input", calcForDerivationPath);
43837 DOM.bip44account.on("input", calcForDerivationPath); 46155 DOM.bip44account.on("input", calcForDerivationPath);
43838 DOM.bip44change.on("input", calcForDerivationPath); 46156 DOM.bip44change.on("input", calcForDerivationPath);
46157 DOM.bip49account.on("input", calcForDerivationPath);
46158 DOM.bip49change.on("input", calcForDerivationPath);
43839 DOM.tab.on("shown.bs.tab", calcForDerivationPath); 46159 DOM.tab.on("shown.bs.tab", calcForDerivationPath);
43840 DOM.hardenedAddresses.on("change", calcForDerivationPath); 46160 DOM.hardenedAddresses.on("change", calcForDerivationPath);
43841 DOM.indexToggle.on("click", toggleIndexes); 46161 DOM.indexToggle.on("click", toggleIndexes);
@@ -43854,8 +46174,17 @@ window.Entropy = new (function() {
43854 // Event handlers 46174 // Event handlers
43855 46175
43856 function networkChanged(e) { 46176 function networkChanged(e) {
46177 clearDerivedKeys();
46178 clearAddressesList();
43857 var networkIndex = e.target.value; 46179 var networkIndex = e.target.value;
43858 networks[networkIndex].onSelect(); 46180 var network = networks[networkIndex];
46181 network.onSelect();
46182 if (network.bip49available) {
46183 showBip49();
46184 }
46185 else {
46186 hideBip49();
46187 }
43859 if (seed != null) { 46188 if (seed != null) {
43860 phraseChanged(); 46189 phraseChanged();
43861 } 46190 }
@@ -43998,8 +46327,13 @@ window.Entropy = new (function() {
43998 46327
43999 function calcForDerivationPath() { 46328 function calcForDerivationPath() {
44000 showPending(); 46329 showPending();
46330 clearDerivedKeys();
44001 clearAddressesList(); 46331 clearAddressesList();
44002 hideValidationError(); 46332 hideValidationError();
46333 // Don't show bip49 if it's selected but network doesn't support it
46334 if (bip49TabSelected() && !networkHasBip49()) {
46335 return;
46336 }
44003 // Get the derivation path 46337 // Get the derivation path
44004 var derivationPath = getDerivationPath(); 46338 var derivationPath = getDerivationPath();
44005 var errorText = findDerivationPathErrors(derivationPath); 46339 var errorText = findDerivationPathErrors(derivationPath);
@@ -44011,6 +46345,9 @@ window.Entropy = new (function() {
44011 if (bip44TabSelected()) { 46345 if (bip44TabSelected()) {
44012 displayBip44Info(); 46346 displayBip44Info();
44013 } 46347 }
46348 if (bip49TabSelected()) {
46349 displayBip49Info();
46350 }
44014 displayBip32Info(); 46351 displayBip32Info();
44015 hidePending(); 46352 hidePending();
44016 } 46353 }
@@ -44082,11 +46419,11 @@ window.Entropy = new (function() {
44082 46419
44083 function calcBip32RootKeyFromSeed(phrase, passphrase) { 46420 function calcBip32RootKeyFromSeed(phrase, passphrase) {
44084 seed = mnemonic.toSeed(phrase, passphrase); 46421 seed = mnemonic.toSeed(phrase, passphrase);
44085 bip32RootKey = bitcoin.HDNode.fromSeedHex(seed, network); 46422 bip32RootKey = bitcoinjs.bitcoin.HDNode.fromSeedHex(seed, network);
44086 } 46423 }
44087 46424
44088 function calcBip32RootKeyFromBase58(rootKeyBase58) { 46425 function calcBip32RootKeyFromBase58(rootKeyBase58) {
44089 bip32RootKey = bitcoin.HDNode.fromBase58(rootKeyBase58, network); 46426 bip32RootKey = bitcoinjs.bitcoin.HDNode.fromBase58(rootKeyBase58, network);
44090 } 46427 }
44091 46428
44092 function calcBip32ExtendedKey(path) { 46429 function calcBip32ExtendedKey(path) {
@@ -44104,7 +46441,7 @@ window.Entropy = new (function() {
44104 continue; 46441 continue;
44105 } 46442 }
44106 var hardened = bit[bit.length-1] == "'"; 46443 var hardened = bit[bit.length-1] == "'";
44107 var isPriv = "privKey" in extendedKey; 46444 var isPriv = !(extendedKey.isNeutered());
44108 var invalidDerivationPath = hardened && !isPriv; 46445 var invalidDerivationPath = hardened && !isPriv;
44109 if (invalidDerivationPath) { 46446 if (invalidDerivationPath) {
44110 extendedKey = null; 46447 extendedKey = null;
@@ -44160,7 +46497,7 @@ window.Entropy = new (function() {
44160 46497
44161 function validateRootKey(rootKeyBase58) { 46498 function validateRootKey(rootKeyBase58) {
44162 try { 46499 try {
44163 bitcoin.HDNode.fromBase58(rootKeyBase58); 46500 bitcoinjs.bitcoin.HDNode.fromBase58(rootKeyBase58);
44164 } 46501 }
44165 catch (e) { 46502 catch (e) {
44166 return "Invalid root key"; 46503 return "Invalid root key";
@@ -44184,6 +46521,21 @@ window.Entropy = new (function() {
44184 console.log("Using derivation path from BIP44 tab: " + derivationPath); 46521 console.log("Using derivation path from BIP44 tab: " + derivationPath);
44185 return derivationPath; 46522 return derivationPath;
44186 } 46523 }
46524 if (bip49TabSelected()) {
46525 var purpose = parseIntNoNaN(DOM.bip49purpose.val(), 49);
46526 var coin = parseIntNoNaN(DOM.bip49coin.val(), 0);
46527 var account = parseIntNoNaN(DOM.bip49account.val(), 0);
46528 var change = parseIntNoNaN(DOM.bip49change.val(), 0);
46529 var path = "m/";
46530 path += purpose + "'/";
46531 path += coin + "'/";
46532 path += account + "'/";
46533 path += change;
46534 DOM.bip49path.val(path);
46535 var derivationPath = DOM.bip49path.val();
46536 console.log("Using derivation path from BIP49 tab: " + derivationPath);
46537 return derivationPath;
46538 }
44187 else if (bip32TabSelected()) { 46539 else if (bip32TabSelected()) {
44188 var derivationPath = DOM.bip32path.val(); 46540 var derivationPath = DOM.bip32path.val();
44189 console.log("Using derivation path from BIP32 tab: " + derivationPath); 46541 console.log("Using derivation path from BIP32 tab: " + derivationPath);
@@ -44234,7 +46586,7 @@ window.Entropy = new (function() {
44234 } 46586 }
44235 // Check no hardened derivation path when using xpub keys 46587 // Check no hardened derivation path when using xpub keys
44236 var hardened = path.indexOf("'") > -1; 46588 var hardened = path.indexOf("'") > -1;
44237 var isXpubkey = !("privKey" in bip32RootKey); 46589 var isXpubkey = bip32RootKey.isNeutered();
44238 if (hardened && isXpubkey) { 46590 if (hardened && isXpubkey) {
44239 return "Hardened derivation path is invalid with xpub key"; 46591 return "Hardened derivation path is invalid with xpub key";
44240 } 46592 }
@@ -44253,24 +46605,42 @@ window.Entropy = new (function() {
44253 // Calculate the account extended keys 46605 // Calculate the account extended keys
44254 var accountExtendedKey = calcBip32ExtendedKey(path); 46606 var accountExtendedKey = calcBip32ExtendedKey(path);
44255 var accountXprv = accountExtendedKey.toBase58(); 46607 var accountXprv = accountExtendedKey.toBase58();
44256 var accountXpub = accountExtendedKey.toBase58(false); 46608 var accountXpub = accountExtendedKey.neutered().toBase58();
44257 // Display the extended keys 46609 // Display the extended keys
44258 DOM.bip44accountXprv.val(accountXprv); 46610 DOM.bip44accountXprv.val(accountXprv);
44259 DOM.bip44accountXpub.val(accountXpub); 46611 DOM.bip44accountXpub.val(accountXpub);
44260 } 46612 }
44261 46613
46614 function displayBip49Info() {
46615 // Get the derivation path for the account
46616 var purpose = parseIntNoNaN(DOM.bip49purpose.val(), 49);
46617 var coin = parseIntNoNaN(DOM.bip49coin.val(), 0);
46618 var account = parseIntNoNaN(DOM.bip49account.val(), 0);
46619 var path = "m/";
46620 path += purpose + "'/";
46621 path += coin + "'/";
46622 path += account + "'/";
46623 // Calculate the account extended keys
46624 var accountExtendedKey = calcBip32ExtendedKey(path);
46625 var accountXprv = accountExtendedKey.toBase58();
46626 var accountXpub = accountExtendedKey.neutered().toBase58();
46627 // Display the extended keys
46628 DOM.bip49accountXprv.val(accountXprv);
46629 DOM.bip49accountXpub.val(accountXpub);
46630 }
46631
44262 function displayBip32Info() { 46632 function displayBip32Info() {
44263 // Display the key 46633 // Display the key
44264 DOM.seed.val(seed); 46634 DOM.seed.val(seed);
44265 var rootKey = bip32RootKey.toBase58(); 46635 var rootKey = bip32RootKey.toBase58();
44266 DOM.rootKey.val(rootKey); 46636 DOM.rootKey.val(rootKey);
44267 var xprvkeyB58 = "NA"; 46637 var xprvkeyB58 = "NA";
44268 if (bip32ExtendedKey.privKey) { 46638 if (!bip32ExtendedKey.isNeutered()) {
44269 xprvkeyB58 = bip32ExtendedKey.toBase58(); 46639 xprvkeyB58 = bip32ExtendedKey.toBase58();
44270 } 46640 }
44271 var extendedPrivKey = xprvkeyB58; 46641 var extendedPrivKey = xprvkeyB58;
44272 DOM.extendedPrivKey.val(extendedPrivKey); 46642 DOM.extendedPrivKey.val(extendedPrivKey);
44273 var extendedPubKey = bip32ExtendedKey.toBase58(false); 46643 var extendedPubKey = bip32ExtendedKey.neutered().toBase58();
44274 DOM.extendedPubKey.val(extendedPubKey); 46644 DOM.extendedPubKey.val(extendedPubKey);
44275 // Display the addresses and privkeys 46645 // Display the addresses and privkeys
44276 clearAddressesList(); 46646 clearAddressesList();
@@ -44301,6 +46671,8 @@ window.Entropy = new (function() {
44301 var self = this; 46671 var self = this;
44302 this.shouldGenerate = true; 46672 this.shouldGenerate = true;
44303 var useHardenedAddresses = DOM.hardenedAddresses.prop("checked"); 46673 var useHardenedAddresses = DOM.hardenedAddresses.prop("checked");
46674 var isBip49 = bip49TabSelected();
46675 var bip49available = networkHasBip49();
44304 46676
44305 function init() { 46677 function init() {
44306 calculateValues(); 46678 calculateValues();
@@ -44311,7 +46683,7 @@ window.Entropy = new (function() {
44311 if (!self.shouldGenerate) { 46683 if (!self.shouldGenerate) {
44312 return; 46684 return;
44313 } 46685 }
44314 var key = ""; 46686 var key = "NA";
44315 if (useHardenedAddresses) { 46687 if (useHardenedAddresses) {
44316 key = bip32ExtendedKey.deriveHardened(index); 46688 key = bip32ExtendedKey.deriveHardened(index);
44317 } 46689 }
@@ -44320,17 +46692,17 @@ window.Entropy = new (function() {
44320 } 46692 }
44321 var address = key.getAddress().toString(); 46693 var address = key.getAddress().toString();
44322 var privkey = "NA"; 46694 var privkey = "NA";
44323 if (key.privKey) { 46695 if (!key.isNeutered()) {
44324 privkey = key.privKey.toWIF(network); 46696 privkey = key.keyPair.toWIF(network);
44325 } 46697 }
44326 var pubkey = key.pubKey.toHex(); 46698 var pubkey = key.getPublicKeyBuffer().toString('hex');
44327 var indexText = getDerivationPath() + "/" + index; 46699 var indexText = getDerivationPath() + "/" + index;
44328 if (useHardenedAddresses) { 46700 if (useHardenedAddresses) {
44329 indexText = indexText + "'"; 46701 indexText = indexText + "'";
44330 } 46702 }
44331 // Ethereum values are different 46703 // Ethereum values are different
44332 if (networks[DOM.network.val()].name == "ETH - Ethereum") { 46704 if (networks[DOM.network.val()].name == "ETH - Ethereum") {
44333 var privKeyBuffer = key.privKey.d.toBuffer(); 46705 var privKeyBuffer = key.keyPair.d.toBuffer();
44334 privkey = privKeyBuffer.toString('hex'); 46706 privkey = privKeyBuffer.toString('hex');
44335 var addressBuffer = ethUtil.privateToAddress(privKeyBuffer); 46707 var addressBuffer = ethUtil.privateToAddress(privKeyBuffer);
44336 var hexAddress = addressBuffer.toString('hex'); 46708 var hexAddress = addressBuffer.toString('hex');
@@ -44344,6 +46716,17 @@ window.Entropy = new (function() {
44344 privkey = convertRipplePriv(privkey); 46716 privkey = convertRipplePriv(privkey);
44345 address = convertRippleAdrr(address); 46717 address = convertRippleAdrr(address);
44346 } 46718 }
46719 // BIP49 addresses are different
46720 if (isBip49) {
46721 if (!bip49available) {
46722 return;
46723 }
46724 var keyhash = bitcoinjs.bitcoin.crypto.hash160(key.getPublicKeyBuffer());
46725 var scriptsig = bitcoinjs.bitcoin.script.witnessPubKeyHash.output.encode(keyhash);
46726 var addressbytes = bitcoinjs.bitcoin.crypto.hash160(scriptsig);
46727 var scriptpubkey = bitcoinjs.bitcoin.script.scriptHash.output.encode(addressbytes);
46728 address = bitcoinjs.bitcoin.address.fromOutputScript(scriptpubkey, network)
46729 }
44347 addAddressToList(indexText, address, pubkey, privkey); 46730 addAddressToList(indexText, address, pubkey, privkey);
44348 }, 50) 46731 }, 50)
44349 } 46732 }
@@ -44371,7 +46754,7 @@ window.Entropy = new (function() {
44371 46754
44372 function clearDisplay() { 46755 function clearDisplay() {
44373 clearAddressesList(); 46756 clearAddressesList();
44374 clearKey(); 46757 clearKeys();
44375 hideValidationError(); 46758 hideValidationError();
44376 } 46759 }
44377 46760
@@ -44387,10 +46770,20 @@ window.Entropy = new (function() {
44387 } 46770 }
44388 } 46771 }
44389 46772
44390 function clearKey() { 46773 function clearKeys() {
46774 clearRootKey();
46775 clearDerivedKeys();
46776 }
46777
46778 function clearRootKey() {
44391 DOM.rootKey.val(""); 46779 DOM.rootKey.val("");
46780 }
46781
46782 function clearDerivedKeys() {
44392 DOM.extendedPrivKey.val(""); 46783 DOM.extendedPrivKey.val("");
44393 DOM.extendedPubKey.val(""); 46784 DOM.extendedPubKey.val("");
46785 DOM.bip44accountXprv.val("");
46786 DOM.bip44accountXpub.val("");
44394 } 46787 }
44395 46788
44396 function addAddressToList(indexText, address, pubkey, privkey) { 46789 function addAddressToList(indexText, address, pubkey, privkey) {
@@ -44799,145 +47192,188 @@ window.Entropy = new (function() {
44799 return DOM.bip32tab.hasClass("active"); 47192 return DOM.bip32tab.hasClass("active");
44800 } 47193 }
44801 47194
47195 function networkHasBip49() {
47196 return networks[DOM.network.val()].bip49available;
47197 }
47198
47199 function bip49TabSelected() {
47200 return DOM.bip49tab.hasClass("active");
47201 }
47202
47203 function setHdCoin(coinValue) {
47204 DOM.bip44coin.val(coinValue);
47205 DOM.bip49coin.val(coinValue);
47206 }
47207
47208 function showBip49() {
47209 DOM.bip49unavailable.addClass("hidden");
47210 DOM.bip49available.removeClass("hidden");
47211 }
47212
47213 function hideBip49() {
47214 DOM.bip49available.addClass("hidden");
47215 DOM.bip49unavailable.removeClass("hidden");
47216 }
47217
44802 var networks = [ 47218 var networks = [
44803 { 47219 {
44804 name: "BTC - Bitcoin", 47220 name: "BTC - Bitcoin",
47221 bip49available: true,
44805 onSelect: function() { 47222 onSelect: function() {
44806 network = bitcoin.networks.bitcoin; 47223 network = bitcoinjs.bitcoin.networks.bitcoin;
44807 DOM.bip44coin.val(0); 47224 setHdCoin(0);
44808 }, 47225 },
44809 }, 47226 },
44810 { 47227 {
44811 name: "BTC - Bitcoin Testnet", 47228 name: "BTC - Bitcoin Testnet",
47229 bip49available: true,
44812 onSelect: function() { 47230 onSelect: function() {
44813 network = bitcoin.networks.testnet; 47231 network = bitcoinjs.bitcoin.networks.testnet;
44814 DOM.bip44coin.val(1); 47232 setHdCoin(1);
44815 }, 47233 },
44816 }, 47234 },
44817 { 47235 {
44818 name: "CLAM - Clams", 47236 name: "CLAM - Clams",
47237 bip49available: false,
44819 onSelect: function() { 47238 onSelect: function() {
44820 network = bitcoin.networks.clam; 47239 network = bitcoinjs.bitcoin.networks.clam;
44821 DOM.bip44coin.val(23); 47240 setHdCoin(23);
44822 }, 47241 },
44823 }, 47242 },
44824 { 47243 {
44825 name: "CRW - Crown", 47244 name: "CRW - Crown",
47245 bip49available: false,
44826 onSelect: function() { 47246 onSelect: function() {
44827 network = bitcoin.networks.crown; 47247 network = bitcoinjs.bitcoin.networks.crown;
44828 DOM.bip44coin.val(72); 47248 setHdCoin(72);
44829 }, 47249 },
44830 }, 47250 },
44831 { 47251 {
44832 name: "DASH - Dash", 47252 name: "DASH - Dash",
47253 bip49available: false,
44833 onSelect: function() { 47254 onSelect: function() {
44834 network = bitcoin.networks.dash; 47255 network = bitcoinjs.bitcoin.networks.dash;
44835 DOM.bip44coin.val(5); 47256 setHdCoin(5);
44836 }, 47257 },
44837 }, 47258 },
44838 { 47259 {
44839 name: "DASH - Dash Testnet", 47260 name: "DASH - Dash Testnet",
47261 bip49available: false,
44840 onSelect: function() { 47262 onSelect: function() {
44841 network = bitcoin.networks.dashtn; 47263 network = bitcoinjs.bitcoin.networks.dashtn;
44842 DOM.bip44coin.val(1); 47264 setHdCoin(1);
44843 }, 47265 },
44844 }, 47266 },
44845 { 47267 {
44846 name: "DOGE - Dogecoin", 47268 name: "DOGE - Dogecoin",
47269 bip49available: false,
44847 onSelect: function() { 47270 onSelect: function() {
44848 network = bitcoin.networks.dogecoin; 47271 network = bitcoinjs.bitcoin.networks.dogecoin;
44849 DOM.bip44coin.val(3); 47272 setHdCoin(3);
44850 }, 47273 },
44851 }, 47274 },
44852 { 47275 {
44853 name: "ETH - Ethereum", 47276 name: "ETH - Ethereum",
47277 bip49available: false,
44854 onSelect: function() { 47278 onSelect: function() {
44855 network = bitcoin.networks.bitcoin; 47279 network = bitcoinjs.bitcoin.networks.bitcoin;
44856 DOM.bip44coin.val(60); 47280 setHdCoin(60);
44857 }, 47281 },
44858 }, 47282 },
44859 { 47283 {
44860 name: "GAME - GameCredits", 47284 name: "GAME - GameCredits",
47285 bip49available: false,
44861 onSelect: function() { 47286 onSelect: function() {
44862 network = bitcoin.networks.game; 47287 network = bitcoinjs.bitcoin.networks.game;
44863 DOM.bip44coin.val(101); 47288 setHdCoin(101);
44864 }, 47289 },
44865 }, 47290 },
44866 { 47291 {
44867 name: "JBS - Jumbucks", 47292 name: "JBS - Jumbucks",
47293 bip49available: false,
44868 onSelect: function() { 47294 onSelect: function() {
44869 network = bitcoin.networks.jumbucks; 47295 network = bitcoinjs.bitcoin.networks.jumbucks;
44870 DOM.bip44coin.val(26); 47296 setHdCoin(26);
44871 }, 47297 },
44872 }, 47298 },
44873 { 47299 {
44874 name: "LTC - Litecoin", 47300 name: "LTC - Litecoin",
47301 bip49available: false,
44875 onSelect: function() { 47302 onSelect: function() {
44876 network = bitcoin.networks.litecoin; 47303 network = bitcoinjs.bitcoin.networks.litecoin;
44877 DOM.bip44coin.val(2); 47304 setHdCoin(2);
44878 }, 47305 },
44879 }, 47306 },
44880 { 47307 {
44881 name: "NMC - Namecoin", 47308 name: "NMC - Namecoin",
47309 bip49available: false,
44882 onSelect: function() { 47310 onSelect: function() {
44883 network = bitcoin.networks.namecoin; 47311 network = bitcoinjs.bitcoin.networks.namecoin;
44884 DOM.bip44coin.val(7); 47312 setHdCoin(7);
44885 }, 47313 },
44886 }, 47314 },
44887 { 47315 {
44888 name: "PPC - Peercoin", 47316 name: "PPC - Peercoin",
47317 bip49available: false,
44889 onSelect: function() { 47318 onSelect: function() {
44890 network = bitcoin.networks.peercoin; 47319 network = bitcoinjs.bitcoin.networks.peercoin;
44891 DOM.bip44coin.val(6); 47320 setHdCoin(6);
44892 }, 47321 },
44893 }, 47322 },
44894 { 47323 {
44895 name: "SDC - ShadowCash", 47324 name: "SDC - ShadowCash",
47325 bip49available: false,
44896 onSelect: function() { 47326 onSelect: function() {
44897 network = bitcoin.networks.shadow; 47327 network = bitcoinjs.bitcoin.networks.shadow;
44898 DOM.bip44coin.val(35); 47328 setHdCoin(35);
44899 }, 47329 },
44900 }, 47330 },
44901 { 47331 {
44902 name: "SDC - ShadowCash Testnet", 47332 name: "SDC - ShadowCash Testnet",
47333 bip49available: false,
44903 onSelect: function() { 47334 onSelect: function() {
44904 network = bitcoin.networks.shadowtn; 47335 network = bitcoinjs.bitcoin.networks.shadowtn;
44905 DOM.bip44coin.val(1); 47336 setHdCoin(1);
44906 }, 47337 },
44907 }, 47338 },
44908 { 47339 {
44909 name: "SLM - Slimcoin", 47340 name: "SLM - Slimcoin",
47341 bip49available: false,
44910 onSelect: function() { 47342 onSelect: function() {
44911 network = bitcoin.networks.slimcoin; 47343 network = bitcoinjs.bitcoin.networks.slimcoin;
44912 DOM.bip44coin.val(63); 47344 setHdCoin(63);
44913 }, 47345 },
44914 }, 47346 },
44915 { 47347 {
44916 name: "SLM - Slimcoin Testnet", 47348 name: "SLM - Slimcoin Testnet",
47349 bip49available: false,
44917 onSelect: function() { 47350 onSelect: function() {
44918 network = bitcoin.networks.slimcointn; 47351 network = bitcoinjs.bitcoin.networks.slimcointn;
44919 DOM.bip44coin.val(111); 47352 setHdCoin(111);
44920 }, 47353 },
44921 }, 47354 },
44922 { 47355 {
44923 name: "VIA - Viacoin", 47356 name: "VIA - Viacoin",
47357 bip49available: false,
44924 onSelect: function() { 47358 onSelect: function() {
44925 network = bitcoin.networks.viacoin; 47359 network = bitcoinjs.bitcoin.networks.viacoin;
44926 DOM.bip44coin.val(14); 47360 setHdCoin(14);
44927 }, 47361 },
44928 }, 47362 },
44929 { 47363 {
44930 name: "VIA - Viacoin Testnet", 47364 name: "VIA - Viacoin Testnet",
47365 bip49available: false,
44931 onSelect: function() { 47366 onSelect: function() {
44932 network = bitcoin.networks.viacointestnet; 47367 network = bitcoinjs.bitcoin.networks.viacointestnet;
44933 DOM.bip44coin.val(1); 47368 setHdCoin(1);
44934 }, 47369 },
44935 }, 47370 },
44936 { 47371 {
44937 name: "XRP - Ripple", 47372 name: "XRP - Ripple",
47373 bip49available: false,
44938 onSelect: function() { 47374 onSelect: function() {
44939 network = bitcoin.networks.bitcoin; 47375 network = bitcoinjs.bitcoin.networks.bitcoin;
44940 DOM.bip44coin.val(144); 47376 setHdCoin(144);
44941 }, 47377 },
44942 } 47378 }
44943 ] 47379 ]
diff --git a/changelog.md b/changelog.md
index 7984bea..9f10cd5 100644
--- a/changelog.md
+++ b/changelog.md
@@ -1,3 +1,12 @@
1# 0.2.0
2
3* BitcoinJS library upgrded to v3.1.1
4* Tab order is alphabetical
5* BIP44 'purpose' and 'coin' fields are readonly
6* Refactor method to clear old data from the display
7* BIP49 support
8* Release process is documented
9
1# 0.1.2 10# 0.1.2
2 11
3* Add Crown network 12* Add Crown network
diff --git a/src/index.html b/src/index.html
index 31e8a2e..c88367e 100644
--- a/src/index.html
+++ b/src/index.html
@@ -114,7 +114,7 @@
114 <div class="container"> 114 <div class="container">
115 115
116 <h1 class="text-center">Mnemonic Code Converter</h1> 116 <h1 class="text-center">Mnemonic Code Converter</h1>
117 <p class="version">v0.1.2</p> 117 <p class="version">v0.2.0</p>
118 <hr> 118 <hr>
119 <div class="row"> 119 <div class="row">
120 <div class="col-md-12"> 120 <div class="col-md-12">