github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/internal/jsre/ethereum_jslib.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package jsre 18 19 const Web3_JS = ` 20 require=(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){ 21 module.exports=[ 22 { 23 "constant": true, 24 "inputs": [ 25 { 26 "name": "_owner", 27 "type": "address" 28 } 29 ], 30 "name": "name", 31 "outputs": [ 32 { 33 "name": "o_name", 34 "type": "bytes32" 35 } 36 ], 37 "type": "function" 38 }, 39 { 40 "constant": true, 41 "inputs": [ 42 { 43 "name": "_name", 44 "type": "bytes32" 45 } 46 ], 47 "name": "owner", 48 "outputs": [ 49 { 50 "name": "", 51 "type": "address" 52 } 53 ], 54 "type": "function" 55 }, 56 { 57 "constant": true, 58 "inputs": [ 59 { 60 "name": "_name", 61 "type": "bytes32" 62 } 63 ], 64 "name": "content", 65 "outputs": [ 66 { 67 "name": "", 68 "type": "bytes32" 69 } 70 ], 71 "type": "function" 72 }, 73 { 74 "constant": true, 75 "inputs": [ 76 { 77 "name": "_name", 78 "type": "bytes32" 79 } 80 ], 81 "name": "addr", 82 "outputs": [ 83 { 84 "name": "", 85 "type": "address" 86 } 87 ], 88 "type": "function" 89 }, 90 { 91 "constant": false, 92 "inputs": [ 93 { 94 "name": "_name", 95 "type": "bytes32" 96 } 97 ], 98 "name": "reserve", 99 "outputs": [], 100 "type": "function" 101 }, 102 { 103 "constant": true, 104 "inputs": [ 105 { 106 "name": "_name", 107 "type": "bytes32" 108 } 109 ], 110 "name": "subRegistrar", 111 "outputs": [ 112 { 113 "name": "", 114 "type": "address" 115 } 116 ], 117 "type": "function" 118 }, 119 { 120 "constant": false, 121 "inputs": [ 122 { 123 "name": "_name", 124 "type": "bytes32" 125 }, 126 { 127 "name": "_newOwner", 128 "type": "address" 129 } 130 ], 131 "name": "transfer", 132 "outputs": [], 133 "type": "function" 134 }, 135 { 136 "constant": false, 137 "inputs": [ 138 { 139 "name": "_name", 140 "type": "bytes32" 141 }, 142 { 143 "name": "_registrar", 144 "type": "address" 145 } 146 ], 147 "name": "setSubRegistrar", 148 "outputs": [], 149 "type": "function" 150 }, 151 { 152 "constant": false, 153 "inputs": [], 154 "name": "Registrar", 155 "outputs": [], 156 "type": "function" 157 }, 158 { 159 "constant": false, 160 "inputs": [ 161 { 162 "name": "_name", 163 "type": "bytes32" 164 }, 165 { 166 "name": "_a", 167 "type": "address" 168 }, 169 { 170 "name": "_primary", 171 "type": "bool" 172 } 173 ], 174 "name": "setAddress", 175 "outputs": [], 176 "type": "function" 177 }, 178 { 179 "constant": false, 180 "inputs": [ 181 { 182 "name": "_name", 183 "type": "bytes32" 184 }, 185 { 186 "name": "_content", 187 "type": "bytes32" 188 } 189 ], 190 "name": "setContent", 191 "outputs": [], 192 "type": "function" 193 }, 194 { 195 "constant": false, 196 "inputs": [ 197 { 198 "name": "_name", 199 "type": "bytes32" 200 } 201 ], 202 "name": "disown", 203 "outputs": [], 204 "type": "function" 205 }, 206 { 207 "anonymous": false, 208 "inputs": [ 209 { 210 "indexed": true, 211 "name": "_name", 212 "type": "bytes32" 213 }, 214 { 215 "indexed": false, 216 "name": "_winner", 217 "type": "address" 218 } 219 ], 220 "name": "AuctionEnded", 221 "type": "event" 222 }, 223 { 224 "anonymous": false, 225 "inputs": [ 226 { 227 "indexed": true, 228 "name": "_name", 229 "type": "bytes32" 230 }, 231 { 232 "indexed": false, 233 "name": "_bidder", 234 "type": "address" 235 }, 236 { 237 "indexed": false, 238 "name": "_value", 239 "type": "uint256" 240 } 241 ], 242 "name": "NewBid", 243 "type": "event" 244 }, 245 { 246 "anonymous": false, 247 "inputs": [ 248 { 249 "indexed": true, 250 "name": "name", 251 "type": "bytes32" 252 } 253 ], 254 "name": "Changed", 255 "type": "event" 256 }, 257 { 258 "anonymous": false, 259 "inputs": [ 260 { 261 "indexed": true, 262 "name": "name", 263 "type": "bytes32" 264 }, 265 { 266 "indexed": true, 267 "name": "addr", 268 "type": "address" 269 } 270 ], 271 "name": "PrimaryChanged", 272 "type": "event" 273 } 274 ] 275 276 },{}],2:[function(require,module,exports){ 277 module.exports=[ 278 { 279 "constant": true, 280 "inputs": [ 281 { 282 "name": "_name", 283 "type": "bytes32" 284 } 285 ], 286 "name": "owner", 287 "outputs": [ 288 { 289 "name": "", 290 "type": "address" 291 } 292 ], 293 "type": "function" 294 }, 295 { 296 "constant": false, 297 "inputs": [ 298 { 299 "name": "_name", 300 "type": "bytes32" 301 }, 302 { 303 "name": "_refund", 304 "type": "address" 305 } 306 ], 307 "name": "disown", 308 "outputs": [], 309 "type": "function" 310 }, 311 { 312 "constant": true, 313 "inputs": [ 314 { 315 "name": "_name", 316 "type": "bytes32" 317 } 318 ], 319 "name": "addr", 320 "outputs": [ 321 { 322 "name": "", 323 "type": "address" 324 } 325 ], 326 "type": "function" 327 }, 328 { 329 "constant": false, 330 "inputs": [ 331 { 332 "name": "_name", 333 "type": "bytes32" 334 } 335 ], 336 "name": "reserve", 337 "outputs": [], 338 "type": "function" 339 }, 340 { 341 "constant": false, 342 "inputs": [ 343 { 344 "name": "_name", 345 "type": "bytes32" 346 }, 347 { 348 "name": "_newOwner", 349 "type": "address" 350 } 351 ], 352 "name": "transfer", 353 "outputs": [], 354 "type": "function" 355 }, 356 { 357 "constant": false, 358 "inputs": [ 359 { 360 "name": "_name", 361 "type": "bytes32" 362 }, 363 { 364 "name": "_a", 365 "type": "address" 366 } 367 ], 368 "name": "setAddr", 369 "outputs": [], 370 "type": "function" 371 }, 372 { 373 "anonymous": false, 374 "inputs": [ 375 { 376 "indexed": true, 377 "name": "name", 378 "type": "bytes32" 379 } 380 ], 381 "name": "Changed", 382 "type": "event" 383 } 384 ] 385 386 },{}],3:[function(require,module,exports){ 387 module.exports=[ 388 { 389 "constant": false, 390 "inputs": [ 391 { 392 "name": "from", 393 "type": "bytes32" 394 }, 395 { 396 "name": "to", 397 "type": "address" 398 }, 399 { 400 "name": "value", 401 "type": "uint256" 402 } 403 ], 404 "name": "transfer", 405 "outputs": [], 406 "type": "function" 407 }, 408 { 409 "constant": false, 410 "inputs": [ 411 { 412 "name": "from", 413 "type": "bytes32" 414 }, 415 { 416 "name": "to", 417 "type": "address" 418 }, 419 { 420 "name": "indirectId", 421 "type": "bytes32" 422 }, 423 { 424 "name": "value", 425 "type": "uint256" 426 } 427 ], 428 "name": "icapTransfer", 429 "outputs": [], 430 "type": "function" 431 }, 432 { 433 "constant": false, 434 "inputs": [ 435 { 436 "name": "to", 437 "type": "bytes32" 438 } 439 ], 440 "name": "deposit", 441 "outputs": [], 442 "type": "function" 443 }, 444 { 445 "anonymous": false, 446 "inputs": [ 447 { 448 "indexed": true, 449 "name": "from", 450 "type": "address" 451 }, 452 { 453 "indexed": false, 454 "name": "value", 455 "type": "uint256" 456 } 457 ], 458 "name": "AnonymousDeposit", 459 "type": "event" 460 }, 461 { 462 "anonymous": false, 463 "inputs": [ 464 { 465 "indexed": true, 466 "name": "from", 467 "type": "address" 468 }, 469 { 470 "indexed": true, 471 "name": "to", 472 "type": "bytes32" 473 }, 474 { 475 "indexed": false, 476 "name": "value", 477 "type": "uint256" 478 } 479 ], 480 "name": "Deposit", 481 "type": "event" 482 }, 483 { 484 "anonymous": false, 485 "inputs": [ 486 { 487 "indexed": true, 488 "name": "from", 489 "type": "bytes32" 490 }, 491 { 492 "indexed": true, 493 "name": "to", 494 "type": "address" 495 }, 496 { 497 "indexed": false, 498 "name": "value", 499 "type": "uint256" 500 } 501 ], 502 "name": "Transfer", 503 "type": "event" 504 }, 505 { 506 "anonymous": false, 507 "inputs": [ 508 { 509 "indexed": true, 510 "name": "from", 511 "type": "bytes32" 512 }, 513 { 514 "indexed": true, 515 "name": "to", 516 "type": "address" 517 }, 518 { 519 "indexed": false, 520 "name": "indirectId", 521 "type": "bytes32" 522 }, 523 { 524 "indexed": false, 525 "name": "value", 526 "type": "uint256" 527 } 528 ], 529 "name": "IcapTransfer", 530 "type": "event" 531 } 532 ] 533 534 },{}],4:[function(require,module,exports){ 535 var f = require('./formatters'); 536 var SolidityType = require('./type'); 537 538 /** 539 * SolidityTypeAddress is a prootype that represents address type 540 * It matches: 541 * address 542 * address[] 543 * address[4] 544 * address[][] 545 * address[3][] 546 * address[][6][], ... 547 */ 548 var SolidityTypeAddress = function () { 549 this._inputFormatter = f.formatInputInt; 550 this._outputFormatter = f.formatOutputAddress; 551 }; 552 553 SolidityTypeAddress.prototype = new SolidityType({}); 554 SolidityTypeAddress.prototype.constructor = SolidityTypeAddress; 555 556 SolidityTypeAddress.prototype.isType = function (name) { 557 return !!name.match(/address(\[([0-9]*)\])?/); 558 }; 559 560 SolidityTypeAddress.prototype.staticPartLength = function (name) { 561 return 32 * this.staticArrayLength(name); 562 }; 563 564 module.exports = SolidityTypeAddress; 565 566 567 },{"./formatters":9,"./type":14}],5:[function(require,module,exports){ 568 var f = require('./formatters'); 569 var SolidityType = require('./type'); 570 571 /** 572 * SolidityTypeBool is a prootype that represents bool type 573 * It matches: 574 * bool 575 * bool[] 576 * bool[4] 577 * bool[][] 578 * bool[3][] 579 * bool[][6][], ... 580 */ 581 var SolidityTypeBool = function () { 582 this._inputFormatter = f.formatInputBool; 583 this._outputFormatter = f.formatOutputBool; 584 }; 585 586 SolidityTypeBool.prototype = new SolidityType({}); 587 SolidityTypeBool.prototype.constructor = SolidityTypeBool; 588 589 SolidityTypeBool.prototype.isType = function (name) { 590 return !!name.match(/^bool(\[([0-9]*)\])*$/); 591 }; 592 593 SolidityTypeBool.prototype.staticPartLength = function (name) { 594 return 32 * this.staticArrayLength(name); 595 }; 596 597 module.exports = SolidityTypeBool; 598 599 },{"./formatters":9,"./type":14}],6:[function(require,module,exports){ 600 var f = require('./formatters'); 601 var SolidityType = require('./type'); 602 603 /** 604 * SolidityTypeBytes is a prootype that represents bytes type 605 * It matches: 606 * bytes 607 * bytes[] 608 * bytes[4] 609 * bytes[][] 610 * bytes[3][] 611 * bytes[][6][], ... 612 * bytes32 613 * bytes64[] 614 * bytes8[4] 615 * bytes256[][] 616 * bytes[3][] 617 * bytes64[][6][], ... 618 */ 619 var SolidityTypeBytes = function () { 620 this._inputFormatter = f.formatInputBytes; 621 this._outputFormatter = f.formatOutputBytes; 622 }; 623 624 SolidityTypeBytes.prototype = new SolidityType({}); 625 SolidityTypeBytes.prototype.constructor = SolidityTypeBytes; 626 627 SolidityTypeBytes.prototype.isType = function (name) { 628 return !!name.match(/^bytes([0-9]{1,})(\[([0-9]*)\])*$/); 629 }; 630 631 SolidityTypeBytes.prototype.staticPartLength = function (name) { 632 var matches = name.match(/^bytes([0-9]*)/); 633 var size = parseInt(matches[1]); 634 return size * this.staticArrayLength(name); 635 }; 636 637 module.exports = SolidityTypeBytes; 638 639 },{"./formatters":9,"./type":14}],7:[function(require,module,exports){ 640 /* 641 This file is part of web3.js. 642 643 web3.js is free software: you can redistribute it and/or modify 644 it under the terms of the GNU Lesser General Public License as published by 645 the Free Software Foundation, either version 3 of the License, or 646 (at your option) any later version. 647 648 web3.js is distributed in the hope that it will be useful, 649 but WITHOUT ANY WARRANTY; without even the implied warranty of 650 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 651 GNU Lesser General Public License for more details. 652 653 You should have received a copy of the GNU Lesser General Public License 654 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 655 */ 656 /** 657 * @file coder.js 658 * @author Marek Kotewicz <marek@ethdev.com> 659 * @date 2015 660 */ 661 662 var f = require('./formatters'); 663 664 var SolidityTypeAddress = require('./address'); 665 var SolidityTypeBool = require('./bool'); 666 var SolidityTypeInt = require('./int'); 667 var SolidityTypeUInt = require('./uint'); 668 var SolidityTypeDynamicBytes = require('./dynamicbytes'); 669 var SolidityTypeString = require('./string'); 670 var SolidityTypeReal = require('./real'); 671 var SolidityTypeUReal = require('./ureal'); 672 var SolidityTypeBytes = require('./bytes'); 673 674 /** 675 * SolidityCoder prototype should be used to encode/decode solidity params of any type 676 */ 677 var SolidityCoder = function (types) { 678 this._types = types; 679 }; 680 681 /** 682 * This method should be used to transform type to SolidityType 683 * 684 * @method _requireType 685 * @param {String} type 686 * @returns {SolidityType} 687 * @throws {Error} throws if no matching type is found 688 */ 689 SolidityCoder.prototype._requireType = function (type) { 690 var solidityType = this._types.filter(function (t) { 691 return t.isType(type); 692 })[0]; 693 694 if (!solidityType) { 695 throw Error('invalid solidity type!: ' + type); 696 } 697 698 return solidityType; 699 }; 700 701 /** 702 * Should be used to encode plain param 703 * 704 * @method encodeParam 705 * @param {String} type 706 * @param {Object} plain param 707 * @return {String} encoded plain param 708 */ 709 SolidityCoder.prototype.encodeParam = function (type, param) { 710 return this.encodeParams([type], [param]); 711 }; 712 713 /** 714 * Should be used to encode list of params 715 * 716 * @method encodeParams 717 * @param {Array} types 718 * @param {Array} params 719 * @return {String} encoded list of params 720 */ 721 SolidityCoder.prototype.encodeParams = function (types, params) { 722 var solidityTypes = this.getSolidityTypes(types); 723 724 var encodeds = solidityTypes.map(function (solidityType, index) { 725 return solidityType.encode(params[index], types[index]); 726 }); 727 728 var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) { 729 var staticPartLength = solidityType.staticPartLength(types[index]); 730 var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32; 731 return acc + roundedStaticPartLength; 732 }, 0); 733 734 var result = this.encodeMultiWithOffset(types, solidityTypes, encodeds, dynamicOffset); 735 736 return result; 737 }; 738 739 SolidityCoder.prototype.encodeMultiWithOffset = function (types, solidityTypes, encodeds, dynamicOffset) { 740 var result = ""; 741 var self = this; 742 743 var isDynamic = function (i) { 744 return solidityTypes[i].isDynamicArray(types[i]) || solidityTypes[i].isDynamicType(types[i]); 745 }; 746 747 types.forEach(function (type, i) { 748 if (isDynamic(i)) { 749 result += f.formatInputInt(dynamicOffset).encode(); 750 var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); 751 dynamicOffset += e.length / 2; 752 } else { 753 // don't add length to dynamicOffset. it's already counted 754 result += self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); 755 } 756 757 // TODO: figure out nested arrays 758 }); 759 760 types.forEach(function (type, i) { 761 if (isDynamic(i)) { 762 var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); 763 dynamicOffset += e.length / 2; 764 result += e; 765 } 766 }); 767 return result; 768 }; 769 770 // TODO: refactor whole encoding! 771 SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded, offset) { 772 var self = this; 773 if (solidityType.isDynamicArray(type)) { 774 return (function () { 775 // offset was already set 776 var nestedName = solidityType.nestedName(type); 777 var nestedStaticPartLength = solidityType.staticPartLength(nestedName); 778 var result = encoded[0]; 779 780 (function () { 781 var previousLength = 2; // in int 782 if (solidityType.isDynamicArray(nestedName)) { 783 for (var i = 1; i < encoded.length; i++) { 784 previousLength += +(encoded[i - 1])[0] || 0; 785 result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode(); 786 } 787 } 788 })(); 789 790 // first element is length, skip it 791 (function () { 792 for (var i = 0; i < encoded.length - 1; i++) { 793 var additionalOffset = result / 2; 794 result += self.encodeWithOffset(nestedName, solidityType, encoded[i + 1], offset + additionalOffset); 795 } 796 })(); 797 798 return result; 799 })(); 800 801 } else if (solidityType.isStaticArray(type)) { 802 return (function () { 803 var nestedName = solidityType.nestedName(type); 804 var nestedStaticPartLength = solidityType.staticPartLength(nestedName); 805 var result = ""; 806 807 808 if (solidityType.isDynamicArray(nestedName)) { 809 (function () { 810 var previousLength = 0; // in int 811 for (var i = 0; i < encoded.length; i++) { 812 // calculate length of previous item 813 previousLength += +(encoded[i - 1] || [])[0] || 0; 814 result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode(); 815 } 816 })(); 817 } 818 819 (function () { 820 for (var i = 0; i < encoded.length; i++) { 821 var additionalOffset = result / 2; 822 result += self.encodeWithOffset(nestedName, solidityType, encoded[i], offset + additionalOffset); 823 } 824 })(); 825 826 return result; 827 })(); 828 } 829 830 return encoded; 831 }; 832 833 /** 834 * Should be used to decode bytes to plain param 835 * 836 * @method decodeParam 837 * @param {String} type 838 * @param {String} bytes 839 * @return {Object} plain param 840 */ 841 SolidityCoder.prototype.decodeParam = function (type, bytes) { 842 return this.decodeParams([type], bytes)[0]; 843 }; 844 845 /** 846 * Should be used to decode list of params 847 * 848 * @method decodeParam 849 * @param {Array} types 850 * @param {String} bytes 851 * @return {Array} array of plain params 852 */ 853 SolidityCoder.prototype.decodeParams = function (types, bytes) { 854 var solidityTypes = this.getSolidityTypes(types); 855 var offsets = this.getOffsets(types, solidityTypes); 856 857 return solidityTypes.map(function (solidityType, index) { 858 return solidityType.decode(bytes, offsets[index], types[index], index); 859 }); 860 }; 861 862 SolidityCoder.prototype.getOffsets = function (types, solidityTypes) { 863 var lengths = solidityTypes.map(function (solidityType, index) { 864 return solidityType.staticPartLength(types[index]); 865 }); 866 867 for (var i = 1; i < lengths.length; i++) { 868 // sum with length of previous element 869 lengths[i] += lengths[i - 1]; 870 } 871 872 return lengths.map(function (length, index) { 873 // remove the current length, so the length is sum of previous elements 874 var staticPartLength = solidityTypes[index].staticPartLength(types[index]); 875 return length - staticPartLength; 876 }); 877 }; 878 879 SolidityCoder.prototype.getSolidityTypes = function (types) { 880 var self = this; 881 return types.map(function (type) { 882 return self._requireType(type); 883 }); 884 }; 885 886 var coder = new SolidityCoder([ 887 new SolidityTypeAddress(), 888 new SolidityTypeBool(), 889 new SolidityTypeInt(), 890 new SolidityTypeUInt(), 891 new SolidityTypeDynamicBytes(), 892 new SolidityTypeBytes(), 893 new SolidityTypeString(), 894 new SolidityTypeReal(), 895 new SolidityTypeUReal() 896 ]); 897 898 module.exports = coder; 899 900 901 },{"./address":4,"./bool":5,"./bytes":6,"./dynamicbytes":8,"./formatters":9,"./int":10,"./real":12,"./string":13,"./uint":15,"./ureal":16}],8:[function(require,module,exports){ 902 var f = require('./formatters'); 903 var SolidityType = require('./type'); 904 905 var SolidityTypeDynamicBytes = function () { 906 this._inputFormatter = f.formatInputDynamicBytes; 907 this._outputFormatter = f.formatOutputDynamicBytes; 908 }; 909 910 SolidityTypeDynamicBytes.prototype = new SolidityType({}); 911 SolidityTypeDynamicBytes.prototype.constructor = SolidityTypeDynamicBytes; 912 913 SolidityTypeDynamicBytes.prototype.isType = function (name) { 914 return !!name.match(/^bytes(\[([0-9]*)\])*$/); 915 }; 916 917 SolidityTypeDynamicBytes.prototype.staticPartLength = function (name) { 918 return 32 * this.staticArrayLength(name); 919 }; 920 921 SolidityTypeDynamicBytes.prototype.isDynamicType = function () { 922 return true; 923 }; 924 925 module.exports = SolidityTypeDynamicBytes; 926 927 928 },{"./formatters":9,"./type":14}],9:[function(require,module,exports){ 929 /* 930 This file is part of web3.js. 931 932 web3.js is free software: you can redistribute it and/or modify 933 it under the terms of the GNU Lesser General Public License as published by 934 the Free Software Foundation, either version 3 of the License, or 935 (at your option) any later version. 936 937 web3.js is distributed in the hope that it will be useful, 938 but WITHOUT ANY WARRANTY; without even the implied warranty of 939 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 940 GNU Lesser General Public License for more details. 941 942 You should have received a copy of the GNU Lesser General Public License 943 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 944 */ 945 /** 946 * @file formatters.js 947 * @author Marek Kotewicz <marek@ethdev.com> 948 * @date 2015 949 */ 950 951 var BigNumber = require('bignumber.js'); 952 var utils = require('../utils/utils'); 953 var c = require('../utils/config'); 954 var SolidityParam = require('./param'); 955 956 957 /** 958 * Formats input value to byte representation of int 959 * If value is negative, return it's two's complement 960 * If the value is floating point, round it down 961 * 962 * @method formatInputInt 963 * @param {String|Number|BigNumber} value that needs to be formatted 964 * @returns {SolidityParam} 965 */ 966 var formatInputInt = function (value) { 967 BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE); 968 var result = utils.padLeft(utils.toTwosComplement(value).round().toString(16), 64); 969 return new SolidityParam(result); 970 }; 971 972 /** 973 * Formats input bytes 974 * 975 * @method formatInputBytes 976 * @param {String} 977 * @returns {SolidityParam} 978 */ 979 var formatInputBytes = function (value) { 980 var result = utils.toHex(value).substr(2); 981 var l = Math.floor((result.length + 63) / 64); 982 result = utils.padRight(result, l * 64); 983 return new SolidityParam(result); 984 }; 985 986 /** 987 * Formats input bytes 988 * 989 * @method formatDynamicInputBytes 990 * @param {String} 991 * @returns {SolidityParam} 992 */ 993 var formatInputDynamicBytes = function (value) { 994 var result = utils.toHex(value).substr(2); 995 var length = result.length / 2; 996 var l = Math.floor((result.length + 63) / 64); 997 result = utils.padRight(result, l * 64); 998 return new SolidityParam(formatInputInt(length).value + result); 999 }; 1000 1001 /** 1002 * Formats input value to byte representation of string 1003 * 1004 * @method formatInputString 1005 * @param {String} 1006 * @returns {SolidityParam} 1007 */ 1008 var formatInputString = function (value) { 1009 var result = utils.fromUtf8(value).substr(2); 1010 var length = result.length / 2; 1011 var l = Math.floor((result.length + 63) / 64); 1012 result = utils.padRight(result, l * 64); 1013 return new SolidityParam(formatInputInt(length).value + result); 1014 }; 1015 1016 /** 1017 * Formats input value to byte representation of bool 1018 * 1019 * @method formatInputBool 1020 * @param {Boolean} 1021 * @returns {SolidityParam} 1022 */ 1023 var formatInputBool = function (value) { 1024 var result = '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0'); 1025 return new SolidityParam(result); 1026 }; 1027 1028 /** 1029 * Formats input value to byte representation of real 1030 * Values are multiplied by 2^m and encoded as integers 1031 * 1032 * @method formatInputReal 1033 * @param {String|Number|BigNumber} 1034 * @returns {SolidityParam} 1035 */ 1036 var formatInputReal = function (value) { 1037 return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128))); 1038 }; 1039 1040 /** 1041 * Check if input value is negative 1042 * 1043 * @method signedIsNegative 1044 * @param {String} value is hex format 1045 * @returns {Boolean} true if it is negative, otherwise false 1046 */ 1047 var signedIsNegative = function (value) { 1048 return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1'; 1049 }; 1050 1051 /** 1052 * Formats right-aligned output bytes to int 1053 * 1054 * @method formatOutputInt 1055 * @param {SolidityParam} param 1056 * @returns {BigNumber} right-aligned output bytes formatted to big number 1057 */ 1058 var formatOutputInt = function (param) { 1059 var value = param.staticPart() || "0"; 1060 1061 // check if it's negative number 1062 // it it is, return two's complement 1063 if (signedIsNegative(value)) { 1064 return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1); 1065 } 1066 return new BigNumber(value, 16); 1067 }; 1068 1069 /** 1070 * Formats right-aligned output bytes to uint 1071 * 1072 * @method formatOutputUInt 1073 * @param {SolidityParam} 1074 * @returns {BigNumeber} right-aligned output bytes formatted to uint 1075 */ 1076 var formatOutputUInt = function (param) { 1077 var value = param.staticPart() || "0"; 1078 return new BigNumber(value, 16); 1079 }; 1080 1081 /** 1082 * Formats right-aligned output bytes to real 1083 * 1084 * @method formatOutputReal 1085 * @param {SolidityParam} 1086 * @returns {BigNumber} input bytes formatted to real 1087 */ 1088 var formatOutputReal = function (param) { 1089 return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128)); 1090 }; 1091 1092 /** 1093 * Formats right-aligned output bytes to ureal 1094 * 1095 * @method formatOutputUReal 1096 * @param {SolidityParam} 1097 * @returns {BigNumber} input bytes formatted to ureal 1098 */ 1099 var formatOutputUReal = function (param) { 1100 return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128)); 1101 }; 1102 1103 /** 1104 * Should be used to format output bool 1105 * 1106 * @method formatOutputBool 1107 * @param {SolidityParam} 1108 * @returns {Boolean} right-aligned input bytes formatted to bool 1109 */ 1110 var formatOutputBool = function (param) { 1111 return param.staticPart() === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false; 1112 }; 1113 1114 /** 1115 * Should be used to format output bytes 1116 * 1117 * @method formatOutputBytes 1118 * @param {SolidityParam} left-aligned hex representation of string 1119 * @returns {String} hex string 1120 */ 1121 var formatOutputBytes = function (param) { 1122 return '0x' + param.staticPart(); 1123 }; 1124 1125 /** 1126 * Should be used to format output bytes 1127 * 1128 * @method formatOutputDynamicBytes 1129 * @param {SolidityParam} left-aligned hex representation of string 1130 * @returns {String} hex string 1131 */ 1132 var formatOutputDynamicBytes = function (param) { 1133 var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2; 1134 return '0x' + param.dynamicPart().substr(64, length); 1135 }; 1136 1137 /** 1138 * Should be used to format output string 1139 * 1140 * @method formatOutputString 1141 * @param {SolidityParam} left-aligned hex representation of string 1142 * @returns {String} ascii string 1143 */ 1144 var formatOutputString = function (param) { 1145 var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2; 1146 return utils.toUtf8(param.dynamicPart().substr(64, length)); 1147 }; 1148 1149 /** 1150 * Should be used to format output address 1151 * 1152 * @method formatOutputAddress 1153 * @param {SolidityParam} right-aligned input bytes 1154 * @returns {String} address 1155 */ 1156 var formatOutputAddress = function (param) { 1157 var value = param.staticPart(); 1158 return "0x" + value.slice(value.length - 40, value.length); 1159 }; 1160 1161 module.exports = { 1162 formatInputInt: formatInputInt, 1163 formatInputBytes: formatInputBytes, 1164 formatInputDynamicBytes: formatInputDynamicBytes, 1165 formatInputString: formatInputString, 1166 formatInputBool: formatInputBool, 1167 formatInputReal: formatInputReal, 1168 formatOutputInt: formatOutputInt, 1169 formatOutputUInt: formatOutputUInt, 1170 formatOutputReal: formatOutputReal, 1171 formatOutputUReal: formatOutputUReal, 1172 formatOutputBool: formatOutputBool, 1173 formatOutputBytes: formatOutputBytes, 1174 formatOutputDynamicBytes: formatOutputDynamicBytes, 1175 formatOutputString: formatOutputString, 1176 formatOutputAddress: formatOutputAddress 1177 }; 1178 1179 1180 },{"../utils/config":18,"../utils/utils":20,"./param":11,"bignumber.js":"bignumber.js"}],10:[function(require,module,exports){ 1181 var f = require('./formatters'); 1182 var SolidityType = require('./type'); 1183 1184 /** 1185 * SolidityTypeInt is a prootype that represents int type 1186 * It matches: 1187 * int 1188 * int[] 1189 * int[4] 1190 * int[][] 1191 * int[3][] 1192 * int[][6][], ... 1193 * int32 1194 * int64[] 1195 * int8[4] 1196 * int256[][] 1197 * int[3][] 1198 * int64[][6][], ... 1199 */ 1200 var SolidityTypeInt = function () { 1201 this._inputFormatter = f.formatInputInt; 1202 this._outputFormatter = f.formatOutputInt; 1203 }; 1204 1205 SolidityTypeInt.prototype = new SolidityType({}); 1206 SolidityTypeInt.prototype.constructor = SolidityTypeInt; 1207 1208 SolidityTypeInt.prototype.isType = function (name) { 1209 return !!name.match(/^int([0-9]*)?(\[([0-9]*)\])*$/); 1210 }; 1211 1212 SolidityTypeInt.prototype.staticPartLength = function (name) { 1213 return 32 * this.staticArrayLength(name); 1214 }; 1215 1216 module.exports = SolidityTypeInt; 1217 1218 },{"./formatters":9,"./type":14}],11:[function(require,module,exports){ 1219 /* 1220 This file is part of web3.js. 1221 1222 web3.js is free software: you can redistribute it and/or modify 1223 it under the terms of the GNU Lesser General Public License as published by 1224 the Free Software Foundation, either version 3 of the License, or 1225 (at your option) any later version. 1226 1227 web3.js is distributed in the hope that it will be useful, 1228 but WITHOUT ANY WARRANTY; without even the implied warranty of 1229 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1230 GNU Lesser General Public License for more details. 1231 1232 You should have received a copy of the GNU Lesser General Public License 1233 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1234 */ 1235 /** 1236 * @file param.js 1237 * @author Marek Kotewicz <marek@ethdev.com> 1238 * @date 2015 1239 */ 1240 1241 var utils = require('../utils/utils'); 1242 1243 /** 1244 * SolidityParam object prototype. 1245 * Should be used when encoding, decoding solidity bytes 1246 */ 1247 var SolidityParam = function (value, offset) { 1248 this.value = value || ''; 1249 this.offset = offset; // offset in bytes 1250 }; 1251 1252 /** 1253 * This method should be used to get length of params's dynamic part 1254 * 1255 * @method dynamicPartLength 1256 * @returns {Number} length of dynamic part (in bytes) 1257 */ 1258 SolidityParam.prototype.dynamicPartLength = function () { 1259 return this.dynamicPart().length / 2; 1260 }; 1261 1262 /** 1263 * This method should be used to create copy of solidity param with different offset 1264 * 1265 * @method withOffset 1266 * @param {Number} offset length in bytes 1267 * @returns {SolidityParam} new solidity param with applied offset 1268 */ 1269 SolidityParam.prototype.withOffset = function (offset) { 1270 return new SolidityParam(this.value, offset); 1271 }; 1272 1273 /** 1274 * This method should be used to combine solidity params together 1275 * eg. when appending an array 1276 * 1277 * @method combine 1278 * @param {SolidityParam} param with which we should combine 1279 * @param {SolidityParam} result of combination 1280 */ 1281 SolidityParam.prototype.combine = function (param) { 1282 return new SolidityParam(this.value + param.value); 1283 }; 1284 1285 /** 1286 * This method should be called to check if param has dynamic size. 1287 * If it has, it returns true, otherwise false 1288 * 1289 * @method isDynamic 1290 * @returns {Boolean} 1291 */ 1292 SolidityParam.prototype.isDynamic = function () { 1293 return this.offset !== undefined; 1294 }; 1295 1296 /** 1297 * This method should be called to transform offset to bytes 1298 * 1299 * @method offsetAsBytes 1300 * @returns {String} bytes representation of offset 1301 */ 1302 SolidityParam.prototype.offsetAsBytes = function () { 1303 return !this.isDynamic() ? '' : utils.padLeft(utils.toTwosComplement(this.offset).toString(16), 64); 1304 }; 1305 1306 /** 1307 * This method should be called to get static part of param 1308 * 1309 * @method staticPart 1310 * @returns {String} offset if it is a dynamic param, otherwise value 1311 */ 1312 SolidityParam.prototype.staticPart = function () { 1313 if (!this.isDynamic()) { 1314 return this.value; 1315 } 1316 return this.offsetAsBytes(); 1317 }; 1318 1319 /** 1320 * This method should be called to get dynamic part of param 1321 * 1322 * @method dynamicPart 1323 * @returns {String} returns a value if it is a dynamic param, otherwise empty string 1324 */ 1325 SolidityParam.prototype.dynamicPart = function () { 1326 return this.isDynamic() ? this.value : ''; 1327 }; 1328 1329 /** 1330 * This method should be called to encode param 1331 * 1332 * @method encode 1333 * @returns {String} 1334 */ 1335 SolidityParam.prototype.encode = function () { 1336 return this.staticPart() + this.dynamicPart(); 1337 }; 1338 1339 /** 1340 * This method should be called to encode array of params 1341 * 1342 * @method encodeList 1343 * @param {Array[SolidityParam]} params 1344 * @returns {String} 1345 */ 1346 SolidityParam.encodeList = function (params) { 1347 1348 // updating offsets 1349 var totalOffset = params.length * 32; 1350 var offsetParams = params.map(function (param) { 1351 if (!param.isDynamic()) { 1352 return param; 1353 } 1354 var offset = totalOffset; 1355 totalOffset += param.dynamicPartLength(); 1356 return param.withOffset(offset); 1357 }); 1358 1359 // encode everything! 1360 return offsetParams.reduce(function (result, param) { 1361 return result + param.dynamicPart(); 1362 }, offsetParams.reduce(function (result, param) { 1363 return result + param.staticPart(); 1364 }, '')); 1365 }; 1366 1367 1368 1369 module.exports = SolidityParam; 1370 1371 1372 },{"../utils/utils":20}],12:[function(require,module,exports){ 1373 var f = require('./formatters'); 1374 var SolidityType = require('./type'); 1375 1376 /** 1377 * SolidityTypeReal is a prootype that represents real type 1378 * It matches: 1379 * real 1380 * real[] 1381 * real[4] 1382 * real[][] 1383 * real[3][] 1384 * real[][6][], ... 1385 * real32 1386 * real64[] 1387 * real8[4] 1388 * real256[][] 1389 * real[3][] 1390 * real64[][6][], ... 1391 */ 1392 var SolidityTypeReal = function () { 1393 this._inputFormatter = f.formatInputReal; 1394 this._outputFormatter = f.formatOutputReal; 1395 }; 1396 1397 SolidityTypeReal.prototype = new SolidityType({}); 1398 SolidityTypeReal.prototype.constructor = SolidityTypeReal; 1399 1400 SolidityTypeReal.prototype.isType = function (name) { 1401 return !!name.match(/real([0-9]*)?(\[([0-9]*)\])?/); 1402 }; 1403 1404 SolidityTypeReal.prototype.staticPartLength = function (name) { 1405 return 32 * this.staticArrayLength(name); 1406 }; 1407 1408 module.exports = SolidityTypeReal; 1409 1410 },{"./formatters":9,"./type":14}],13:[function(require,module,exports){ 1411 var f = require('./formatters'); 1412 var SolidityType = require('./type'); 1413 1414 var SolidityTypeString = function () { 1415 this._inputFormatter = f.formatInputString; 1416 this._outputFormatter = f.formatOutputString; 1417 }; 1418 1419 SolidityTypeString.prototype = new SolidityType({}); 1420 SolidityTypeString.prototype.constructor = SolidityTypeString; 1421 1422 SolidityTypeString.prototype.isType = function (name) { 1423 return !!name.match(/^string(\[([0-9]*)\])*$/); 1424 }; 1425 1426 SolidityTypeString.prototype.staticPartLength = function (name) { 1427 return 32 * this.staticArrayLength(name); 1428 }; 1429 1430 SolidityTypeString.prototype.isDynamicType = function () { 1431 return true; 1432 }; 1433 1434 module.exports = SolidityTypeString; 1435 1436 1437 },{"./formatters":9,"./type":14}],14:[function(require,module,exports){ 1438 var f = require('./formatters'); 1439 var SolidityParam = require('./param'); 1440 1441 /** 1442 * SolidityType prototype is used to encode/decode solidity params of certain type 1443 */ 1444 var SolidityType = function (config) { 1445 this._inputFormatter = config.inputFormatter; 1446 this._outputFormatter = config.outputFormatter; 1447 }; 1448 1449 /** 1450 * Should be used to determine if this SolidityType do match given name 1451 * 1452 * @method isType 1453 * @param {String} name 1454 * @return {Bool} true if type match this SolidityType, otherwise false 1455 */ 1456 SolidityType.prototype.isType = function (name) { 1457 throw "this method should be overrwritten for type " + name; 1458 }; 1459 1460 /** 1461 * Should be used to determine what is the length of static part in given type 1462 * 1463 * @method staticPartLength 1464 * @param {String} name 1465 * @return {Number} length of static part in bytes 1466 */ 1467 SolidityType.prototype.staticPartLength = function (name) { 1468 throw "this method should be overrwritten for type: " + name; 1469 }; 1470 1471 /** 1472 * Should be used to determine if type is dynamic array 1473 * eg: 1474 * "type[]" => true 1475 * "type[4]" => false 1476 * 1477 * @method isDynamicArray 1478 * @param {String} name 1479 * @return {Bool} true if the type is dynamic array 1480 */ 1481 SolidityType.prototype.isDynamicArray = function (name) { 1482 var nestedTypes = this.nestedTypes(name); 1483 return !!nestedTypes && !nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g); 1484 }; 1485 1486 /** 1487 * Should be used to determine if type is static array 1488 * eg: 1489 * "type[]" => false 1490 * "type[4]" => true 1491 * 1492 * @method isStaticArray 1493 * @param {String} name 1494 * @return {Bool} true if the type is static array 1495 */ 1496 SolidityType.prototype.isStaticArray = function (name) { 1497 var nestedTypes = this.nestedTypes(name); 1498 return !!nestedTypes && !!nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g); 1499 }; 1500 1501 /** 1502 * Should return length of static array 1503 * eg. 1504 * "int[32]" => 32 1505 * "int256[14]" => 14 1506 * "int[2][3]" => 3 1507 * "int" => 1 1508 * "int[1]" => 1 1509 * "int[]" => 1 1510 * 1511 * @method staticArrayLength 1512 * @param {String} name 1513 * @return {Number} static array length 1514 */ 1515 SolidityType.prototype.staticArrayLength = function (name) { 1516 var nestedTypes = this.nestedTypes(name); 1517 if (nestedTypes) { 1518 return parseInt(nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g) || 1); 1519 } 1520 return 1; 1521 }; 1522 1523 /** 1524 * Should return nested type 1525 * eg. 1526 * "int[32]" => "int" 1527 * "int256[14]" => "int256" 1528 * "int[2][3]" => "int[2]" 1529 * "int" => "int" 1530 * "int[]" => "int" 1531 * 1532 * @method nestedName 1533 * @param {String} name 1534 * @return {String} nested name 1535 */ 1536 SolidityType.prototype.nestedName = function (name) { 1537 // remove last [] in name 1538 var nestedTypes = this.nestedTypes(name); 1539 if (!nestedTypes) { 1540 return name; 1541 } 1542 1543 return name.substr(0, name.length - nestedTypes[nestedTypes.length - 1].length); 1544 }; 1545 1546 /** 1547 * Should return true if type has dynamic size by default 1548 * such types are "string", "bytes" 1549 * 1550 * @method isDynamicType 1551 * @param {String} name 1552 * @return {Bool} true if is dynamic, otherwise false 1553 */ 1554 SolidityType.prototype.isDynamicType = function () { 1555 return false; 1556 }; 1557 1558 /** 1559 * Should return array of nested types 1560 * eg. 1561 * "int[2][3][]" => ["[2]", "[3]", "[]"] 1562 * "int[] => ["[]"] 1563 * "int" => null 1564 * 1565 * @method nestedTypes 1566 * @param {String} name 1567 * @return {Array} array of nested types 1568 */ 1569 SolidityType.prototype.nestedTypes = function (name) { 1570 // return list of strings eg. "[]", "[3]", "[]", "[2]" 1571 return name.match(/(\[[0-9]*\])/g); 1572 }; 1573 1574 /** 1575 * Should be used to encode the value 1576 * 1577 * @method encode 1578 * @param {Object} value 1579 * @param {String} name 1580 * @return {String} encoded value 1581 */ 1582 SolidityType.prototype.encode = function (value, name) { 1583 var self = this; 1584 if (this.isDynamicArray(name)) { 1585 1586 return (function () { 1587 var length = value.length; // in int 1588 var nestedName = self.nestedName(name); 1589 1590 var result = []; 1591 result.push(f.formatInputInt(length).encode()); 1592 1593 value.forEach(function (v) { 1594 result.push(self.encode(v, nestedName)); 1595 }); 1596 1597 return result; 1598 })(); 1599 1600 } else if (this.isStaticArray(name)) { 1601 1602 return (function () { 1603 var length = self.staticArrayLength(name); // in int 1604 var nestedName = self.nestedName(name); 1605 1606 var result = []; 1607 for (var i = 0; i < length; i++) { 1608 result.push(self.encode(value[i], nestedName)); 1609 } 1610 1611 return result; 1612 })(); 1613 1614 } 1615 1616 return this._inputFormatter(value, name).encode(); 1617 }; 1618 1619 /** 1620 * Should be used to decode value from bytes 1621 * 1622 * @method decode 1623 * @param {String} bytes 1624 * @param {Number} offset in bytes 1625 * @param {String} name type name 1626 * @returns {Object} decoded value 1627 */ 1628 SolidityType.prototype.decode = function (bytes, offset, name) { 1629 var self = this; 1630 1631 if (this.isDynamicArray(name)) { 1632 1633 return (function () { 1634 var arrayOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes 1635 var length = parseInt('0x' + bytes.substr(arrayOffset * 2, 64)); // in int 1636 var arrayStart = arrayOffset + 32; // array starts after length; // in bytes 1637 1638 var nestedName = self.nestedName(name); 1639 var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes 1640 var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32; 1641 var result = []; 1642 1643 for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) { 1644 result.push(self.decode(bytes, arrayStart + i, nestedName)); 1645 } 1646 1647 return result; 1648 })(); 1649 1650 } else if (this.isStaticArray(name)) { 1651 1652 return (function () { 1653 var length = self.staticArrayLength(name); // in int 1654 var arrayStart = offset; // in bytes 1655 1656 var nestedName = self.nestedName(name); 1657 var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes 1658 var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32; 1659 var result = []; 1660 1661 for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) { 1662 result.push(self.decode(bytes, arrayStart + i, nestedName)); 1663 } 1664 1665 return result; 1666 })(); 1667 } else if (this.isDynamicType(name)) { 1668 1669 return (function () { 1670 var dynamicOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes 1671 var length = parseInt('0x' + bytes.substr(dynamicOffset * 2, 64)); // in bytes 1672 var roundedLength = Math.floor((length + 31) / 32); // in int 1673 1674 return self._outputFormatter(new SolidityParam(bytes.substr(dynamicOffset * 2, ( 1 + roundedLength) * 64), 0)); 1675 })(); 1676 } 1677 1678 var length = this.staticPartLength(name); 1679 return this._outputFormatter(new SolidityParam(bytes.substr(offset * 2, length * 2))); 1680 }; 1681 1682 module.exports = SolidityType; 1683 1684 },{"./formatters":9,"./param":11}],15:[function(require,module,exports){ 1685 var f = require('./formatters'); 1686 var SolidityType = require('./type'); 1687 1688 /** 1689 * SolidityTypeUInt is a prootype that represents uint type 1690 * It matches: 1691 * uint 1692 * uint[] 1693 * uint[4] 1694 * uint[][] 1695 * uint[3][] 1696 * uint[][6][], ... 1697 * uint32 1698 * uint64[] 1699 * uint8[4] 1700 * uint256[][] 1701 * uint[3][] 1702 * uint64[][6][], ... 1703 */ 1704 var SolidityTypeUInt = function () { 1705 this._inputFormatter = f.formatInputInt; 1706 this._outputFormatter = f.formatOutputUInt; 1707 }; 1708 1709 SolidityTypeUInt.prototype = new SolidityType({}); 1710 SolidityTypeUInt.prototype.constructor = SolidityTypeUInt; 1711 1712 SolidityTypeUInt.prototype.isType = function (name) { 1713 return !!name.match(/^uint([0-9]*)?(\[([0-9]*)\])*$/); 1714 }; 1715 1716 SolidityTypeUInt.prototype.staticPartLength = function (name) { 1717 return 32 * this.staticArrayLength(name); 1718 }; 1719 1720 module.exports = SolidityTypeUInt; 1721 1722 },{"./formatters":9,"./type":14}],16:[function(require,module,exports){ 1723 var f = require('./formatters'); 1724 var SolidityType = require('./type'); 1725 1726 /** 1727 * SolidityTypeUReal is a prootype that represents ureal type 1728 * It matches: 1729 * ureal 1730 * ureal[] 1731 * ureal[4] 1732 * ureal[][] 1733 * ureal[3][] 1734 * ureal[][6][], ... 1735 * ureal32 1736 * ureal64[] 1737 * ureal8[4] 1738 * ureal256[][] 1739 * ureal[3][] 1740 * ureal64[][6][], ... 1741 */ 1742 var SolidityTypeUReal = function () { 1743 this._inputFormatter = f.formatInputReal; 1744 this._outputFormatter = f.formatOutputUReal; 1745 }; 1746 1747 SolidityTypeUReal.prototype = new SolidityType({}); 1748 SolidityTypeUReal.prototype.constructor = SolidityTypeUReal; 1749 1750 SolidityTypeUReal.prototype.isType = function (name) { 1751 return !!name.match(/^ureal([0-9]*)?(\[([0-9]*)\])*$/); 1752 }; 1753 1754 SolidityTypeUReal.prototype.staticPartLength = function (name) { 1755 return 32 * this.staticArrayLength(name); 1756 }; 1757 1758 module.exports = SolidityTypeUReal; 1759 1760 },{"./formatters":9,"./type":14}],17:[function(require,module,exports){ 1761 'use strict'; 1762 1763 // go env doesn't have and need XMLHttpRequest 1764 if (typeof XMLHttpRequest === 'undefined') { 1765 exports.XMLHttpRequest = {}; 1766 } else { 1767 exports.XMLHttpRequest = XMLHttpRequest; // jshint ignore:line 1768 } 1769 1770 1771 },{}],18:[function(require,module,exports){ 1772 /* 1773 This file is part of web3.js. 1774 1775 web3.js is free software: you can redistribute it and/or modify 1776 it under the terms of the GNU Lesser General Public License as published by 1777 the Free Software Foundation, either version 3 of the License, or 1778 (at your option) any later version. 1779 1780 web3.js is distributed in the hope that it will be useful, 1781 but WITHOUT ANY WARRANTY; without even the implied warranty of 1782 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1783 GNU Lesser General Public License for more details. 1784 1785 You should have received a copy of the GNU Lesser General Public License 1786 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1787 */ 1788 /** @file config.js 1789 * @authors: 1790 * Marek Kotewicz <marek@ethdev.com> 1791 * @date 2015 1792 */ 1793 1794 /** 1795 * Utils 1796 * 1797 * @module utils 1798 */ 1799 1800 /** 1801 * Utility functions 1802 * 1803 * @class [utils] config 1804 * @constructor 1805 */ 1806 1807 1808 /// required to define ETH_BIGNUMBER_ROUNDING_MODE 1809 var BigNumber = require('bignumber.js'); 1810 1811 var ETH_UNITS = [ 1812 'wei', 1813 'kwei', 1814 'Mwei', 1815 'Gwei', 1816 'szabo', 1817 'finney', 1818 'femtoether', 1819 'picoether', 1820 'nanoether', 1821 'microether', 1822 'milliether', 1823 'nano', 1824 'micro', 1825 'milli', 1826 'ether', 1827 'grand', 1828 'Mether', 1829 'Gether', 1830 'Tether', 1831 'Pether', 1832 'Eether', 1833 'Zether', 1834 'Yether', 1835 'Nether', 1836 'Dether', 1837 'Vether', 1838 'Uether' 1839 ]; 1840 1841 module.exports = { 1842 ETH_PADDING: 32, 1843 ETH_SIGNATURE_LENGTH: 4, 1844 ETH_UNITS: ETH_UNITS, 1845 ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN }, 1846 ETH_POLLING_TIMEOUT: 1000/2, 1847 defaultBlock: 'latest', 1848 defaultAccount: undefined 1849 }; 1850 1851 1852 },{"bignumber.js":"bignumber.js"}],19:[function(require,module,exports){ 1853 /* 1854 This file is part of web3.js. 1855 1856 web3.js is free software: you can redistribute it and/or modify 1857 it under the terms of the GNU Lesser General Public License as published by 1858 the Free Software Foundation, either version 3 of the License, or 1859 (at your option) any later version. 1860 1861 web3.js is distributed in the hope that it will be useful, 1862 but WITHOUT ANY WARRANTY; without even the implied warranty of 1863 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1864 GNU Lesser General Public License for more details. 1865 1866 You should have received a copy of the GNU Lesser General Public License 1867 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1868 */ 1869 /** 1870 * @file sha3.js 1871 * @author Marek Kotewicz <marek@ethdev.com> 1872 * @date 2015 1873 */ 1874 1875 var CryptoJS = require('crypto-js'); 1876 var sha3 = require('crypto-js/sha3'); 1877 1878 module.exports = function (value, options) { 1879 if (options && options.encoding === 'hex') { 1880 if (value.length > 2 && value.substr(0, 2) === '0x') { 1881 value = value.substr(2); 1882 } 1883 value = CryptoJS.enc.Hex.parse(value); 1884 } 1885 1886 return sha3(value, { 1887 outputLength: 256 1888 }).toString(); 1889 }; 1890 1891 1892 },{"crypto-js":58,"crypto-js/sha3":79}],20:[function(require,module,exports){ 1893 /* 1894 This file is part of web3.js. 1895 1896 web3.js is free software: you can redistribute it and/or modify 1897 it under the terms of the GNU Lesser General Public License as published by 1898 the Free Software Foundation, either version 3 of the License, or 1899 (at your option) any later version. 1900 1901 web3.js is distributed in the hope that it will be useful, 1902 but WITHOUT ANY WARRANTY; without even the implied warranty of 1903 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1904 GNU Lesser General Public License for more details. 1905 1906 You should have received a copy of the GNU Lesser General Public License 1907 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1908 */ 1909 /** 1910 * @file utils.js 1911 * @author Marek Kotewicz <marek@ethdev.com> 1912 * @date 2015 1913 */ 1914 1915 /** 1916 * Utils 1917 * 1918 * @module utils 1919 */ 1920 1921 /** 1922 * Utility functions 1923 * 1924 * @class [utils] utils 1925 * @constructor 1926 */ 1927 1928 1929 var BigNumber = require('bignumber.js'); 1930 var sha3 = require('./sha3.js'); 1931 var utf8 = require('utf8'); 1932 1933 var unitMap = { 1934 'noether': '0', 1935 'wei': '1', 1936 'kwei': '1000', 1937 'Kwei': '1000', 1938 'babbage': '1000', 1939 'femtoether': '1000', 1940 'mwei': '1000000', 1941 'Mwei': '1000000', 1942 'lovelace': '1000000', 1943 'picoether': '1000000', 1944 'gwei': '1000000000', 1945 'Gwei': '1000000000', 1946 'shannon': '1000000000', 1947 'nanoether': '1000000000', 1948 'nano': '1000000000', 1949 'szabo': '1000000000000', 1950 'microether': '1000000000000', 1951 'micro': '1000000000000', 1952 'finney': '1000000000000000', 1953 'milliether': '1000000000000000', 1954 'milli': '1000000000000000', 1955 'ether': '1000000000000000000', 1956 'kether': '1000000000000000000000', 1957 'grand': '1000000000000000000000', 1958 'mether': '1000000000000000000000000', 1959 'gether': '1000000000000000000000000000', 1960 'tether': '1000000000000000000000000000000' 1961 }; 1962 1963 /** 1964 * Should be called to pad string to expected length 1965 * 1966 * @method padLeft 1967 * @param {String} string to be padded 1968 * @param {Number} characters that result string should have 1969 * @param {String} sign, by default 0 1970 * @returns {String} right aligned string 1971 */ 1972 var padLeft = function (string, chars, sign) { 1973 return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; 1974 }; 1975 1976 /** 1977 * Should be called to pad string to expected length 1978 * 1979 * @method padRight 1980 * @param {String} string to be padded 1981 * @param {Number} characters that result string should have 1982 * @param {String} sign, by default 0 1983 * @returns {String} right aligned string 1984 */ 1985 var padRight = function (string, chars, sign) { 1986 return string + (new Array(chars - string.length + 1).join(sign ? sign : "0")); 1987 }; 1988 1989 /** 1990 * Should be called to get utf8 from it's hex representation 1991 * 1992 * @method toUtf8 1993 * @param {String} string in hex 1994 * @returns {String} ascii string representation of hex value 1995 */ 1996 var toUtf8 = function(hex) { 1997 // Find termination 1998 var str = ""; 1999 var i = 0, l = hex.length; 2000 if (hex.substring(0, 2) === '0x') { 2001 i = 2; 2002 } 2003 for (; i < l; i+=2) { 2004 var code = parseInt(hex.substr(i, 2), 16); 2005 if (code === 0) 2006 break; 2007 str += String.fromCharCode(code); 2008 } 2009 2010 return utf8.decode(str); 2011 }; 2012 2013 /** 2014 * Should be called to get ascii from it's hex representation 2015 * 2016 * @method toAscii 2017 * @param {String} string in hex 2018 * @returns {String} ascii string representation of hex value 2019 */ 2020 var toAscii = function(hex) { 2021 // Find termination 2022 var str = ""; 2023 var i = 0, l = hex.length; 2024 if (hex.substring(0, 2) === '0x') { 2025 i = 2; 2026 } 2027 for (; i < l; i+=2) { 2028 var code = parseInt(hex.substr(i, 2), 16); 2029 str += String.fromCharCode(code); 2030 } 2031 2032 return str; 2033 }; 2034 2035 /** 2036 * Should be called to get hex representation (prefixed by 0x) of utf8 string 2037 * 2038 * @method fromUtf8 2039 * @param {String} string 2040 * @param {Number} optional padding 2041 * @returns {String} hex representation of input string 2042 */ 2043 var fromUtf8 = function(str) { 2044 str = utf8.encode(str); 2045 var hex = ""; 2046 for(var i = 0; i < str.length; i++) { 2047 var code = str.charCodeAt(i); 2048 if (code === 0) 2049 break; 2050 var n = code.toString(16); 2051 hex += n.length < 2 ? '0' + n : n; 2052 } 2053 2054 return "0x" + hex; 2055 }; 2056 2057 /** 2058 * Should be called to get hex representation (prefixed by 0x) of ascii string 2059 * 2060 * @method fromAscii 2061 * @param {String} string 2062 * @param {Number} optional padding 2063 * @returns {String} hex representation of input string 2064 */ 2065 var fromAscii = function(str) { 2066 var hex = ""; 2067 for(var i = 0; i < str.length; i++) { 2068 var code = str.charCodeAt(i); 2069 var n = code.toString(16); 2070 hex += n.length < 2 ? '0' + n : n; 2071 } 2072 2073 return "0x" + hex; 2074 }; 2075 2076 /** 2077 * Should be used to create full function/event name from json abi 2078 * 2079 * @method transformToFullName 2080 * @param {Object} json-abi 2081 * @return {String} full fnction/event name 2082 */ 2083 var transformToFullName = function (json) { 2084 if (json.name.indexOf('(') !== -1) { 2085 return json.name; 2086 } 2087 2088 var typeName = json.inputs.map(function(i){return i.type; }).join(); 2089 return json.name + '(' + typeName + ')'; 2090 }; 2091 2092 /** 2093 * Should be called to get display name of contract function 2094 * 2095 * @method extractDisplayName 2096 * @param {String} name of function/event 2097 * @returns {String} display name for function/event eg. multiply(uint256) -> multiply 2098 */ 2099 var extractDisplayName = function (name) { 2100 var length = name.indexOf('('); 2101 return length !== -1 ? name.substr(0, length) : name; 2102 }; 2103 2104 /// @returns overloaded part of function/event name 2105 var extractTypeName = function (name) { 2106 /// TODO: make it invulnerable 2107 var length = name.indexOf('('); 2108 return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : ""; 2109 }; 2110 2111 /** 2112 * Converts value to it's decimal representation in string 2113 * 2114 * @method toDecimal 2115 * @param {String|Number|BigNumber} 2116 * @return {String} 2117 */ 2118 var toDecimal = function (value) { 2119 return toBigNumber(value).toNumber(); 2120 }; 2121 2122 /** 2123 * Converts value to it's hex representation 2124 * 2125 * @method fromDecimal 2126 * @param {String|Number|BigNumber} 2127 * @return {String} 2128 */ 2129 var fromDecimal = function (value) { 2130 var number = toBigNumber(value); 2131 var result = number.toString(16); 2132 2133 return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result; 2134 }; 2135 2136 /** 2137 * Auto converts any given value into it's hex representation. 2138 * 2139 * And even stringifys objects before. 2140 * 2141 * @method toHex 2142 * @param {String|Number|BigNumber|Object} 2143 * @return {String} 2144 */ 2145 var toHex = function (val) { 2146 /*jshint maxcomplexity: 8 */ 2147 2148 if (isBoolean(val)) 2149 return fromDecimal(+val); 2150 2151 if (isBigNumber(val)) 2152 return fromDecimal(val); 2153 2154 if (isObject(val)) 2155 return fromUtf8(JSON.stringify(val)); 2156 2157 // if its a negative number, pass it through fromDecimal 2158 if (isString(val)) { 2159 if (val.indexOf('-0x') === 0) 2160 return fromDecimal(val); 2161 else if(val.indexOf('0x') === 0) 2162 return val; 2163 else if (!isFinite(val)) 2164 return fromAscii(val); 2165 } 2166 2167 return fromDecimal(val); 2168 }; 2169 2170 /** 2171 * Returns value of unit in Wei 2172 * 2173 * @method getValueOfUnit 2174 * @param {String} unit the unit to convert to, default ether 2175 * @returns {BigNumber} value of the unit (in Wei) 2176 * @throws error if the unit is not correct:w 2177 */ 2178 var getValueOfUnit = function (unit) { 2179 unit = unit ? unit.toLowerCase() : 'ether'; 2180 var unitValue = unitMap[unit]; 2181 if (unitValue === undefined) { 2182 throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2)); 2183 } 2184 return new BigNumber(unitValue, 10); 2185 }; 2186 2187 /** 2188 * Takes a number of wei and converts it to any other ether unit. 2189 * 2190 * Possible units are: 2191 * SI Short SI Full Effigy Other 2192 * - kwei femtoether babbage 2193 * - mwei picoether lovelace 2194 * - gwei nanoether shannon nano 2195 * - -- microether szabo micro 2196 * - -- milliether finney milli 2197 * - ether -- -- 2198 * - kether -- grand 2199 * - mether 2200 * - gether 2201 * - tether 2202 * 2203 * @method fromWei 2204 * @param {Number|String} number can be a number, number string or a HEX of a decimal 2205 * @param {String} unit the unit to convert to, default ether 2206 * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number 2207 */ 2208 var fromWei = function(number, unit) { 2209 var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); 2210 2211 return isBigNumber(number) ? returnValue : returnValue.toString(10); 2212 }; 2213 2214 /** 2215 * Takes a number of a unit and converts it to wei. 2216 * 2217 * Possible units are: 2218 * SI Short SI Full Effigy Other 2219 * - kwei femtoether babbage 2220 * - mwei picoether lovelace 2221 * - gwei nanoether shannon nano 2222 * - -- microether szabo micro 2223 * - -- microether szabo micro 2224 * - -- milliether finney milli 2225 * - ether -- -- 2226 * - kether -- grand 2227 * - mether 2228 * - gether 2229 * - tether 2230 * 2231 * @method toWei 2232 * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal 2233 * @param {String} unit the unit to convert from, default ether 2234 * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number 2235 */ 2236 var toWei = function(number, unit) { 2237 var returnValue = toBigNumber(number).times(getValueOfUnit(unit)); 2238 2239 return isBigNumber(number) ? returnValue : returnValue.toString(10); 2240 }; 2241 2242 /** 2243 * Takes an input and transforms it into an bignumber 2244 * 2245 * @method toBigNumber 2246 * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber 2247 * @return {BigNumber} BigNumber 2248 */ 2249 var toBigNumber = function(number) { 2250 /*jshint maxcomplexity:5 */ 2251 number = number || 0; 2252 if (isBigNumber(number)) 2253 return number; 2254 2255 if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) { 2256 return new BigNumber(number.replace('0x',''), 16); 2257 } 2258 2259 return new BigNumber(number.toString(10), 10); 2260 }; 2261 2262 /** 2263 * Takes and input transforms it into bignumber and if it is negative value, into two's complement 2264 * 2265 * @method toTwosComplement 2266 * @param {Number|String|BigNumber} 2267 * @return {BigNumber} 2268 */ 2269 var toTwosComplement = function (number) { 2270 var bigNumber = toBigNumber(number); 2271 if (bigNumber.lessThan(0)) { 2272 return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1); 2273 } 2274 return bigNumber; 2275 }; 2276 2277 /** 2278 * Checks if the given string is strictly an address 2279 * 2280 * @method isStrictAddress 2281 * @param {String} address the given HEX adress 2282 * @return {Boolean} 2283 */ 2284 var isStrictAddress = function (address) { 2285 return /^0x[0-9a-f]{40}$/i.test(address); 2286 }; 2287 2288 /** 2289 * Checks if the given string is an address 2290 * 2291 * @method isAddress 2292 * @param {String} address the given HEX adress 2293 * @return {Boolean} 2294 */ 2295 var isAddress = function (address) { 2296 if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { 2297 // check if it has the basic requirements of an address 2298 return false; 2299 } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { 2300 // If it's all small caps or all all caps, return true 2301 return true; 2302 } else { 2303 // Otherwise check each case 2304 return isChecksumAddress(address); 2305 } 2306 }; 2307 2308 2309 2310 /** 2311 * Checks if the given string is a checksummed address 2312 * 2313 * @method isChecksumAddress 2314 * @param {String} address the given HEX adress 2315 * @return {Boolean} 2316 */ 2317 var isChecksumAddress = function (address) { 2318 // Check each case 2319 address = address.replace('0x',''); 2320 var addressHash = sha3(address.toLowerCase()); 2321 2322 for (var i = 0; i < 40; i++ ) { 2323 // the nth letter should be uppercase if the nth digit of casemap is 1 2324 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { 2325 return false; 2326 } 2327 } 2328 return true; 2329 }; 2330 2331 2332 2333 /** 2334 * Makes a checksum address 2335 * 2336 * @method toChecksumAddress 2337 * @param {String} address the given HEX adress 2338 * @return {String} 2339 */ 2340 var toChecksumAddress = function (address) { 2341 if (typeof address === 'undefined') return ''; 2342 2343 address = address.toLowerCase().replace('0x',''); 2344 var addressHash = sha3(address); 2345 var checksumAddress = '0x'; 2346 2347 for (var i = 0; i < address.length; i++ ) { 2348 // If ith character is 9 to f then make it uppercase 2349 if (parseInt(addressHash[i], 16) > 7) { 2350 checksumAddress += address[i].toUpperCase(); 2351 } else { 2352 checksumAddress += address[i]; 2353 } 2354 } 2355 return checksumAddress; 2356 }; 2357 2358 /** 2359 * Transforms given string to valid 20 bytes-length addres with 0x prefix 2360 * 2361 * @method toAddress 2362 * @param {String} address 2363 * @return {String} formatted address 2364 */ 2365 var toAddress = function (address) { 2366 if (isStrictAddress(address)) { 2367 return address; 2368 } 2369 2370 if (/^[0-9a-f]{40}$/.test(address)) { 2371 return '0x' + address; 2372 } 2373 2374 return '0x' + padLeft(toHex(address).substr(2), 40); 2375 }; 2376 2377 /** 2378 * Returns true if object is BigNumber, otherwise false 2379 * 2380 * @method isBigNumber 2381 * @param {Object} 2382 * @return {Boolean} 2383 */ 2384 var isBigNumber = function (object) { 2385 return object instanceof BigNumber || 2386 (object && object.constructor && object.constructor.name === 'BigNumber'); 2387 }; 2388 2389 /** 2390 * Returns true if object is string, otherwise false 2391 * 2392 * @method isString 2393 * @param {Object} 2394 * @return {Boolean} 2395 */ 2396 var isString = function (object) { 2397 return typeof object === 'string' || 2398 (object && object.constructor && object.constructor.name === 'String'); 2399 }; 2400 2401 /** 2402 * Returns true if object is function, otherwise false 2403 * 2404 * @method isFunction 2405 * @param {Object} 2406 * @return {Boolean} 2407 */ 2408 var isFunction = function (object) { 2409 return typeof object === 'function'; 2410 }; 2411 2412 /** 2413 * Returns true if object is Objet, otherwise false 2414 * 2415 * @method isObject 2416 * @param {Object} 2417 * @return {Boolean} 2418 */ 2419 var isObject = function (object) { 2420 return typeof object === 'object'; 2421 }; 2422 2423 /** 2424 * Returns true if object is boolean, otherwise false 2425 * 2426 * @method isBoolean 2427 * @param {Object} 2428 * @return {Boolean} 2429 */ 2430 var isBoolean = function (object) { 2431 return typeof object === 'boolean'; 2432 }; 2433 2434 /** 2435 * Returns true if object is array, otherwise false 2436 * 2437 * @method isArray 2438 * @param {Object} 2439 * @return {Boolean} 2440 */ 2441 var isArray = function (object) { 2442 return object instanceof Array; 2443 }; 2444 2445 /** 2446 * Returns true if given string is valid json object 2447 * 2448 * @method isJson 2449 * @param {String} 2450 * @return {Boolean} 2451 */ 2452 var isJson = function (str) { 2453 try { 2454 return !!JSON.parse(str); 2455 } catch (e) { 2456 return false; 2457 } 2458 }; 2459 2460 module.exports = { 2461 padLeft: padLeft, 2462 padRight: padRight, 2463 toHex: toHex, 2464 toDecimal: toDecimal, 2465 fromDecimal: fromDecimal, 2466 toUtf8: toUtf8, 2467 toAscii: toAscii, 2468 fromUtf8: fromUtf8, 2469 fromAscii: fromAscii, 2470 transformToFullName: transformToFullName, 2471 extractDisplayName: extractDisplayName, 2472 extractTypeName: extractTypeName, 2473 toWei: toWei, 2474 fromWei: fromWei, 2475 toBigNumber: toBigNumber, 2476 toTwosComplement: toTwosComplement, 2477 toAddress: toAddress, 2478 isBigNumber: isBigNumber, 2479 isStrictAddress: isStrictAddress, 2480 isAddress: isAddress, 2481 isChecksumAddress: isChecksumAddress, 2482 toChecksumAddress: toChecksumAddress, 2483 isFunction: isFunction, 2484 isString: isString, 2485 isObject: isObject, 2486 isBoolean: isBoolean, 2487 isArray: isArray, 2488 isJson: isJson 2489 }; 2490 2491 },{"./sha3.js":19,"bignumber.js":"bignumber.js","utf8":84}],21:[function(require,module,exports){ 2492 module.exports={ 2493 "version": "0.15.3" 2494 } 2495 2496 },{}],22:[function(require,module,exports){ 2497 /* 2498 This file is part of web3.js. 2499 2500 web3.js is free software: you can redistribute it and/or modify 2501 it under the terms of the GNU Lesser General Public License as published by 2502 the Free Software Foundation, either version 3 of the License, or 2503 (at your option) any later version. 2504 2505 web3.js is distributed in the hope that it will be useful, 2506 but WITHOUT ANY WARRANTY; without even the implied warranty of 2507 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2508 GNU Lesser General Public License for more details. 2509 2510 You should have received a copy of the GNU Lesser General Public License 2511 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2512 */ 2513 /** 2514 * @file web3.js 2515 * @authors: 2516 * Jeffrey Wilcke <jeff@ethdev.com> 2517 * Marek Kotewicz <marek@ethdev.com> 2518 * Marian Oancea <marian@ethdev.com> 2519 * Fabian Vogelsteller <fabian@ethdev.com> 2520 * Gav Wood <g@ethdev.com> 2521 * @date 2014 2522 */ 2523 2524 var RequestManager = require('./web3/requestmanager'); 2525 var Iban = require('./web3/iban'); 2526 var Eth = require('./web3/methods/eth'); 2527 var DB = require('./web3/methods/db'); 2528 var Shh = require('./web3/methods/shh'); 2529 var Net = require('./web3/methods/net'); 2530 var Personal = require('./web3/methods/personal'); 2531 var Settings = require('./web3/settings'); 2532 var version = require('./version.json'); 2533 var utils = require('./utils/utils'); 2534 var sha3 = require('./utils/sha3'); 2535 var extend = require('./web3/extend'); 2536 var Batch = require('./web3/batch'); 2537 var Property = require('./web3/property'); 2538 var HttpProvider = require('./web3/httpprovider'); 2539 var IpcProvider = require('./web3/ipcprovider'); 2540 2541 2542 2543 function Web3 (provider) { 2544 this._requestManager = new RequestManager(provider); 2545 this.currentProvider = provider; 2546 this.eth = new Eth(this); 2547 this.db = new DB(this); 2548 this.shh = new Shh(this); 2549 this.net = new Net(this); 2550 this.personal = new Personal(this); 2551 this.settings = new Settings(); 2552 this.version = { 2553 api: version.version 2554 }; 2555 this.providers = { 2556 HttpProvider: HttpProvider, 2557 IpcProvider: IpcProvider 2558 }; 2559 this._extend = extend(this); 2560 this._extend({ 2561 properties: properties() 2562 }); 2563 } 2564 2565 // expose providers on the class 2566 Web3.providers = { 2567 HttpProvider: HttpProvider, 2568 IpcProvider: IpcProvider 2569 }; 2570 2571 Web3.prototype.setProvider = function (provider) { 2572 this._requestManager.setProvider(provider); 2573 this.currentProvider = provider; 2574 }; 2575 2576 Web3.prototype.reset = function (keepIsSyncing) { 2577 this._requestManager.reset(keepIsSyncing); 2578 this.settings = new Settings(); 2579 }; 2580 2581 Web3.prototype.toHex = utils.toHex; 2582 Web3.prototype.toAscii = utils.toAscii; 2583 Web3.prototype.toUtf8 = utils.toUtf8; 2584 Web3.prototype.fromAscii = utils.fromAscii; 2585 Web3.prototype.fromUtf8 = utils.fromUtf8; 2586 Web3.prototype.toDecimal = utils.toDecimal; 2587 Web3.prototype.fromDecimal = utils.fromDecimal; 2588 Web3.prototype.toBigNumber = utils.toBigNumber; 2589 Web3.prototype.toWei = utils.toWei; 2590 Web3.prototype.fromWei = utils.fromWei; 2591 Web3.prototype.isAddress = utils.isAddress; 2592 Web3.prototype.isChecksumAddress = utils.isChecksumAddress; 2593 Web3.prototype.toChecksumAddress = utils.toChecksumAddress; 2594 Web3.prototype.isIBAN = utils.isIBAN; 2595 2596 2597 Web3.prototype.sha3 = function(string, options) { 2598 return '0x' + sha3(string, options); 2599 }; 2600 2601 /** 2602 * Transforms direct icap to address 2603 */ 2604 Web3.prototype.fromICAP = function (icap) { 2605 var iban = new Iban(icap); 2606 return iban.address(); 2607 }; 2608 2609 var properties = function () { 2610 return [ 2611 new Property({ 2612 name: 'version.node', 2613 getter: 'web3_clientVersion' 2614 }), 2615 new Property({ 2616 name: 'version.network', 2617 getter: 'net_version', 2618 inputFormatter: utils.toDecimal 2619 }), 2620 new Property({ 2621 name: 'version.ethereum', 2622 getter: 'eth_protocolVersion', 2623 inputFormatter: utils.toDecimal 2624 }), 2625 new Property({ 2626 name: 'version.whisper', 2627 getter: 'shh_version', 2628 inputFormatter: utils.toDecimal 2629 }) 2630 ]; 2631 }; 2632 2633 Web3.prototype.isConnected = function(){ 2634 return (this.currentProvider && this.currentProvider.isConnected()); 2635 }; 2636 2637 Web3.prototype.createBatch = function () { 2638 return new Batch(this); 2639 }; 2640 2641 module.exports = Web3; 2642 2643 2644 },{"./utils/sha3":19,"./utils/utils":20,"./version.json":21,"./web3/batch":24,"./web3/extend":28,"./web3/httpprovider":32,"./web3/iban":33,"./web3/ipcprovider":34,"./web3/methods/db":37,"./web3/methods/eth":38,"./web3/methods/net":39,"./web3/methods/personal":40,"./web3/methods/shh":41,"./web3/property":44,"./web3/requestmanager":45,"./web3/settings":46}],23:[function(require,module,exports){ 2645 /* 2646 This file is part of web3.js. 2647 2648 web3.js is free software: you can redistribute it and/or modify 2649 it under the terms of the GNU Lesser General Public License as published by 2650 the Free Software Foundation, either version 3 of the License, or 2651 (at your option) any later version. 2652 2653 web3.js is distributed in the hope that it will be useful, 2654 but WITHOUT ANY WARRANTY; without even the implied warranty of 2655 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2656 GNU Lesser General Public License for more details. 2657 2658 You should have received a copy of the GNU Lesser General Public License 2659 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2660 */ 2661 /** 2662 * @file allevents.js 2663 * @author Marek Kotewicz <marek@ethdev.com> 2664 * @date 2014 2665 */ 2666 2667 var sha3 = require('../utils/sha3'); 2668 var SolidityEvent = require('./event'); 2669 var formatters = require('./formatters'); 2670 var utils = require('../utils/utils'); 2671 var Filter = require('./filter'); 2672 var watches = require('./methods/watches'); 2673 2674 var AllSolidityEvents = function (requestManager, json, address) { 2675 this._requestManager = requestManager; 2676 this._json = json; 2677 this._address = address; 2678 }; 2679 2680 AllSolidityEvents.prototype.encode = function (options) { 2681 options = options || {}; 2682 var result = {}; 2683 2684 ['fromBlock', 'toBlock'].filter(function (f) { 2685 return options[f] !== undefined; 2686 }).forEach(function (f) { 2687 result[f] = formatters.inputBlockNumberFormatter(options[f]); 2688 }); 2689 2690 result.address = this._address; 2691 2692 return result; 2693 }; 2694 2695 AllSolidityEvents.prototype.decode = function (data) { 2696 data.data = data.data || ''; 2697 data.topics = data.topics || []; 2698 2699 var eventTopic = data.topics[0].slice(2); 2700 var match = this._json.filter(function (j) { 2701 return eventTopic === sha3(utils.transformToFullName(j)); 2702 })[0]; 2703 2704 if (!match) { // cannot find matching event? 2705 console.warn('cannot find event for log'); 2706 return data; 2707 } 2708 2709 var event = new SolidityEvent(this._requestManager, match, this._address); 2710 return event.decode(data); 2711 }; 2712 2713 AllSolidityEvents.prototype.execute = function (options, callback) { 2714 2715 if (utils.isFunction(arguments[arguments.length - 1])) { 2716 callback = arguments[arguments.length - 1]; 2717 if(arguments.length === 1) 2718 options = null; 2719 } 2720 2721 var o = this.encode(options); 2722 var formatter = this.decode.bind(this); 2723 return new Filter(this._requestManager, o, watches.eth(), formatter, callback); 2724 }; 2725 2726 AllSolidityEvents.prototype.attachToContract = function (contract) { 2727 var execute = this.execute.bind(this); 2728 contract.allEvents = execute; 2729 }; 2730 2731 module.exports = AllSolidityEvents; 2732 2733 2734 },{"../utils/sha3":19,"../utils/utils":20,"./event":27,"./filter":29,"./formatters":30,"./methods/watches":42}],24:[function(require,module,exports){ 2735 /* 2736 This file is part of web3.js. 2737 2738 web3.js is free software: you can redistribute it and/or modify 2739 it under the terms of the GNU Lesser General Public License as published by 2740 the Free Software Foundation, either version 3 of the License, or 2741 (at your option) any later version. 2742 2743 web3.js is distributed in the hope that it will be useful, 2744 but WITHOUT ANY WARRANTY; without even the implied warranty of 2745 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2746 GNU Lesser General Public License for more details. 2747 2748 You should have received a copy of the GNU Lesser General Public License 2749 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2750 */ 2751 /** 2752 * @file batch.js 2753 * @author Marek Kotewicz <marek@ethdev.com> 2754 * @date 2015 2755 */ 2756 2757 var Jsonrpc = require('./jsonrpc'); 2758 var errors = require('./errors'); 2759 2760 var Batch = function (web3) { 2761 this.requestManager = web3._requestManager; 2762 this.requests = []; 2763 }; 2764 2765 /** 2766 * Should be called to add create new request to batch request 2767 * 2768 * @method add 2769 * @param {Object} jsonrpc requet object 2770 */ 2771 Batch.prototype.add = function (request) { 2772 this.requests.push(request); 2773 }; 2774 2775 /** 2776 * Should be called to execute batch request 2777 * 2778 * @method execute 2779 */ 2780 Batch.prototype.execute = function () { 2781 var requests = this.requests; 2782 this.requestManager.sendBatch(requests, function (err, results) { 2783 results = results || []; 2784 requests.map(function (request, index) { 2785 return results[index] || {}; 2786 }).forEach(function (result, index) { 2787 if (requests[index].callback) { 2788 2789 if (!Jsonrpc.getInstance().isValidResponse(result)) { 2790 return requests[index].callback(errors.InvalidResponse(result)); 2791 } 2792 2793 requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result)); 2794 } 2795 }); 2796 }); 2797 }; 2798 2799 module.exports = Batch; 2800 2801 2802 },{"./errors":26,"./jsonrpc":35}],25:[function(require,module,exports){ 2803 /* 2804 This file is part of web3.js. 2805 2806 web3.js is free software: you can redistribute it and/or modify 2807 it under the terms of the GNU Lesser General Public License as published by 2808 the Free Software Foundation, either version 3 of the License, or 2809 (at your option) any later version. 2810 2811 web3.js is distributed in the hope that it will be useful, 2812 but WITHOUT ANY WARRANTY; without even the implied warranty of 2813 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2814 GNU Lesser General Public License for more details. 2815 2816 You should have received a copy of the GNU Lesser General Public License 2817 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2818 */ 2819 /** 2820 * @file contract.js 2821 * @author Marek Kotewicz <marek@ethdev.com> 2822 * @date 2014 2823 */ 2824 2825 var utils = require('../utils/utils'); 2826 var coder = require('../solidity/coder'); 2827 var SolidityEvent = require('./event'); 2828 var SolidityFunction = require('./function'); 2829 var AllEvents = require('./allevents'); 2830 2831 /** 2832 * Should be called to encode constructor params 2833 * 2834 * @method encodeConstructorParams 2835 * @param {Array} abi 2836 * @param {Array} constructor params 2837 */ 2838 var encodeConstructorParams = function (abi, params) { 2839 return abi.filter(function (json) { 2840 return json.type === 'constructor' && json.inputs.length === params.length; 2841 }).map(function (json) { 2842 return json.inputs.map(function (input) { 2843 return input.type; 2844 }); 2845 }).map(function (types) { 2846 return coder.encodeParams(types, params); 2847 })[0] || ''; 2848 }; 2849 2850 /** 2851 * Should be called to add functions to contract object 2852 * 2853 * @method addFunctionsToContract 2854 * @param {Contract} contract 2855 * @param {Array} abi 2856 */ 2857 var addFunctionsToContract = function (contract) { 2858 contract.abi.filter(function (json) { 2859 return json.type === 'function'; 2860 }).map(function (json) { 2861 return new SolidityFunction(contract._eth, json, contract.address); 2862 }).forEach(function (f) { 2863 f.attachToContract(contract); 2864 }); 2865 }; 2866 2867 /** 2868 * Should be called to add events to contract object 2869 * 2870 * @method addEventsToContract 2871 * @param {Contract} contract 2872 * @param {Array} abi 2873 */ 2874 var addEventsToContract = function (contract) { 2875 var events = contract.abi.filter(function (json) { 2876 return json.type === 'event'; 2877 }); 2878 2879 var All = new AllEvents(contract._eth._requestManager, events, contract.address); 2880 All.attachToContract(contract); 2881 2882 events.map(function (json) { 2883 return new SolidityEvent(contract._eth._requestManager, json, contract.address); 2884 }).forEach(function (e) { 2885 e.attachToContract(contract); 2886 }); 2887 }; 2888 2889 2890 /** 2891 * Should be called to check if the contract gets properly deployed on the blockchain. 2892 * 2893 * @method checkForContractAddress 2894 * @param {Object} contract 2895 * @param {Function} callback 2896 * @returns {Undefined} 2897 */ 2898 var checkForContractAddress = function(contract, callback){ 2899 var count = 0, 2900 callbackFired = false; 2901 2902 // wait for receipt 2903 var filter = contract._eth.filter('latest', function(e){ 2904 if (!e && !callbackFired) { 2905 count++; 2906 2907 // stop watching after 50 blocks (timeout) 2908 if (count > 50) { 2909 2910 filter.stopWatching(); 2911 callbackFired = true; 2912 2913 if (callback) 2914 callback(new Error('Contract transaction couldn\'t be found after 50 blocks')); 2915 else 2916 throw new Error('Contract transaction couldn\'t be found after 50 blocks'); 2917 2918 2919 } else { 2920 2921 contract._eth.getTransactionReceipt(contract.transactionHash, function(e, receipt){ 2922 if(receipt && !callbackFired) { 2923 2924 contract._eth.getCode(receipt.contractAddress, function(e, code){ 2925 /*jshint maxcomplexity: 6 */ 2926 2927 if(callbackFired || !code) 2928 return; 2929 2930 filter.stopWatching(); 2931 callbackFired = true; 2932 2933 if(code.length > 2) { 2934 2935 // console.log('Contract code deployed!'); 2936 2937 contract.address = receipt.contractAddress; 2938 2939 // attach events and methods again after we have 2940 addFunctionsToContract(contract); 2941 addEventsToContract(contract); 2942 2943 // call callback for the second time 2944 if(callback) 2945 callback(null, contract); 2946 2947 } else { 2948 if(callback) 2949 callback(new Error('The contract code couldn\'t be stored, please check your gas amount.')); 2950 else 2951 throw new Error('The contract code couldn\'t be stored, please check your gas amount.'); 2952 } 2953 }); 2954 } 2955 }); 2956 } 2957 } 2958 }); 2959 }; 2960 2961 /** 2962 * Should be called to create new ContractFactory instance 2963 * 2964 * @method ContractFactory 2965 * @param {Array} abi 2966 */ 2967 var ContractFactory = function (eth, abi) { 2968 this.eth = eth; 2969 this.abi = abi; 2970 2971 /** 2972 * Should be called to create new contract on a blockchain 2973 * 2974 * @method new 2975 * @param {Any} contract constructor param1 (optional) 2976 * @param {Any} contract constructor param2 (optional) 2977 * @param {Object} contract transaction object (required) 2978 * @param {Function} callback 2979 * @returns {Contract} returns contract instance 2980 */ 2981 this.new = function () { 2982 var contract = new Contract(this.eth, this.abi); 2983 2984 // parse arguments 2985 var options = {}; // required! 2986 var callback; 2987 2988 var args = Array.prototype.slice.call(arguments); 2989 if (utils.isFunction(args[args.length - 1])) { 2990 callback = args.pop(); 2991 } 2992 2993 var last = args[args.length - 1]; 2994 if (utils.isObject(last) && !utils.isArray(last)) { 2995 options = args.pop(); 2996 } 2997 2998 var bytes = encodeConstructorParams(this.abi, args); 2999 options.data += bytes; 3000 3001 if (callback) { 3002 3003 // wait for the contract address adn check if the code was deployed 3004 this.eth.sendTransaction(options, function (err, hash) { 3005 if (err) { 3006 callback(err); 3007 } else { 3008 // add the transaction hash 3009 contract.transactionHash = hash; 3010 3011 // call callback for the first time 3012 callback(null, contract); 3013 3014 checkForContractAddress(contract, callback); 3015 } 3016 }); 3017 } else { 3018 var hash = this.eth.sendTransaction(options); 3019 // add the transaction hash 3020 contract.transactionHash = hash; 3021 checkForContractAddress(contract); 3022 } 3023 3024 return contract; 3025 }; 3026 3027 this.new.getData = this.getData.bind(this); 3028 }; 3029 3030 /** 3031 * Should be called to create new ContractFactory 3032 * 3033 * @method contract 3034 * @param {Array} abi 3035 * @returns {ContractFactory} new contract factory 3036 */ 3037 //var contract = function (abi) { 3038 //return new ContractFactory(abi); 3039 //}; 3040 3041 3042 3043 /** 3044 * Should be called to get access to existing contract on a blockchain 3045 * 3046 * @method at 3047 * @param {Address} contract address (required) 3048 * @param {Function} callback {optional) 3049 * @returns {Contract} returns contract if no callback was passed, 3050 * otherwise calls callback function (err, contract) 3051 */ 3052 ContractFactory.prototype.at = function (address, callback) { 3053 var contract = new Contract(this.eth, this.abi, address); 3054 3055 // this functions are not part of prototype, 3056 // because we dont want to spoil the interface 3057 addFunctionsToContract(contract); 3058 addEventsToContract(contract); 3059 3060 if (callback) { 3061 callback(null, contract); 3062 } 3063 return contract; 3064 }; 3065 3066 /** 3067 * Gets the data, which is data to deploy plus constructor params 3068 * 3069 * @method getData 3070 */ 3071 ContractFactory.prototype.getData = function () { 3072 var options = {}; // required! 3073 var args = Array.prototype.slice.call(arguments); 3074 3075 var last = args[args.length - 1]; 3076 if (utils.isObject(last) && !utils.isArray(last)) { 3077 options = args.pop(); 3078 } 3079 3080 var bytes = encodeConstructorParams(this.abi, args); 3081 options.data += bytes; 3082 3083 return options.data; 3084 }; 3085 3086 /** 3087 * Should be called to create new contract instance 3088 * 3089 * @method Contract 3090 * @param {Array} abi 3091 * @param {Address} contract address 3092 */ 3093 var Contract = function (eth, abi, address) { 3094 this._eth = eth; 3095 this.transactionHash = null; 3096 this.address = address; 3097 this.abi = abi; 3098 }; 3099 3100 module.exports = ContractFactory; 3101 3102 },{"../solidity/coder":7,"../utils/utils":20,"./allevents":23,"./event":27,"./function":31}],26:[function(require,module,exports){ 3103 /* 3104 This file is part of web3.js. 3105 3106 web3.js is free software: you can redistribute it and/or modify 3107 it under the terms of the GNU Lesser General Public License as published by 3108 the Free Software Foundation, either version 3 of the License, or 3109 (at your option) any later version. 3110 3111 web3.js is distributed in the hope that it will be useful, 3112 but WITHOUT ANY WARRANTY; without even the implied warranty of 3113 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3114 GNU Lesser General Public License for more details. 3115 3116 You should have received a copy of the GNU Lesser General Public License 3117 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3118 */ 3119 /** 3120 * @file errors.js 3121 * @author Marek Kotewicz <marek@ethdev.com> 3122 * @date 2015 3123 */ 3124 3125 module.exports = { 3126 InvalidNumberOfParams: function () { 3127 return new Error('Invalid number of input parameters'); 3128 }, 3129 InvalidConnection: function (host){ 3130 return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.'); 3131 }, 3132 InvalidProvider: function () { 3133 return new Error('Provider not set or invalid'); 3134 }, 3135 InvalidResponse: function (result){ 3136 var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); 3137 return new Error(message); 3138 } 3139 }; 3140 3141 3142 },{}],27:[function(require,module,exports){ 3143 /* 3144 This file is part of web3.js. 3145 3146 web3.js is free software: you can redistribute it and/or modify 3147 it under the terms of the GNU Lesser General Public License as published by 3148 the Free Software Foundation, either version 3 of the License, or 3149 (at your option) any later version. 3150 3151 web3.js is distributed in the hope that it will be useful, 3152 but WITHOUT ANY WARRANTY; without even the implied warranty of 3153 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3154 GNU Lesser General Public License for more details. 3155 3156 You should have received a copy of the GNU Lesser General Public License 3157 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3158 */ 3159 /** 3160 * @file event.js 3161 * @author Marek Kotewicz <marek@ethdev.com> 3162 * @date 2014 3163 */ 3164 3165 var utils = require('../utils/utils'); 3166 var coder = require('../solidity/coder'); 3167 var formatters = require('./formatters'); 3168 var sha3 = require('../utils/sha3'); 3169 var Filter = require('./filter'); 3170 var watches = require('./methods/watches'); 3171 3172 /** 3173 * This prototype should be used to create event filters 3174 */ 3175 var SolidityEvent = function (requestManager, json, address) { 3176 this._requestManager = requestManager; 3177 this._params = json.inputs; 3178 this._name = utils.transformToFullName(json); 3179 this._address = address; 3180 this._anonymous = json.anonymous; 3181 }; 3182 3183 /** 3184 * Should be used to get filtered param types 3185 * 3186 * @method types 3187 * @param {Bool} decide if returned typed should be indexed 3188 * @return {Array} array of types 3189 */ 3190 SolidityEvent.prototype.types = function (indexed) { 3191 return this._params.filter(function (i) { 3192 return i.indexed === indexed; 3193 }).map(function (i) { 3194 return i.type; 3195 }); 3196 }; 3197 3198 /** 3199 * Should be used to get event display name 3200 * 3201 * @method displayName 3202 * @return {String} event display name 3203 */ 3204 SolidityEvent.prototype.displayName = function () { 3205 return utils.extractDisplayName(this._name); 3206 }; 3207 3208 /** 3209 * Should be used to get event type name 3210 * 3211 * @method typeName 3212 * @return {String} event type name 3213 */ 3214 SolidityEvent.prototype.typeName = function () { 3215 return utils.extractTypeName(this._name); 3216 }; 3217 3218 /** 3219 * Should be used to get event signature 3220 * 3221 * @method signature 3222 * @return {String} event signature 3223 */ 3224 SolidityEvent.prototype.signature = function () { 3225 return sha3(this._name); 3226 }; 3227 3228 /** 3229 * Should be used to encode indexed params and options to one final object 3230 * 3231 * @method encode 3232 * @param {Object} indexed 3233 * @param {Object} options 3234 * @return {Object} everything combined together and encoded 3235 */ 3236 SolidityEvent.prototype.encode = function (indexed, options) { 3237 indexed = indexed || {}; 3238 options = options || {}; 3239 var result = {}; 3240 3241 ['fromBlock', 'toBlock'].filter(function (f) { 3242 return options[f] !== undefined; 3243 }).forEach(function (f) { 3244 result[f] = formatters.inputBlockNumberFormatter(options[f]); 3245 }); 3246 3247 result.topics = []; 3248 3249 result.address = this._address; 3250 if (!this._anonymous) { 3251 result.topics.push('0x' + this.signature()); 3252 } 3253 3254 var indexedTopics = this._params.filter(function (i) { 3255 return i.indexed === true; 3256 }).map(function (i) { 3257 var value = indexed[i.name]; 3258 if (value === undefined || value === null) { 3259 return null; 3260 } 3261 3262 if (utils.isArray(value)) { 3263 return value.map(function (v) { 3264 return '0x' + coder.encodeParam(i.type, v); 3265 }); 3266 } 3267 return '0x' + coder.encodeParam(i.type, value); 3268 }); 3269 3270 result.topics = result.topics.concat(indexedTopics); 3271 3272 return result; 3273 }; 3274 3275 /** 3276 * Should be used to decode indexed params and options 3277 * 3278 * @method decode 3279 * @param {Object} data 3280 * @return {Object} result object with decoded indexed && not indexed params 3281 */ 3282 SolidityEvent.prototype.decode = function (data) { 3283 3284 data.data = data.data || ''; 3285 data.topics = data.topics || []; 3286 3287 var argTopics = this._anonymous ? data.topics : data.topics.slice(1); 3288 var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join(""); 3289 var indexedParams = coder.decodeParams(this.types(true), indexedData); 3290 3291 var notIndexedData = data.data.slice(2); 3292 var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData); 3293 3294 var result = formatters.outputLogFormatter(data); 3295 result.event = this.displayName(); 3296 result.address = data.address; 3297 3298 result.args = this._params.reduce(function (acc, current) { 3299 acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift(); 3300 return acc; 3301 }, {}); 3302 3303 delete result.data; 3304 delete result.topics; 3305 3306 return result; 3307 }; 3308 3309 /** 3310 * Should be used to create new filter object from event 3311 * 3312 * @method execute 3313 * @param {Object} indexed 3314 * @param {Object} options 3315 * @return {Object} filter object 3316 */ 3317 SolidityEvent.prototype.execute = function (indexed, options, callback) { 3318 3319 if (utils.isFunction(arguments[arguments.length - 1])) { 3320 callback = arguments[arguments.length - 1]; 3321 if(arguments.length === 2) 3322 options = null; 3323 if(arguments.length === 1) { 3324 options = null; 3325 indexed = {}; 3326 } 3327 } 3328 3329 var o = this.encode(indexed, options); 3330 var formatter = this.decode.bind(this); 3331 return new Filter(this._requestManager, o, watches.eth(), formatter, callback); 3332 }; 3333 3334 /** 3335 * Should be used to attach event to contract object 3336 * 3337 * @method attachToContract 3338 * @param {Contract} 3339 */ 3340 SolidityEvent.prototype.attachToContract = function (contract) { 3341 var execute = this.execute.bind(this); 3342 var displayName = this.displayName(); 3343 if (!contract[displayName]) { 3344 contract[displayName] = execute; 3345 } 3346 contract[displayName][this.typeName()] = this.execute.bind(this, contract); 3347 }; 3348 3349 module.exports = SolidityEvent; 3350 3351 3352 },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters":30,"./methods/watches":42}],28:[function(require,module,exports){ 3353 var formatters = require('./formatters'); 3354 var utils = require('./../utils/utils'); 3355 var Method = require('./method'); 3356 var Property = require('./property'); 3357 3358 // TODO: refactor, so the input params are not altered. 3359 // it's necessary to make same 'extension' work with multiple providers 3360 var extend = function (web3) { 3361 /* jshint maxcomplexity:5 */ 3362 var ex = function (extension) { 3363 3364 var extendedObject; 3365 if (extension.property) { 3366 if (!web3[extension.property]) { 3367 web3[extension.property] = {}; 3368 } 3369 extendedObject = web3[extension.property]; 3370 } else { 3371 extendedObject = web3; 3372 } 3373 3374 if (extension.methods) { 3375 extension.methods.forEach(function (method) { 3376 method.attachToObject(extendedObject); 3377 method.setRequestManager(web3._requestManager); 3378 }); 3379 } 3380 3381 if (extension.properties) { 3382 extension.properties.forEach(function (property) { 3383 property.attachToObject(extendedObject); 3384 property.setRequestManager(web3._requestManager); 3385 }); 3386 } 3387 }; 3388 3389 ex.formatters = formatters; 3390 ex.utils = utils; 3391 ex.Method = Method; 3392 ex.Property = Property; 3393 3394 return ex; 3395 }; 3396 3397 3398 3399 module.exports = extend; 3400 3401 3402 },{"./../utils/utils":20,"./formatters":30,"./method":36,"./property":44}],29:[function(require,module,exports){ 3403 /* 3404 This file is part of web3.js. 3405 3406 web3.js is free software: you can redistribute it and/or modify 3407 it under the terms of the GNU Lesser General Public License as published by 3408 the Free Software Foundation, either version 3 of the License, or 3409 (at your option) any later version. 3410 3411 web3.js is distributed in the hope that it will be useful, 3412 but WITHOUT ANY WARRANTY; without even the implied warranty of 3413 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3414 GNU Lesser General Public License for more details. 3415 3416 You should have received a copy of the GNU Lesser General Public License 3417 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3418 */ 3419 /** @file filter.js 3420 * @authors: 3421 * Jeffrey Wilcke <jeff@ethdev.com> 3422 * Marek Kotewicz <marek@ethdev.com> 3423 * Marian Oancea <marian@ethdev.com> 3424 * Fabian Vogelsteller <fabian@ethdev.com> 3425 * Gav Wood <g@ethdev.com> 3426 * @date 2014 3427 */ 3428 3429 var formatters = require('./formatters'); 3430 var utils = require('../utils/utils'); 3431 3432 /** 3433 * Converts a given topic to a hex string, but also allows null values. 3434 * 3435 * @param {Mixed} value 3436 * @return {String} 3437 */ 3438 var toTopic = function(value){ 3439 3440 if(value === null || typeof value === 'undefined') 3441 return null; 3442 3443 value = String(value); 3444 3445 if(value.indexOf('0x') === 0) 3446 return value; 3447 else 3448 return utils.fromUtf8(value); 3449 }; 3450 3451 /// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones 3452 /// @param should be string or object 3453 /// @returns options string or object 3454 var getOptions = function (options) { 3455 3456 if (utils.isString(options)) { 3457 return options; 3458 } 3459 3460 options = options || {}; 3461 3462 // make sure topics, get converted to hex 3463 options.topics = options.topics || []; 3464 options.topics = options.topics.map(function(topic){ 3465 return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic); 3466 }); 3467 3468 return { 3469 topics: options.topics, 3470 from: options.from, 3471 to: options.to, 3472 address: options.address, 3473 fromBlock: formatters.inputBlockNumberFormatter(options.fromBlock), 3474 toBlock: formatters.inputBlockNumberFormatter(options.toBlock) 3475 }; 3476 }; 3477 3478 /** 3479 Adds the callback and sets up the methods, to iterate over the results. 3480 3481 @method getLogsAtStart 3482 @param {Object} self 3483 @param {funciton} 3484 */ 3485 var getLogsAtStart = function(self, callback){ 3486 // call getFilterLogs for the first watch callback start 3487 if (!utils.isString(self.options)) { 3488 self.get(function (err, messages) { 3489 // don't send all the responses to all the watches again... just to self one 3490 if (err) { 3491 callback(err); 3492 } 3493 3494 if(utils.isArray(messages)) { 3495 messages.forEach(function (message) { 3496 callback(null, message); 3497 }); 3498 } 3499 }); 3500 } 3501 }; 3502 3503 /** 3504 Adds the callback and sets up the methods, to iterate over the results. 3505 3506 @method pollFilter 3507 @param {Object} self 3508 */ 3509 var pollFilter = function(self) { 3510 3511 var onMessage = function (error, messages) { 3512 if (error) { 3513 return self.callbacks.forEach(function (callback) { 3514 callback(error); 3515 }); 3516 } 3517 3518 if(utils.isArray(messages)) { 3519 messages.forEach(function (message) { 3520 message = self.formatter ? self.formatter(message) : message; 3521 self.callbacks.forEach(function (callback) { 3522 callback(null, message); 3523 }); 3524 }); 3525 } 3526 }; 3527 3528 self.requestManager.startPolling({ 3529 method: self.implementation.poll.call, 3530 params: [self.filterId], 3531 }, self.filterId, onMessage, self.stopWatching.bind(self)); 3532 3533 }; 3534 3535 var Filter = function (requestManager, options, methods, formatter, callback) { 3536 var self = this; 3537 var implementation = {}; 3538 methods.forEach(function (method) { 3539 method.setRequestManager(requestManager); 3540 method.attachToObject(implementation); 3541 }); 3542 this.requestManager = requestManager; 3543 this.options = getOptions(options); 3544 this.implementation = implementation; 3545 this.filterId = null; 3546 this.callbacks = []; 3547 this.getLogsCallbacks = []; 3548 this.pollFilters = []; 3549 this.formatter = formatter; 3550 this.implementation.newFilter(this.options, function(error, id){ 3551 if(error) { 3552 self.callbacks.forEach(function(cb){ 3553 cb(error); 3554 }); 3555 } else { 3556 self.filterId = id; 3557 3558 // check if there are get pending callbacks as a consequence 3559 // of calling get() with filterId unassigned. 3560 self.getLogsCallbacks.forEach(function (cb){ 3561 self.get(cb); 3562 }); 3563 self.getLogsCallbacks = []; 3564 3565 // get filter logs for the already existing watch calls 3566 self.callbacks.forEach(function(cb){ 3567 getLogsAtStart(self, cb); 3568 }); 3569 if(self.callbacks.length > 0) 3570 pollFilter(self); 3571 3572 // start to watch immediately 3573 if(typeof callback === 'function') { 3574 return self.watch(callback); 3575 } 3576 } 3577 }); 3578 3579 return this; 3580 }; 3581 3582 Filter.prototype.watch = function (callback) { 3583 this.callbacks.push(callback); 3584 3585 if(this.filterId) { 3586 getLogsAtStart(this, callback); 3587 pollFilter(this); 3588 } 3589 3590 return this; 3591 }; 3592 3593 Filter.prototype.stopWatching = function () { 3594 this.requestManager.stopPolling(this.filterId); 3595 // remove filter async 3596 this.implementation.uninstallFilter(this.filterId, function(){}); 3597 this.callbacks = []; 3598 }; 3599 3600 Filter.prototype.get = function (callback) { 3601 var self = this; 3602 if (utils.isFunction(callback)) { 3603 if (this.filterId === null) { 3604 // If filterId is not set yet, call it back 3605 // when newFilter() assigns it. 3606 this.getLogsCallbacks.push(callback); 3607 } else { 3608 this.implementation.getLogs(this.filterId, function(err, res){ 3609 if (err) { 3610 callback(err); 3611 } else { 3612 callback(null, res.map(function (log) { 3613 return self.formatter ? self.formatter(log) : log; 3614 })); 3615 } 3616 }); 3617 } 3618 } else { 3619 if (this.filterId === null) { 3620 throw new Error('Filter ID Error: filter().get() can\'t be chained synchronous, please provide a callback for the get() method.'); 3621 } 3622 var logs = this.implementation.getLogs(this.filterId); 3623 return logs.map(function (log) { 3624 return self.formatter ? self.formatter(log) : log; 3625 }); 3626 } 3627 3628 return this; 3629 }; 3630 3631 module.exports = Filter; 3632 3633 3634 },{"../utils/utils":20,"./formatters":30}],30:[function(require,module,exports){ 3635 /* 3636 This file is part of web3.js. 3637 3638 web3.js is free software: you can redistribute it and/or modify 3639 it under the terms of the GNU Lesser General Public License as published by 3640 the Free Software Foundation, either version 3 of the License, or 3641 (at your option) any later version. 3642 3643 web3.js is distributed in the hope that it will be useful, 3644 but WITHOUT ANY WARRANTY; without even the implied warranty of 3645 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3646 GNU Lesser General Public License for more details. 3647 3648 You should have received a copy of the GNU Lesser General Public License 3649 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3650 */ 3651 /** 3652 * @file formatters.js 3653 * @author Marek Kotewicz <marek@ethdev.com> 3654 * @author Fabian Vogelsteller <fabian@ethdev.com> 3655 * @date 2015 3656 */ 3657 3658 var utils = require('../utils/utils'); 3659 var config = require('../utils/config'); 3660 var Iban = require('./iban'); 3661 3662 /** 3663 * Should the format output to a big number 3664 * 3665 * @method outputBigNumberFormatter 3666 * @param {String|Number|BigNumber} 3667 * @returns {BigNumber} object 3668 */ 3669 var outputBigNumberFormatter = function (number) { 3670 return utils.toBigNumber(number); 3671 }; 3672 3673 var isPredefinedBlockNumber = function (blockNumber) { 3674 return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest'; 3675 }; 3676 3677 var inputDefaultBlockNumberFormatter = function (blockNumber) { 3678 if (blockNumber === undefined) { 3679 return config.defaultBlock; 3680 } 3681 return inputBlockNumberFormatter(blockNumber); 3682 }; 3683 3684 var inputBlockNumberFormatter = function (blockNumber) { 3685 if (blockNumber === undefined) { 3686 return undefined; 3687 } else if (isPredefinedBlockNumber(blockNumber)) { 3688 return blockNumber; 3689 } 3690 return utils.toHex(blockNumber); 3691 }; 3692 3693 /** 3694 * Formats the input of a transaction and converts all values to HEX 3695 * 3696 * @method inputCallFormatter 3697 * @param {Object} transaction options 3698 * @returns object 3699 */ 3700 var inputCallFormatter = function (options){ 3701 3702 options.from = options.from || config.defaultAccount; 3703 3704 if (options.from) { 3705 options.from = inputAddressFormatter(options.from); 3706 } 3707 3708 if (options.to) { // it might be contract creation 3709 options.to = inputAddressFormatter(options.to); 3710 } 3711 3712 ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { 3713 return options[key] !== undefined; 3714 }).forEach(function(key){ 3715 options[key] = utils.fromDecimal(options[key]); 3716 }); 3717 3718 return options; 3719 }; 3720 3721 /** 3722 * Formats the input of a transaction and converts all values to HEX 3723 * 3724 * @method inputTransactionFormatter 3725 * @param {Object} transaction options 3726 * @returns object 3727 */ 3728 var inputTransactionFormatter = function (options){ 3729 3730 options.from = options.from || config.defaultAccount; 3731 options.from = inputAddressFormatter(options.from); 3732 3733 if (options.to) { // it might be contract creation 3734 options.to = inputAddressFormatter(options.to); 3735 } 3736 3737 ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { 3738 return options[key] !== undefined; 3739 }).forEach(function(key){ 3740 options[key] = utils.fromDecimal(options[key]); 3741 }); 3742 3743 return options; 3744 }; 3745 3746 /** 3747 * Allows optional boolean value as input. If null input, returns false. 3748 * 3749 * @method inputOptionalBoolFormatter 3750 * @param {bool} optional bool val, either of form [bool] or bool 3751 * @returns bool 3752 */ 3753 var inputOptionalBoolFormatter = function (options) { 3754 if (typeof options === 'boolean') { 3755 return options; 3756 } 3757 if (typeof options === 'object') { 3758 return options[0]; 3759 } 3760 return false; 3761 }; 3762 3763 /** 3764 * Allows optional number value as input. If null or empty input, returns 0. 3765 * 3766 * @method inputOptionalNumberFormatter 3767 * @param {bool} optional number val, either of form [number] or number 3768 * @returns number 3769 */ 3770 var inputOptionalNumberFormatter = function (numbers) { 3771 if (typeof numbers === 'number') { 3772 return numbers; 3773 } 3774 if (typeof numbers === 'object') { 3775 return numbers[0]; 3776 } 3777 return 0; 3778 }; 3779 3780 /** 3781 * Allows optional string value as input. If null input, returns "". 3782 * 3783 * @method inputOptionalStringFormatter 3784 * @param {string} optional string val, either of form [string] or string 3785 * @returns string 3786 */ 3787 var inputOptionalStringFormatter = function (optionalString) { 3788 if (typeof optionalString === 'string') { 3789 return optionalString; 3790 } 3791 if (typeof optionalString === 'object') { 3792 return optionalString[0]; 3793 } 3794 return ""; 3795 }; 3796 3797 /** 3798 * Formats the output of a transaction to its proper values 3799 * 3800 * @method outputTransactionFormatter 3801 * @param {Object} tx 3802 * @returns {Object} 3803 */ 3804 var outputTransactionFormatter = function (tx){ 3805 if(tx.blockNumber !== null) 3806 tx.blockNumber = utils.toDecimal(tx.blockNumber); 3807 if(tx.transactionIndex !== null) 3808 tx.transactionIndex = utils.toDecimal(tx.transactionIndex); 3809 tx.nonce = utils.toDecimal(tx.nonce); 3810 tx.gas = utils.toDecimal(tx.gas); 3811 tx.gasPrice = utils.toBigNumber(tx.gasPrice); 3812 tx.value = utils.toBigNumber(tx.value); 3813 return tx; 3814 }; 3815 3816 /** 3817 * Formats the output of a transaction receipt to its proper values 3818 * 3819 * @method outputTransactionReceiptFormatter 3820 * @param {Object} receipt 3821 * @returns {Object} 3822 */ 3823 var outputTransactionReceiptFormatter = function (receipt){ 3824 if(receipt.blockNumber !== null) 3825 receipt.blockNumber = utils.toDecimal(receipt.blockNumber); 3826 if(receipt.transactionIndex !== null) 3827 receipt.transactionIndex = utils.toDecimal(receipt.transactionIndex); 3828 receipt.cumulativeGasUsed = utils.toDecimal(receipt.cumulativeGasUsed); 3829 receipt.gasUsed = utils.toDecimal(receipt.gasUsed); 3830 receipt.status = utils.toDecimal(receipt.status); 3831 3832 if(utils.isArray(receipt.logs)) { 3833 receipt.logs = receipt.logs.map(function(log){ 3834 return outputLogFormatter(log); 3835 }); 3836 } 3837 3838 return receipt; 3839 }; 3840 3841 /** 3842 * Formats the output of a block to its proper values 3843 * 3844 * @method outputBlockFormatter 3845 * @param {Object} block 3846 * @returns {Object} 3847 */ 3848 var outputBlockFormatter = function(block) { 3849 3850 // transform to number 3851 block.gasLimit = utils.toDecimal(block.gasLimit); 3852 block.gasUsed = utils.toDecimal(block.gasUsed); 3853 block.size = utils.toDecimal(block.size); 3854 block.timestamp = utils.toDecimal(block.timestamp); 3855 if(block.number !== null) 3856 block.number = utils.toDecimal(block.number); 3857 3858 block.difficulty = utils.toBigNumber(block.difficulty); 3859 block.totalDifficulty = utils.toBigNumber(block.totalDifficulty); 3860 3861 if (utils.isArray(block.transactions)) { 3862 block.transactions.forEach(function(item){ 3863 if(!utils.isString(item)) 3864 return outputTransactionFormatter(item); 3865 }); 3866 } 3867 3868 return block; 3869 }; 3870 3871 /** 3872 * Formats the output of a log 3873 * 3874 * @method outputLogFormatter 3875 * @param {Object} log object 3876 * @returns {Object} log 3877 */ 3878 var outputLogFormatter = function(log) { 3879 if(log.blockNumber !== null) 3880 log.blockNumber = utils.toDecimal(log.blockNumber); 3881 if(log.transactionIndex !== null) 3882 log.transactionIndex = utils.toDecimal(log.transactionIndex); 3883 if(log.logIndex !== null) 3884 log.logIndex = utils.toDecimal(log.logIndex); 3885 3886 return log; 3887 }; 3888 3889 /** 3890 * Formats the input of a whisper post and converts all values to HEX 3891 * 3892 * @method inputPostFormatter 3893 * @param {Object} transaction object 3894 * @returns {Object} 3895 */ 3896 var inputPostFormatter = function(post) { 3897 3898 // post.payload = utils.toHex(post.payload); 3899 post.ttl = utils.fromDecimal(post.ttl); 3900 post.workToProve = utils.fromDecimal(post.workToProve); 3901 post.priority = utils.fromDecimal(post.priority); 3902 3903 // fallback 3904 if (!utils.isArray(post.topics)) { 3905 post.topics = post.topics ? [post.topics] : []; 3906 } 3907 3908 // format the following options 3909 post.topics = post.topics.map(function(topic){ 3910 // convert only if not hex 3911 return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); 3912 }); 3913 3914 return post; 3915 }; 3916 3917 /** 3918 * Formats the output of a received post message 3919 * 3920 * @method outputPostFormatter 3921 * @param {Object} 3922 * @returns {Object} 3923 */ 3924 var outputPostFormatter = function(post){ 3925 3926 post.expiry = utils.toDecimal(post.expiry); 3927 post.sent = utils.toDecimal(post.sent); 3928 post.ttl = utils.toDecimal(post.ttl); 3929 post.workProved = utils.toDecimal(post.workProved); 3930 // post.payloadRaw = post.payload; 3931 // post.payload = utils.toAscii(post.payload); 3932 3933 // if (utils.isJson(post.payload)) { 3934 // post.payload = JSON.parse(post.payload); 3935 // } 3936 3937 // format the following options 3938 if (!post.topics) { 3939 post.topics = []; 3940 } 3941 post.topics = post.topics.map(function(topic){ 3942 return utils.toAscii(topic); 3943 }); 3944 3945 return post; 3946 }; 3947 3948 var inputAddressFormatter = function (address) { 3949 var iban = new Iban(address); 3950 if (iban.isValid() && iban.isDirect()) { 3951 return '0x' + iban.address(); 3952 } else if (utils.isStrictAddress(address)) { 3953 return address; 3954 } else if (utils.isAddress(address)) { 3955 return '0x' + address; 3956 } 3957 throw new Error('invalid address'); 3958 }; 3959 3960 3961 var outputSyncingFormatter = function(result) { 3962 3963 result.startingBlock = utils.toDecimal(result.startingBlock); 3964 result.currentBlock = utils.toDecimal(result.currentBlock); 3965 result.highestBlock = utils.toDecimal(result.highestBlock); 3966 if (result.knownStates !== undefined) { 3967 result.knownStates = utils.toDecimal(result.knownStates); 3968 } 3969 if (result.pulledStates !== undefined) { 3970 result.pulledStates = utils.toDecimal(result.pulledStates); 3971 } 3972 return result; 3973 }; 3974 3975 module.exports = { 3976 inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, 3977 inputBlockNumberFormatter: inputBlockNumberFormatter, 3978 inputCallFormatter: inputCallFormatter, 3979 inputTransactionFormatter: inputTransactionFormatter, 3980 inputAddressFormatter: inputAddressFormatter, 3981 inputOptionalBoolFormatter: inputOptionalBoolFormatter, 3982 inputOptionalStringFormatter: inputOptionalStringFormatter, 3983 inputOptionalNumberFormatter: inputOptionalNumberFormatter, 3984 inputPostFormatter: inputPostFormatter, 3985 outputBigNumberFormatter: outputBigNumberFormatter, 3986 outputTransactionFormatter: outputTransactionFormatter, 3987 outputTransactionReceiptFormatter: outputTransactionReceiptFormatter, 3988 outputBlockFormatter: outputBlockFormatter, 3989 outputLogFormatter: outputLogFormatter, 3990 outputPostFormatter: outputPostFormatter, 3991 outputSyncingFormatter: outputSyncingFormatter 3992 }; 3993 3994 3995 },{"../utils/config":18,"../utils/utils":20,"./iban":33}],31:[function(require,module,exports){ 3996 /* 3997 This file is part of web3.js. 3998 3999 web3.js is free software: you can redistribute it and/or modify 4000 it under the terms of the GNU Lesser General Public License as published by 4001 the Free Software Foundation, either version 3 of the License, or 4002 (at your option) any later version. 4003 4004 web3.js is distributed in the hope that it will be useful, 4005 but WITHOUT ANY WARRANTY; without even the implied warranty of 4006 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4007 GNU Lesser General Public License for more details. 4008 4009 You should have received a copy of the GNU Lesser General Public License 4010 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4011 */ 4012 /** 4013 * @file function.js 4014 * @author Marek Kotewicz <marek@ethdev.com> 4015 * @date 2015 4016 */ 4017 4018 var coder = require('../solidity/coder'); 4019 var utils = require('../utils/utils'); 4020 var formatters = require('./formatters'); 4021 var sha3 = require('../utils/sha3'); 4022 4023 /** 4024 * This prototype should be used to call/sendTransaction to solidity functions 4025 */ 4026 var SolidityFunction = function (eth, json, address) { 4027 this._eth = eth; 4028 this._inputTypes = json.inputs.map(function (i) { 4029 return i.type; 4030 }); 4031 this._outputTypes = json.outputs.map(function (i) { 4032 return i.type; 4033 }); 4034 this._constant = json.constant; 4035 this._name = utils.transformToFullName(json); 4036 this._address = address; 4037 }; 4038 4039 SolidityFunction.prototype.extractCallback = function (args) { 4040 if (utils.isFunction(args[args.length - 1])) { 4041 return args.pop(); // modify the args array! 4042 } 4043 }; 4044 4045 SolidityFunction.prototype.extractDefaultBlock = function (args) { 4046 if (args.length > this._inputTypes.length && !utils.isObject(args[args.length -1])) { 4047 return formatters.inputDefaultBlockNumberFormatter(args.pop()); // modify the args array! 4048 } 4049 }; 4050 4051 /** 4052 * Should be used to create payload from arguments 4053 * 4054 * @method toPayload 4055 * @param {Array} solidity function params 4056 * @param {Object} optional payload options 4057 */ 4058 SolidityFunction.prototype.toPayload = function (args) { 4059 var options = {}; 4060 if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) { 4061 options = args[args.length - 1]; 4062 } 4063 options.to = this._address; 4064 options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args); 4065 return options; 4066 }; 4067 4068 /** 4069 * Should be used to get function signature 4070 * 4071 * @method signature 4072 * @return {String} function signature 4073 */ 4074 SolidityFunction.prototype.signature = function () { 4075 return sha3(this._name).slice(0, 8); 4076 }; 4077 4078 4079 SolidityFunction.prototype.unpackOutput = function (output) { 4080 if (!output) { 4081 return; 4082 } 4083 4084 output = output.length >= 2 ? output.slice(2) : output; 4085 var result = coder.decodeParams(this._outputTypes, output); 4086 return result.length === 1 ? result[0] : result; 4087 }; 4088 4089 /** 4090 * Calls a contract function. 4091 * 4092 * @method call 4093 * @param {...Object} Contract function arguments 4094 * @param {function} If the last argument is a function, the contract function 4095 * call will be asynchronous, and the callback will be passed the 4096 * error and result. 4097 * @return {String} output bytes 4098 */ 4099 SolidityFunction.prototype.call = function () { 4100 var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); 4101 var callback = this.extractCallback(args); 4102 var defaultBlock = this.extractDefaultBlock(args); 4103 var payload = this.toPayload(args); 4104 4105 4106 if (!callback) { 4107 var output = this._eth.call(payload, defaultBlock); 4108 return this.unpackOutput(output); 4109 } 4110 4111 var self = this; 4112 this._eth.call(payload, defaultBlock, function (error, output) { 4113 callback(error, self.unpackOutput(output)); 4114 }); 4115 }; 4116 4117 /** 4118 * Should be used to sendTransaction to solidity function 4119 * 4120 * @method sendTransaction 4121 */ 4122 SolidityFunction.prototype.sendTransaction = function () { 4123 var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); 4124 var callback = this.extractCallback(args); 4125 var payload = this.toPayload(args); 4126 4127 if (!callback) { 4128 return this._eth.sendTransaction(payload); 4129 } 4130 4131 this._eth.sendTransaction(payload, callback); 4132 }; 4133 4134 /** 4135 * Should be used to estimateGas of solidity function 4136 * 4137 * @method estimateGas 4138 */ 4139 SolidityFunction.prototype.estimateGas = function () { 4140 var args = Array.prototype.slice.call(arguments); 4141 var callback = this.extractCallback(args); 4142 var payload = this.toPayload(args); 4143 4144 if (!callback) { 4145 return this._eth.estimateGas(payload); 4146 } 4147 4148 this._eth.estimateGas(payload, callback); 4149 }; 4150 4151 /** 4152 * Return the encoded data of the call 4153 * 4154 * @method getData 4155 * @return {String} the encoded data 4156 */ 4157 SolidityFunction.prototype.getData = function () { 4158 var args = Array.prototype.slice.call(arguments); 4159 var payload = this.toPayload(args); 4160 4161 return payload.data; 4162 }; 4163 4164 /** 4165 * Should be used to get function display name 4166 * 4167 * @method displayName 4168 * @return {String} display name of the function 4169 */ 4170 SolidityFunction.prototype.displayName = function () { 4171 return utils.extractDisplayName(this._name); 4172 }; 4173 4174 /** 4175 * Should be used to get function type name 4176 * 4177 * @method typeName 4178 * @return {String} type name of the function 4179 */ 4180 SolidityFunction.prototype.typeName = function () { 4181 return utils.extractTypeName(this._name); 4182 }; 4183 4184 /** 4185 * Should be called to get rpc requests from solidity function 4186 * 4187 * @method request 4188 * @returns {Object} 4189 */ 4190 SolidityFunction.prototype.request = function () { 4191 var args = Array.prototype.slice.call(arguments); 4192 var callback = this.extractCallback(args); 4193 var payload = this.toPayload(args); 4194 var format = this.unpackOutput.bind(this); 4195 4196 return { 4197 method: this._constant ? 'eth_call' : 'eth_sendTransaction', 4198 callback: callback, 4199 params: [payload], 4200 format: format 4201 }; 4202 }; 4203 4204 /** 4205 * Should be called to execute function 4206 * 4207 * @method execute 4208 */ 4209 SolidityFunction.prototype.execute = function () { 4210 var transaction = !this._constant; 4211 4212 // send transaction 4213 if (transaction) { 4214 return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments)); 4215 } 4216 4217 // call 4218 return this.call.apply(this, Array.prototype.slice.call(arguments)); 4219 }; 4220 4221 /** 4222 * Should be called to attach function to contract 4223 * 4224 * @method attachToContract 4225 * @param {Contract} 4226 */ 4227 SolidityFunction.prototype.attachToContract = function (contract) { 4228 var execute = this.execute.bind(this); 4229 execute.request = this.request.bind(this); 4230 execute.call = this.call.bind(this); 4231 execute.sendTransaction = this.sendTransaction.bind(this); 4232 execute.estimateGas = this.estimateGas.bind(this); 4233 execute.getData = this.getData.bind(this); 4234 var displayName = this.displayName(); 4235 if (!contract[displayName]) { 4236 contract[displayName] = execute; 4237 } 4238 contract[displayName][this.typeName()] = execute; // circular!!!! 4239 }; 4240 4241 module.exports = SolidityFunction; 4242 4243 4244 },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./formatters":30}],32:[function(require,module,exports){ 4245 /* 4246 This file is part of web3.js. 4247 4248 web3.js is free software: you can redistribute it and/or modify 4249 it under the terms of the GNU Lesser General Public License as published by 4250 the Free Software Foundation, either version 3 of the License, or 4251 (at your option) any later version. 4252 4253 web3.js is distributed in the hope that it will be useful, 4254 but WITHOUT ANY WARRANTY; without even the implied warranty of 4255 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4256 GNU Lesser General Public License for more details. 4257 4258 You should have received a copy of the GNU Lesser General Public License 4259 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4260 */ 4261 /** @file httpprovider.js 4262 * @authors: 4263 * Marek Kotewicz <marek@ethdev.com> 4264 * Marian Oancea <marian@ethdev.com> 4265 * Fabian Vogelsteller <fabian@ethdev.com> 4266 * @date 2015 4267 */ 4268 4269 "use strict"; 4270 4271 var errors = require('./errors'); 4272 4273 // workaround to use httpprovider in different envs 4274 var XMLHttpRequest; // jshint ignore: line 4275 4276 // meteor server environment 4277 if (typeof Meteor !== 'undefined' && Meteor.isServer) { // jshint ignore: line 4278 XMLHttpRequest = Npm.require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line 4279 4280 // browser 4281 } else if (typeof window !== 'undefined' && window.XMLHttpRequest) { 4282 XMLHttpRequest = window.XMLHttpRequest; // jshint ignore: line 4283 4284 // node 4285 } else { 4286 XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line 4287 } 4288 4289 /** 4290 * HttpProvider should be used to send rpc calls over http 4291 */ 4292 var HttpProvider = function (host) { 4293 this.host = host || 'http://localhost:8545'; 4294 }; 4295 4296 /** 4297 * Should be called to prepare new XMLHttpRequest 4298 * 4299 * @method prepareRequest 4300 * @param {Boolean} true if request should be async 4301 * @return {XMLHttpRequest} object 4302 */ 4303 HttpProvider.prototype.prepareRequest = function (async) { 4304 var request = new XMLHttpRequest(); 4305 request.open('POST', this.host, async); 4306 request.setRequestHeader('Content-Type','application/json'); 4307 return request; 4308 }; 4309 4310 /** 4311 * Should be called to make sync request 4312 * 4313 * @method send 4314 * @param {Object} payload 4315 * @return {Object} result 4316 */ 4317 HttpProvider.prototype.send = function (payload) { 4318 var request = this.prepareRequest(false); 4319 4320 try { 4321 request.send(JSON.stringify(payload)); 4322 } catch(error) { 4323 throw errors.InvalidConnection(this.host); 4324 } 4325 4326 var result = request.responseText; 4327 4328 try { 4329 result = JSON.parse(result); 4330 } catch(e) { 4331 throw errors.InvalidResponse(request.responseText); 4332 } 4333 4334 return result; 4335 }; 4336 4337 /** 4338 * Should be used to make async request 4339 * 4340 * @method sendAsync 4341 * @param {Object} payload 4342 * @param {Function} callback triggered on end with (err, result) 4343 */ 4344 HttpProvider.prototype.sendAsync = function (payload, callback) { 4345 var request = this.prepareRequest(true); 4346 4347 request.onreadystatechange = function() { 4348 if (request.readyState === 4) { 4349 var result = request.responseText; 4350 var error = null; 4351 4352 try { 4353 result = JSON.parse(result); 4354 } catch(e) { 4355 error = errors.InvalidResponse(request.responseText); 4356 } 4357 4358 callback(error, result); 4359 } 4360 }; 4361 4362 try { 4363 request.send(JSON.stringify(payload)); 4364 } catch(error) { 4365 callback(errors.InvalidConnection(this.host)); 4366 } 4367 }; 4368 4369 /** 4370 * Synchronously tries to make Http request 4371 * 4372 * @method isConnected 4373 * @return {Boolean} returns true if request haven't failed. Otherwise false 4374 */ 4375 HttpProvider.prototype.isConnected = function() { 4376 try { 4377 this.send({ 4378 id: 9999999999, 4379 jsonrpc: '2.0', 4380 method: 'net_listening', 4381 params: [] 4382 }); 4383 return true; 4384 } catch(e) { 4385 return false; 4386 } 4387 }; 4388 4389 module.exports = HttpProvider; 4390 4391 4392 },{"./errors":26,"xmlhttprequest":17}],33:[function(require,module,exports){ 4393 /* 4394 This file is part of web3.js. 4395 4396 web3.js is free software: you can redistribute it and/or modify 4397 it under the terms of the GNU Lesser General Public License as published by 4398 the Free Software Foundation, either version 3 of the License, or 4399 (at your option) any later version. 4400 4401 web3.js is distributed in the hope that it will be useful, 4402 but WITHOUT ANY WARRANTY; without even the implied warranty of 4403 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4404 GNU Lesser General Public License for more details. 4405 4406 You should have received a copy of the GNU Lesser General Public License 4407 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4408 */ 4409 /** 4410 * @file iban.js 4411 * @author Marek Kotewicz <marek@ethdev.com> 4412 * @date 2015 4413 */ 4414 4415 var BigNumber = require('bignumber.js'); 4416 4417 var padLeft = function (string, bytes) { 4418 var result = string; 4419 while (result.length < bytes * 2) { 4420 result = '00' + result; 4421 } 4422 return result; 4423 }; 4424 4425 /** 4426 * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to 4427 * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. 4428 * 4429 * @method iso13616Prepare 4430 * @param {String} iban the IBAN 4431 * @returns {String} the prepared IBAN 4432 */ 4433 var iso13616Prepare = function (iban) { 4434 var A = 'A'.charCodeAt(0); 4435 var Z = 'Z'.charCodeAt(0); 4436 4437 iban = iban.toUpperCase(); 4438 iban = iban.substr(4) + iban.substr(0,4); 4439 4440 return iban.split('').map(function(n){ 4441 var code = n.charCodeAt(0); 4442 if (code >= A && code <= Z){ 4443 // A = 10, B = 11, ... Z = 35 4444 return code - A + 10; 4445 } else { 4446 return n; 4447 } 4448 }).join(''); 4449 }; 4450 4451 /** 4452 * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. 4453 * 4454 * @method mod9710 4455 * @param {String} iban 4456 * @returns {Number} 4457 */ 4458 var mod9710 = function (iban) { 4459 var remainder = iban, 4460 block; 4461 4462 while (remainder.length > 2){ 4463 block = remainder.slice(0, 9); 4464 remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); 4465 } 4466 4467 return parseInt(remainder, 10) % 97; 4468 }; 4469 4470 /** 4471 * This prototype should be used to create iban object from iban correct string 4472 * 4473 * @param {String} iban 4474 */ 4475 var Iban = function (iban) { 4476 this._iban = iban; 4477 }; 4478 4479 /** 4480 * This method should be used to create iban object from ethereum address 4481 * 4482 * @method fromAddress 4483 * @param {String} address 4484 * @return {Iban} the IBAN object 4485 */ 4486 Iban.fromAddress = function (address) { 4487 var asBn = new BigNumber(address, 16); 4488 var base36 = asBn.toString(36); 4489 var padded = padLeft(base36, 15); 4490 return Iban.fromBban(padded.toUpperCase()); 4491 }; 4492 4493 /** 4494 * Convert the passed BBAN to an IBAN for this country specification. 4495 * Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. 4496 * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits 4497 * 4498 * @method fromBban 4499 * @param {String} bban the BBAN to convert to IBAN 4500 * @returns {Iban} the IBAN object 4501 */ 4502 Iban.fromBban = function (bban) { 4503 var countryCode = 'XE'; 4504 4505 var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); 4506 var checkDigit = ('0' + (98 - remainder)).slice(-2); 4507 4508 return new Iban(countryCode + checkDigit + bban); 4509 }; 4510 4511 /** 4512 * Should be used to create IBAN object for given institution and identifier 4513 * 4514 * @method createIndirect 4515 * @param {Object} options, required options are "institution" and "identifier" 4516 * @return {Iban} the IBAN object 4517 */ 4518 Iban.createIndirect = function (options) { 4519 return Iban.fromBban('ETH' + options.institution + options.identifier); 4520 }; 4521 4522 /** 4523 * Thos method should be used to check if given string is valid iban object 4524 * 4525 * @method isValid 4526 * @param {String} iban string 4527 * @return {Boolean} true if it is valid IBAN 4528 */ 4529 Iban.isValid = function (iban) { 4530 var i = new Iban(iban); 4531 return i.isValid(); 4532 }; 4533 4534 /** 4535 * Should be called to check if iban is correct 4536 * 4537 * @method isValid 4538 * @returns {Boolean} true if it is, otherwise false 4539 */ 4540 Iban.prototype.isValid = function () { 4541 return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && 4542 mod9710(iso13616Prepare(this._iban)) === 1; 4543 }; 4544 4545 /** 4546 * Should be called to check if iban number is direct 4547 * 4548 * @method isDirect 4549 * @returns {Boolean} true if it is, otherwise false 4550 */ 4551 Iban.prototype.isDirect = function () { 4552 return this._iban.length === 34 || this._iban.length === 35; 4553 }; 4554 4555 /** 4556 * Should be called to check if iban number if indirect 4557 * 4558 * @method isIndirect 4559 * @returns {Boolean} true if it is, otherwise false 4560 */ 4561 Iban.prototype.isIndirect = function () { 4562 return this._iban.length === 20; 4563 }; 4564 4565 /** 4566 * Should be called to get iban checksum 4567 * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) 4568 * 4569 * @method checksum 4570 * @returns {String} checksum 4571 */ 4572 Iban.prototype.checksum = function () { 4573 return this._iban.substr(2, 2); 4574 }; 4575 4576 /** 4577 * Should be called to get institution identifier 4578 * eg. XREG 4579 * 4580 * @method institution 4581 * @returns {String} institution identifier 4582 */ 4583 Iban.prototype.institution = function () { 4584 return this.isIndirect() ? this._iban.substr(7, 4) : ''; 4585 }; 4586 4587 /** 4588 * Should be called to get client identifier within institution 4589 * eg. GAVOFYORK 4590 * 4591 * @method client 4592 * @returns {String} client identifier 4593 */ 4594 Iban.prototype.client = function () { 4595 return this.isIndirect() ? this._iban.substr(11) : ''; 4596 }; 4597 4598 /** 4599 * Should be called to get client direct address 4600 * 4601 * @method address 4602 * @returns {String} client direct address 4603 */ 4604 Iban.prototype.address = function () { 4605 if (this.isDirect()) { 4606 var base36 = this._iban.substr(4); 4607 var asBn = new BigNumber(base36, 36); 4608 return padLeft(asBn.toString(16), 20); 4609 } 4610 4611 return ''; 4612 }; 4613 4614 Iban.prototype.toString = function () { 4615 return this._iban; 4616 }; 4617 4618 module.exports = Iban; 4619 4620 4621 },{"bignumber.js":"bignumber.js"}],34:[function(require,module,exports){ 4622 /* 4623 This file is part of web3.js. 4624 4625 web3.js is free software: you can redistribute it and/or modify 4626 it under the terms of the GNU Lesser General Public License as published by 4627 the Free Software Foundation, either version 3 of the License, or 4628 (at your option) any later version. 4629 4630 web3.js is distributed in the hope that it will be useful, 4631 but WITHOUT ANY WARRANTY; without even the implied warranty of 4632 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4633 GNU Lesser General Public License for more details. 4634 4635 You should have received a copy of the GNU Lesser General Public License 4636 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4637 */ 4638 /** @file ipcprovider.js 4639 * @authors: 4640 * Fabian Vogelsteller <fabian@ethdev.com> 4641 * @date 2015 4642 */ 4643 4644 "use strict"; 4645 4646 var utils = require('../utils/utils'); 4647 var errors = require('./errors'); 4648 4649 4650 var IpcProvider = function (path, net) { 4651 var _this = this; 4652 this.responseCallbacks = {}; 4653 this.path = path; 4654 4655 this.connection = net.connect({path: this.path}); 4656 4657 this.connection.on('error', function(e){ 4658 console.error('IPC Connection Error', e); 4659 _this._timeout(); 4660 }); 4661 4662 this.connection.on('end', function(){ 4663 _this._timeout(); 4664 }); 4665 4666 4667 // LISTEN FOR CONNECTION RESPONSES 4668 this.connection.on('data', function(data) { 4669 /*jshint maxcomplexity: 6 */ 4670 4671 _this._parseResponse(data.toString()).forEach(function(result){ 4672 4673 var id = null; 4674 4675 // get the id which matches the returned id 4676 if(utils.isArray(result)) { 4677 result.forEach(function(load){ 4678 if(_this.responseCallbacks[load.id]) 4679 id = load.id; 4680 }); 4681 } else { 4682 id = result.id; 4683 } 4684 4685 // fire the callback 4686 if(_this.responseCallbacks[id]) { 4687 _this.responseCallbacks[id](null, result); 4688 delete _this.responseCallbacks[id]; 4689 } 4690 }); 4691 }); 4692 }; 4693 4694 /** 4695 Will parse the response and make an array out of it. 4696 4697 @method _parseResponse 4698 @param {String} data 4699 */ 4700 IpcProvider.prototype._parseResponse = function(data) { 4701 var _this = this, 4702 returnValues = []; 4703 4704 // DE-CHUNKER 4705 var dechunkedData = data 4706 .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ 4707 .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ 4708 .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ 4709 .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ 4710 .split('|--|'); 4711 4712 dechunkedData.forEach(function(data){ 4713 4714 // prepend the last chunk 4715 if(_this.lastChunk) 4716 data = _this.lastChunk + data; 4717 4718 var result = null; 4719 4720 try { 4721 result = JSON.parse(data); 4722 4723 } catch(e) { 4724 4725 _this.lastChunk = data; 4726 4727 // start timeout to cancel all requests 4728 clearTimeout(_this.lastChunkTimeout); 4729 _this.lastChunkTimeout = setTimeout(function(){ 4730 _this._timeout(); 4731 throw errors.InvalidResponse(data); 4732 }, 1000 * 15); 4733 4734 return; 4735 } 4736 4737 // cancel timeout and set chunk to null 4738 clearTimeout(_this.lastChunkTimeout); 4739 _this.lastChunk = null; 4740 4741 if(result) 4742 returnValues.push(result); 4743 }); 4744 4745 return returnValues; 4746 }; 4747 4748 4749 /** 4750 Get the adds a callback to the responseCallbacks object, 4751 which will be called if a response matching the response Id will arrive. 4752 4753 @method _addResponseCallback 4754 */ 4755 IpcProvider.prototype._addResponseCallback = function(payload, callback) { 4756 var id = payload.id || payload[0].id; 4757 var method = payload.method || payload[0].method; 4758 4759 this.responseCallbacks[id] = callback; 4760 this.responseCallbacks[id].method = method; 4761 }; 4762 4763 /** 4764 Timeout all requests when the end/error event is fired 4765 4766 @method _timeout 4767 */ 4768 IpcProvider.prototype._timeout = function() { 4769 for(var key in this.responseCallbacks) { 4770 if(this.responseCallbacks.hasOwnProperty(key)){ 4771 this.responseCallbacks[key](errors.InvalidConnection('on IPC')); 4772 delete this.responseCallbacks[key]; 4773 } 4774 } 4775 }; 4776 4777 4778 /** 4779 Check if the current connection is still valid. 4780 4781 @method isConnected 4782 */ 4783 IpcProvider.prototype.isConnected = function() { 4784 var _this = this; 4785 4786 // try reconnect, when connection is gone 4787 if(!_this.connection.writable) 4788 _this.connection.connect({path: _this.path}); 4789 4790 return !!this.connection.writable; 4791 }; 4792 4793 IpcProvider.prototype.send = function (payload) { 4794 4795 if(this.connection.writeSync) { 4796 var result; 4797 4798 // try reconnect, when connection is gone 4799 if(!this.connection.writable) 4800 this.connection.connect({path: this.path}); 4801 4802 var data = this.connection.writeSync(JSON.stringify(payload)); 4803 4804 try { 4805 result = JSON.parse(data); 4806 } catch(e) { 4807 throw errors.InvalidResponse(data); 4808 } 4809 4810 return result; 4811 4812 } else { 4813 throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported by the IPC provider.'); 4814 } 4815 }; 4816 4817 IpcProvider.prototype.sendAsync = function (payload, callback) { 4818 // try reconnect, when connection is gone 4819 if(!this.connection.writable) 4820 this.connection.connect({path: this.path}); 4821 4822 4823 this.connection.write(JSON.stringify(payload)); 4824 this._addResponseCallback(payload, callback); 4825 }; 4826 4827 module.exports = IpcProvider; 4828 4829 4830 },{"../utils/utils":20,"./errors":26}],35:[function(require,module,exports){ 4831 /* 4832 This file is part of web3.js. 4833 4834 web3.js is free software: you can redistribute it and/or modify 4835 it under the terms of the GNU Lesser General Public License as published by 4836 the Free Software Foundation, either version 3 of the License, or 4837 (at your option) any later version. 4838 4839 web3.js is distributed in the hope that it will be useful, 4840 but WITHOUT ANY WARRANTY; without even the implied warranty of 4841 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4842 GNU Lesser General Public License for more details. 4843 4844 You should have received a copy of the GNU Lesser General Public License 4845 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4846 */ 4847 /** @file jsonrpc.js 4848 * @authors: 4849 * Marek Kotewicz <marek@ethdev.com> 4850 * @date 2015 4851 */ 4852 4853 var Jsonrpc = function () { 4854 // singleton pattern 4855 if (arguments.callee._singletonInstance) { 4856 return arguments.callee._singletonInstance; 4857 } 4858 arguments.callee._singletonInstance = this; 4859 4860 this.messageId = 1; 4861 }; 4862 4863 /** 4864 * @return {Jsonrpc} singleton 4865 */ 4866 Jsonrpc.getInstance = function () { 4867 var instance = new Jsonrpc(); 4868 return instance; 4869 }; 4870 4871 /** 4872 * Should be called to valid json create payload object 4873 * 4874 * @method toPayload 4875 * @param {Function} method of jsonrpc call, required 4876 * @param {Array} params, an array of method params, optional 4877 * @returns {Object} valid jsonrpc payload object 4878 */ 4879 Jsonrpc.prototype.toPayload = function (method, params) { 4880 if (!method) 4881 console.error('jsonrpc method should be specified!'); 4882 4883 return { 4884 jsonrpc: '2.0', 4885 method: method, 4886 params: params || [], 4887 id: this.messageId++ 4888 }; 4889 }; 4890 4891 /** 4892 * Should be called to check if jsonrpc response is valid 4893 * 4894 * @method isValidResponse 4895 * @param {Object} 4896 * @returns {Boolean} true if response is valid, otherwise false 4897 */ 4898 Jsonrpc.prototype.isValidResponse = function (response) { 4899 return !!response && 4900 !response.error && 4901 response.jsonrpc === '2.0' && 4902 typeof response.id === 'number' && 4903 response.result !== undefined; // only undefined is not valid json object 4904 }; 4905 4906 /** 4907 * Should be called to create batch payload object 4908 * 4909 * @method toBatchPayload 4910 * @param {Array} messages, an array of objects with method (required) and params (optional) fields 4911 * @returns {Array} batch payload 4912 */ 4913 Jsonrpc.prototype.toBatchPayload = function (messages) { 4914 var self = this; 4915 return messages.map(function (message) { 4916 return self.toPayload(message.method, message.params); 4917 }); 4918 }; 4919 4920 module.exports = Jsonrpc; 4921 4922 4923 },{}],36:[function(require,module,exports){ 4924 /* 4925 This file is part of web3.js. 4926 4927 web3.js is free software: you can redistribute it and/or modify 4928 it under the terms of the GNU Lesser General Public License as published by 4929 the Free Software Foundation, either version 3 of the License, or 4930 (at your option) any later version. 4931 4932 web3.js is distributed in the hope that it will be useful, 4933 but WITHOUT ANY WARRANTY; without even the implied warranty of 4934 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4935 GNU Lesser General Public License for more details. 4936 4937 You should have received a copy of the GNU Lesser General Public License 4938 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4939 */ 4940 /** 4941 * @file method.js 4942 * @author Marek Kotewicz <marek@ethdev.com> 4943 * @date 2015 4944 */ 4945 4946 var utils = require('../utils/utils'); 4947 var errors = require('./errors'); 4948 4949 var Method = function (options) { 4950 this.name = options.name; 4951 this.call = options.call; 4952 this.params = options.params || 0; 4953 this.inputFormatter = options.inputFormatter; 4954 this.outputFormatter = options.outputFormatter; 4955 this.requestManager = null; 4956 }; 4957 4958 Method.prototype.setRequestManager = function (rm) { 4959 this.requestManager = rm; 4960 }; 4961 4962 /** 4963 * Should be used to determine name of the jsonrpc method based on arguments 4964 * 4965 * @method getCall 4966 * @param {Array} arguments 4967 * @return {String} name of jsonrpc method 4968 */ 4969 Method.prototype.getCall = function (args) { 4970 return utils.isFunction(this.call) ? this.call(args) : this.call; 4971 }; 4972 4973 /** 4974 * Should be used to extract callback from array of arguments. Modifies input param 4975 * 4976 * @method extractCallback 4977 * @param {Array} arguments 4978 * @return {Function|Null} callback, if exists 4979 */ 4980 Method.prototype.extractCallback = function (args) { 4981 if (utils.isFunction(args[args.length - 1])) { 4982 return args.pop(); // modify the args array! 4983 } 4984 }; 4985 4986 /** 4987 * Should be called to check if the number of arguments is correct 4988 * 4989 * @method validateArgs 4990 * @param {Array} arguments 4991 * @throws {Error} if it is not 4992 */ 4993 Method.prototype.validateArgs = function (args) { 4994 if (args.length !== this.params) { 4995 throw errors.InvalidNumberOfParams(); 4996 } 4997 }; 4998 4999 /** 5000 * Should be called to format input args of method 5001 * 5002 * @method formatInput 5003 * @param {Array} 5004 * @return {Array} 5005 */ 5006 Method.prototype.formatInput = function (args) { 5007 if (!this.inputFormatter) { 5008 return args; 5009 } 5010 5011 return this.inputFormatter.map(function (formatter, index) { 5012 return formatter ? formatter(args[index]) : args[index]; 5013 }); 5014 }; 5015 5016 /** 5017 * Should be called to format output(result) of method 5018 * 5019 * @method formatOutput 5020 * @param {Object} 5021 * @return {Object} 5022 */ 5023 Method.prototype.formatOutput = function (result) { 5024 return this.outputFormatter && result ? this.outputFormatter(result) : result; 5025 }; 5026 5027 /** 5028 * Should create payload from given input args 5029 * 5030 * @method toPayload 5031 * @param {Array} args 5032 * @return {Object} 5033 */ 5034 Method.prototype.toPayload = function (args) { 5035 var call = this.getCall(args); 5036 var callback = this.extractCallback(args); 5037 var params = this.formatInput(args); 5038 this.validateArgs(params); 5039 5040 return { 5041 method: call, 5042 params: params, 5043 callback: callback 5044 }; 5045 }; 5046 5047 Method.prototype.attachToObject = function (obj) { 5048 var func = this.buildCall(); 5049 func.call = this.call; // TODO!!! that's ugly. filter.js uses it 5050 var name = this.name.split('.'); 5051 if (name.length > 1) { 5052 obj[name[0]] = obj[name[0]] || {}; 5053 obj[name[0]][name[1]] = func; 5054 } else { 5055 obj[name[0]] = func; 5056 } 5057 }; 5058 5059 Method.prototype.buildCall = function() { 5060 var method = this; 5061 var send = function () { 5062 var payload = method.toPayload(Array.prototype.slice.call(arguments)); 5063 if (payload.callback) { 5064 return method.requestManager.sendAsync(payload, function (err, result) { 5065 payload.callback(err, method.formatOutput(result)); 5066 }); 5067 } 5068 return method.formatOutput(method.requestManager.send(payload)); 5069 }; 5070 send.request = this.request.bind(this); 5071 return send; 5072 }; 5073 5074 /** 5075 * Should be called to create pure JSONRPC request which can be used in batch request 5076 * 5077 * @method request 5078 * @param {...} params 5079 * @return {Object} jsonrpc request 5080 */ 5081 Method.prototype.request = function () { 5082 var payload = this.toPayload(Array.prototype.slice.call(arguments)); 5083 payload.format = this.formatOutput.bind(this); 5084 return payload; 5085 }; 5086 5087 module.exports = Method; 5088 5089 5090 },{"../utils/utils":20,"./errors":26}],37:[function(require,module,exports){ 5091 /* 5092 This file is part of web3.js. 5093 5094 web3.js is free software: you can redistribute it and/or modify 5095 it under the terms of the GNU Lesser General Public License as published by 5096 the Free Software Foundation, either version 3 of the License, or 5097 (at your option) any later version. 5098 5099 web3.js is distributed in the hope that it will be useful, 5100 but WITHOUT ANY WARRANTY; without even the implied warranty of 5101 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5102 GNU Lesser General Public License for more details. 5103 5104 You should have received a copy of the GNU Lesser General Public License 5105 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5106 */ 5107 /** @file db.js 5108 * @authors: 5109 * Marek Kotewicz <marek@ethdev.com> 5110 * @date 2015 5111 */ 5112 5113 var Method = require('../method'); 5114 5115 var DB = function (web3) { 5116 this._requestManager = web3._requestManager; 5117 5118 var self = this; 5119 5120 methods().forEach(function(method) { 5121 method.attachToObject(self); 5122 method.setRequestManager(web3._requestManager); 5123 }); 5124 }; 5125 5126 var methods = function () { 5127 var putString = new Method({ 5128 name: 'putString', 5129 call: 'db_putString', 5130 params: 3 5131 }); 5132 5133 var getString = new Method({ 5134 name: 'getString', 5135 call: 'db_getString', 5136 params: 2 5137 }); 5138 5139 var putHex = new Method({ 5140 name: 'putHex', 5141 call: 'db_putHex', 5142 params: 3 5143 }); 5144 5145 var getHex = new Method({ 5146 name: 'getHex', 5147 call: 'db_getHex', 5148 params: 2 5149 }); 5150 5151 return [ 5152 putString, getString, putHex, getHex 5153 ]; 5154 }; 5155 5156 module.exports = DB; 5157 5158 },{"../method":36}],38:[function(require,module,exports){ 5159 /* 5160 This file is part of web3.js. 5161 5162 web3.js is free software: you can redistribute it and/or modify 5163 it under the terms of the GNU Lesser General Public License as published by 5164 the Free Software Foundation, either version 3 of the License, or 5165 (at your option) any later version. 5166 5167 web3.js is distributed in the hope that it will be useful, 5168 but WITHOUT ANY WARRANTY; without even the implied warranty of 5169 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5170 GNU Lesser General Public License for more details. 5171 5172 You should have received a copy of the GNU Lesser General Public License 5173 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5174 */ 5175 /** 5176 * @file eth.js 5177 * @author Marek Kotewicz <marek@ethdev.com> 5178 * @author Fabian Vogelsteller <fabian@ethdev.com> 5179 * @date 2015 5180 */ 5181 5182 "use strict"; 5183 5184 var formatters = require('../formatters'); 5185 var utils = require('../../utils/utils'); 5186 var Method = require('../method'); 5187 var Property = require('../property'); 5188 var c = require('../../utils/config'); 5189 var Contract = require('../contract'); 5190 var watches = require('./watches'); 5191 var Filter = require('../filter'); 5192 var IsSyncing = require('../syncing'); 5193 var namereg = require('../namereg'); 5194 var Iban = require('../iban'); 5195 var transfer = require('../transfer'); 5196 5197 var blockCall = function (args) { 5198 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber"; 5199 }; 5200 5201 var transactionFromBlockCall = function (args) { 5202 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex'; 5203 }; 5204 5205 var uncleCall = function (args) { 5206 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex'; 5207 }; 5208 5209 var getBlockTransactionCountCall = function (args) { 5210 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber'; 5211 }; 5212 5213 var uncleCountCall = function (args) { 5214 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber'; 5215 }; 5216 5217 function Eth(web3) { 5218 this._requestManager = web3._requestManager; 5219 5220 var self = this; 5221 5222 methods().forEach(function(method) { 5223 method.attachToObject(self); 5224 method.setRequestManager(self._requestManager); 5225 }); 5226 5227 properties().forEach(function(p) { 5228 p.attachToObject(self); 5229 p.setRequestManager(self._requestManager); 5230 }); 5231 5232 5233 this.iban = Iban; 5234 this.sendIBANTransaction = transfer.bind(null, this); 5235 } 5236 5237 Object.defineProperty(Eth.prototype, 'defaultBlock', { 5238 get: function () { 5239 return c.defaultBlock; 5240 }, 5241 set: function (val) { 5242 c.defaultBlock = val; 5243 return val; 5244 } 5245 }); 5246 5247 Object.defineProperty(Eth.prototype, 'defaultAccount', { 5248 get: function () { 5249 return c.defaultAccount; 5250 }, 5251 set: function (val) { 5252 c.defaultAccount = val; 5253 return val; 5254 } 5255 }); 5256 5257 var methods = function () { 5258 var getBalance = new Method({ 5259 name: 'getBalance', 5260 call: 'eth_getBalance', 5261 params: 2, 5262 inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter], 5263 outputFormatter: formatters.outputBigNumberFormatter 5264 }); 5265 5266 var getStorageAt = new Method({ 5267 name: 'getStorageAt', 5268 call: 'eth_getStorageAt', 5269 params: 3, 5270 inputFormatter: [null, utils.toHex, formatters.inputDefaultBlockNumberFormatter] 5271 }); 5272 5273 var getCode = new Method({ 5274 name: 'getCode', 5275 call: 'eth_getCode', 5276 params: 2, 5277 inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter] 5278 }); 5279 5280 var getBlock = new Method({ 5281 name: 'getBlock', 5282 call: blockCall, 5283 params: 2, 5284 inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }], 5285 outputFormatter: formatters.outputBlockFormatter 5286 }); 5287 5288 var getUncle = new Method({ 5289 name: 'getUncle', 5290 call: uncleCall, 5291 params: 2, 5292 inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex], 5293 outputFormatter: formatters.outputBlockFormatter, 5294 5295 }); 5296 5297 var getCompilers = new Method({ 5298 name: 'getCompilers', 5299 call: 'eth_getCompilers', 5300 params: 0 5301 }); 5302 5303 var getBlockTransactionCount = new Method({ 5304 name: 'getBlockTransactionCount', 5305 call: getBlockTransactionCountCall, 5306 params: 1, 5307 inputFormatter: [formatters.inputBlockNumberFormatter], 5308 outputFormatter: utils.toDecimal 5309 }); 5310 5311 var getBlockUncleCount = new Method({ 5312 name: 'getBlockUncleCount', 5313 call: uncleCountCall, 5314 params: 1, 5315 inputFormatter: [formatters.inputBlockNumberFormatter], 5316 outputFormatter: utils.toDecimal 5317 }); 5318 5319 var getTransaction = new Method({ 5320 name: 'getTransaction', 5321 call: 'eth_getTransactionByHash', 5322 params: 1, 5323 outputFormatter: formatters.outputTransactionFormatter 5324 }); 5325 5326 var getTransactionFromBlock = new Method({ 5327 name: 'getTransactionFromBlock', 5328 call: transactionFromBlockCall, 5329 params: 2, 5330 inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex], 5331 outputFormatter: formatters.outputTransactionFormatter 5332 }); 5333 5334 var getTransactionReceipt = new Method({ 5335 name: 'getTransactionReceipt', 5336 call: 'eth_getTransactionReceipt', 5337 params: 1, 5338 outputFormatter: formatters.outputTransactionReceiptFormatter 5339 }); 5340 5341 var getTransactionCount = new Method({ 5342 name: 'getTransactionCount', 5343 call: 'eth_getTransactionCount', 5344 params: 2, 5345 inputFormatter: [null, formatters.inputDefaultBlockNumberFormatter], 5346 outputFormatter: utils.toDecimal 5347 }); 5348 5349 var sendRawTransaction = new Method({ 5350 name: 'sendRawTransaction', 5351 call: 'eth_sendRawTransaction', 5352 params: 1, 5353 inputFormatter: [null] 5354 }); 5355 5356 var sendTransaction = new Method({ 5357 name: 'sendTransaction', 5358 call: 'eth_sendTransaction', 5359 params: 1, 5360 inputFormatter: [formatters.inputTransactionFormatter] 5361 }); 5362 5363 var sign = new Method({ 5364 name: 'sign', 5365 call: 'eth_sign', 5366 params: 2, 5367 inputFormatter: [formatters.inputAddressFormatter, null] 5368 }); 5369 5370 var call = new Method({ 5371 name: 'call', 5372 call: 'eth_call', 5373 params: 2, 5374 inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter] 5375 }); 5376 5377 var estimateGas = new Method({ 5378 name: 'estimateGas', 5379 call: 'eth_estimateGas', 5380 params: 1, 5381 inputFormatter: [formatters.inputCallFormatter], 5382 outputFormatter: utils.toDecimal 5383 }); 5384 5385 var compileSolidity = new Method({ 5386 name: 'compile.solidity', 5387 call: 'eth_compileSolidity', 5388 params: 1 5389 }); 5390 5391 var compileLLL = new Method({ 5392 name: 'compile.lll', 5393 call: 'eth_compileLLL', 5394 params: 1 5395 }); 5396 5397 var compileSerpent = new Method({ 5398 name: 'compile.serpent', 5399 call: 'eth_compileSerpent', 5400 params: 1 5401 }); 5402 5403 var submitWork = new Method({ 5404 name: 'submitWork', 5405 call: 'eth_submitWork', 5406 params: 3 5407 }); 5408 5409 var getWork = new Method({ 5410 name: 'getWork', 5411 call: 'eth_getWork', 5412 params: 0 5413 }); 5414 5415 return [ 5416 getBalance, 5417 getStorageAt, 5418 getCode, 5419 getBlock, 5420 getUncle, 5421 getCompilers, 5422 getBlockTransactionCount, 5423 getBlockUncleCount, 5424 getTransaction, 5425 getTransactionFromBlock, 5426 getTransactionReceipt, 5427 getTransactionCount, 5428 call, 5429 estimateGas, 5430 sendRawTransaction, 5431 sendTransaction, 5432 sign, 5433 compileSolidity, 5434 compileLLL, 5435 compileSerpent, 5436 submitWork, 5437 getWork 5438 ]; 5439 }; 5440 5441 5442 var properties = function () { 5443 return [ 5444 new Property({ 5445 name: 'coinbase', 5446 getter: 'eth_coinbase' 5447 }), 5448 new Property({ 5449 name: 'mining', 5450 getter: 'eth_mining' 5451 }), 5452 new Property({ 5453 name: 'hashrate', 5454 getter: 'eth_hashrate', 5455 outputFormatter: utils.toDecimal 5456 }), 5457 new Property({ 5458 name: 'syncing', 5459 getter: 'eth_syncing', 5460 outputFormatter: formatters.outputSyncingFormatter 5461 }), 5462 new Property({ 5463 name: 'gasPrice', 5464 getter: 'eth_gasPrice', 5465 outputFormatter: formatters.outputBigNumberFormatter 5466 }), 5467 new Property({ 5468 name: 'accounts', 5469 getter: 'eth_accounts' 5470 }), 5471 new Property({ 5472 name: 'blockNumber', 5473 getter: 'eth_blockNumber', 5474 outputFormatter: utils.toDecimal 5475 }) 5476 ]; 5477 }; 5478 5479 Eth.prototype.contract = function (abi) { 5480 var factory = new Contract(this, abi); 5481 return factory; 5482 }; 5483 5484 Eth.prototype.filter = function (fil, callback) { 5485 return new Filter(this._requestManager, fil, watches.eth(), formatters.outputLogFormatter, callback); 5486 }; 5487 5488 Eth.prototype.namereg = function () { 5489 return this.contract(namereg.global.abi).at(namereg.global.address); 5490 }; 5491 5492 Eth.prototype.icapNamereg = function () { 5493 return this.contract(namereg.icap.abi).at(namereg.icap.address); 5494 }; 5495 5496 Eth.prototype.isSyncing = function (callback) { 5497 return new IsSyncing(this._requestManager, callback); 5498 }; 5499 5500 module.exports = Eth; 5501 5502 5503 },{"../../utils/config":18,"../../utils/utils":20,"../contract":25,"../filter":29,"../formatters":30,"../iban":33,"../method":36,"../namereg":43,"../property":44,"../syncing":47,"../transfer":48,"./watches":42}],39:[function(require,module,exports){ 5504 /* 5505 This file is part of web3.js. 5506 5507 web3.js is free software: you can redistribute it and/or modify 5508 it under the terms of the GNU Lesser General Public License as published by 5509 the Free Software Foundation, either version 3 of the License, or 5510 (at your option) any later version. 5511 5512 web3.js is distributed in the hope that it will be useful, 5513 but WITHOUT ANY WARRANTY; without even the implied warranty of 5514 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5515 GNU Lesser General Public License for more details. 5516 5517 You should have received a copy of the GNU Lesser General Public License 5518 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5519 */ 5520 /** @file eth.js 5521 * @authors: 5522 * Marek Kotewicz <marek@ethdev.com> 5523 * @date 2015 5524 */ 5525 5526 var utils = require('../../utils/utils'); 5527 var Property = require('../property'); 5528 5529 var Net = function (web3) { 5530 this._requestManager = web3._requestManager; 5531 5532 var self = this; 5533 5534 properties().forEach(function(p) { 5535 p.attachToObject(self); 5536 p.setRequestManager(web3._requestManager); 5537 }); 5538 }; 5539 5540 /// @returns an array of objects describing web3.eth api properties 5541 var properties = function () { 5542 return [ 5543 new Property({ 5544 name: 'listening', 5545 getter: 'net_listening' 5546 }), 5547 new Property({ 5548 name: 'peerCount', 5549 getter: 'net_peerCount', 5550 outputFormatter: utils.toDecimal 5551 }) 5552 ]; 5553 }; 5554 5555 module.exports = Net; 5556 5557 },{"../../utils/utils":20,"../property":44}],40:[function(require,module,exports){ 5558 /* 5559 This file is part of web3.js. 5560 5561 web3.js is free software: you can redistribute it and/or modify 5562 it under the terms of the GNU Lesser General Public License as published by 5563 the Free Software Foundation, either version 3 of the License, or 5564 (at your option) any later version. 5565 5566 web3.js is distributed in the hope that it will be useful, 5567 but WITHOUT ANY WARRANTY; without even the implied warranty of 5568 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5569 GNU Lesser General Public License for more details. 5570 5571 You should have received a copy of the GNU Lesser General Public License 5572 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5573 */ 5574 /** 5575 * @file eth.js 5576 * @author Marek Kotewicz <marek@ethdev.com> 5577 * @author Fabian Vogelsteller <fabian@ethdev.com> 5578 * @date 2015 5579 */ 5580 5581 "use strict"; 5582 5583 var Method = require('../method'); 5584 var Property = require('../property'); 5585 var formatters = require('../formatters'); 5586 5587 function Personal(web3) { 5588 this._requestManager = web3._requestManager; 5589 5590 var self = this; 5591 5592 methods().forEach(function(method) { 5593 method.attachToObject(self); 5594 method.setRequestManager(self._requestManager); 5595 }); 5596 5597 properties().forEach(function(p) { 5598 p.attachToObject(self); 5599 p.setRequestManager(self._requestManager); 5600 }); 5601 } 5602 5603 var methods = function () { 5604 var newAccount = new Method({ 5605 name: 'newAccount', 5606 call: 'personal_newAccount', 5607 params: 1, 5608 inputFormatter: [null] 5609 }); 5610 5611 var unlockAccount = new Method({ 5612 name: 'unlockAccount', 5613 call: 'personal_unlockAccount', 5614 params: 3, 5615 inputFormatter: [formatters.inputAddressFormatter, null, null] 5616 }); 5617 5618 var lockAccount = new Method({ 5619 name: 'lockAccount', 5620 call: 'personal_lockAccount', 5621 params: 1, 5622 inputFormatter: [formatters.inputAddressFormatter] 5623 }); 5624 5625 var sign = new Method({ 5626 name: 'sign', 5627 call: 'personal_sign', 5628 params: 3, 5629 inputFormatter: [null, formatters.inputAddressFormatter, null] 5630 }); 5631 5632 return [ 5633 newAccount, 5634 unlockAccount, 5635 lockAccount, 5636 sign 5637 ]; 5638 }; 5639 5640 var properties = function () { 5641 return [ 5642 new Property({ 5643 name: 'listAccounts', 5644 getter: 'personal_listAccounts' 5645 }) 5646 ]; 5647 }; 5648 5649 5650 module.exports = Personal; 5651 5652 },{"../formatters":30,"../method":36,"../property":44}],41:[function(require,module,exports){ 5653 /* 5654 This file is part of web3.js. 5655 5656 web3.js is free software: you can redistribute it and/or modify 5657 it under the terms of the GNU Lesser General Public License as published by 5658 the Free Software Foundation, either version 3 of the License, or 5659 (at your option) any later version. 5660 5661 web3.js is distributed in the hope that it will be useful, 5662 but WITHOUT ANY WARRANTY; without even the implied warranty of 5663 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5664 GNU Lesser General Public License for more details. 5665 5666 You should have received a copy of the GNU Lesser General Public License 5667 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5668 */ 5669 /** @file shh.js 5670 * @authors: 5671 * Marek Kotewicz <marek@ethdev.com> 5672 * @date 2015 5673 */ 5674 5675 var Method = require('../method'); 5676 var formatters = require('../formatters'); 5677 var Filter = require('../filter'); 5678 var watches = require('./watches'); 5679 5680 var Shh = function (web3) { 5681 this._requestManager = web3._requestManager; 5682 5683 var self = this; 5684 5685 methods().forEach(function(method) { 5686 method.attachToObject(self); 5687 method.setRequestManager(self._requestManager); 5688 }); 5689 }; 5690 5691 Shh.prototype.filter = function (fil, callback) { 5692 return new Filter(this._requestManager, fil, watches.shh(), formatters.outputPostFormatter, callback); 5693 }; 5694 5695 var methods = function () { 5696 5697 var post = new Method({ 5698 name: 'post', 5699 call: 'shh_post', 5700 params: 1, 5701 inputFormatter: [formatters.inputPostFormatter] 5702 }); 5703 5704 var newIdentity = new Method({ 5705 name: 'newIdentity', 5706 call: 'shh_newIdentity', 5707 params: 0 5708 }); 5709 5710 var hasIdentity = new Method({ 5711 name: 'hasIdentity', 5712 call: 'shh_hasIdentity', 5713 params: 1 5714 }); 5715 5716 var newGroup = new Method({ 5717 name: 'newGroup', 5718 call: 'shh_newGroup', 5719 params: 0 5720 }); 5721 5722 var addToGroup = new Method({ 5723 name: 'addToGroup', 5724 call: 'shh_addToGroup', 5725 params: 0 5726 }); 5727 5728 return [ 5729 post, 5730 newIdentity, 5731 hasIdentity, 5732 newGroup, 5733 addToGroup 5734 ]; 5735 }; 5736 5737 module.exports = Shh; 5738 5739 5740 },{"../filter":29,"../formatters":30,"../method":36,"./watches":42}],42:[function(require,module,exports){ 5741 /* 5742 This file is part of web3.js. 5743 5744 web3.js is free software: you can redistribute it and/or modify 5745 it under the terms of the GNU Lesser General Public License as published by 5746 the Free Software Foundation, either version 3 of the License, or 5747 (at your option) any later version. 5748 5749 web3.js is distributed in the hope that it will be useful, 5750 but WITHOUT ANY WARRANTY; without even the implied warranty of 5751 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5752 GNU Lesser General Public License for more details. 5753 5754 You should have received a copy of the GNU Lesser General Public License 5755 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5756 */ 5757 /** @file watches.js 5758 * @authors: 5759 * Marek Kotewicz <marek@ethdev.com> 5760 * @date 2015 5761 */ 5762 5763 var Method = require('../method'); 5764 5765 /// @returns an array of objects describing web3.eth.filter api methods 5766 var eth = function () { 5767 var newFilterCall = function (args) { 5768 var type = args[0]; 5769 5770 switch(type) { 5771 case 'latest': 5772 args.shift(); 5773 this.params = 0; 5774 return 'eth_newBlockFilter'; 5775 case 'pending': 5776 args.shift(); 5777 this.params = 0; 5778 return 'eth_newPendingTransactionFilter'; 5779 default: 5780 return 'eth_newFilter'; 5781 } 5782 }; 5783 5784 var newFilter = new Method({ 5785 name: 'newFilter', 5786 call: newFilterCall, 5787 params: 1 5788 }); 5789 5790 var uninstallFilter = new Method({ 5791 name: 'uninstallFilter', 5792 call: 'eth_uninstallFilter', 5793 params: 1 5794 }); 5795 5796 var getLogs = new Method({ 5797 name: 'getLogs', 5798 call: 'eth_getFilterLogs', 5799 params: 1 5800 }); 5801 5802 var poll = new Method({ 5803 name: 'poll', 5804 call: 'eth_getFilterChanges', 5805 params: 1 5806 }); 5807 5808 return [ 5809 newFilter, 5810 uninstallFilter, 5811 getLogs, 5812 poll 5813 ]; 5814 }; 5815 5816 /// @returns an array of objects describing web3.shh.watch api methods 5817 var shh = function () { 5818 var newFilter = new Method({ 5819 name: 'newFilter', 5820 call: 'shh_newFilter', 5821 params: 1 5822 }); 5823 5824 var uninstallFilter = new Method({ 5825 name: 'uninstallFilter', 5826 call: 'shh_uninstallFilter', 5827 params: 1 5828 }); 5829 5830 var getLogs = new Method({ 5831 name: 'getLogs', 5832 call: 'shh_getMessages', 5833 params: 1 5834 }); 5835 5836 var poll = new Method({ 5837 name: 'poll', 5838 call: 'shh_getFilterChanges', 5839 params: 1 5840 }); 5841 5842 return [ 5843 newFilter, 5844 uninstallFilter, 5845 getLogs, 5846 poll 5847 ]; 5848 }; 5849 5850 module.exports = { 5851 eth: eth, 5852 shh: shh 5853 }; 5854 5855 5856 },{"../method":36}],43:[function(require,module,exports){ 5857 /* 5858 This file is part of web3.js. 5859 5860 web3.js is free software: you can redistribute it and/or modify 5861 it under the terms of the GNU Lesser General Public License as published by 5862 the Free Software Foundation, either version 3 of the License, or 5863 (at your option) any later version. 5864 5865 web3.js is distributed in the hope that it will be useful, 5866 but WITHOUT ANY WARRANTY; without even the implied warranty of 5867 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5868 GNU Lesser General Public License for more details. 5869 5870 You should have received a copy of the GNU Lesser General Public License 5871 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5872 */ 5873 /** 5874 * @file namereg.js 5875 * @author Marek Kotewicz <marek@ethdev.com> 5876 * @date 2015 5877 */ 5878 5879 var globalRegistrarAbi = require('../contracts/GlobalRegistrar.json'); 5880 var icapRegistrarAbi= require('../contracts/ICAPRegistrar.json'); 5881 5882 var globalNameregAddress = '0xc6d9d2cd449a754c494264e1809c50e34d64562b'; 5883 var icapNameregAddress = '0xa1a111bc074c9cfa781f0c38e63bd51c91b8af00'; 5884 5885 module.exports = { 5886 global: { 5887 abi: globalRegistrarAbi, 5888 address: globalNameregAddress 5889 }, 5890 icap: { 5891 abi: icapRegistrarAbi, 5892 address: icapNameregAddress 5893 } 5894 }; 5895 5896 5897 },{"../contracts/GlobalRegistrar.json":1,"../contracts/ICAPRegistrar.json":2}],44:[function(require,module,exports){ 5898 /* 5899 This file is part of web3.js. 5900 5901 web3.js is free software: you can redistribute it and/or modify 5902 it under the terms of the GNU Lesser General Public License as published by 5903 the Free Software Foundation, either version 3 of the License, or 5904 (at your option) any later version. 5905 5906 web3.js is distributed in the hope that it will be useful, 5907 but WITHOUT ANY WARRANTY; without even the implied warranty of 5908 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5909 GNU Lesser General Public License for more details. 5910 5911 You should have received a copy of the GNU Lesser General Public License 5912 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5913 */ 5914 /** 5915 * @file property.js 5916 * @author Fabian Vogelsteller <fabian@frozeman.de> 5917 * @author Marek Kotewicz <marek@ethdev.com> 5918 * @date 2015 5919 */ 5920 5921 var utils = require('../utils/utils'); 5922 5923 var Property = function (options) { 5924 this.name = options.name; 5925 this.getter = options.getter; 5926 this.setter = options.setter; 5927 this.outputFormatter = options.outputFormatter; 5928 this.inputFormatter = options.inputFormatter; 5929 this.requestManager = null; 5930 }; 5931 5932 Property.prototype.setRequestManager = function (rm) { 5933 this.requestManager = rm; 5934 }; 5935 5936 /** 5937 * Should be called to format input args of method 5938 * 5939 * @method formatInput 5940 * @param {Array} 5941 * @return {Array} 5942 */ 5943 Property.prototype.formatInput = function (arg) { 5944 return this.inputFormatter ? this.inputFormatter(arg) : arg; 5945 }; 5946 5947 /** 5948 * Should be called to format output(result) of method 5949 * 5950 * @method formatOutput 5951 * @param {Object} 5952 * @return {Object} 5953 */ 5954 Property.prototype.formatOutput = function (result) { 5955 return this.outputFormatter && result !== null ? this.outputFormatter(result) : result; 5956 }; 5957 5958 /** 5959 * Should be used to extract callback from array of arguments. Modifies input param 5960 * 5961 * @method extractCallback 5962 * @param {Array} arguments 5963 * @return {Function|Null} callback, if exists 5964 */ 5965 Property.prototype.extractCallback = function (args) { 5966 if (utils.isFunction(args[args.length - 1])) { 5967 return args.pop(); // modify the args array! 5968 } 5969 }; 5970 5971 5972 /** 5973 * Should attach function to method 5974 * 5975 * @method attachToObject 5976 * @param {Object} 5977 * @param {Function} 5978 */ 5979 Property.prototype.attachToObject = function (obj) { 5980 var proto = { 5981 get: this.buildGet(), 5982 enumerable: true 5983 }; 5984 5985 var names = this.name.split('.'); 5986 var name = names[0]; 5987 if (names.length > 1) { 5988 obj[names[0]] = obj[names[0]] || {}; 5989 obj = obj[names[0]]; 5990 name = names[1]; 5991 } 5992 5993 Object.defineProperty(obj, name, proto); 5994 obj[asyncGetterName(name)] = this.buildAsyncGet(); 5995 }; 5996 5997 var asyncGetterName = function (name) { 5998 return 'get' + name.charAt(0).toUpperCase() + name.slice(1); 5999 }; 6000 6001 Property.prototype.buildGet = function () { 6002 var property = this; 6003 return function get() { 6004 return property.formatOutput(property.requestManager.send({ 6005 method: property.getter 6006 })); 6007 }; 6008 }; 6009 6010 Property.prototype.buildAsyncGet = function () { 6011 var property = this; 6012 var get = function (callback) { 6013 property.requestManager.sendAsync({ 6014 method: property.getter 6015 }, function (err, result) { 6016 callback(err, property.formatOutput(result)); 6017 }); 6018 }; 6019 get.request = this.request.bind(this); 6020 return get; 6021 }; 6022 6023 /** 6024 * Should be called to create pure JSONRPC request which can be used in batch request 6025 * 6026 * @method request 6027 * @param {...} params 6028 * @return {Object} jsonrpc request 6029 */ 6030 Property.prototype.request = function () { 6031 var payload = { 6032 method: this.getter, 6033 params: [], 6034 callback: this.extractCallback(Array.prototype.slice.call(arguments)) 6035 }; 6036 payload.format = this.formatOutput.bind(this); 6037 return payload; 6038 }; 6039 6040 module.exports = Property; 6041 6042 6043 },{"../utils/utils":20}],45:[function(require,module,exports){ 6044 /* 6045 This file is part of web3.js. 6046 6047 web3.js is free software: you can redistribute it and/or modify 6048 it under the terms of the GNU Lesser General Public License as published by 6049 the Free Software Foundation, either version 3 of the License, or 6050 (at your option) any later version. 6051 6052 web3.js is distributed in the hope that it will be useful, 6053 but WITHOUT ANY WARRANTY; without even the implied warranty of 6054 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6055 GNU Lesser General Public License for more details. 6056 6057 You should have received a copy of the GNU Lesser General Public License 6058 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6059 */ 6060 /** 6061 * @file requestmanager.js 6062 * @author Jeffrey Wilcke <jeff@ethdev.com> 6063 * @author Marek Kotewicz <marek@ethdev.com> 6064 * @author Marian Oancea <marian@ethdev.com> 6065 * @author Fabian Vogelsteller <fabian@ethdev.com> 6066 * @author Gav Wood <g@ethdev.com> 6067 * @date 2014 6068 */ 6069 6070 var Jsonrpc = require('./jsonrpc'); 6071 var utils = require('../utils/utils'); 6072 var c = require('../utils/config'); 6073 var errors = require('./errors'); 6074 6075 /** 6076 * It's responsible for passing messages to providers 6077 * It's also responsible for polling the ethereum node for incoming messages 6078 * Default poll timeout is 1 second 6079 * Singleton 6080 */ 6081 var RequestManager = function (provider) { 6082 this.provider = provider; 6083 this.polls = {}; 6084 this.timeout = null; 6085 }; 6086 6087 /** 6088 * Should be used to synchronously send request 6089 * 6090 * @method send 6091 * @param {Object} data 6092 * @return {Object} 6093 */ 6094 RequestManager.prototype.send = function (data) { 6095 if (!this.provider) { 6096 console.error(errors.InvalidProvider()); 6097 return null; 6098 } 6099 6100 var payload = Jsonrpc.getInstance().toPayload(data.method, data.params); 6101 var result = this.provider.send(payload); 6102 6103 if (!Jsonrpc.getInstance().isValidResponse(result)) { 6104 throw errors.InvalidResponse(result); 6105 } 6106 6107 return result.result; 6108 }; 6109 6110 /** 6111 * Should be used to asynchronously send request 6112 * 6113 * @method sendAsync 6114 * @param {Object} data 6115 * @param {Function} callback 6116 */ 6117 RequestManager.prototype.sendAsync = function (data, callback) { 6118 if (!this.provider) { 6119 return callback(errors.InvalidProvider()); 6120 } 6121 6122 var payload = Jsonrpc.getInstance().toPayload(data.method, data.params); 6123 this.provider.sendAsync(payload, function (err, result) { 6124 if (err) { 6125 return callback(err); 6126 } 6127 6128 if (!Jsonrpc.getInstance().isValidResponse(result)) { 6129 return callback(errors.InvalidResponse(result)); 6130 } 6131 6132 callback(null, result.result); 6133 }); 6134 }; 6135 6136 /** 6137 * Should be called to asynchronously send batch request 6138 * 6139 * @method sendBatch 6140 * @param {Array} batch data 6141 * @param {Function} callback 6142 */ 6143 RequestManager.prototype.sendBatch = function (data, callback) { 6144 if (!this.provider) { 6145 return callback(errors.InvalidProvider()); 6146 } 6147 6148 var payload = Jsonrpc.getInstance().toBatchPayload(data); 6149 6150 this.provider.sendAsync(payload, function (err, results) { 6151 if (err) { 6152 return callback(err); 6153 } 6154 6155 if (!utils.isArray(results)) { 6156 return callback(errors.InvalidResponse(results)); 6157 } 6158 6159 callback(err, results); 6160 }); 6161 }; 6162 6163 /** 6164 * Should be used to set provider of request manager 6165 * 6166 * @method setProvider 6167 * @param {Object} 6168 */ 6169 RequestManager.prototype.setProvider = function (p) { 6170 this.provider = p; 6171 }; 6172 6173 /** 6174 * Should be used to start polling 6175 * 6176 * @method startPolling 6177 * @param {Object} data 6178 * @param {Number} pollId 6179 * @param {Function} callback 6180 * @param {Function} uninstall 6181 * 6182 * @todo cleanup number of params 6183 */ 6184 RequestManager.prototype.startPolling = function (data, pollId, callback, uninstall) { 6185 this.polls[pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall}; 6186 6187 6188 // start polling 6189 if (!this.timeout) { 6190 this.poll(); 6191 } 6192 }; 6193 6194 /** 6195 * Should be used to stop polling for filter with given id 6196 * 6197 * @method stopPolling 6198 * @param {Number} pollId 6199 */ 6200 RequestManager.prototype.stopPolling = function (pollId) { 6201 delete this.polls[pollId]; 6202 6203 // stop polling 6204 if(Object.keys(this.polls).length === 0 && this.timeout) { 6205 clearTimeout(this.timeout); 6206 this.timeout = null; 6207 } 6208 }; 6209 6210 /** 6211 * Should be called to reset the polling mechanism of the request manager 6212 * 6213 * @method reset 6214 */ 6215 RequestManager.prototype.reset = function (keepIsSyncing) { 6216 /*jshint maxcomplexity:5 */ 6217 6218 for (var key in this.polls) { 6219 // remove all polls, except sync polls, 6220 // they need to be removed manually by calling syncing.stopWatching() 6221 if(!keepIsSyncing || key.indexOf('syncPoll_') === -1) { 6222 this.polls[key].uninstall(); 6223 delete this.polls[key]; 6224 } 6225 } 6226 6227 // stop polling 6228 if(Object.keys(this.polls).length === 0 && this.timeout) { 6229 clearTimeout(this.timeout); 6230 this.timeout = null; 6231 } 6232 }; 6233 6234 /** 6235 * Should be called to poll for changes on filter with given id 6236 * 6237 * @method poll 6238 */ 6239 RequestManager.prototype.poll = function () { 6240 /*jshint maxcomplexity: 6 */ 6241 this.timeout = setTimeout(this.poll.bind(this), c.ETH_POLLING_TIMEOUT); 6242 6243 if (Object.keys(this.polls).length === 0) { 6244 return; 6245 } 6246 6247 if (!this.provider) { 6248 console.error(errors.InvalidProvider()); 6249 return; 6250 } 6251 6252 var pollsData = []; 6253 var pollsIds = []; 6254 for (var key in this.polls) { 6255 pollsData.push(this.polls[key].data); 6256 pollsIds.push(key); 6257 } 6258 6259 if (pollsData.length === 0) { 6260 return; 6261 } 6262 6263 var payload = Jsonrpc.getInstance().toBatchPayload(pollsData); 6264 6265 // map the request id to they poll id 6266 var pollsIdMap = {}; 6267 payload.forEach(function(load, index){ 6268 pollsIdMap[load.id] = pollsIds[index]; 6269 }); 6270 6271 6272 var self = this; 6273 this.provider.sendAsync(payload, function (error, results) { 6274 6275 6276 // TODO: console log? 6277 if (error) { 6278 return; 6279 } 6280 6281 if (!utils.isArray(results)) { 6282 throw errors.InvalidResponse(results); 6283 } 6284 results.map(function (result) { 6285 var id = pollsIdMap[result.id]; 6286 6287 // make sure the filter is still installed after arrival of the request 6288 if (self.polls[id]) { 6289 result.callback = self.polls[id].callback; 6290 return result; 6291 } else 6292 return false; 6293 }).filter(function (result) { 6294 return !!result; 6295 }).filter(function (result) { 6296 var valid = Jsonrpc.getInstance().isValidResponse(result); 6297 if (!valid) { 6298 result.callback(errors.InvalidResponse(result)); 6299 } 6300 return valid; 6301 }).forEach(function (result) { 6302 result.callback(null, result.result); 6303 }); 6304 }); 6305 }; 6306 6307 module.exports = RequestManager; 6308 6309 6310 },{"../utils/config":18,"../utils/utils":20,"./errors":26,"./jsonrpc":35}],46:[function(require,module,exports){ 6311 6312 6313 var Settings = function () { 6314 this.defaultBlock = 'latest'; 6315 this.defaultAccount = undefined; 6316 }; 6317 6318 module.exports = Settings; 6319 6320 6321 },{}],47:[function(require,module,exports){ 6322 /* 6323 This file is part of web3.js. 6324 6325 web3.js is free software: you can redistribute it and/or modify 6326 it under the terms of the GNU Lesser General Public License as published by 6327 the Free Software Foundation, either version 3 of the License, or 6328 (at your option) any later version. 6329 6330 web3.js is distributed in the hope that it will be useful, 6331 but WITHOUT ANY WARRANTY; without even the implied warranty of 6332 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6333 GNU Lesser General Public License for more details. 6334 6335 You should have received a copy of the GNU Lesser General Public License 6336 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6337 */ 6338 /** @file syncing.js 6339 * @authors: 6340 * Fabian Vogelsteller <fabian@ethdev.com> 6341 * @date 2015 6342 */ 6343 6344 var formatters = require('./formatters'); 6345 var utils = require('../utils/utils'); 6346 6347 var count = 1; 6348 6349 /** 6350 Adds the callback and sets up the methods, to iterate over the results. 6351 6352 @method pollSyncing 6353 @param {Object} self 6354 */ 6355 var pollSyncing = function(self) { 6356 6357 var onMessage = function (error, sync) { 6358 if (error) { 6359 return self.callbacks.forEach(function (callback) { 6360 callback(error); 6361 }); 6362 } 6363 6364 if(utils.isObject(sync) && sync.startingBlock) 6365 sync = formatters.outputSyncingFormatter(sync); 6366 6367 self.callbacks.forEach(function (callback) { 6368 if (self.lastSyncState !== sync) { 6369 6370 // call the callback with true first so the app can stop anything, before receiving the sync data 6371 if(!self.lastSyncState && utils.isObject(sync)) 6372 callback(null, true); 6373 6374 // call on the next CPU cycle, so the actions of the sync stop can be processes first 6375 setTimeout(function() { 6376 callback(null, sync); 6377 }, 0); 6378 6379 self.lastSyncState = sync; 6380 } 6381 }); 6382 }; 6383 6384 self.requestManager.startPolling({ 6385 method: 'eth_syncing', 6386 params: [], 6387 }, self.pollId, onMessage, self.stopWatching.bind(self)); 6388 6389 }; 6390 6391 var IsSyncing = function (requestManager, callback) { 6392 this.requestManager = requestManager; 6393 this.pollId = 'syncPoll_'+ count++; 6394 this.callbacks = []; 6395 this.addCallback(callback); 6396 this.lastSyncState = false; 6397 pollSyncing(this); 6398 6399 return this; 6400 }; 6401 6402 IsSyncing.prototype.addCallback = function (callback) { 6403 if(callback) 6404 this.callbacks.push(callback); 6405 return this; 6406 }; 6407 6408 IsSyncing.prototype.stopWatching = function () { 6409 this.requestManager.stopPolling(this.pollId); 6410 this.callbacks = []; 6411 }; 6412 6413 module.exports = IsSyncing; 6414 6415 6416 },{"../utils/utils":20,"./formatters":30}],48:[function(require,module,exports){ 6417 /* 6418 This file is part of web3.js. 6419 6420 web3.js is free software: you can redistribute it and/or modify 6421 it under the terms of the GNU Lesser General Public License as published by 6422 the Free Software Foundation, either version 3 of the License, or 6423 (at your option) any later version. 6424 6425 web3.js is distributed in the hope that it will be useful, 6426 but WITHOUT ANY WARRANTY; without even the implied warranty of 6427 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6428 GNU Lesser General Public License for more details. 6429 6430 You should have received a copy of the GNU Lesser General Public License 6431 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6432 */ 6433 /** 6434 * @file transfer.js 6435 * @author Marek Kotewicz <marek@ethdev.com> 6436 * @date 2015 6437 */ 6438 6439 var Iban = require('./iban'); 6440 var exchangeAbi = require('../contracts/SmartExchange.json'); 6441 6442 /** 6443 * Should be used to make Iban transfer 6444 * 6445 * @method transfer 6446 * @param {String} from 6447 * @param {String} to iban 6448 * @param {Value} value to be tranfered 6449 * @param {Function} callback, callback 6450 */ 6451 var transfer = function (eth, from, to, value, callback) { 6452 var iban = new Iban(to); 6453 if (!iban.isValid()) { 6454 throw new Error('invalid iban address'); 6455 } 6456 6457 if (iban.isDirect()) { 6458 return transferToAddress(eth, from, iban.address(), value, callback); 6459 } 6460 6461 if (!callback) { 6462 var address = eth.icapNamereg().addr(iban.institution()); 6463 return deposit(eth, from, address, value, iban.client()); 6464 } 6465 6466 eth.icapNamereg().addr(iban.institution(), function (err, address) { 6467 return deposit(eth, from, address, value, iban.client(), callback); 6468 }); 6469 6470 }; 6471 6472 /** 6473 * Should be used to transfer funds to certain address 6474 * 6475 * @method transferToAddress 6476 * @param {String} from 6477 * @param {String} to 6478 * @param {Value} value to be tranfered 6479 * @param {Function} callback, callback 6480 */ 6481 var transferToAddress = function (eth, from, to, value, callback) { 6482 return eth.sendTransaction({ 6483 address: to, 6484 from: from, 6485 value: value 6486 }, callback); 6487 }; 6488 6489 /** 6490 * Should be used to deposit funds to generic Exchange contract (must implement deposit(bytes32) method!) 6491 * 6492 * @method deposit 6493 * @param {String} from 6494 * @param {String} to 6495 * @param {Value} value to be transfered 6496 * @param {String} client unique identifier 6497 * @param {Function} callback, callback 6498 */ 6499 var deposit = function (eth, from, to, value, client, callback) { 6500 var abi = exchangeAbi; 6501 return eth.contract(abi).at(to).deposit(client, { 6502 from: from, 6503 value: value 6504 }, callback); 6505 }; 6506 6507 module.exports = transfer; 6508 6509 6510 },{"../contracts/SmartExchange.json":3,"./iban":33}],49:[function(require,module,exports){ 6511 6512 },{}],50:[function(require,module,exports){ 6513 ;(function (root, factory, undef) { 6514 if (typeof exports === "object") { 6515 // CommonJS 6516 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 6517 } 6518 else if (typeof define === "function" && define.amd) { 6519 // AMD 6520 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 6521 } 6522 else { 6523 // Global (browser) 6524 factory(root.CryptoJS); 6525 } 6526 }(this, function (CryptoJS) { 6527 6528 (function () { 6529 // Shortcuts 6530 var C = CryptoJS; 6531 var C_lib = C.lib; 6532 var BlockCipher = C_lib.BlockCipher; 6533 var C_algo = C.algo; 6534 6535 // Lookup tables 6536 var SBOX = []; 6537 var INV_SBOX = []; 6538 var SUB_MIX_0 = []; 6539 var SUB_MIX_1 = []; 6540 var SUB_MIX_2 = []; 6541 var SUB_MIX_3 = []; 6542 var INV_SUB_MIX_0 = []; 6543 var INV_SUB_MIX_1 = []; 6544 var INV_SUB_MIX_2 = []; 6545 var INV_SUB_MIX_3 = []; 6546 6547 // Compute lookup tables 6548 (function () { 6549 // Compute double table 6550 var d = []; 6551 for (var i = 0; i < 256; i++) { 6552 if (i < 128) { 6553 d[i] = i << 1; 6554 } else { 6555 d[i] = (i << 1) ^ 0x11b; 6556 } 6557 } 6558 6559 // Walk GF(2^8) 6560 var x = 0; 6561 var xi = 0; 6562 for (var i = 0; i < 256; i++) { 6563 // Compute sbox 6564 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); 6565 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; 6566 SBOX[x] = sx; 6567 INV_SBOX[sx] = x; 6568 6569 // Compute multiplication 6570 var x2 = d[x]; 6571 var x4 = d[x2]; 6572 var x8 = d[x4]; 6573 6574 // Compute sub bytes, mix columns tables 6575 var t = (d[sx] * 0x101) ^ (sx * 0x1010100); 6576 SUB_MIX_0[x] = (t << 24) | (t >>> 8); 6577 SUB_MIX_1[x] = (t << 16) | (t >>> 16); 6578 SUB_MIX_2[x] = (t << 8) | (t >>> 24); 6579 SUB_MIX_3[x] = t; 6580 6581 // Compute inv sub bytes, inv mix columns tables 6582 var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); 6583 INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); 6584 INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); 6585 INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); 6586 INV_SUB_MIX_3[sx] = t; 6587 6588 // Compute next counter 6589 if (!x) { 6590 x = xi = 1; 6591 } else { 6592 x = x2 ^ d[d[d[x8 ^ x2]]]; 6593 xi ^= d[d[xi]]; 6594 } 6595 } 6596 }()); 6597 6598 // Precomputed Rcon lookup 6599 var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; 6600 6601 /** 6602 * AES block cipher algorithm. 6603 */ 6604 var AES = C_algo.AES = BlockCipher.extend({ 6605 _doReset: function () { 6606 // Shortcuts 6607 var key = this._key; 6608 var keyWords = key.words; 6609 var keySize = key.sigBytes / 4; 6610 6611 // Compute number of rounds 6612 var nRounds = this._nRounds = keySize + 6 6613 6614 // Compute number of key schedule rows 6615 var ksRows = (nRounds + 1) * 4; 6616 6617 // Compute key schedule 6618 var keySchedule = this._keySchedule = []; 6619 for (var ksRow = 0; ksRow < ksRows; ksRow++) { 6620 if (ksRow < keySize) { 6621 keySchedule[ksRow] = keyWords[ksRow]; 6622 } else { 6623 var t = keySchedule[ksRow - 1]; 6624 6625 if (!(ksRow % keySize)) { 6626 // Rot word 6627 t = (t << 8) | (t >>> 24); 6628 6629 // Sub word 6630 t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; 6631 6632 // Mix Rcon 6633 t ^= RCON[(ksRow / keySize) | 0] << 24; 6634 } else if (keySize > 6 && ksRow % keySize == 4) { 6635 // Sub word 6636 t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; 6637 } 6638 6639 keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; 6640 } 6641 } 6642 6643 // Compute inv key schedule 6644 var invKeySchedule = this._invKeySchedule = []; 6645 for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { 6646 var ksRow = ksRows - invKsRow; 6647 6648 if (invKsRow % 4) { 6649 var t = keySchedule[ksRow]; 6650 } else { 6651 var t = keySchedule[ksRow - 4]; 6652 } 6653 6654 if (invKsRow < 4 || ksRow <= 4) { 6655 invKeySchedule[invKsRow] = t; 6656 } else { 6657 invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ 6658 INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; 6659 } 6660 } 6661 }, 6662 6663 encryptBlock: function (M, offset) { 6664 this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); 6665 }, 6666 6667 decryptBlock: function (M, offset) { 6668 // Swap 2nd and 4th rows 6669 var t = M[offset + 1]; 6670 M[offset + 1] = M[offset + 3]; 6671 M[offset + 3] = t; 6672 6673 this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); 6674 6675 // Inv swap 2nd and 4th rows 6676 var t = M[offset + 1]; 6677 M[offset + 1] = M[offset + 3]; 6678 M[offset + 3] = t; 6679 }, 6680 6681 _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { 6682 // Shortcut 6683 var nRounds = this._nRounds; 6684 6685 // Get input, add round key 6686 var s0 = M[offset] ^ keySchedule[0]; 6687 var s1 = M[offset + 1] ^ keySchedule[1]; 6688 var s2 = M[offset + 2] ^ keySchedule[2]; 6689 var s3 = M[offset + 3] ^ keySchedule[3]; 6690 6691 // Key schedule row counter 6692 var ksRow = 4; 6693 6694 // Rounds 6695 for (var round = 1; round < nRounds; round++) { 6696 // Shift rows, sub bytes, mix columns, add round key 6697 var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; 6698 var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; 6699 var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; 6700 var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; 6701 6702 // Update state 6703 s0 = t0; 6704 s1 = t1; 6705 s2 = t2; 6706 s3 = t3; 6707 } 6708 6709 // Shift rows, sub bytes, add round key 6710 var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; 6711 var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; 6712 var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; 6713 var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; 6714 6715 // Set output 6716 M[offset] = t0; 6717 M[offset + 1] = t1; 6718 M[offset + 2] = t2; 6719 M[offset + 3] = t3; 6720 }, 6721 6722 keySize: 256/32 6723 }); 6724 6725 /** 6726 * Shortcut functions to the cipher's object interface. 6727 * 6728 * @example 6729 * 6730 * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); 6731 * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); 6732 */ 6733 C.AES = BlockCipher._createHelper(AES); 6734 }()); 6735 6736 6737 return CryptoJS.AES; 6738 6739 })); 6740 },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],51:[function(require,module,exports){ 6741 ;(function (root, factory) { 6742 if (typeof exports === "object") { 6743 // CommonJS 6744 module.exports = exports = factory(require("./core")); 6745 } 6746 else if (typeof define === "function" && define.amd) { 6747 // AMD 6748 define(["./core"], factory); 6749 } 6750 else { 6751 // Global (browser) 6752 factory(root.CryptoJS); 6753 } 6754 }(this, function (CryptoJS) { 6755 6756 /** 6757 * Cipher core components. 6758 */ 6759 CryptoJS.lib.Cipher || (function (undefined) { 6760 // Shortcuts 6761 var C = CryptoJS; 6762 var C_lib = C.lib; 6763 var Base = C_lib.Base; 6764 var WordArray = C_lib.WordArray; 6765 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; 6766 var C_enc = C.enc; 6767 var Utf8 = C_enc.Utf8; 6768 var Base64 = C_enc.Base64; 6769 var C_algo = C.algo; 6770 var EvpKDF = C_algo.EvpKDF; 6771 6772 /** 6773 * Abstract base cipher template. 6774 * 6775 * @property {number} keySize This cipher's key size. Default: 4 (128 bits) 6776 * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) 6777 * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. 6778 * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. 6779 */ 6780 var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ 6781 /** 6782 * Configuration options. 6783 * 6784 * @property {WordArray} iv The IV to use for this operation. 6785 */ 6786 cfg: Base.extend(), 6787 6788 /** 6789 * Creates this cipher in encryption mode. 6790 * 6791 * @param {WordArray} key The key. 6792 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6793 * 6794 * @return {Cipher} A cipher instance. 6795 * 6796 * @static 6797 * 6798 * @example 6799 * 6800 * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); 6801 */ 6802 createEncryptor: function (key, cfg) { 6803 return this.create(this._ENC_XFORM_MODE, key, cfg); 6804 }, 6805 6806 /** 6807 * Creates this cipher in decryption mode. 6808 * 6809 * @param {WordArray} key The key. 6810 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6811 * 6812 * @return {Cipher} A cipher instance. 6813 * 6814 * @static 6815 * 6816 * @example 6817 * 6818 * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); 6819 */ 6820 createDecryptor: function (key, cfg) { 6821 return this.create(this._DEC_XFORM_MODE, key, cfg); 6822 }, 6823 6824 /** 6825 * Initializes a newly created cipher. 6826 * 6827 * @param {number} xformMode Either the encryption or decryption transormation mode constant. 6828 * @param {WordArray} key The key. 6829 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6830 * 6831 * @example 6832 * 6833 * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); 6834 */ 6835 init: function (xformMode, key, cfg) { 6836 // Apply config defaults 6837 this.cfg = this.cfg.extend(cfg); 6838 6839 // Store transform mode and key 6840 this._xformMode = xformMode; 6841 this._key = key; 6842 6843 // Set initial values 6844 this.reset(); 6845 }, 6846 6847 /** 6848 * Resets this cipher to its initial state. 6849 * 6850 * @example 6851 * 6852 * cipher.reset(); 6853 */ 6854 reset: function () { 6855 // Reset data buffer 6856 BufferedBlockAlgorithm.reset.call(this); 6857 6858 // Perform concrete-cipher logic 6859 this._doReset(); 6860 }, 6861 6862 /** 6863 * Adds data to be encrypted or decrypted. 6864 * 6865 * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. 6866 * 6867 * @return {WordArray} The data after processing. 6868 * 6869 * @example 6870 * 6871 * var encrypted = cipher.process('data'); 6872 * var encrypted = cipher.process(wordArray); 6873 */ 6874 process: function (dataUpdate) { 6875 // Append 6876 this._append(dataUpdate); 6877 6878 // Process available blocks 6879 return this._process(); 6880 }, 6881 6882 /** 6883 * Finalizes the encryption or decryption process. 6884 * Note that the finalize operation is effectively a destructive, read-once operation. 6885 * 6886 * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. 6887 * 6888 * @return {WordArray} The data after final processing. 6889 * 6890 * @example 6891 * 6892 * var encrypted = cipher.finalize(); 6893 * var encrypted = cipher.finalize('data'); 6894 * var encrypted = cipher.finalize(wordArray); 6895 */ 6896 finalize: function (dataUpdate) { 6897 // Final data update 6898 if (dataUpdate) { 6899 this._append(dataUpdate); 6900 } 6901 6902 // Perform concrete-cipher logic 6903 var finalProcessedData = this._doFinalize(); 6904 6905 return finalProcessedData; 6906 }, 6907 6908 keySize: 128/32, 6909 6910 ivSize: 128/32, 6911 6912 _ENC_XFORM_MODE: 1, 6913 6914 _DEC_XFORM_MODE: 2, 6915 6916 /** 6917 * Creates shortcut functions to a cipher's object interface. 6918 * 6919 * @param {Cipher} cipher The cipher to create a helper for. 6920 * 6921 * @return {Object} An object with encrypt and decrypt shortcut functions. 6922 * 6923 * @static 6924 * 6925 * @example 6926 * 6927 * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); 6928 */ 6929 _createHelper: (function () { 6930 function selectCipherStrategy(key) { 6931 if (typeof key == 'string') { 6932 return PasswordBasedCipher; 6933 } else { 6934 return SerializableCipher; 6935 } 6936 } 6937 6938 return function (cipher) { 6939 return { 6940 encrypt: function (message, key, cfg) { 6941 return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); 6942 }, 6943 6944 decrypt: function (ciphertext, key, cfg) { 6945 return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); 6946 } 6947 }; 6948 }; 6949 }()) 6950 }); 6951 6952 /** 6953 * Abstract base stream cipher template. 6954 * 6955 * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) 6956 */ 6957 var StreamCipher = C_lib.StreamCipher = Cipher.extend({ 6958 _doFinalize: function () { 6959 // Process partial blocks 6960 var finalProcessedBlocks = this._process(!!'flush'); 6961 6962 return finalProcessedBlocks; 6963 }, 6964 6965 blockSize: 1 6966 }); 6967 6968 /** 6969 * Mode namespace. 6970 */ 6971 var C_mode = C.mode = {}; 6972 6973 /** 6974 * Abstract base block cipher mode template. 6975 */ 6976 var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ 6977 /** 6978 * Creates this mode for encryption. 6979 * 6980 * @param {Cipher} cipher A block cipher instance. 6981 * @param {Array} iv The IV words. 6982 * 6983 * @static 6984 * 6985 * @example 6986 * 6987 * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); 6988 */ 6989 createEncryptor: function (cipher, iv) { 6990 return this.Encryptor.create(cipher, iv); 6991 }, 6992 6993 /** 6994 * Creates this mode for decryption. 6995 * 6996 * @param {Cipher} cipher A block cipher instance. 6997 * @param {Array} iv The IV words. 6998 * 6999 * @static 7000 * 7001 * @example 7002 * 7003 * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); 7004 */ 7005 createDecryptor: function (cipher, iv) { 7006 return this.Decryptor.create(cipher, iv); 7007 }, 7008 7009 /** 7010 * Initializes a newly created mode. 7011 * 7012 * @param {Cipher} cipher A block cipher instance. 7013 * @param {Array} iv The IV words. 7014 * 7015 * @example 7016 * 7017 * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); 7018 */ 7019 init: function (cipher, iv) { 7020 this._cipher = cipher; 7021 this._iv = iv; 7022 } 7023 }); 7024 7025 /** 7026 * Cipher Block Chaining mode. 7027 */ 7028 var CBC = C_mode.CBC = (function () { 7029 /** 7030 * Abstract base CBC mode. 7031 */ 7032 var CBC = BlockCipherMode.extend(); 7033 7034 /** 7035 * CBC encryptor. 7036 */ 7037 CBC.Encryptor = CBC.extend({ 7038 /** 7039 * Processes the data block at offset. 7040 * 7041 * @param {Array} words The data words to operate on. 7042 * @param {number} offset The offset where the block starts. 7043 * 7044 * @example 7045 * 7046 * mode.processBlock(data.words, offset); 7047 */ 7048 processBlock: function (words, offset) { 7049 // Shortcuts 7050 var cipher = this._cipher; 7051 var blockSize = cipher.blockSize; 7052 7053 // XOR and encrypt 7054 xorBlock.call(this, words, offset, blockSize); 7055 cipher.encryptBlock(words, offset); 7056 7057 // Remember this block to use with next block 7058 this._prevBlock = words.slice(offset, offset + blockSize); 7059 } 7060 }); 7061 7062 /** 7063 * CBC decryptor. 7064 */ 7065 CBC.Decryptor = CBC.extend({ 7066 /** 7067 * Processes the data block at offset. 7068 * 7069 * @param {Array} words The data words to operate on. 7070 * @param {number} offset The offset where the block starts. 7071 * 7072 * @example 7073 * 7074 * mode.processBlock(data.words, offset); 7075 */ 7076 processBlock: function (words, offset) { 7077 // Shortcuts 7078 var cipher = this._cipher; 7079 var blockSize = cipher.blockSize; 7080 7081 // Remember this block to use with next block 7082 var thisBlock = words.slice(offset, offset + blockSize); 7083 7084 // Decrypt and XOR 7085 cipher.decryptBlock(words, offset); 7086 xorBlock.call(this, words, offset, blockSize); 7087 7088 // This block becomes the previous block 7089 this._prevBlock = thisBlock; 7090 } 7091 }); 7092 7093 function xorBlock(words, offset, blockSize) { 7094 // Shortcut 7095 var iv = this._iv; 7096 7097 // Choose mixing block 7098 if (iv) { 7099 var block = iv; 7100 7101 // Remove IV for subsequent blocks 7102 this._iv = undefined; 7103 } else { 7104 var block = this._prevBlock; 7105 } 7106 7107 // XOR blocks 7108 for (var i = 0; i < blockSize; i++) { 7109 words[offset + i] ^= block[i]; 7110 } 7111 } 7112 7113 return CBC; 7114 }()); 7115 7116 /** 7117 * Padding namespace. 7118 */ 7119 var C_pad = C.pad = {}; 7120 7121 /** 7122 * PKCS #5/7 padding strategy. 7123 */ 7124 var Pkcs7 = C_pad.Pkcs7 = { 7125 /** 7126 * Pads data using the algorithm defined in PKCS #5/7. 7127 * 7128 * @param {WordArray} data The data to pad. 7129 * @param {number} blockSize The multiple that the data should be padded to. 7130 * 7131 * @static 7132 * 7133 * @example 7134 * 7135 * CryptoJS.pad.Pkcs7.pad(wordArray, 4); 7136 */ 7137 pad: function (data, blockSize) { 7138 // Shortcut 7139 var blockSizeBytes = blockSize * 4; 7140 7141 // Count padding bytes 7142 var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; 7143 7144 // Create padding word 7145 var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; 7146 7147 // Create padding 7148 var paddingWords = []; 7149 for (var i = 0; i < nPaddingBytes; i += 4) { 7150 paddingWords.push(paddingWord); 7151 } 7152 var padding = WordArray.create(paddingWords, nPaddingBytes); 7153 7154 // Add padding 7155 data.concat(padding); 7156 }, 7157 7158 /** 7159 * Unpads data that had been padded using the algorithm defined in PKCS #5/7. 7160 * 7161 * @param {WordArray} data The data to unpad. 7162 * 7163 * @static 7164 * 7165 * @example 7166 * 7167 * CryptoJS.pad.Pkcs7.unpad(wordArray); 7168 */ 7169 unpad: function (data) { 7170 // Get number of padding bytes from last byte 7171 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 7172 7173 // Remove padding 7174 data.sigBytes -= nPaddingBytes; 7175 } 7176 }; 7177 7178 /** 7179 * Abstract base block cipher template. 7180 * 7181 * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) 7182 */ 7183 var BlockCipher = C_lib.BlockCipher = Cipher.extend({ 7184 /** 7185 * Configuration options. 7186 * 7187 * @property {Mode} mode The block mode to use. Default: CBC 7188 * @property {Padding} padding The padding strategy to use. Default: Pkcs7 7189 */ 7190 cfg: Cipher.cfg.extend({ 7191 mode: CBC, 7192 padding: Pkcs7 7193 }), 7194 7195 reset: function () { 7196 // Reset cipher 7197 Cipher.reset.call(this); 7198 7199 // Shortcuts 7200 var cfg = this.cfg; 7201 var iv = cfg.iv; 7202 var mode = cfg.mode; 7203 7204 // Reset block mode 7205 if (this._xformMode == this._ENC_XFORM_MODE) { 7206 var modeCreator = mode.createEncryptor; 7207 } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { 7208 var modeCreator = mode.createDecryptor; 7209 7210 // Keep at least one block in the buffer for unpadding 7211 this._minBufferSize = 1; 7212 } 7213 this._mode = modeCreator.call(mode, this, iv && iv.words); 7214 }, 7215 7216 _doProcessBlock: function (words, offset) { 7217 this._mode.processBlock(words, offset); 7218 }, 7219 7220 _doFinalize: function () { 7221 // Shortcut 7222 var padding = this.cfg.padding; 7223 7224 // Finalize 7225 if (this._xformMode == this._ENC_XFORM_MODE) { 7226 // Pad data 7227 padding.pad(this._data, this.blockSize); 7228 7229 // Process final blocks 7230 var finalProcessedBlocks = this._process(!!'flush'); 7231 } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { 7232 // Process final blocks 7233 var finalProcessedBlocks = this._process(!!'flush'); 7234 7235 // Unpad data 7236 padding.unpad(finalProcessedBlocks); 7237 } 7238 7239 return finalProcessedBlocks; 7240 }, 7241 7242 blockSize: 128/32 7243 }); 7244 7245 /** 7246 * A collection of cipher parameters. 7247 * 7248 * @property {WordArray} ciphertext The raw ciphertext. 7249 * @property {WordArray} key The key to this ciphertext. 7250 * @property {WordArray} iv The IV used in the ciphering operation. 7251 * @property {WordArray} salt The salt used with a key derivation function. 7252 * @property {Cipher} algorithm The cipher algorithm. 7253 * @property {Mode} mode The block mode used in the ciphering operation. 7254 * @property {Padding} padding The padding scheme used in the ciphering operation. 7255 * @property {number} blockSize The block size of the cipher. 7256 * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. 7257 */ 7258 var CipherParams = C_lib.CipherParams = Base.extend({ 7259 /** 7260 * Initializes a newly created cipher params object. 7261 * 7262 * @param {Object} cipherParams An object with any of the possible cipher parameters. 7263 * 7264 * @example 7265 * 7266 * var cipherParams = CryptoJS.lib.CipherParams.create({ 7267 * ciphertext: ciphertextWordArray, 7268 * key: keyWordArray, 7269 * iv: ivWordArray, 7270 * salt: saltWordArray, 7271 * algorithm: CryptoJS.algo.AES, 7272 * mode: CryptoJS.mode.CBC, 7273 * padding: CryptoJS.pad.PKCS7, 7274 * blockSize: 4, 7275 * formatter: CryptoJS.format.OpenSSL 7276 * }); 7277 */ 7278 init: function (cipherParams) { 7279 this.mixIn(cipherParams); 7280 }, 7281 7282 /** 7283 * Converts this cipher params object to a string. 7284 * 7285 * @param {Format} formatter (Optional) The formatting strategy to use. 7286 * 7287 * @return {string} The stringified cipher params. 7288 * 7289 * @throws Error If neither the formatter nor the default formatter is set. 7290 * 7291 * @example 7292 * 7293 * var string = cipherParams + ''; 7294 * var string = cipherParams.toString(); 7295 * var string = cipherParams.toString(CryptoJS.format.OpenSSL); 7296 */ 7297 toString: function (formatter) { 7298 return (formatter || this.formatter).stringify(this); 7299 } 7300 }); 7301 7302 /** 7303 * Format namespace. 7304 */ 7305 var C_format = C.format = {}; 7306 7307 /** 7308 * OpenSSL formatting strategy. 7309 */ 7310 var OpenSSLFormatter = C_format.OpenSSL = { 7311 /** 7312 * Converts a cipher params object to an OpenSSL-compatible string. 7313 * 7314 * @param {CipherParams} cipherParams The cipher params object. 7315 * 7316 * @return {string} The OpenSSL-compatible string. 7317 * 7318 * @static 7319 * 7320 * @example 7321 * 7322 * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); 7323 */ 7324 stringify: function (cipherParams) { 7325 // Shortcuts 7326 var ciphertext = cipherParams.ciphertext; 7327 var salt = cipherParams.salt; 7328 7329 // Format 7330 if (salt) { 7331 var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); 7332 } else { 7333 var wordArray = ciphertext; 7334 } 7335 7336 return wordArray.toString(Base64); 7337 }, 7338 7339 /** 7340 * Converts an OpenSSL-compatible string to a cipher params object. 7341 * 7342 * @param {string} openSSLStr The OpenSSL-compatible string. 7343 * 7344 * @return {CipherParams} The cipher params object. 7345 * 7346 * @static 7347 * 7348 * @example 7349 * 7350 * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); 7351 */ 7352 parse: function (openSSLStr) { 7353 // Parse base64 7354 var ciphertext = Base64.parse(openSSLStr); 7355 7356 // Shortcut 7357 var ciphertextWords = ciphertext.words; 7358 7359 // Test for salt 7360 if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { 7361 // Extract salt 7362 var salt = WordArray.create(ciphertextWords.slice(2, 4)); 7363 7364 // Remove salt from ciphertext 7365 ciphertextWords.splice(0, 4); 7366 ciphertext.sigBytes -= 16; 7367 } 7368 7369 return CipherParams.create({ ciphertext: ciphertext, salt: salt }); 7370 } 7371 }; 7372 7373 /** 7374 * A cipher wrapper that returns ciphertext as a serializable cipher params object. 7375 */ 7376 var SerializableCipher = C_lib.SerializableCipher = Base.extend({ 7377 /** 7378 * Configuration options. 7379 * 7380 * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL 7381 */ 7382 cfg: Base.extend({ 7383 format: OpenSSLFormatter 7384 }), 7385 7386 /** 7387 * Encrypts a message. 7388 * 7389 * @param {Cipher} cipher The cipher algorithm to use. 7390 * @param {WordArray|string} message The message to encrypt. 7391 * @param {WordArray} key The key. 7392 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7393 * 7394 * @return {CipherParams} A cipher params object. 7395 * 7396 * @static 7397 * 7398 * @example 7399 * 7400 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); 7401 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); 7402 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7403 */ 7404 encrypt: function (cipher, message, key, cfg) { 7405 // Apply config defaults 7406 cfg = this.cfg.extend(cfg); 7407 7408 // Encrypt 7409 var encryptor = cipher.createEncryptor(key, cfg); 7410 var ciphertext = encryptor.finalize(message); 7411 7412 // Shortcut 7413 var cipherCfg = encryptor.cfg; 7414 7415 // Create and return serializable cipher params 7416 return CipherParams.create({ 7417 ciphertext: ciphertext, 7418 key: key, 7419 iv: cipherCfg.iv, 7420 algorithm: cipher, 7421 mode: cipherCfg.mode, 7422 padding: cipherCfg.padding, 7423 blockSize: cipher.blockSize, 7424 formatter: cfg.format 7425 }); 7426 }, 7427 7428 /** 7429 * Decrypts serialized ciphertext. 7430 * 7431 * @param {Cipher} cipher The cipher algorithm to use. 7432 * @param {CipherParams|string} ciphertext The ciphertext to decrypt. 7433 * @param {WordArray} key The key. 7434 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7435 * 7436 * @return {WordArray} The plaintext. 7437 * 7438 * @static 7439 * 7440 * @example 7441 * 7442 * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7443 * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7444 */ 7445 decrypt: function (cipher, ciphertext, key, cfg) { 7446 // Apply config defaults 7447 cfg = this.cfg.extend(cfg); 7448 7449 // Convert string to CipherParams 7450 ciphertext = this._parse(ciphertext, cfg.format); 7451 7452 // Decrypt 7453 var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); 7454 7455 return plaintext; 7456 }, 7457 7458 /** 7459 * Converts serialized ciphertext to CipherParams, 7460 * else assumed CipherParams already and returns ciphertext unchanged. 7461 * 7462 * @param {CipherParams|string} ciphertext The ciphertext. 7463 * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. 7464 * 7465 * @return {CipherParams} The unserialized ciphertext. 7466 * 7467 * @static 7468 * 7469 * @example 7470 * 7471 * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); 7472 */ 7473 _parse: function (ciphertext, format) { 7474 if (typeof ciphertext == 'string') { 7475 return format.parse(ciphertext, this); 7476 } else { 7477 return ciphertext; 7478 } 7479 } 7480 }); 7481 7482 /** 7483 * Key derivation function namespace. 7484 */ 7485 var C_kdf = C.kdf = {}; 7486 7487 /** 7488 * OpenSSL key derivation function. 7489 */ 7490 var OpenSSLKdf = C_kdf.OpenSSL = { 7491 /** 7492 * Derives a key and IV from a password. 7493 * 7494 * @param {string} password The password to derive from. 7495 * @param {number} keySize The size in words of the key to generate. 7496 * @param {number} ivSize The size in words of the IV to generate. 7497 * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. 7498 * 7499 * @return {CipherParams} A cipher params object with the key, IV, and salt. 7500 * 7501 * @static 7502 * 7503 * @example 7504 * 7505 * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); 7506 * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); 7507 */ 7508 execute: function (password, keySize, ivSize, salt) { 7509 // Generate random salt 7510 if (!salt) { 7511 salt = WordArray.random(64/8); 7512 } 7513 7514 // Derive key and IV 7515 var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); 7516 7517 // Separate key and IV 7518 var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); 7519 key.sigBytes = keySize * 4; 7520 7521 // Return params 7522 return CipherParams.create({ key: key, iv: iv, salt: salt }); 7523 } 7524 }; 7525 7526 /** 7527 * A serializable cipher wrapper that derives the key from a password, 7528 * and returns ciphertext as a serializable cipher params object. 7529 */ 7530 var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ 7531 /** 7532 * Configuration options. 7533 * 7534 * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL 7535 */ 7536 cfg: SerializableCipher.cfg.extend({ 7537 kdf: OpenSSLKdf 7538 }), 7539 7540 /** 7541 * Encrypts a message using a password. 7542 * 7543 * @param {Cipher} cipher The cipher algorithm to use. 7544 * @param {WordArray|string} message The message to encrypt. 7545 * @param {string} password The password. 7546 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7547 * 7548 * @return {CipherParams} A cipher params object. 7549 * 7550 * @static 7551 * 7552 * @example 7553 * 7554 * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); 7555 * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); 7556 */ 7557 encrypt: function (cipher, message, password, cfg) { 7558 // Apply config defaults 7559 cfg = this.cfg.extend(cfg); 7560 7561 // Derive key and other params 7562 var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); 7563 7564 // Add IV to config 7565 cfg.iv = derivedParams.iv; 7566 7567 // Encrypt 7568 var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); 7569 7570 // Mix in derived params 7571 ciphertext.mixIn(derivedParams); 7572 7573 return ciphertext; 7574 }, 7575 7576 /** 7577 * Decrypts serialized ciphertext using a password. 7578 * 7579 * @param {Cipher} cipher The cipher algorithm to use. 7580 * @param {CipherParams|string} ciphertext The ciphertext to decrypt. 7581 * @param {string} password The password. 7582 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7583 * 7584 * @return {WordArray} The plaintext. 7585 * 7586 * @static 7587 * 7588 * @example 7589 * 7590 * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); 7591 * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); 7592 */ 7593 decrypt: function (cipher, ciphertext, password, cfg) { 7594 // Apply config defaults 7595 cfg = this.cfg.extend(cfg); 7596 7597 // Convert string to CipherParams 7598 ciphertext = this._parse(ciphertext, cfg.format); 7599 7600 // Derive key and other params 7601 var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); 7602 7603 // Add IV to config 7604 cfg.iv = derivedParams.iv; 7605 7606 // Decrypt 7607 var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); 7608 7609 return plaintext; 7610 } 7611 }); 7612 }()); 7613 7614 7615 })); 7616 },{"./core":52}],52:[function(require,module,exports){ 7617 ;(function (root, factory) { 7618 if (typeof exports === "object") { 7619 // CommonJS 7620 module.exports = exports = factory(); 7621 } 7622 else if (typeof define === "function" && define.amd) { 7623 // AMD 7624 define([], factory); 7625 } 7626 else { 7627 // Global (browser) 7628 root.CryptoJS = factory(); 7629 } 7630 }(this, function () { 7631 7632 /** 7633 * CryptoJS core components. 7634 */ 7635 var CryptoJS = CryptoJS || (function (Math, undefined) { 7636 /** 7637 * CryptoJS namespace. 7638 */ 7639 var C = {}; 7640 7641 /** 7642 * Library namespace. 7643 */ 7644 var C_lib = C.lib = {}; 7645 7646 /** 7647 * Base object for prototypal inheritance. 7648 */ 7649 var Base = C_lib.Base = (function () { 7650 function F() {} 7651 7652 return { 7653 /** 7654 * Creates a new object that inherits from this object. 7655 * 7656 * @param {Object} overrides Properties to copy into the new object. 7657 * 7658 * @return {Object} The new object. 7659 * 7660 * @static 7661 * 7662 * @example 7663 * 7664 * var MyType = CryptoJS.lib.Base.extend({ 7665 * field: 'value', 7666 * 7667 * method: function () { 7668 * } 7669 * }); 7670 */ 7671 extend: function (overrides) { 7672 // Spawn 7673 F.prototype = this; 7674 var subtype = new F(); 7675 7676 // Augment 7677 if (overrides) { 7678 subtype.mixIn(overrides); 7679 } 7680 7681 // Create default initializer 7682 if (!subtype.hasOwnProperty('init')) { 7683 subtype.init = function () { 7684 subtype.$super.init.apply(this, arguments); 7685 }; 7686 } 7687 7688 // Initializer's prototype is the subtype object 7689 subtype.init.prototype = subtype; 7690 7691 // Reference supertype 7692 subtype.$super = this; 7693 7694 return subtype; 7695 }, 7696 7697 /** 7698 * Extends this object and runs the init method. 7699 * Arguments to create() will be passed to init(). 7700 * 7701 * @return {Object} The new object. 7702 * 7703 * @static 7704 * 7705 * @example 7706 * 7707 * var instance = MyType.create(); 7708 */ 7709 create: function () { 7710 var instance = this.extend(); 7711 instance.init.apply(instance, arguments); 7712 7713 return instance; 7714 }, 7715 7716 /** 7717 * Initializes a newly created object. 7718 * Override this method to add some logic when your objects are created. 7719 * 7720 * @example 7721 * 7722 * var MyType = CryptoJS.lib.Base.extend({ 7723 * init: function () { 7724 * // ... 7725 * } 7726 * }); 7727 */ 7728 init: function () { 7729 }, 7730 7731 /** 7732 * Copies properties into this object. 7733 * 7734 * @param {Object} properties The properties to mix in. 7735 * 7736 * @example 7737 * 7738 * MyType.mixIn({ 7739 * field: 'value' 7740 * }); 7741 */ 7742 mixIn: function (properties) { 7743 for (var propertyName in properties) { 7744 if (properties.hasOwnProperty(propertyName)) { 7745 this[propertyName] = properties[propertyName]; 7746 } 7747 } 7748 7749 // IE won't copy toString using the loop above 7750 if (properties.hasOwnProperty('toString')) { 7751 this.toString = properties.toString; 7752 } 7753 }, 7754 7755 /** 7756 * Creates a copy of this object. 7757 * 7758 * @return {Object} The clone. 7759 * 7760 * @example 7761 * 7762 * var clone = instance.clone(); 7763 */ 7764 clone: function () { 7765 return this.init.prototype.extend(this); 7766 } 7767 }; 7768 }()); 7769 7770 /** 7771 * An array of 32-bit words. 7772 * 7773 * @property {Array} words The array of 32-bit words. 7774 * @property {number} sigBytes The number of significant bytes in this word array. 7775 */ 7776 var WordArray = C_lib.WordArray = Base.extend({ 7777 /** 7778 * Initializes a newly created word array. 7779 * 7780 * @param {Array} words (Optional) An array of 32-bit words. 7781 * @param {number} sigBytes (Optional) The number of significant bytes in the words. 7782 * 7783 * @example 7784 * 7785 * var wordArray = CryptoJS.lib.WordArray.create(); 7786 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); 7787 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); 7788 */ 7789 init: function (words, sigBytes) { 7790 words = this.words = words || []; 7791 7792 if (sigBytes != undefined) { 7793 this.sigBytes = sigBytes; 7794 } else { 7795 this.sigBytes = words.length * 4; 7796 } 7797 }, 7798 7799 /** 7800 * Converts this word array to a string. 7801 * 7802 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex 7803 * 7804 * @return {string} The stringified word array. 7805 * 7806 * @example 7807 * 7808 * var string = wordArray + ''; 7809 * var string = wordArray.toString(); 7810 * var string = wordArray.toString(CryptoJS.enc.Utf8); 7811 */ 7812 toString: function (encoder) { 7813 return (encoder || Hex).stringify(this); 7814 }, 7815 7816 /** 7817 * Concatenates a word array to this word array. 7818 * 7819 * @param {WordArray} wordArray The word array to append. 7820 * 7821 * @return {WordArray} This word array. 7822 * 7823 * @example 7824 * 7825 * wordArray1.concat(wordArray2); 7826 */ 7827 concat: function (wordArray) { 7828 // Shortcuts 7829 var thisWords = this.words; 7830 var thatWords = wordArray.words; 7831 var thisSigBytes = this.sigBytes; 7832 var thatSigBytes = wordArray.sigBytes; 7833 7834 // Clamp excess bits 7835 this.clamp(); 7836 7837 // Concat 7838 if (thisSigBytes % 4) { 7839 // Copy one byte at a time 7840 for (var i = 0; i < thatSigBytes; i++) { 7841 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 7842 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); 7843 } 7844 } else { 7845 // Copy one word at a time 7846 for (var i = 0; i < thatSigBytes; i += 4) { 7847 thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; 7848 } 7849 } 7850 this.sigBytes += thatSigBytes; 7851 7852 // Chainable 7853 return this; 7854 }, 7855 7856 /** 7857 * Removes insignificant bits. 7858 * 7859 * @example 7860 * 7861 * wordArray.clamp(); 7862 */ 7863 clamp: function () { 7864 // Shortcuts 7865 var words = this.words; 7866 var sigBytes = this.sigBytes; 7867 7868 // Clamp 7869 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); 7870 words.length = Math.ceil(sigBytes / 4); 7871 }, 7872 7873 /** 7874 * Creates a copy of this word array. 7875 * 7876 * @return {WordArray} The clone. 7877 * 7878 * @example 7879 * 7880 * var clone = wordArray.clone(); 7881 */ 7882 clone: function () { 7883 var clone = Base.clone.call(this); 7884 clone.words = this.words.slice(0); 7885 7886 return clone; 7887 }, 7888 7889 /** 7890 * Creates a word array filled with random bytes. 7891 * 7892 * @param {number} nBytes The number of random bytes to generate. 7893 * 7894 * @return {WordArray} The random word array. 7895 * 7896 * @static 7897 * 7898 * @example 7899 * 7900 * var wordArray = CryptoJS.lib.WordArray.random(16); 7901 */ 7902 random: function (nBytes) { 7903 var words = []; 7904 7905 var r = (function (m_w) { 7906 var m_w = m_w; 7907 var m_z = 0x3ade68b1; 7908 var mask = 0xffffffff; 7909 7910 return function () { 7911 m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; 7912 m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; 7913 var result = ((m_z << 0x10) + m_w) & mask; 7914 result /= 0x100000000; 7915 result += 0.5; 7916 return result * (Math.random() > .5 ? 1 : -1); 7917 } 7918 }); 7919 7920 for (var i = 0, rcache; i < nBytes; i += 4) { 7921 var _r = r((rcache || Math.random()) * 0x100000000); 7922 7923 rcache = _r() * 0x3ade67b7; 7924 words.push((_r() * 0x100000000) | 0); 7925 } 7926 7927 return new WordArray.init(words, nBytes); 7928 } 7929 }); 7930 7931 /** 7932 * Encoder namespace. 7933 */ 7934 var C_enc = C.enc = {}; 7935 7936 /** 7937 * Hex encoding strategy. 7938 */ 7939 var Hex = C_enc.Hex = { 7940 /** 7941 * Converts a word array to a hex string. 7942 * 7943 * @param {WordArray} wordArray The word array. 7944 * 7945 * @return {string} The hex string. 7946 * 7947 * @static 7948 * 7949 * @example 7950 * 7951 * var hexString = CryptoJS.enc.Hex.stringify(wordArray); 7952 */ 7953 stringify: function (wordArray) { 7954 // Shortcuts 7955 var words = wordArray.words; 7956 var sigBytes = wordArray.sigBytes; 7957 7958 // Convert 7959 var hexChars = []; 7960 for (var i = 0; i < sigBytes; i++) { 7961 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 7962 hexChars.push((bite >>> 4).toString(16)); 7963 hexChars.push((bite & 0x0f).toString(16)); 7964 } 7965 7966 return hexChars.join(''); 7967 }, 7968 7969 /** 7970 * Converts a hex string to a word array. 7971 * 7972 * @param {string} hexStr The hex string. 7973 * 7974 * @return {WordArray} The word array. 7975 * 7976 * @static 7977 * 7978 * @example 7979 * 7980 * var wordArray = CryptoJS.enc.Hex.parse(hexString); 7981 */ 7982 parse: function (hexStr) { 7983 // Shortcut 7984 var hexStrLength = hexStr.length; 7985 7986 // Convert 7987 var words = []; 7988 for (var i = 0; i < hexStrLength; i += 2) { 7989 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); 7990 } 7991 7992 return new WordArray.init(words, hexStrLength / 2); 7993 } 7994 }; 7995 7996 /** 7997 * Latin1 encoding strategy. 7998 */ 7999 var Latin1 = C_enc.Latin1 = { 8000 /** 8001 * Converts a word array to a Latin1 string. 8002 * 8003 * @param {WordArray} wordArray The word array. 8004 * 8005 * @return {string} The Latin1 string. 8006 * 8007 * @static 8008 * 8009 * @example 8010 * 8011 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); 8012 */ 8013 stringify: function (wordArray) { 8014 // Shortcuts 8015 var words = wordArray.words; 8016 var sigBytes = wordArray.sigBytes; 8017 8018 // Convert 8019 var latin1Chars = []; 8020 for (var i = 0; i < sigBytes; i++) { 8021 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 8022 latin1Chars.push(String.fromCharCode(bite)); 8023 } 8024 8025 return latin1Chars.join(''); 8026 }, 8027 8028 /** 8029 * Converts a Latin1 string to a word array. 8030 * 8031 * @param {string} latin1Str The Latin1 string. 8032 * 8033 * @return {WordArray} The word array. 8034 * 8035 * @static 8036 * 8037 * @example 8038 * 8039 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); 8040 */ 8041 parse: function (latin1Str) { 8042 // Shortcut 8043 var latin1StrLength = latin1Str.length; 8044 8045 // Convert 8046 var words = []; 8047 for (var i = 0; i < latin1StrLength; i++) { 8048 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); 8049 } 8050 8051 return new WordArray.init(words, latin1StrLength); 8052 } 8053 }; 8054 8055 /** 8056 * UTF-8 encoding strategy. 8057 */ 8058 var Utf8 = C_enc.Utf8 = { 8059 /** 8060 * Converts a word array to a UTF-8 string. 8061 * 8062 * @param {WordArray} wordArray The word array. 8063 * 8064 * @return {string} The UTF-8 string. 8065 * 8066 * @static 8067 * 8068 * @example 8069 * 8070 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); 8071 */ 8072 stringify: function (wordArray) { 8073 try { 8074 return decodeURIComponent(escape(Latin1.stringify(wordArray))); 8075 } catch (e) { 8076 throw new Error('Malformed UTF-8 data'); 8077 } 8078 }, 8079 8080 /** 8081 * Converts a UTF-8 string to a word array. 8082 * 8083 * @param {string} utf8Str The UTF-8 string. 8084 * 8085 * @return {WordArray} The word array. 8086 * 8087 * @static 8088 * 8089 * @example 8090 * 8091 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); 8092 */ 8093 parse: function (utf8Str) { 8094 return Latin1.parse(unescape(encodeURIComponent(utf8Str))); 8095 } 8096 }; 8097 8098 /** 8099 * Abstract buffered block algorithm template. 8100 * 8101 * The property blockSize must be implemented in a concrete subtype. 8102 * 8103 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 8104 */ 8105 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ 8106 /** 8107 * Resets this block algorithm's data buffer to its initial state. 8108 * 8109 * @example 8110 * 8111 * bufferedBlockAlgorithm.reset(); 8112 */ 8113 reset: function () { 8114 // Initial values 8115 this._data = new WordArray.init(); 8116 this._nDataBytes = 0; 8117 }, 8118 8119 /** 8120 * Adds new data to this block algorithm's buffer. 8121 * 8122 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. 8123 * 8124 * @example 8125 * 8126 * bufferedBlockAlgorithm._append('data'); 8127 * bufferedBlockAlgorithm._append(wordArray); 8128 */ 8129 _append: function (data) { 8130 // Convert string to WordArray, else assume WordArray already 8131 if (typeof data == 'string') { 8132 data = Utf8.parse(data); 8133 } 8134 8135 // Append 8136 this._data.concat(data); 8137 this._nDataBytes += data.sigBytes; 8138 }, 8139 8140 /** 8141 * Processes available data blocks. 8142 * 8143 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. 8144 * 8145 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. 8146 * 8147 * @return {WordArray} The processed data. 8148 * 8149 * @example 8150 * 8151 * var processedData = bufferedBlockAlgorithm._process(); 8152 * var processedData = bufferedBlockAlgorithm._process(!!'flush'); 8153 */ 8154 _process: function (doFlush) { 8155 // Shortcuts 8156 var data = this._data; 8157 var dataWords = data.words; 8158 var dataSigBytes = data.sigBytes; 8159 var blockSize = this.blockSize; 8160 var blockSizeBytes = blockSize * 4; 8161 8162 // Count blocks ready 8163 var nBlocksReady = dataSigBytes / blockSizeBytes; 8164 if (doFlush) { 8165 // Round up to include partial blocks 8166 nBlocksReady = Math.ceil(nBlocksReady); 8167 } else { 8168 // Round down to include only full blocks, 8169 // less the number of blocks that must remain in the buffer 8170 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); 8171 } 8172 8173 // Count words ready 8174 var nWordsReady = nBlocksReady * blockSize; 8175 8176 // Count bytes ready 8177 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); 8178 8179 // Process blocks 8180 if (nWordsReady) { 8181 for (var offset = 0; offset < nWordsReady; offset += blockSize) { 8182 // Perform concrete-algorithm logic 8183 this._doProcessBlock(dataWords, offset); 8184 } 8185 8186 // Remove processed words 8187 var processedWords = dataWords.splice(0, nWordsReady); 8188 data.sigBytes -= nBytesReady; 8189 } 8190 8191 // Return processed words 8192 return new WordArray.init(processedWords, nBytesReady); 8193 }, 8194 8195 /** 8196 * Creates a copy of this object. 8197 * 8198 * @return {Object} The clone. 8199 * 8200 * @example 8201 * 8202 * var clone = bufferedBlockAlgorithm.clone(); 8203 */ 8204 clone: function () { 8205 var clone = Base.clone.call(this); 8206 clone._data = this._data.clone(); 8207 8208 return clone; 8209 }, 8210 8211 _minBufferSize: 0 8212 }); 8213 8214 /** 8215 * Abstract hasher template. 8216 * 8217 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) 8218 */ 8219 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ 8220 /** 8221 * Configuration options. 8222 */ 8223 cfg: Base.extend(), 8224 8225 /** 8226 * Initializes a newly created hasher. 8227 * 8228 * @param {Object} cfg (Optional) The configuration options to use for this hash computation. 8229 * 8230 * @example 8231 * 8232 * var hasher = CryptoJS.algo.SHA256.create(); 8233 */ 8234 init: function (cfg) { 8235 // Apply config defaults 8236 this.cfg = this.cfg.extend(cfg); 8237 8238 // Set initial values 8239 this.reset(); 8240 }, 8241 8242 /** 8243 * Resets this hasher to its initial state. 8244 * 8245 * @example 8246 * 8247 * hasher.reset(); 8248 */ 8249 reset: function () { 8250 // Reset data buffer 8251 BufferedBlockAlgorithm.reset.call(this); 8252 8253 // Perform concrete-hasher logic 8254 this._doReset(); 8255 }, 8256 8257 /** 8258 * Updates this hasher with a message. 8259 * 8260 * @param {WordArray|string} messageUpdate The message to append. 8261 * 8262 * @return {Hasher} This hasher. 8263 * 8264 * @example 8265 * 8266 * hasher.update('message'); 8267 * hasher.update(wordArray); 8268 */ 8269 update: function (messageUpdate) { 8270 // Append 8271 this._append(messageUpdate); 8272 8273 // Update the hash 8274 this._process(); 8275 8276 // Chainable 8277 return this; 8278 }, 8279 8280 /** 8281 * Finalizes the hash computation. 8282 * Note that the finalize operation is effectively a destructive, read-once operation. 8283 * 8284 * @param {WordArray|string} messageUpdate (Optional) A final message update. 8285 * 8286 * @return {WordArray} The hash. 8287 * 8288 * @example 8289 * 8290 * var hash = hasher.finalize(); 8291 * var hash = hasher.finalize('message'); 8292 * var hash = hasher.finalize(wordArray); 8293 */ 8294 finalize: function (messageUpdate) { 8295 // Final message update 8296 if (messageUpdate) { 8297 this._append(messageUpdate); 8298 } 8299 8300 // Perform concrete-hasher logic 8301 var hash = this._doFinalize(); 8302 8303 return hash; 8304 }, 8305 8306 blockSize: 512/32, 8307 8308 /** 8309 * Creates a shortcut function to a hasher's object interface. 8310 * 8311 * @param {Hasher} hasher The hasher to create a helper for. 8312 * 8313 * @return {Function} The shortcut function. 8314 * 8315 * @static 8316 * 8317 * @example 8318 * 8319 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); 8320 */ 8321 _createHelper: function (hasher) { 8322 return function (message, cfg) { 8323 return new hasher.init(cfg).finalize(message); 8324 }; 8325 }, 8326 8327 /** 8328 * Creates a shortcut function to the HMAC's object interface. 8329 * 8330 * @param {Hasher} hasher The hasher to use in this HMAC helper. 8331 * 8332 * @return {Function} The shortcut function. 8333 * 8334 * @static 8335 * 8336 * @example 8337 * 8338 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); 8339 */ 8340 _createHmacHelper: function (hasher) { 8341 return function (message, key) { 8342 return new C_algo.HMAC.init(hasher, key).finalize(message); 8343 }; 8344 } 8345 }); 8346 8347 /** 8348 * Algorithm namespace. 8349 */ 8350 var C_algo = C.algo = {}; 8351 8352 return C; 8353 }(Math)); 8354 8355 8356 return CryptoJS; 8357 8358 })); 8359 },{}],53:[function(require,module,exports){ 8360 ;(function (root, factory) { 8361 if (typeof exports === "object") { 8362 // CommonJS 8363 module.exports = exports = factory(require("./core")); 8364 } 8365 else if (typeof define === "function" && define.amd) { 8366 // AMD 8367 define(["./core"], factory); 8368 } 8369 else { 8370 // Global (browser) 8371 factory(root.CryptoJS); 8372 } 8373 }(this, function (CryptoJS) { 8374 8375 (function () { 8376 // Shortcuts 8377 var C = CryptoJS; 8378 var C_lib = C.lib; 8379 var WordArray = C_lib.WordArray; 8380 var C_enc = C.enc; 8381 8382 /** 8383 * Base64 encoding strategy. 8384 */ 8385 var Base64 = C_enc.Base64 = { 8386 /** 8387 * Converts a word array to a Base64 string. 8388 * 8389 * @param {WordArray} wordArray The word array. 8390 * 8391 * @return {string} The Base64 string. 8392 * 8393 * @static 8394 * 8395 * @example 8396 * 8397 * var base64String = CryptoJS.enc.Base64.stringify(wordArray); 8398 */ 8399 stringify: function (wordArray) { 8400 // Shortcuts 8401 var words = wordArray.words; 8402 var sigBytes = wordArray.sigBytes; 8403 var map = this._map; 8404 8405 // Clamp excess bits 8406 wordArray.clamp(); 8407 8408 // Convert 8409 var base64Chars = []; 8410 for (var i = 0; i < sigBytes; i += 3) { 8411 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 8412 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; 8413 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; 8414 8415 var triplet = (byte1 << 16) | (byte2 << 8) | byte3; 8416 8417 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { 8418 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); 8419 } 8420 } 8421 8422 // Add padding 8423 var paddingChar = map.charAt(64); 8424 if (paddingChar) { 8425 while (base64Chars.length % 4) { 8426 base64Chars.push(paddingChar); 8427 } 8428 } 8429 8430 return base64Chars.join(''); 8431 }, 8432 8433 /** 8434 * Converts a Base64 string to a word array. 8435 * 8436 * @param {string} base64Str The Base64 string. 8437 * 8438 * @return {WordArray} The word array. 8439 * 8440 * @static 8441 * 8442 * @example 8443 * 8444 * var wordArray = CryptoJS.enc.Base64.parse(base64String); 8445 */ 8446 parse: function (base64Str) { 8447 // Shortcuts 8448 var base64StrLength = base64Str.length; 8449 var map = this._map; 8450 8451 // Ignore padding 8452 var paddingChar = map.charAt(64); 8453 if (paddingChar) { 8454 var paddingIndex = base64Str.indexOf(paddingChar); 8455 if (paddingIndex != -1) { 8456 base64StrLength = paddingIndex; 8457 } 8458 } 8459 8460 // Convert 8461 var words = []; 8462 var nBytes = 0; 8463 for (var i = 0; i < base64StrLength; i++) { 8464 if (i % 4) { 8465 var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); 8466 var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); 8467 words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); 8468 nBytes++; 8469 } 8470 } 8471 8472 return WordArray.create(words, nBytes); 8473 }, 8474 8475 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' 8476 }; 8477 }()); 8478 8479 8480 return CryptoJS.enc.Base64; 8481 8482 })); 8483 },{"./core":52}],54:[function(require,module,exports){ 8484 ;(function (root, factory) { 8485 if (typeof exports === "object") { 8486 // CommonJS 8487 module.exports = exports = factory(require("./core")); 8488 } 8489 else if (typeof define === "function" && define.amd) { 8490 // AMD 8491 define(["./core"], factory); 8492 } 8493 else { 8494 // Global (browser) 8495 factory(root.CryptoJS); 8496 } 8497 }(this, function (CryptoJS) { 8498 8499 (function () { 8500 // Shortcuts 8501 var C = CryptoJS; 8502 var C_lib = C.lib; 8503 var WordArray = C_lib.WordArray; 8504 var C_enc = C.enc; 8505 8506 /** 8507 * UTF-16 BE encoding strategy. 8508 */ 8509 var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { 8510 /** 8511 * Converts a word array to a UTF-16 BE string. 8512 * 8513 * @param {WordArray} wordArray The word array. 8514 * 8515 * @return {string} The UTF-16 BE string. 8516 * 8517 * @static 8518 * 8519 * @example 8520 * 8521 * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); 8522 */ 8523 stringify: function (wordArray) { 8524 // Shortcuts 8525 var words = wordArray.words; 8526 var sigBytes = wordArray.sigBytes; 8527 8528 // Convert 8529 var utf16Chars = []; 8530 for (var i = 0; i < sigBytes; i += 2) { 8531 var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; 8532 utf16Chars.push(String.fromCharCode(codePoint)); 8533 } 8534 8535 return utf16Chars.join(''); 8536 }, 8537 8538 /** 8539 * Converts a UTF-16 BE string to a word array. 8540 * 8541 * @param {string} utf16Str The UTF-16 BE string. 8542 * 8543 * @return {WordArray} The word array. 8544 * 8545 * @static 8546 * 8547 * @example 8548 * 8549 * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); 8550 */ 8551 parse: function (utf16Str) { 8552 // Shortcut 8553 var utf16StrLength = utf16Str.length; 8554 8555 // Convert 8556 var words = []; 8557 for (var i = 0; i < utf16StrLength; i++) { 8558 words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); 8559 } 8560 8561 return WordArray.create(words, utf16StrLength * 2); 8562 } 8563 }; 8564 8565 /** 8566 * UTF-16 LE encoding strategy. 8567 */ 8568 C_enc.Utf16LE = { 8569 /** 8570 * Converts a word array to a UTF-16 LE string. 8571 * 8572 * @param {WordArray} wordArray The word array. 8573 * 8574 * @return {string} The UTF-16 LE string. 8575 * 8576 * @static 8577 * 8578 * @example 8579 * 8580 * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); 8581 */ 8582 stringify: function (wordArray) { 8583 // Shortcuts 8584 var words = wordArray.words; 8585 var sigBytes = wordArray.sigBytes; 8586 8587 // Convert 8588 var utf16Chars = []; 8589 for (var i = 0; i < sigBytes; i += 2) { 8590 var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); 8591 utf16Chars.push(String.fromCharCode(codePoint)); 8592 } 8593 8594 return utf16Chars.join(''); 8595 }, 8596 8597 /** 8598 * Converts a UTF-16 LE string to a word array. 8599 * 8600 * @param {string} utf16Str The UTF-16 LE string. 8601 * 8602 * @return {WordArray} The word array. 8603 * 8604 * @static 8605 * 8606 * @example 8607 * 8608 * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); 8609 */ 8610 parse: function (utf16Str) { 8611 // Shortcut 8612 var utf16StrLength = utf16Str.length; 8613 8614 // Convert 8615 var words = []; 8616 for (var i = 0; i < utf16StrLength; i++) { 8617 words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); 8618 } 8619 8620 return WordArray.create(words, utf16StrLength * 2); 8621 } 8622 }; 8623 8624 function swapEndian(word) { 8625 return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); 8626 } 8627 }()); 8628 8629 8630 return CryptoJS.enc.Utf16; 8631 8632 })); 8633 },{"./core":52}],55:[function(require,module,exports){ 8634 ;(function (root, factory, undef) { 8635 if (typeof exports === "object") { 8636 // CommonJS 8637 module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); 8638 } 8639 else if (typeof define === "function" && define.amd) { 8640 // AMD 8641 define(["./core", "./sha1", "./hmac"], factory); 8642 } 8643 else { 8644 // Global (browser) 8645 factory(root.CryptoJS); 8646 } 8647 }(this, function (CryptoJS) { 8648 8649 (function () { 8650 // Shortcuts 8651 var C = CryptoJS; 8652 var C_lib = C.lib; 8653 var Base = C_lib.Base; 8654 var WordArray = C_lib.WordArray; 8655 var C_algo = C.algo; 8656 var MD5 = C_algo.MD5; 8657 8658 /** 8659 * This key derivation function is meant to conform with EVP_BytesToKey. 8660 * www.openssl.org/docs/crypto/EVP_BytesToKey.html 8661 */ 8662 var EvpKDF = C_algo.EvpKDF = Base.extend({ 8663 /** 8664 * Configuration options. 8665 * 8666 * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) 8667 * @property {Hasher} hasher The hash algorithm to use. Default: MD5 8668 * @property {number} iterations The number of iterations to perform. Default: 1 8669 */ 8670 cfg: Base.extend({ 8671 keySize: 128/32, 8672 hasher: MD5, 8673 iterations: 1 8674 }), 8675 8676 /** 8677 * Initializes a newly created key derivation function. 8678 * 8679 * @param {Object} cfg (Optional) The configuration options to use for the derivation. 8680 * 8681 * @example 8682 * 8683 * var kdf = CryptoJS.algo.EvpKDF.create(); 8684 * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); 8685 * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); 8686 */ 8687 init: function (cfg) { 8688 this.cfg = this.cfg.extend(cfg); 8689 }, 8690 8691 /** 8692 * Derives a key from a password. 8693 * 8694 * @param {WordArray|string} password The password. 8695 * @param {WordArray|string} salt A salt. 8696 * 8697 * @return {WordArray} The derived key. 8698 * 8699 * @example 8700 * 8701 * var key = kdf.compute(password, salt); 8702 */ 8703 compute: function (password, salt) { 8704 // Shortcut 8705 var cfg = this.cfg; 8706 8707 // Init hasher 8708 var hasher = cfg.hasher.create(); 8709 8710 // Initial values 8711 var derivedKey = WordArray.create(); 8712 8713 // Shortcuts 8714 var derivedKeyWords = derivedKey.words; 8715 var keySize = cfg.keySize; 8716 var iterations = cfg.iterations; 8717 8718 // Generate key 8719 while (derivedKeyWords.length < keySize) { 8720 if (block) { 8721 hasher.update(block); 8722 } 8723 var block = hasher.update(password).finalize(salt); 8724 hasher.reset(); 8725 8726 // Iterations 8727 for (var i = 1; i < iterations; i++) { 8728 block = hasher.finalize(block); 8729 hasher.reset(); 8730 } 8731 8732 derivedKey.concat(block); 8733 } 8734 derivedKey.sigBytes = keySize * 4; 8735 8736 return derivedKey; 8737 } 8738 }); 8739 8740 /** 8741 * Derives a key from a password. 8742 * 8743 * @param {WordArray|string} password The password. 8744 * @param {WordArray|string} salt A salt. 8745 * @param {Object} cfg (Optional) The configuration options to use for this computation. 8746 * 8747 * @return {WordArray} The derived key. 8748 * 8749 * @static 8750 * 8751 * @example 8752 * 8753 * var key = CryptoJS.EvpKDF(password, salt); 8754 * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); 8755 * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); 8756 */ 8757 C.EvpKDF = function (password, salt, cfg) { 8758 return EvpKDF.create(cfg).compute(password, salt); 8759 }; 8760 }()); 8761 8762 8763 return CryptoJS.EvpKDF; 8764 8765 })); 8766 },{"./core":52,"./hmac":57,"./sha1":76}],56:[function(require,module,exports){ 8767 ;(function (root, factory, undef) { 8768 if (typeof exports === "object") { 8769 // CommonJS 8770 module.exports = exports = factory(require("./core"), require("./cipher-core")); 8771 } 8772 else if (typeof define === "function" && define.amd) { 8773 // AMD 8774 define(["./core", "./cipher-core"], factory); 8775 } 8776 else { 8777 // Global (browser) 8778 factory(root.CryptoJS); 8779 } 8780 }(this, function (CryptoJS) { 8781 8782 (function (undefined) { 8783 // Shortcuts 8784 var C = CryptoJS; 8785 var C_lib = C.lib; 8786 var CipherParams = C_lib.CipherParams; 8787 var C_enc = C.enc; 8788 var Hex = C_enc.Hex; 8789 var C_format = C.format; 8790 8791 var HexFormatter = C_format.Hex = { 8792 /** 8793 * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. 8794 * 8795 * @param {CipherParams} cipherParams The cipher params object. 8796 * 8797 * @return {string} The hexadecimally encoded string. 8798 * 8799 * @static 8800 * 8801 * @example 8802 * 8803 * var hexString = CryptoJS.format.Hex.stringify(cipherParams); 8804 */ 8805 stringify: function (cipherParams) { 8806 return cipherParams.ciphertext.toString(Hex); 8807 }, 8808 8809 /** 8810 * Converts a hexadecimally encoded ciphertext string to a cipher params object. 8811 * 8812 * @param {string} input The hexadecimally encoded string. 8813 * 8814 * @return {CipherParams} The cipher params object. 8815 * 8816 * @static 8817 * 8818 * @example 8819 * 8820 * var cipherParams = CryptoJS.format.Hex.parse(hexString); 8821 */ 8822 parse: function (input) { 8823 var ciphertext = Hex.parse(input); 8824 return CipherParams.create({ ciphertext: ciphertext }); 8825 } 8826 }; 8827 }()); 8828 8829 8830 return CryptoJS.format.Hex; 8831 8832 })); 8833 },{"./cipher-core":51,"./core":52}],57:[function(require,module,exports){ 8834 ;(function (root, factory) { 8835 if (typeof exports === "object") { 8836 // CommonJS 8837 module.exports = exports = factory(require("./core")); 8838 } 8839 else if (typeof define === "function" && define.amd) { 8840 // AMD 8841 define(["./core"], factory); 8842 } 8843 else { 8844 // Global (browser) 8845 factory(root.CryptoJS); 8846 } 8847 }(this, function (CryptoJS) { 8848 8849 (function () { 8850 // Shortcuts 8851 var C = CryptoJS; 8852 var C_lib = C.lib; 8853 var Base = C_lib.Base; 8854 var C_enc = C.enc; 8855 var Utf8 = C_enc.Utf8; 8856 var C_algo = C.algo; 8857 8858 /** 8859 * HMAC algorithm. 8860 */ 8861 var HMAC = C_algo.HMAC = Base.extend({ 8862 /** 8863 * Initializes a newly created HMAC. 8864 * 8865 * @param {Hasher} hasher The hash algorithm to use. 8866 * @param {WordArray|string} key The secret key. 8867 * 8868 * @example 8869 * 8870 * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); 8871 */ 8872 init: function (hasher, key) { 8873 // Init hasher 8874 hasher = this._hasher = new hasher.init(); 8875 8876 // Convert string to WordArray, else assume WordArray already 8877 if (typeof key == 'string') { 8878 key = Utf8.parse(key); 8879 } 8880 8881 // Shortcuts 8882 var hasherBlockSize = hasher.blockSize; 8883 var hasherBlockSizeBytes = hasherBlockSize * 4; 8884 8885 // Allow arbitrary length keys 8886 if (key.sigBytes > hasherBlockSizeBytes) { 8887 key = hasher.finalize(key); 8888 } 8889 8890 // Clamp excess bits 8891 key.clamp(); 8892 8893 // Clone key for inner and outer pads 8894 var oKey = this._oKey = key.clone(); 8895 var iKey = this._iKey = key.clone(); 8896 8897 // Shortcuts 8898 var oKeyWords = oKey.words; 8899 var iKeyWords = iKey.words; 8900 8901 // XOR keys with pad constants 8902 for (var i = 0; i < hasherBlockSize; i++) { 8903 oKeyWords[i] ^= 0x5c5c5c5c; 8904 iKeyWords[i] ^= 0x36363636; 8905 } 8906 oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; 8907 8908 // Set initial values 8909 this.reset(); 8910 }, 8911 8912 /** 8913 * Resets this HMAC to its initial state. 8914 * 8915 * @example 8916 * 8917 * hmacHasher.reset(); 8918 */ 8919 reset: function () { 8920 // Shortcut 8921 var hasher = this._hasher; 8922 8923 // Reset 8924 hasher.reset(); 8925 hasher.update(this._iKey); 8926 }, 8927 8928 /** 8929 * Updates this HMAC with a message. 8930 * 8931 * @param {WordArray|string} messageUpdate The message to append. 8932 * 8933 * @return {HMAC} This HMAC instance. 8934 * 8935 * @example 8936 * 8937 * hmacHasher.update('message'); 8938 * hmacHasher.update(wordArray); 8939 */ 8940 update: function (messageUpdate) { 8941 this._hasher.update(messageUpdate); 8942 8943 // Chainable 8944 return this; 8945 }, 8946 8947 /** 8948 * Finalizes the HMAC computation. 8949 * Note that the finalize operation is effectively a destructive, read-once operation. 8950 * 8951 * @param {WordArray|string} messageUpdate (Optional) A final message update. 8952 * 8953 * @return {WordArray} The HMAC. 8954 * 8955 * @example 8956 * 8957 * var hmac = hmacHasher.finalize(); 8958 * var hmac = hmacHasher.finalize('message'); 8959 * var hmac = hmacHasher.finalize(wordArray); 8960 */ 8961 finalize: function (messageUpdate) { 8962 // Shortcut 8963 var hasher = this._hasher; 8964 8965 // Compute HMAC 8966 var innerHash = hasher.finalize(messageUpdate); 8967 hasher.reset(); 8968 var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); 8969 8970 return hmac; 8971 } 8972 }); 8973 }()); 8974 8975 8976 })); 8977 },{"./core":52}],58:[function(require,module,exports){ 8978 ;(function (root, factory, undef) { 8979 if (typeof exports === "object") { 8980 // CommonJS 8981 module.exports = exports = factory(require("./core"), require("./x64-core"), require("./lib-typedarrays"), require("./enc-utf16"), require("./enc-base64"), require("./md5"), require("./sha1"), require("./sha256"), require("./sha224"), require("./sha512"), require("./sha384"), require("./sha3"), require("./ripemd160"), require("./hmac"), require("./pbkdf2"), require("./evpkdf"), require("./cipher-core"), require("./mode-cfb"), require("./mode-ctr"), require("./mode-ctr-gladman"), require("./mode-ofb"), require("./mode-ecb"), require("./pad-ansix923"), require("./pad-iso10126"), require("./pad-iso97971"), require("./pad-zeropadding"), require("./pad-nopadding"), require("./format-hex"), require("./aes"), require("./tripledes"), require("./rc4"), require("./rabbit"), require("./rabbit-legacy")); 8982 } 8983 else if (typeof define === "function" && define.amd) { 8984 // AMD 8985 define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); 8986 } 8987 else { 8988 // Global (browser) 8989 root.CryptoJS = factory(root.CryptoJS); 8990 } 8991 }(this, function (CryptoJS) { 8992 8993 return CryptoJS; 8994 8995 })); 8996 },{"./aes":50,"./cipher-core":51,"./core":52,"./enc-base64":53,"./enc-utf16":54,"./evpkdf":55,"./format-hex":56,"./hmac":57,"./lib-typedarrays":59,"./md5":60,"./mode-cfb":61,"./mode-ctr":63,"./mode-ctr-gladman":62,"./mode-ecb":64,"./mode-ofb":65,"./pad-ansix923":66,"./pad-iso10126":67,"./pad-iso97971":68,"./pad-nopadding":69,"./pad-zeropadding":70,"./pbkdf2":71,"./rabbit":73,"./rabbit-legacy":72,"./rc4":74,"./ripemd160":75,"./sha1":76,"./sha224":77,"./sha256":78,"./sha3":79,"./sha384":80,"./sha512":81,"./tripledes":82,"./x64-core":83}],59:[function(require,module,exports){ 8997 ;(function (root, factory) { 8998 if (typeof exports === "object") { 8999 // CommonJS 9000 module.exports = exports = factory(require("./core")); 9001 } 9002 else if (typeof define === "function" && define.amd) { 9003 // AMD 9004 define(["./core"], factory); 9005 } 9006 else { 9007 // Global (browser) 9008 factory(root.CryptoJS); 9009 } 9010 }(this, function (CryptoJS) { 9011 9012 (function () { 9013 // Check if typed arrays are supported 9014 if (typeof ArrayBuffer != 'function') { 9015 return; 9016 } 9017 9018 // Shortcuts 9019 var C = CryptoJS; 9020 var C_lib = C.lib; 9021 var WordArray = C_lib.WordArray; 9022 9023 // Reference original init 9024 var superInit = WordArray.init; 9025 9026 // Augment WordArray.init to handle typed arrays 9027 var subInit = WordArray.init = function (typedArray) { 9028 // Convert buffers to uint8 9029 if (typedArray instanceof ArrayBuffer) { 9030 typedArray = new Uint8Array(typedArray); 9031 } 9032 9033 // Convert other array views to uint8 9034 if ( 9035 typedArray instanceof Int8Array || 9036 (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || 9037 typedArray instanceof Int16Array || 9038 typedArray instanceof Uint16Array || 9039 typedArray instanceof Int32Array || 9040 typedArray instanceof Uint32Array || 9041 typedArray instanceof Float32Array || 9042 typedArray instanceof Float64Array 9043 ) { 9044 typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); 9045 } 9046 9047 // Handle Uint8Array 9048 if (typedArray instanceof Uint8Array) { 9049 // Shortcut 9050 var typedArrayByteLength = typedArray.byteLength; 9051 9052 // Extract bytes 9053 var words = []; 9054 for (var i = 0; i < typedArrayByteLength; i++) { 9055 words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); 9056 } 9057 9058 // Initialize this word array 9059 superInit.call(this, words, typedArrayByteLength); 9060 } else { 9061 // Else call normal init 9062 superInit.apply(this, arguments); 9063 } 9064 }; 9065 9066 subInit.prototype = WordArray; 9067 }()); 9068 9069 9070 return CryptoJS.lib.WordArray; 9071 9072 })); 9073 },{"./core":52}],60:[function(require,module,exports){ 9074 ;(function (root, factory) { 9075 if (typeof exports === "object") { 9076 // CommonJS 9077 module.exports = exports = factory(require("./core")); 9078 } 9079 else if (typeof define === "function" && define.amd) { 9080 // AMD 9081 define(["./core"], factory); 9082 } 9083 else { 9084 // Global (browser) 9085 factory(root.CryptoJS); 9086 } 9087 }(this, function (CryptoJS) { 9088 9089 (function (Math) { 9090 // Shortcuts 9091 var C = CryptoJS; 9092 var C_lib = C.lib; 9093 var WordArray = C_lib.WordArray; 9094 var Hasher = C_lib.Hasher; 9095 var C_algo = C.algo; 9096 9097 // Constants table 9098 var T = []; 9099 9100 // Compute constants 9101 (function () { 9102 for (var i = 0; i < 64; i++) { 9103 T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; 9104 } 9105 }()); 9106 9107 /** 9108 * MD5 hash algorithm. 9109 */ 9110 var MD5 = C_algo.MD5 = Hasher.extend({ 9111 _doReset: function () { 9112 this._hash = new WordArray.init([ 9113 0x67452301, 0xefcdab89, 9114 0x98badcfe, 0x10325476 9115 ]); 9116 }, 9117 9118 _doProcessBlock: function (M, offset) { 9119 // Swap endian 9120 for (var i = 0; i < 16; i++) { 9121 // Shortcuts 9122 var offset_i = offset + i; 9123 var M_offset_i = M[offset_i]; 9124 9125 M[offset_i] = ( 9126 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | 9127 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) 9128 ); 9129 } 9130 9131 // Shortcuts 9132 var H = this._hash.words; 9133 9134 var M_offset_0 = M[offset + 0]; 9135 var M_offset_1 = M[offset + 1]; 9136 var M_offset_2 = M[offset + 2]; 9137 var M_offset_3 = M[offset + 3]; 9138 var M_offset_4 = M[offset + 4]; 9139 var M_offset_5 = M[offset + 5]; 9140 var M_offset_6 = M[offset + 6]; 9141 var M_offset_7 = M[offset + 7]; 9142 var M_offset_8 = M[offset + 8]; 9143 var M_offset_9 = M[offset + 9]; 9144 var M_offset_10 = M[offset + 10]; 9145 var M_offset_11 = M[offset + 11]; 9146 var M_offset_12 = M[offset + 12]; 9147 var M_offset_13 = M[offset + 13]; 9148 var M_offset_14 = M[offset + 14]; 9149 var M_offset_15 = M[offset + 15]; 9150 9151 // Working varialbes 9152 var a = H[0]; 9153 var b = H[1]; 9154 var c = H[2]; 9155 var d = H[3]; 9156 9157 // Computation 9158 a = FF(a, b, c, d, M_offset_0, 7, T[0]); 9159 d = FF(d, a, b, c, M_offset_1, 12, T[1]); 9160 c = FF(c, d, a, b, M_offset_2, 17, T[2]); 9161 b = FF(b, c, d, a, M_offset_3, 22, T[3]); 9162 a = FF(a, b, c, d, M_offset_4, 7, T[4]); 9163 d = FF(d, a, b, c, M_offset_5, 12, T[5]); 9164 c = FF(c, d, a, b, M_offset_6, 17, T[6]); 9165 b = FF(b, c, d, a, M_offset_7, 22, T[7]); 9166 a = FF(a, b, c, d, M_offset_8, 7, T[8]); 9167 d = FF(d, a, b, c, M_offset_9, 12, T[9]); 9168 c = FF(c, d, a, b, M_offset_10, 17, T[10]); 9169 b = FF(b, c, d, a, M_offset_11, 22, T[11]); 9170 a = FF(a, b, c, d, M_offset_12, 7, T[12]); 9171 d = FF(d, a, b, c, M_offset_13, 12, T[13]); 9172 c = FF(c, d, a, b, M_offset_14, 17, T[14]); 9173 b = FF(b, c, d, a, M_offset_15, 22, T[15]); 9174 9175 a = GG(a, b, c, d, M_offset_1, 5, T[16]); 9176 d = GG(d, a, b, c, M_offset_6, 9, T[17]); 9177 c = GG(c, d, a, b, M_offset_11, 14, T[18]); 9178 b = GG(b, c, d, a, M_offset_0, 20, T[19]); 9179 a = GG(a, b, c, d, M_offset_5, 5, T[20]); 9180 d = GG(d, a, b, c, M_offset_10, 9, T[21]); 9181 c = GG(c, d, a, b, M_offset_15, 14, T[22]); 9182 b = GG(b, c, d, a, M_offset_4, 20, T[23]); 9183 a = GG(a, b, c, d, M_offset_9, 5, T[24]); 9184 d = GG(d, a, b, c, M_offset_14, 9, T[25]); 9185 c = GG(c, d, a, b, M_offset_3, 14, T[26]); 9186 b = GG(b, c, d, a, M_offset_8, 20, T[27]); 9187 a = GG(a, b, c, d, M_offset_13, 5, T[28]); 9188 d = GG(d, a, b, c, M_offset_2, 9, T[29]); 9189 c = GG(c, d, a, b, M_offset_7, 14, T[30]); 9190 b = GG(b, c, d, a, M_offset_12, 20, T[31]); 9191 9192 a = HH(a, b, c, d, M_offset_5, 4, T[32]); 9193 d = HH(d, a, b, c, M_offset_8, 11, T[33]); 9194 c = HH(c, d, a, b, M_offset_11, 16, T[34]); 9195 b = HH(b, c, d, a, M_offset_14, 23, T[35]); 9196 a = HH(a, b, c, d, M_offset_1, 4, T[36]); 9197 d = HH(d, a, b, c, M_offset_4, 11, T[37]); 9198 c = HH(c, d, a, b, M_offset_7, 16, T[38]); 9199 b = HH(b, c, d, a, M_offset_10, 23, T[39]); 9200 a = HH(a, b, c, d, M_offset_13, 4, T[40]); 9201 d = HH(d, a, b, c, M_offset_0, 11, T[41]); 9202 c = HH(c, d, a, b, M_offset_3, 16, T[42]); 9203 b = HH(b, c, d, a, M_offset_6, 23, T[43]); 9204 a = HH(a, b, c, d, M_offset_9, 4, T[44]); 9205 d = HH(d, a, b, c, M_offset_12, 11, T[45]); 9206 c = HH(c, d, a, b, M_offset_15, 16, T[46]); 9207 b = HH(b, c, d, a, M_offset_2, 23, T[47]); 9208 9209 a = II(a, b, c, d, M_offset_0, 6, T[48]); 9210 d = II(d, a, b, c, M_offset_7, 10, T[49]); 9211 c = II(c, d, a, b, M_offset_14, 15, T[50]); 9212 b = II(b, c, d, a, M_offset_5, 21, T[51]); 9213 a = II(a, b, c, d, M_offset_12, 6, T[52]); 9214 d = II(d, a, b, c, M_offset_3, 10, T[53]); 9215 c = II(c, d, a, b, M_offset_10, 15, T[54]); 9216 b = II(b, c, d, a, M_offset_1, 21, T[55]); 9217 a = II(a, b, c, d, M_offset_8, 6, T[56]); 9218 d = II(d, a, b, c, M_offset_15, 10, T[57]); 9219 c = II(c, d, a, b, M_offset_6, 15, T[58]); 9220 b = II(b, c, d, a, M_offset_13, 21, T[59]); 9221 a = II(a, b, c, d, M_offset_4, 6, T[60]); 9222 d = II(d, a, b, c, M_offset_11, 10, T[61]); 9223 c = II(c, d, a, b, M_offset_2, 15, T[62]); 9224 b = II(b, c, d, a, M_offset_9, 21, T[63]); 9225 9226 // Intermediate hash value 9227 H[0] = (H[0] + a) | 0; 9228 H[1] = (H[1] + b) | 0; 9229 H[2] = (H[2] + c) | 0; 9230 H[3] = (H[3] + d) | 0; 9231 }, 9232 9233 _doFinalize: function () { 9234 // Shortcuts 9235 var data = this._data; 9236 var dataWords = data.words; 9237 9238 var nBitsTotal = this._nDataBytes * 8; 9239 var nBitsLeft = data.sigBytes * 8; 9240 9241 // Add padding 9242 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 9243 9244 var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); 9245 var nBitsTotalL = nBitsTotal; 9246 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( 9247 (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | 9248 (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) 9249 ); 9250 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( 9251 (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | 9252 (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) 9253 ); 9254 9255 data.sigBytes = (dataWords.length + 1) * 4; 9256 9257 // Hash final blocks 9258 this._process(); 9259 9260 // Shortcuts 9261 var hash = this._hash; 9262 var H = hash.words; 9263 9264 // Swap endian 9265 for (var i = 0; i < 4; i++) { 9266 // Shortcut 9267 var H_i = H[i]; 9268 9269 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | 9270 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); 9271 } 9272 9273 // Return final computed hash 9274 return hash; 9275 }, 9276 9277 clone: function () { 9278 var clone = Hasher.clone.call(this); 9279 clone._hash = this._hash.clone(); 9280 9281 return clone; 9282 } 9283 }); 9284 9285 function FF(a, b, c, d, x, s, t) { 9286 var n = a + ((b & c) | (~b & d)) + x + t; 9287 return ((n << s) | (n >>> (32 - s))) + b; 9288 } 9289 9290 function GG(a, b, c, d, x, s, t) { 9291 var n = a + ((b & d) | (c & ~d)) + x + t; 9292 return ((n << s) | (n >>> (32 - s))) + b; 9293 } 9294 9295 function HH(a, b, c, d, x, s, t) { 9296 var n = a + (b ^ c ^ d) + x + t; 9297 return ((n << s) | (n >>> (32 - s))) + b; 9298 } 9299 9300 function II(a, b, c, d, x, s, t) { 9301 var n = a + (c ^ (b | ~d)) + x + t; 9302 return ((n << s) | (n >>> (32 - s))) + b; 9303 } 9304 9305 /** 9306 * Shortcut function to the hasher's object interface. 9307 * 9308 * @param {WordArray|string} message The message to hash. 9309 * 9310 * @return {WordArray} The hash. 9311 * 9312 * @static 9313 * 9314 * @example 9315 * 9316 * var hash = CryptoJS.MD5('message'); 9317 * var hash = CryptoJS.MD5(wordArray); 9318 */ 9319 C.MD5 = Hasher._createHelper(MD5); 9320 9321 /** 9322 * Shortcut function to the HMAC's object interface. 9323 * 9324 * @param {WordArray|string} message The message to hash. 9325 * @param {WordArray|string} key The secret key. 9326 * 9327 * @return {WordArray} The HMAC. 9328 * 9329 * @static 9330 * 9331 * @example 9332 * 9333 * var hmac = CryptoJS.HmacMD5(message, key); 9334 */ 9335 C.HmacMD5 = Hasher._createHmacHelper(MD5); 9336 }(Math)); 9337 9338 9339 return CryptoJS.MD5; 9340 9341 })); 9342 },{"./core":52}],61:[function(require,module,exports){ 9343 ;(function (root, factory, undef) { 9344 if (typeof exports === "object") { 9345 // CommonJS 9346 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9347 } 9348 else if (typeof define === "function" && define.amd) { 9349 // AMD 9350 define(["./core", "./cipher-core"], factory); 9351 } 9352 else { 9353 // Global (browser) 9354 factory(root.CryptoJS); 9355 } 9356 }(this, function (CryptoJS) { 9357 9358 /** 9359 * Cipher Feedback block mode. 9360 */ 9361 CryptoJS.mode.CFB = (function () { 9362 var CFB = CryptoJS.lib.BlockCipherMode.extend(); 9363 9364 CFB.Encryptor = CFB.extend({ 9365 processBlock: function (words, offset) { 9366 // Shortcuts 9367 var cipher = this._cipher; 9368 var blockSize = cipher.blockSize; 9369 9370 generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); 9371 9372 // Remember this block to use with next block 9373 this._prevBlock = words.slice(offset, offset + blockSize); 9374 } 9375 }); 9376 9377 CFB.Decryptor = CFB.extend({ 9378 processBlock: function (words, offset) { 9379 // Shortcuts 9380 var cipher = this._cipher; 9381 var blockSize = cipher.blockSize; 9382 9383 // Remember this block to use with next block 9384 var thisBlock = words.slice(offset, offset + blockSize); 9385 9386 generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); 9387 9388 // This block becomes the previous block 9389 this._prevBlock = thisBlock; 9390 } 9391 }); 9392 9393 function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { 9394 // Shortcut 9395 var iv = this._iv; 9396 9397 // Generate keystream 9398 if (iv) { 9399 var keystream = iv.slice(0); 9400 9401 // Remove IV for subsequent blocks 9402 this._iv = undefined; 9403 } else { 9404 var keystream = this._prevBlock; 9405 } 9406 cipher.encryptBlock(keystream, 0); 9407 9408 // Encrypt 9409 for (var i = 0; i < blockSize; i++) { 9410 words[offset + i] ^= keystream[i]; 9411 } 9412 } 9413 9414 return CFB; 9415 }()); 9416 9417 9418 return CryptoJS.mode.CFB; 9419 9420 })); 9421 },{"./cipher-core":51,"./core":52}],62:[function(require,module,exports){ 9422 ;(function (root, factory, undef) { 9423 if (typeof exports === "object") { 9424 // CommonJS 9425 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9426 } 9427 else if (typeof define === "function" && define.amd) { 9428 // AMD 9429 define(["./core", "./cipher-core"], factory); 9430 } 9431 else { 9432 // Global (browser) 9433 factory(root.CryptoJS); 9434 } 9435 }(this, function (CryptoJS) { 9436 9437 /** @preserve 9438 * Counter block mode compatible with Dr Brian Gladman fileenc.c 9439 * derived from CryptoJS.mode.CTR 9440 * Jan Hruby jhruby.web@gmail.com 9441 */ 9442 CryptoJS.mode.CTRGladman = (function () { 9443 var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); 9444 9445 function incWord(word) 9446 { 9447 if (((word >> 24) & 0xff) === 0xff) { //overflow 9448 var b1 = (word >> 16)&0xff; 9449 var b2 = (word >> 8)&0xff; 9450 var b3 = word & 0xff; 9451 9452 if (b1 === 0xff) // overflow b1 9453 { 9454 b1 = 0; 9455 if (b2 === 0xff) 9456 { 9457 b2 = 0; 9458 if (b3 === 0xff) 9459 { 9460 b3 = 0; 9461 } 9462 else 9463 { 9464 ++b3; 9465 } 9466 } 9467 else 9468 { 9469 ++b2; 9470 } 9471 } 9472 else 9473 { 9474 ++b1; 9475 } 9476 9477 word = 0; 9478 word += (b1 << 16); 9479 word += (b2 << 8); 9480 word += b3; 9481 } 9482 else 9483 { 9484 word += (0x01 << 24); 9485 } 9486 return word; 9487 } 9488 9489 function incCounter(counter) 9490 { 9491 if ((counter[0] = incWord(counter[0])) === 0) 9492 { 9493 // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 9494 counter[1] = incWord(counter[1]); 9495 } 9496 return counter; 9497 } 9498 9499 var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ 9500 processBlock: function (words, offset) { 9501 // Shortcuts 9502 var cipher = this._cipher 9503 var blockSize = cipher.blockSize; 9504 var iv = this._iv; 9505 var counter = this._counter; 9506 9507 // Generate keystream 9508 if (iv) { 9509 counter = this._counter = iv.slice(0); 9510 9511 // Remove IV for subsequent blocks 9512 this._iv = undefined; 9513 } 9514 9515 incCounter(counter); 9516 9517 var keystream = counter.slice(0); 9518 cipher.encryptBlock(keystream, 0); 9519 9520 // Encrypt 9521 for (var i = 0; i < blockSize; i++) { 9522 words[offset + i] ^= keystream[i]; 9523 } 9524 } 9525 }); 9526 9527 CTRGladman.Decryptor = Encryptor; 9528 9529 return CTRGladman; 9530 }()); 9531 9532 9533 9534 9535 return CryptoJS.mode.CTRGladman; 9536 9537 })); 9538 },{"./cipher-core":51,"./core":52}],63:[function(require,module,exports){ 9539 ;(function (root, factory, undef) { 9540 if (typeof exports === "object") { 9541 // CommonJS 9542 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9543 } 9544 else if (typeof define === "function" && define.amd) { 9545 // AMD 9546 define(["./core", "./cipher-core"], factory); 9547 } 9548 else { 9549 // Global (browser) 9550 factory(root.CryptoJS); 9551 } 9552 }(this, function (CryptoJS) { 9553 9554 /** 9555 * Counter block mode. 9556 */ 9557 CryptoJS.mode.CTR = (function () { 9558 var CTR = CryptoJS.lib.BlockCipherMode.extend(); 9559 9560 var Encryptor = CTR.Encryptor = CTR.extend({ 9561 processBlock: function (words, offset) { 9562 // Shortcuts 9563 var cipher = this._cipher 9564 var blockSize = cipher.blockSize; 9565 var iv = this._iv; 9566 var counter = this._counter; 9567 9568 // Generate keystream 9569 if (iv) { 9570 counter = this._counter = iv.slice(0); 9571 9572 // Remove IV for subsequent blocks 9573 this._iv = undefined; 9574 } 9575 var keystream = counter.slice(0); 9576 cipher.encryptBlock(keystream, 0); 9577 9578 // Increment counter 9579 counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 9580 9581 // Encrypt 9582 for (var i = 0; i < blockSize; i++) { 9583 words[offset + i] ^= keystream[i]; 9584 } 9585 } 9586 }); 9587 9588 CTR.Decryptor = Encryptor; 9589 9590 return CTR; 9591 }()); 9592 9593 9594 return CryptoJS.mode.CTR; 9595 9596 })); 9597 },{"./cipher-core":51,"./core":52}],64:[function(require,module,exports){ 9598 ;(function (root, factory, undef) { 9599 if (typeof exports === "object") { 9600 // CommonJS 9601 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9602 } 9603 else if (typeof define === "function" && define.amd) { 9604 // AMD 9605 define(["./core", "./cipher-core"], factory); 9606 } 9607 else { 9608 // Global (browser) 9609 factory(root.CryptoJS); 9610 } 9611 }(this, function (CryptoJS) { 9612 9613 /** 9614 * Electronic Codebook block mode. 9615 */ 9616 CryptoJS.mode.ECB = (function () { 9617 var ECB = CryptoJS.lib.BlockCipherMode.extend(); 9618 9619 ECB.Encryptor = ECB.extend({ 9620 processBlock: function (words, offset) { 9621 this._cipher.encryptBlock(words, offset); 9622 } 9623 }); 9624 9625 ECB.Decryptor = ECB.extend({ 9626 processBlock: function (words, offset) { 9627 this._cipher.decryptBlock(words, offset); 9628 } 9629 }); 9630 9631 return ECB; 9632 }()); 9633 9634 9635 return CryptoJS.mode.ECB; 9636 9637 })); 9638 },{"./cipher-core":51,"./core":52}],65:[function(require,module,exports){ 9639 ;(function (root, factory, undef) { 9640 if (typeof exports === "object") { 9641 // CommonJS 9642 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9643 } 9644 else if (typeof define === "function" && define.amd) { 9645 // AMD 9646 define(["./core", "./cipher-core"], factory); 9647 } 9648 else { 9649 // Global (browser) 9650 factory(root.CryptoJS); 9651 } 9652 }(this, function (CryptoJS) { 9653 9654 /** 9655 * Output Feedback block mode. 9656 */ 9657 CryptoJS.mode.OFB = (function () { 9658 var OFB = CryptoJS.lib.BlockCipherMode.extend(); 9659 9660 var Encryptor = OFB.Encryptor = OFB.extend({ 9661 processBlock: function (words, offset) { 9662 // Shortcuts 9663 var cipher = this._cipher 9664 var blockSize = cipher.blockSize; 9665 var iv = this._iv; 9666 var keystream = this._keystream; 9667 9668 // Generate keystream 9669 if (iv) { 9670 keystream = this._keystream = iv.slice(0); 9671 9672 // Remove IV for subsequent blocks 9673 this._iv = undefined; 9674 } 9675 cipher.encryptBlock(keystream, 0); 9676 9677 // Encrypt 9678 for (var i = 0; i < blockSize; i++) { 9679 words[offset + i] ^= keystream[i]; 9680 } 9681 } 9682 }); 9683 9684 OFB.Decryptor = Encryptor; 9685 9686 return OFB; 9687 }()); 9688 9689 9690 return CryptoJS.mode.OFB; 9691 9692 })); 9693 },{"./cipher-core":51,"./core":52}],66:[function(require,module,exports){ 9694 ;(function (root, factory, undef) { 9695 if (typeof exports === "object") { 9696 // CommonJS 9697 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9698 } 9699 else if (typeof define === "function" && define.amd) { 9700 // AMD 9701 define(["./core", "./cipher-core"], factory); 9702 } 9703 else { 9704 // Global (browser) 9705 factory(root.CryptoJS); 9706 } 9707 }(this, function (CryptoJS) { 9708 9709 /** 9710 * ANSI X.923 padding strategy. 9711 */ 9712 CryptoJS.pad.AnsiX923 = { 9713 pad: function (data, blockSize) { 9714 // Shortcuts 9715 var dataSigBytes = data.sigBytes; 9716 var blockSizeBytes = blockSize * 4; 9717 9718 // Count padding bytes 9719 var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; 9720 9721 // Compute last byte position 9722 var lastBytePos = dataSigBytes + nPaddingBytes - 1; 9723 9724 // Pad 9725 data.clamp(); 9726 data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); 9727 data.sigBytes += nPaddingBytes; 9728 }, 9729 9730 unpad: function (data) { 9731 // Get number of padding bytes from last byte 9732 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 9733 9734 // Remove padding 9735 data.sigBytes -= nPaddingBytes; 9736 } 9737 }; 9738 9739 9740 return CryptoJS.pad.Ansix923; 9741 9742 })); 9743 },{"./cipher-core":51,"./core":52}],67:[function(require,module,exports){ 9744 ;(function (root, factory, undef) { 9745 if (typeof exports === "object") { 9746 // CommonJS 9747 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9748 } 9749 else if (typeof define === "function" && define.amd) { 9750 // AMD 9751 define(["./core", "./cipher-core"], factory); 9752 } 9753 else { 9754 // Global (browser) 9755 factory(root.CryptoJS); 9756 } 9757 }(this, function (CryptoJS) { 9758 9759 /** 9760 * ISO 10126 padding strategy. 9761 */ 9762 CryptoJS.pad.Iso10126 = { 9763 pad: function (data, blockSize) { 9764 // Shortcut 9765 var blockSizeBytes = blockSize * 4; 9766 9767 // Count padding bytes 9768 var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; 9769 9770 // Pad 9771 data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). 9772 concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); 9773 }, 9774 9775 unpad: function (data) { 9776 // Get number of padding bytes from last byte 9777 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 9778 9779 // Remove padding 9780 data.sigBytes -= nPaddingBytes; 9781 } 9782 }; 9783 9784 9785 return CryptoJS.pad.Iso10126; 9786 9787 })); 9788 },{"./cipher-core":51,"./core":52}],68:[function(require,module,exports){ 9789 ;(function (root, factory, undef) { 9790 if (typeof exports === "object") { 9791 // CommonJS 9792 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9793 } 9794 else if (typeof define === "function" && define.amd) { 9795 // AMD 9796 define(["./core", "./cipher-core"], factory); 9797 } 9798 else { 9799 // Global (browser) 9800 factory(root.CryptoJS); 9801 } 9802 }(this, function (CryptoJS) { 9803 9804 /** 9805 * ISO/IEC 9797-1 Padding Method 2. 9806 */ 9807 CryptoJS.pad.Iso97971 = { 9808 pad: function (data, blockSize) { 9809 // Add 0x80 byte 9810 data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); 9811 9812 // Zero pad the rest 9813 CryptoJS.pad.ZeroPadding.pad(data, blockSize); 9814 }, 9815 9816 unpad: function (data) { 9817 // Remove zero padding 9818 CryptoJS.pad.ZeroPadding.unpad(data); 9819 9820 // Remove one more byte -- the 0x80 byte 9821 data.sigBytes--; 9822 } 9823 }; 9824 9825 9826 return CryptoJS.pad.Iso97971; 9827 9828 })); 9829 },{"./cipher-core":51,"./core":52}],69:[function(require,module,exports){ 9830 ;(function (root, factory, undef) { 9831 if (typeof exports === "object") { 9832 // CommonJS 9833 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9834 } 9835 else if (typeof define === "function" && define.amd) { 9836 // AMD 9837 define(["./core", "./cipher-core"], factory); 9838 } 9839 else { 9840 // Global (browser) 9841 factory(root.CryptoJS); 9842 } 9843 }(this, function (CryptoJS) { 9844 9845 /** 9846 * A noop padding strategy. 9847 */ 9848 CryptoJS.pad.NoPadding = { 9849 pad: function () { 9850 }, 9851 9852 unpad: function () { 9853 } 9854 }; 9855 9856 9857 return CryptoJS.pad.NoPadding; 9858 9859 })); 9860 },{"./cipher-core":51,"./core":52}],70:[function(require,module,exports){ 9861 ;(function (root, factory, undef) { 9862 if (typeof exports === "object") { 9863 // CommonJS 9864 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9865 } 9866 else if (typeof define === "function" && define.amd) { 9867 // AMD 9868 define(["./core", "./cipher-core"], factory); 9869 } 9870 else { 9871 // Global (browser) 9872 factory(root.CryptoJS); 9873 } 9874 }(this, function (CryptoJS) { 9875 9876 /** 9877 * Zero padding strategy. 9878 */ 9879 CryptoJS.pad.ZeroPadding = { 9880 pad: function (data, blockSize) { 9881 // Shortcut 9882 var blockSizeBytes = blockSize * 4; 9883 9884 // Pad 9885 data.clamp(); 9886 data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); 9887 }, 9888 9889 unpad: function (data) { 9890 // Shortcut 9891 var dataWords = data.words; 9892 9893 // Unpad 9894 var i = data.sigBytes - 1; 9895 while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { 9896 i--; 9897 } 9898 data.sigBytes = i + 1; 9899 } 9900 }; 9901 9902 9903 return CryptoJS.pad.ZeroPadding; 9904 9905 })); 9906 },{"./cipher-core":51,"./core":52}],71:[function(require,module,exports){ 9907 ;(function (root, factory, undef) { 9908 if (typeof exports === "object") { 9909 // CommonJS 9910 module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); 9911 } 9912 else if (typeof define === "function" && define.amd) { 9913 // AMD 9914 define(["./core", "./sha1", "./hmac"], factory); 9915 } 9916 else { 9917 // Global (browser) 9918 factory(root.CryptoJS); 9919 } 9920 }(this, function (CryptoJS) { 9921 9922 (function () { 9923 // Shortcuts 9924 var C = CryptoJS; 9925 var C_lib = C.lib; 9926 var Base = C_lib.Base; 9927 var WordArray = C_lib.WordArray; 9928 var C_algo = C.algo; 9929 var SHA1 = C_algo.SHA1; 9930 var HMAC = C_algo.HMAC; 9931 9932 /** 9933 * Password-Based Key Derivation Function 2 algorithm. 9934 */ 9935 var PBKDF2 = C_algo.PBKDF2 = Base.extend({ 9936 /** 9937 * Configuration options. 9938 * 9939 * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) 9940 * @property {Hasher} hasher The hasher to use. Default: SHA1 9941 * @property {number} iterations The number of iterations to perform. Default: 1 9942 */ 9943 cfg: Base.extend({ 9944 keySize: 128/32, 9945 hasher: SHA1, 9946 iterations: 1 9947 }), 9948 9949 /** 9950 * Initializes a newly created key derivation function. 9951 * 9952 * @param {Object} cfg (Optional) The configuration options to use for the derivation. 9953 * 9954 * @example 9955 * 9956 * var kdf = CryptoJS.algo.PBKDF2.create(); 9957 * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); 9958 * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); 9959 */ 9960 init: function (cfg) { 9961 this.cfg = this.cfg.extend(cfg); 9962 }, 9963 9964 /** 9965 * Computes the Password-Based Key Derivation Function 2. 9966 * 9967 * @param {WordArray|string} password The password. 9968 * @param {WordArray|string} salt A salt. 9969 * 9970 * @return {WordArray} The derived key. 9971 * 9972 * @example 9973 * 9974 * var key = kdf.compute(password, salt); 9975 */ 9976 compute: function (password, salt) { 9977 // Shortcut 9978 var cfg = this.cfg; 9979 9980 // Init HMAC 9981 var hmac = HMAC.create(cfg.hasher, password); 9982 9983 // Initial values 9984 var derivedKey = WordArray.create(); 9985 var blockIndex = WordArray.create([0x00000001]); 9986 9987 // Shortcuts 9988 var derivedKeyWords = derivedKey.words; 9989 var blockIndexWords = blockIndex.words; 9990 var keySize = cfg.keySize; 9991 var iterations = cfg.iterations; 9992 9993 // Generate key 9994 while (derivedKeyWords.length < keySize) { 9995 var block = hmac.update(salt).finalize(blockIndex); 9996 hmac.reset(); 9997 9998 // Shortcuts 9999 var blockWords = block.words; 10000 var blockWordsLength = blockWords.length; 10001 10002 // Iterations 10003 var intermediate = block; 10004 for (var i = 1; i < iterations; i++) { 10005 intermediate = hmac.finalize(intermediate); 10006 hmac.reset(); 10007 10008 // Shortcut 10009 var intermediateWords = intermediate.words; 10010 10011 // XOR intermediate with block 10012 for (var j = 0; j < blockWordsLength; j++) { 10013 blockWords[j] ^= intermediateWords[j]; 10014 } 10015 } 10016 10017 derivedKey.concat(block); 10018 blockIndexWords[0]++; 10019 } 10020 derivedKey.sigBytes = keySize * 4; 10021 10022 return derivedKey; 10023 } 10024 }); 10025 10026 /** 10027 * Computes the Password-Based Key Derivation Function 2. 10028 * 10029 * @param {WordArray|string} password The password. 10030 * @param {WordArray|string} salt A salt. 10031 * @param {Object} cfg (Optional) The configuration options to use for this computation. 10032 * 10033 * @return {WordArray} The derived key. 10034 * 10035 * @static 10036 * 10037 * @example 10038 * 10039 * var key = CryptoJS.PBKDF2(password, salt); 10040 * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); 10041 * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); 10042 */ 10043 C.PBKDF2 = function (password, salt, cfg) { 10044 return PBKDF2.create(cfg).compute(password, salt); 10045 }; 10046 }()); 10047 10048 10049 return CryptoJS.PBKDF2; 10050 10051 })); 10052 },{"./core":52,"./hmac":57,"./sha1":76}],72:[function(require,module,exports){ 10053 ;(function (root, factory, undef) { 10054 if (typeof exports === "object") { 10055 // CommonJS 10056 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10057 } 10058 else if (typeof define === "function" && define.amd) { 10059 // AMD 10060 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10061 } 10062 else { 10063 // Global (browser) 10064 factory(root.CryptoJS); 10065 } 10066 }(this, function (CryptoJS) { 10067 10068 (function () { 10069 // Shortcuts 10070 var C = CryptoJS; 10071 var C_lib = C.lib; 10072 var StreamCipher = C_lib.StreamCipher; 10073 var C_algo = C.algo; 10074 10075 // Reusable objects 10076 var S = []; 10077 var C_ = []; 10078 var G = []; 10079 10080 /** 10081 * Rabbit stream cipher algorithm. 10082 * 10083 * This is a legacy version that neglected to convert the key to little-endian. 10084 * This error doesn't affect the cipher's security, 10085 * but it does affect its compatibility with other implementations. 10086 */ 10087 var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ 10088 _doReset: function () { 10089 // Shortcuts 10090 var K = this._key.words; 10091 var iv = this.cfg.iv; 10092 10093 // Generate initial state values 10094 var X = this._X = [ 10095 K[0], (K[3] << 16) | (K[2] >>> 16), 10096 K[1], (K[0] << 16) | (K[3] >>> 16), 10097 K[2], (K[1] << 16) | (K[0] >>> 16), 10098 K[3], (K[2] << 16) | (K[1] >>> 16) 10099 ]; 10100 10101 // Generate initial counter values 10102 var C = this._C = [ 10103 (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), 10104 (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), 10105 (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), 10106 (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) 10107 ]; 10108 10109 // Carry bit 10110 this._b = 0; 10111 10112 // Iterate the system four times 10113 for (var i = 0; i < 4; i++) { 10114 nextState.call(this); 10115 } 10116 10117 // Modify the counters 10118 for (var i = 0; i < 8; i++) { 10119 C[i] ^= X[(i + 4) & 7]; 10120 } 10121 10122 // IV setup 10123 if (iv) { 10124 // Shortcuts 10125 var IV = iv.words; 10126 var IV_0 = IV[0]; 10127 var IV_1 = IV[1]; 10128 10129 // Generate four subvectors 10130 var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); 10131 var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); 10132 var i1 = (i0 >>> 16) | (i2 & 0xffff0000); 10133 var i3 = (i2 << 16) | (i0 & 0x0000ffff); 10134 10135 // Modify counter values 10136 C[0] ^= i0; 10137 C[1] ^= i1; 10138 C[2] ^= i2; 10139 C[3] ^= i3; 10140 C[4] ^= i0; 10141 C[5] ^= i1; 10142 C[6] ^= i2; 10143 C[7] ^= i3; 10144 10145 // Iterate the system four times 10146 for (var i = 0; i < 4; i++) { 10147 nextState.call(this); 10148 } 10149 } 10150 }, 10151 10152 _doProcessBlock: function (M, offset) { 10153 // Shortcut 10154 var X = this._X; 10155 10156 // Iterate the system 10157 nextState.call(this); 10158 10159 // Generate four keystream words 10160 S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); 10161 S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); 10162 S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); 10163 S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); 10164 10165 for (var i = 0; i < 4; i++) { 10166 // Swap endian 10167 S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | 10168 (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); 10169 10170 // Encrypt 10171 M[offset + i] ^= S[i]; 10172 } 10173 }, 10174 10175 blockSize: 128/32, 10176 10177 ivSize: 64/32 10178 }); 10179 10180 function nextState() { 10181 // Shortcuts 10182 var X = this._X; 10183 var C = this._C; 10184 10185 // Save old counter values 10186 for (var i = 0; i < 8; i++) { 10187 C_[i] = C[i]; 10188 } 10189 10190 // Calculate new counter values 10191 C[0] = (C[0] + 0x4d34d34d + this._b) | 0; 10192 C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; 10193 C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; 10194 C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; 10195 C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; 10196 C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; 10197 C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; 10198 C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; 10199 this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; 10200 10201 // Calculate the g-values 10202 for (var i = 0; i < 8; i++) { 10203 var gx = X[i] + C[i]; 10204 10205 // Construct high and low argument for squaring 10206 var ga = gx & 0xffff; 10207 var gb = gx >>> 16; 10208 10209 // Calculate high and low result of squaring 10210 var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; 10211 var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); 10212 10213 // High XOR low 10214 G[i] = gh ^ gl; 10215 } 10216 10217 // Calculate new state values 10218 X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; 10219 X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; 10220 X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; 10221 X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; 10222 X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; 10223 X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; 10224 X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; 10225 X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; 10226 } 10227 10228 /** 10229 * Shortcut functions to the cipher's object interface. 10230 * 10231 * @example 10232 * 10233 * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); 10234 * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); 10235 */ 10236 C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); 10237 }()); 10238 10239 10240 return CryptoJS.RabbitLegacy; 10241 10242 })); 10243 },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],73:[function(require,module,exports){ 10244 ;(function (root, factory, undef) { 10245 if (typeof exports === "object") { 10246 // CommonJS 10247 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10248 } 10249 else if (typeof define === "function" && define.amd) { 10250 // AMD 10251 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10252 } 10253 else { 10254 // Global (browser) 10255 factory(root.CryptoJS); 10256 } 10257 }(this, function (CryptoJS) { 10258 10259 (function () { 10260 // Shortcuts 10261 var C = CryptoJS; 10262 var C_lib = C.lib; 10263 var StreamCipher = C_lib.StreamCipher; 10264 var C_algo = C.algo; 10265 10266 // Reusable objects 10267 var S = []; 10268 var C_ = []; 10269 var G = []; 10270 10271 /** 10272 * Rabbit stream cipher algorithm 10273 */ 10274 var Rabbit = C_algo.Rabbit = StreamCipher.extend({ 10275 _doReset: function () { 10276 // Shortcuts 10277 var K = this._key.words; 10278 var iv = this.cfg.iv; 10279 10280 // Swap endian 10281 for (var i = 0; i < 4; i++) { 10282 K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | 10283 (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); 10284 } 10285 10286 // Generate initial state values 10287 var X = this._X = [ 10288 K[0], (K[3] << 16) | (K[2] >>> 16), 10289 K[1], (K[0] << 16) | (K[3] >>> 16), 10290 K[2], (K[1] << 16) | (K[0] >>> 16), 10291 K[3], (K[2] << 16) | (K[1] >>> 16) 10292 ]; 10293 10294 // Generate initial counter values 10295 var C = this._C = [ 10296 (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), 10297 (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), 10298 (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), 10299 (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) 10300 ]; 10301 10302 // Carry bit 10303 this._b = 0; 10304 10305 // Iterate the system four times 10306 for (var i = 0; i < 4; i++) { 10307 nextState.call(this); 10308 } 10309 10310 // Modify the counters 10311 for (var i = 0; i < 8; i++) { 10312 C[i] ^= X[(i + 4) & 7]; 10313 } 10314 10315 // IV setup 10316 if (iv) { 10317 // Shortcuts 10318 var IV = iv.words; 10319 var IV_0 = IV[0]; 10320 var IV_1 = IV[1]; 10321 10322 // Generate four subvectors 10323 var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); 10324 var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); 10325 var i1 = (i0 >>> 16) | (i2 & 0xffff0000); 10326 var i3 = (i2 << 16) | (i0 & 0x0000ffff); 10327 10328 // Modify counter values 10329 C[0] ^= i0; 10330 C[1] ^= i1; 10331 C[2] ^= i2; 10332 C[3] ^= i3; 10333 C[4] ^= i0; 10334 C[5] ^= i1; 10335 C[6] ^= i2; 10336 C[7] ^= i3; 10337 10338 // Iterate the system four times 10339 for (var i = 0; i < 4; i++) { 10340 nextState.call(this); 10341 } 10342 } 10343 }, 10344 10345 _doProcessBlock: function (M, offset) { 10346 // Shortcut 10347 var X = this._X; 10348 10349 // Iterate the system 10350 nextState.call(this); 10351 10352 // Generate four keystream words 10353 S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); 10354 S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); 10355 S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); 10356 S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); 10357 10358 for (var i = 0; i < 4; i++) { 10359 // Swap endian 10360 S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | 10361 (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); 10362 10363 // Encrypt 10364 M[offset + i] ^= S[i]; 10365 } 10366 }, 10367 10368 blockSize: 128/32, 10369 10370 ivSize: 64/32 10371 }); 10372 10373 function nextState() { 10374 // Shortcuts 10375 var X = this._X; 10376 var C = this._C; 10377 10378 // Save old counter values 10379 for (var i = 0; i < 8; i++) { 10380 C_[i] = C[i]; 10381 } 10382 10383 // Calculate new counter values 10384 C[0] = (C[0] + 0x4d34d34d + this._b) | 0; 10385 C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; 10386 C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; 10387 C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; 10388 C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; 10389 C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; 10390 C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; 10391 C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; 10392 this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; 10393 10394 // Calculate the g-values 10395 for (var i = 0; i < 8; i++) { 10396 var gx = X[i] + C[i]; 10397 10398 // Construct high and low argument for squaring 10399 var ga = gx & 0xffff; 10400 var gb = gx >>> 16; 10401 10402 // Calculate high and low result of squaring 10403 var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; 10404 var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); 10405 10406 // High XOR low 10407 G[i] = gh ^ gl; 10408 } 10409 10410 // Calculate new state values 10411 X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; 10412 X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; 10413 X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; 10414 X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; 10415 X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; 10416 X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; 10417 X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; 10418 X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; 10419 } 10420 10421 /** 10422 * Shortcut functions to the cipher's object interface. 10423 * 10424 * @example 10425 * 10426 * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); 10427 * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); 10428 */ 10429 C.Rabbit = StreamCipher._createHelper(Rabbit); 10430 }()); 10431 10432 10433 return CryptoJS.Rabbit; 10434 10435 })); 10436 },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],74:[function(require,module,exports){ 10437 ;(function (root, factory, undef) { 10438 if (typeof exports === "object") { 10439 // CommonJS 10440 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10441 } 10442 else if (typeof define === "function" && define.amd) { 10443 // AMD 10444 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10445 } 10446 else { 10447 // Global (browser) 10448 factory(root.CryptoJS); 10449 } 10450 }(this, function (CryptoJS) { 10451 10452 (function () { 10453 // Shortcuts 10454 var C = CryptoJS; 10455 var C_lib = C.lib; 10456 var StreamCipher = C_lib.StreamCipher; 10457 var C_algo = C.algo; 10458 10459 /** 10460 * RC4 stream cipher algorithm. 10461 */ 10462 var RC4 = C_algo.RC4 = StreamCipher.extend({ 10463 _doReset: function () { 10464 // Shortcuts 10465 var key = this._key; 10466 var keyWords = key.words; 10467 var keySigBytes = key.sigBytes; 10468 10469 // Init sbox 10470 var S = this._S = []; 10471 for (var i = 0; i < 256; i++) { 10472 S[i] = i; 10473 } 10474 10475 // Key setup 10476 for (var i = 0, j = 0; i < 256; i++) { 10477 var keyByteIndex = i % keySigBytes; 10478 var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; 10479 10480 j = (j + S[i] + keyByte) % 256; 10481 10482 // Swap 10483 var t = S[i]; 10484 S[i] = S[j]; 10485 S[j] = t; 10486 } 10487 10488 // Counters 10489 this._i = this._j = 0; 10490 }, 10491 10492 _doProcessBlock: function (M, offset) { 10493 M[offset] ^= generateKeystreamWord.call(this); 10494 }, 10495 10496 keySize: 256/32, 10497 10498 ivSize: 0 10499 }); 10500 10501 function generateKeystreamWord() { 10502 // Shortcuts 10503 var S = this._S; 10504 var i = this._i; 10505 var j = this._j; 10506 10507 // Generate keystream word 10508 var keystreamWord = 0; 10509 for (var n = 0; n < 4; n++) { 10510 i = (i + 1) % 256; 10511 j = (j + S[i]) % 256; 10512 10513 // Swap 10514 var t = S[i]; 10515 S[i] = S[j]; 10516 S[j] = t; 10517 10518 keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); 10519 } 10520 10521 // Update counters 10522 this._i = i; 10523 this._j = j; 10524 10525 return keystreamWord; 10526 } 10527 10528 /** 10529 * Shortcut functions to the cipher's object interface. 10530 * 10531 * @example 10532 * 10533 * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); 10534 * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); 10535 */ 10536 C.RC4 = StreamCipher._createHelper(RC4); 10537 10538 /** 10539 * Modified RC4 stream cipher algorithm. 10540 */ 10541 var RC4Drop = C_algo.RC4Drop = RC4.extend({ 10542 /** 10543 * Configuration options. 10544 * 10545 * @property {number} drop The number of keystream words to drop. Default 192 10546 */ 10547 cfg: RC4.cfg.extend({ 10548 drop: 192 10549 }), 10550 10551 _doReset: function () { 10552 RC4._doReset.call(this); 10553 10554 // Drop 10555 for (var i = this.cfg.drop; i > 0; i--) { 10556 generateKeystreamWord.call(this); 10557 } 10558 } 10559 }); 10560 10561 /** 10562 * Shortcut functions to the cipher's object interface. 10563 * 10564 * @example 10565 * 10566 * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); 10567 * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); 10568 */ 10569 C.RC4Drop = StreamCipher._createHelper(RC4Drop); 10570 }()); 10571 10572 10573 return CryptoJS.RC4; 10574 10575 })); 10576 },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],75:[function(require,module,exports){ 10577 ;(function (root, factory) { 10578 if (typeof exports === "object") { 10579 // CommonJS 10580 module.exports = exports = factory(require("./core")); 10581 } 10582 else if (typeof define === "function" && define.amd) { 10583 // AMD 10584 define(["./core"], factory); 10585 } 10586 else { 10587 // Global (browser) 10588 factory(root.CryptoJS); 10589 } 10590 }(this, function (CryptoJS) { 10591 10592 /** @preserve 10593 (c) 2012 by Cédric Mesnil. All rights reserved. 10594 10595 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 10596 10597 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 10598 - 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. 10599 10600 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 10601 */ 10602 10603 (function (Math) { 10604 // Shortcuts 10605 var C = CryptoJS; 10606 var C_lib = C.lib; 10607 var WordArray = C_lib.WordArray; 10608 var Hasher = C_lib.Hasher; 10609 var C_algo = C.algo; 10610 10611 // Constants table 10612 var _zl = WordArray.create([ 10613 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 10614 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 10615 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 10616 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 10617 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); 10618 var _zr = WordArray.create([ 10619 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 10620 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 10621 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 10622 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 10623 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); 10624 var _sl = WordArray.create([ 10625 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 10626 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 10627 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 10628 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 10629 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); 10630 var _sr = WordArray.create([ 10631 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 10632 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 10633 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 10634 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 10635 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); 10636 10637 var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); 10638 var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); 10639 10640 /** 10641 * RIPEMD160 hash algorithm. 10642 */ 10643 var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ 10644 _doReset: function () { 10645 this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); 10646 }, 10647 10648 _doProcessBlock: function (M, offset) { 10649 10650 // Swap endian 10651 for (var i = 0; i < 16; i++) { 10652 // Shortcuts 10653 var offset_i = offset + i; 10654 var M_offset_i = M[offset_i]; 10655 10656 // Swap 10657 M[offset_i] = ( 10658 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | 10659 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) 10660 ); 10661 } 10662 // Shortcut 10663 var H = this._hash.words; 10664 var hl = _hl.words; 10665 var hr = _hr.words; 10666 var zl = _zl.words; 10667 var zr = _zr.words; 10668 var sl = _sl.words; 10669 var sr = _sr.words; 10670 10671 // Working variables 10672 var al, bl, cl, dl, el; 10673 var ar, br, cr, dr, er; 10674 10675 ar = al = H[0]; 10676 br = bl = H[1]; 10677 cr = cl = H[2]; 10678 dr = dl = H[3]; 10679 er = el = H[4]; 10680 // Computation 10681 var t; 10682 for (var i = 0; i < 80; i += 1) { 10683 t = (al + M[offset+zl[i]])|0; 10684 if (i<16){ 10685 t += f1(bl,cl,dl) + hl[0]; 10686 } else if (i<32) { 10687 t += f2(bl,cl,dl) + hl[1]; 10688 } else if (i<48) { 10689 t += f3(bl,cl,dl) + hl[2]; 10690 } else if (i<64) { 10691 t += f4(bl,cl,dl) + hl[3]; 10692 } else {// if (i<80) { 10693 t += f5(bl,cl,dl) + hl[4]; 10694 } 10695 t = t|0; 10696 t = rotl(t,sl[i]); 10697 t = (t+el)|0; 10698 al = el; 10699 el = dl; 10700 dl = rotl(cl, 10); 10701 cl = bl; 10702 bl = t; 10703 10704 t = (ar + M[offset+zr[i]])|0; 10705 if (i<16){ 10706 t += f5(br,cr,dr) + hr[0]; 10707 } else if (i<32) { 10708 t += f4(br,cr,dr) + hr[1]; 10709 } else if (i<48) { 10710 t += f3(br,cr,dr) + hr[2]; 10711 } else if (i<64) { 10712 t += f2(br,cr,dr) + hr[3]; 10713 } else {// if (i<80) { 10714 t += f1(br,cr,dr) + hr[4]; 10715 } 10716 t = t|0; 10717 t = rotl(t,sr[i]) ; 10718 t = (t+er)|0; 10719 ar = er; 10720 er = dr; 10721 dr = rotl(cr, 10); 10722 cr = br; 10723 br = t; 10724 } 10725 // Intermediate hash value 10726 t = (H[1] + cl + dr)|0; 10727 H[1] = (H[2] + dl + er)|0; 10728 H[2] = (H[3] + el + ar)|0; 10729 H[3] = (H[4] + al + br)|0; 10730 H[4] = (H[0] + bl + cr)|0; 10731 H[0] = t; 10732 }, 10733 10734 _doFinalize: function () { 10735 // Shortcuts 10736 var data = this._data; 10737 var dataWords = data.words; 10738 10739 var nBitsTotal = this._nDataBytes * 8; 10740 var nBitsLeft = data.sigBytes * 8; 10741 10742 // Add padding 10743 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 10744 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( 10745 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | 10746 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) 10747 ); 10748 data.sigBytes = (dataWords.length + 1) * 4; 10749 10750 // Hash final blocks 10751 this._process(); 10752 10753 // Shortcuts 10754 var hash = this._hash; 10755 var H = hash.words; 10756 10757 // Swap endian 10758 for (var i = 0; i < 5; i++) { 10759 // Shortcut 10760 var H_i = H[i]; 10761 10762 // Swap 10763 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | 10764 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); 10765 } 10766 10767 // Return final computed hash 10768 return hash; 10769 }, 10770 10771 clone: function () { 10772 var clone = Hasher.clone.call(this); 10773 clone._hash = this._hash.clone(); 10774 10775 return clone; 10776 } 10777 }); 10778 10779 10780 function f1(x, y, z) { 10781 return ((x) ^ (y) ^ (z)); 10782 10783 } 10784 10785 function f2(x, y, z) { 10786 return (((x)&(y)) | ((~x)&(z))); 10787 } 10788 10789 function f3(x, y, z) { 10790 return (((x) | (~(y))) ^ (z)); 10791 } 10792 10793 function f4(x, y, z) { 10794 return (((x) & (z)) | ((y)&(~(z)))); 10795 } 10796 10797 function f5(x, y, z) { 10798 return ((x) ^ ((y) |(~(z)))); 10799 10800 } 10801 10802 function rotl(x,n) { 10803 return (x<<n) | (x>>>(32-n)); 10804 } 10805 10806 10807 /** 10808 * Shortcut function to the hasher's object interface. 10809 * 10810 * @param {WordArray|string} message The message to hash. 10811 * 10812 * @return {WordArray} The hash. 10813 * 10814 * @static 10815 * 10816 * @example 10817 * 10818 * var hash = CryptoJS.RIPEMD160('message'); 10819 * var hash = CryptoJS.RIPEMD160(wordArray); 10820 */ 10821 C.RIPEMD160 = Hasher._createHelper(RIPEMD160); 10822 10823 /** 10824 * Shortcut function to the HMAC's object interface. 10825 * 10826 * @param {WordArray|string} message The message to hash. 10827 * @param {WordArray|string} key The secret key. 10828 * 10829 * @return {WordArray} The HMAC. 10830 * 10831 * @static 10832 * 10833 * @example 10834 * 10835 * var hmac = CryptoJS.HmacRIPEMD160(message, key); 10836 */ 10837 C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); 10838 }(Math)); 10839 10840 10841 return CryptoJS.RIPEMD160; 10842 10843 })); 10844 },{"./core":52}],76:[function(require,module,exports){ 10845 ;(function (root, factory) { 10846 if (typeof exports === "object") { 10847 // CommonJS 10848 module.exports = exports = factory(require("./core")); 10849 } 10850 else if (typeof define === "function" && define.amd) { 10851 // AMD 10852 define(["./core"], factory); 10853 } 10854 else { 10855 // Global (browser) 10856 factory(root.CryptoJS); 10857 } 10858 }(this, function (CryptoJS) { 10859 10860 (function () { 10861 // Shortcuts 10862 var C = CryptoJS; 10863 var C_lib = C.lib; 10864 var WordArray = C_lib.WordArray; 10865 var Hasher = C_lib.Hasher; 10866 var C_algo = C.algo; 10867 10868 // Reusable object 10869 var W = []; 10870 10871 /** 10872 * SHA-1 hash algorithm. 10873 */ 10874 var SHA1 = C_algo.SHA1 = Hasher.extend({ 10875 _doReset: function () { 10876 this._hash = new WordArray.init([ 10877 0x67452301, 0xefcdab89, 10878 0x98badcfe, 0x10325476, 10879 0xc3d2e1f0 10880 ]); 10881 }, 10882 10883 _doProcessBlock: function (M, offset) { 10884 // Shortcut 10885 var H = this._hash.words; 10886 10887 // Working variables 10888 var a = H[0]; 10889 var b = H[1]; 10890 var c = H[2]; 10891 var d = H[3]; 10892 var e = H[4]; 10893 10894 // Computation 10895 for (var i = 0; i < 80; i++) { 10896 if (i < 16) { 10897 W[i] = M[offset + i] | 0; 10898 } else { 10899 var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; 10900 W[i] = (n << 1) | (n >>> 31); 10901 } 10902 10903 var t = ((a << 5) | (a >>> 27)) + e + W[i]; 10904 if (i < 20) { 10905 t += ((b & c) | (~b & d)) + 0x5a827999; 10906 } else if (i < 40) { 10907 t += (b ^ c ^ d) + 0x6ed9eba1; 10908 } else if (i < 60) { 10909 t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; 10910 } else /* if (i < 80) */ { 10911 t += (b ^ c ^ d) - 0x359d3e2a; 10912 } 10913 10914 e = d; 10915 d = c; 10916 c = (b << 30) | (b >>> 2); 10917 b = a; 10918 a = t; 10919 } 10920 10921 // Intermediate hash value 10922 H[0] = (H[0] + a) | 0; 10923 H[1] = (H[1] + b) | 0; 10924 H[2] = (H[2] + c) | 0; 10925 H[3] = (H[3] + d) | 0; 10926 H[4] = (H[4] + e) | 0; 10927 }, 10928 10929 _doFinalize: function () { 10930 // Shortcuts 10931 var data = this._data; 10932 var dataWords = data.words; 10933 10934 var nBitsTotal = this._nDataBytes * 8; 10935 var nBitsLeft = data.sigBytes * 8; 10936 10937 // Add padding 10938 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 10939 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); 10940 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; 10941 data.sigBytes = dataWords.length * 4; 10942 10943 // Hash final blocks 10944 this._process(); 10945 10946 // Return final computed hash 10947 return this._hash; 10948 }, 10949 10950 clone: function () { 10951 var clone = Hasher.clone.call(this); 10952 clone._hash = this._hash.clone(); 10953 10954 return clone; 10955 } 10956 }); 10957 10958 /** 10959 * Shortcut function to the hasher's object interface. 10960 * 10961 * @param {WordArray|string} message The message to hash. 10962 * 10963 * @return {WordArray} The hash. 10964 * 10965 * @static 10966 * 10967 * @example 10968 * 10969 * var hash = CryptoJS.SHA1('message'); 10970 * var hash = CryptoJS.SHA1(wordArray); 10971 */ 10972 C.SHA1 = Hasher._createHelper(SHA1); 10973 10974 /** 10975 * Shortcut function to the HMAC's object interface. 10976 * 10977 * @param {WordArray|string} message The message to hash. 10978 * @param {WordArray|string} key The secret key. 10979 * 10980 * @return {WordArray} The HMAC. 10981 * 10982 * @static 10983 * 10984 * @example 10985 * 10986 * var hmac = CryptoJS.HmacSHA1(message, key); 10987 */ 10988 C.HmacSHA1 = Hasher._createHmacHelper(SHA1); 10989 }()); 10990 10991 10992 return CryptoJS.SHA1; 10993 10994 })); 10995 },{"./core":52}],77:[function(require,module,exports){ 10996 ;(function (root, factory, undef) { 10997 if (typeof exports === "object") { 10998 // CommonJS 10999 module.exports = exports = factory(require("./core"), require("./sha256")); 11000 } 11001 else if (typeof define === "function" && define.amd) { 11002 // AMD 11003 define(["./core", "./sha256"], factory); 11004 } 11005 else { 11006 // Global (browser) 11007 factory(root.CryptoJS); 11008 } 11009 }(this, function (CryptoJS) { 11010 11011 (function () { 11012 // Shortcuts 11013 var C = CryptoJS; 11014 var C_lib = C.lib; 11015 var WordArray = C_lib.WordArray; 11016 var C_algo = C.algo; 11017 var SHA256 = C_algo.SHA256; 11018 11019 /** 11020 * SHA-224 hash algorithm. 11021 */ 11022 var SHA224 = C_algo.SHA224 = SHA256.extend({ 11023 _doReset: function () { 11024 this._hash = new WordArray.init([ 11025 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 11026 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 11027 ]); 11028 }, 11029 11030 _doFinalize: function () { 11031 var hash = SHA256._doFinalize.call(this); 11032 11033 hash.sigBytes -= 4; 11034 11035 return hash; 11036 } 11037 }); 11038 11039 /** 11040 * Shortcut function to the hasher's object interface. 11041 * 11042 * @param {WordArray|string} message The message to hash. 11043 * 11044 * @return {WordArray} The hash. 11045 * 11046 * @static 11047 * 11048 * @example 11049 * 11050 * var hash = CryptoJS.SHA224('message'); 11051 * var hash = CryptoJS.SHA224(wordArray); 11052 */ 11053 C.SHA224 = SHA256._createHelper(SHA224); 11054 11055 /** 11056 * Shortcut function to the HMAC's object interface. 11057 * 11058 * @param {WordArray|string} message The message to hash. 11059 * @param {WordArray|string} key The secret key. 11060 * 11061 * @return {WordArray} The HMAC. 11062 * 11063 * @static 11064 * 11065 * @example 11066 * 11067 * var hmac = CryptoJS.HmacSHA224(message, key); 11068 */ 11069 C.HmacSHA224 = SHA256._createHmacHelper(SHA224); 11070 }()); 11071 11072 11073 return CryptoJS.SHA224; 11074 11075 })); 11076 },{"./core":52,"./sha256":78}],78:[function(require,module,exports){ 11077 ;(function (root, factory) { 11078 if (typeof exports === "object") { 11079 // CommonJS 11080 module.exports = exports = factory(require("./core")); 11081 } 11082 else if (typeof define === "function" && define.amd) { 11083 // AMD 11084 define(["./core"], factory); 11085 } 11086 else { 11087 // Global (browser) 11088 factory(root.CryptoJS); 11089 } 11090 }(this, function (CryptoJS) { 11091 11092 (function (Math) { 11093 // Shortcuts 11094 var C = CryptoJS; 11095 var C_lib = C.lib; 11096 var WordArray = C_lib.WordArray; 11097 var Hasher = C_lib.Hasher; 11098 var C_algo = C.algo; 11099 11100 // Initialization and round constants tables 11101 var H = []; 11102 var K = []; 11103 11104 // Compute constants 11105 (function () { 11106 function isPrime(n) { 11107 var sqrtN = Math.sqrt(n); 11108 for (var factor = 2; factor <= sqrtN; factor++) { 11109 if (!(n % factor)) { 11110 return false; 11111 } 11112 } 11113 11114 return true; 11115 } 11116 11117 function getFractionalBits(n) { 11118 return ((n - (n | 0)) * 0x100000000) | 0; 11119 } 11120 11121 var n = 2; 11122 var nPrime = 0; 11123 while (nPrime < 64) { 11124 if (isPrime(n)) { 11125 if (nPrime < 8) { 11126 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); 11127 } 11128 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); 11129 11130 nPrime++; 11131 } 11132 11133 n++; 11134 } 11135 }()); 11136 11137 // Reusable object 11138 var W = []; 11139 11140 /** 11141 * SHA-256 hash algorithm. 11142 */ 11143 var SHA256 = C_algo.SHA256 = Hasher.extend({ 11144 _doReset: function () { 11145 this._hash = new WordArray.init(H.slice(0)); 11146 }, 11147 11148 _doProcessBlock: function (M, offset) { 11149 // Shortcut 11150 var H = this._hash.words; 11151 11152 // Working variables 11153 var a = H[0]; 11154 var b = H[1]; 11155 var c = H[2]; 11156 var d = H[3]; 11157 var e = H[4]; 11158 var f = H[5]; 11159 var g = H[6]; 11160 var h = H[7]; 11161 11162 // Computation 11163 for (var i = 0; i < 64; i++) { 11164 if (i < 16) { 11165 W[i] = M[offset + i] | 0; 11166 } else { 11167 var gamma0x = W[i - 15]; 11168 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ 11169 ((gamma0x << 14) | (gamma0x >>> 18)) ^ 11170 (gamma0x >>> 3); 11171 11172 var gamma1x = W[i - 2]; 11173 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ 11174 ((gamma1x << 13) | (gamma1x >>> 19)) ^ 11175 (gamma1x >>> 10); 11176 11177 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; 11178 } 11179 11180 var ch = (e & f) ^ (~e & g); 11181 var maj = (a & b) ^ (a & c) ^ (b & c); 11182 11183 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); 11184 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); 11185 11186 var t1 = h + sigma1 + ch + K[i] + W[i]; 11187 var t2 = sigma0 + maj; 11188 11189 h = g; 11190 g = f; 11191 f = e; 11192 e = (d + t1) | 0; 11193 d = c; 11194 c = b; 11195 b = a; 11196 a = (t1 + t2) | 0; 11197 } 11198 11199 // Intermediate hash value 11200 H[0] = (H[0] + a) | 0; 11201 H[1] = (H[1] + b) | 0; 11202 H[2] = (H[2] + c) | 0; 11203 H[3] = (H[3] + d) | 0; 11204 H[4] = (H[4] + e) | 0; 11205 H[5] = (H[5] + f) | 0; 11206 H[6] = (H[6] + g) | 0; 11207 H[7] = (H[7] + h) | 0; 11208 }, 11209 11210 _doFinalize: function () { 11211 // Shortcuts 11212 var data = this._data; 11213 var dataWords = data.words; 11214 11215 var nBitsTotal = this._nDataBytes * 8; 11216 var nBitsLeft = data.sigBytes * 8; 11217 11218 // Add padding 11219 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 11220 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); 11221 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; 11222 data.sigBytes = dataWords.length * 4; 11223 11224 // Hash final blocks 11225 this._process(); 11226 11227 // Return final computed hash 11228 return this._hash; 11229 }, 11230 11231 clone: function () { 11232 var clone = Hasher.clone.call(this); 11233 clone._hash = this._hash.clone(); 11234 11235 return clone; 11236 } 11237 }); 11238 11239 /** 11240 * Shortcut function to the hasher's object interface. 11241 * 11242 * @param {WordArray|string} message The message to hash. 11243 * 11244 * @return {WordArray} The hash. 11245 * 11246 * @static 11247 * 11248 * @example 11249 * 11250 * var hash = CryptoJS.SHA256('message'); 11251 * var hash = CryptoJS.SHA256(wordArray); 11252 */ 11253 C.SHA256 = Hasher._createHelper(SHA256); 11254 11255 /** 11256 * Shortcut function to the HMAC's object interface. 11257 * 11258 * @param {WordArray|string} message The message to hash. 11259 * @param {WordArray|string} key The secret key. 11260 * 11261 * @return {WordArray} The HMAC. 11262 * 11263 * @static 11264 * 11265 * @example 11266 * 11267 * var hmac = CryptoJS.HmacSHA256(message, key); 11268 */ 11269 C.HmacSHA256 = Hasher._createHmacHelper(SHA256); 11270 }(Math)); 11271 11272 11273 return CryptoJS.SHA256; 11274 11275 })); 11276 },{"./core":52}],79:[function(require,module,exports){ 11277 ;(function (root, factory, undef) { 11278 if (typeof exports === "object") { 11279 // CommonJS 11280 module.exports = exports = factory(require("./core"), require("./x64-core")); 11281 } 11282 else if (typeof define === "function" && define.amd) { 11283 // AMD 11284 define(["./core", "./x64-core"], factory); 11285 } 11286 else { 11287 // Global (browser) 11288 factory(root.CryptoJS); 11289 } 11290 }(this, function (CryptoJS) { 11291 11292 (function (Math) { 11293 // Shortcuts 11294 var C = CryptoJS; 11295 var C_lib = C.lib; 11296 var WordArray = C_lib.WordArray; 11297 var Hasher = C_lib.Hasher; 11298 var C_x64 = C.x64; 11299 var X64Word = C_x64.Word; 11300 var C_algo = C.algo; 11301 11302 // Constants tables 11303 var RHO_OFFSETS = []; 11304 var PI_INDEXES = []; 11305 var ROUND_CONSTANTS = []; 11306 11307 // Compute Constants 11308 (function () { 11309 // Compute rho offset constants 11310 var x = 1, y = 0; 11311 for (var t = 0; t < 24; t++) { 11312 RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; 11313 11314 var newX = y % 5; 11315 var newY = (2 * x + 3 * y) % 5; 11316 x = newX; 11317 y = newY; 11318 } 11319 11320 // Compute pi index constants 11321 for (var x = 0; x < 5; x++) { 11322 for (var y = 0; y < 5; y++) { 11323 PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; 11324 } 11325 } 11326 11327 // Compute round constants 11328 var LFSR = 0x01; 11329 for (var i = 0; i < 24; i++) { 11330 var roundConstantMsw = 0; 11331 var roundConstantLsw = 0; 11332 11333 for (var j = 0; j < 7; j++) { 11334 if (LFSR & 0x01) { 11335 var bitPosition = (1 << j) - 1; 11336 if (bitPosition < 32) { 11337 roundConstantLsw ^= 1 << bitPosition; 11338 } else /* if (bitPosition >= 32) */ { 11339 roundConstantMsw ^= 1 << (bitPosition - 32); 11340 } 11341 } 11342 11343 // Compute next LFSR 11344 if (LFSR & 0x80) { 11345 // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 11346 LFSR = (LFSR << 1) ^ 0x71; 11347 } else { 11348 LFSR <<= 1; 11349 } 11350 } 11351 11352 ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); 11353 } 11354 }()); 11355 11356 // Reusable objects for temporary values 11357 var T = []; 11358 (function () { 11359 for (var i = 0; i < 25; i++) { 11360 T[i] = X64Word.create(); 11361 } 11362 }()); 11363 11364 /** 11365 * SHA-3 hash algorithm. 11366 */ 11367 var SHA3 = C_algo.SHA3 = Hasher.extend({ 11368 /** 11369 * Configuration options. 11370 * 11371 * @property {number} outputLength 11372 * The desired number of bits in the output hash. 11373 * Only values permitted are: 224, 256, 384, 512. 11374 * Default: 512 11375 */ 11376 cfg: Hasher.cfg.extend({ 11377 outputLength: 512 11378 }), 11379 11380 _doReset: function () { 11381 var state = this._state = [] 11382 for (var i = 0; i < 25; i++) { 11383 state[i] = new X64Word.init(); 11384 } 11385 11386 this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; 11387 }, 11388 11389 _doProcessBlock: function (M, offset) { 11390 // Shortcuts 11391 var state = this._state; 11392 var nBlockSizeLanes = this.blockSize / 2; 11393 11394 // Absorb 11395 for (var i = 0; i < nBlockSizeLanes; i++) { 11396 // Shortcuts 11397 var M2i = M[offset + 2 * i]; 11398 var M2i1 = M[offset + 2 * i + 1]; 11399 11400 // Swap endian 11401 M2i = ( 11402 (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | 11403 (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) 11404 ); 11405 M2i1 = ( 11406 (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | 11407 (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) 11408 ); 11409 11410 // Absorb message into state 11411 var lane = state[i]; 11412 lane.high ^= M2i1; 11413 lane.low ^= M2i; 11414 } 11415 11416 // Rounds 11417 for (var round = 0; round < 24; round++) { 11418 // Theta 11419 for (var x = 0; x < 5; x++) { 11420 // Mix column lanes 11421 var tMsw = 0, tLsw = 0; 11422 for (var y = 0; y < 5; y++) { 11423 var lane = state[x + 5 * y]; 11424 tMsw ^= lane.high; 11425 tLsw ^= lane.low; 11426 } 11427 11428 // Temporary values 11429 var Tx = T[x]; 11430 Tx.high = tMsw; 11431 Tx.low = tLsw; 11432 } 11433 for (var x = 0; x < 5; x++) { 11434 // Shortcuts 11435 var Tx4 = T[(x + 4) % 5]; 11436 var Tx1 = T[(x + 1) % 5]; 11437 var Tx1Msw = Tx1.high; 11438 var Tx1Lsw = Tx1.low; 11439 11440 // Mix surrounding columns 11441 var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); 11442 var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); 11443 for (var y = 0; y < 5; y++) { 11444 var lane = state[x + 5 * y]; 11445 lane.high ^= tMsw; 11446 lane.low ^= tLsw; 11447 } 11448 } 11449 11450 // Rho Pi 11451 for (var laneIndex = 1; laneIndex < 25; laneIndex++) { 11452 // Shortcuts 11453 var lane = state[laneIndex]; 11454 var laneMsw = lane.high; 11455 var laneLsw = lane.low; 11456 var rhoOffset = RHO_OFFSETS[laneIndex]; 11457 11458 // Rotate lanes 11459 if (rhoOffset < 32) { 11460 var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); 11461 var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); 11462 } else /* if (rhoOffset >= 32) */ { 11463 var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); 11464 var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); 11465 } 11466 11467 // Transpose lanes 11468 var TPiLane = T[PI_INDEXES[laneIndex]]; 11469 TPiLane.high = tMsw; 11470 TPiLane.low = tLsw; 11471 } 11472 11473 // Rho pi at x = y = 0 11474 var T0 = T[0]; 11475 var state0 = state[0]; 11476 T0.high = state0.high; 11477 T0.low = state0.low; 11478 11479 // Chi 11480 for (var x = 0; x < 5; x++) { 11481 for (var y = 0; y < 5; y++) { 11482 // Shortcuts 11483 var laneIndex = x + 5 * y; 11484 var lane = state[laneIndex]; 11485 var TLane = T[laneIndex]; 11486 var Tx1Lane = T[((x + 1) % 5) + 5 * y]; 11487 var Tx2Lane = T[((x + 2) % 5) + 5 * y]; 11488 11489 // Mix rows 11490 lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); 11491 lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); 11492 } 11493 } 11494 11495 // Iota 11496 var lane = state[0]; 11497 var roundConstant = ROUND_CONSTANTS[round]; 11498 lane.high ^= roundConstant.high; 11499 lane.low ^= roundConstant.low;; 11500 } 11501 }, 11502 11503 _doFinalize: function () { 11504 // Shortcuts 11505 var data = this._data; 11506 var dataWords = data.words; 11507 var nBitsTotal = this._nDataBytes * 8; 11508 var nBitsLeft = data.sigBytes * 8; 11509 var blockSizeBits = this.blockSize * 32; 11510 11511 // Add padding 11512 dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); 11513 dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; 11514 data.sigBytes = dataWords.length * 4; 11515 11516 // Hash final blocks 11517 this._process(); 11518 11519 // Shortcuts 11520 var state = this._state; 11521 var outputLengthBytes = this.cfg.outputLength / 8; 11522 var outputLengthLanes = outputLengthBytes / 8; 11523 11524 // Squeeze 11525 var hashWords = []; 11526 for (var i = 0; i < outputLengthLanes; i++) { 11527 // Shortcuts 11528 var lane = state[i]; 11529 var laneMsw = lane.high; 11530 var laneLsw = lane.low; 11531 11532 // Swap endian 11533 laneMsw = ( 11534 (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | 11535 (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) 11536 ); 11537 laneLsw = ( 11538 (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | 11539 (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) 11540 ); 11541 11542 // Squeeze state to retrieve hash 11543 hashWords.push(laneLsw); 11544 hashWords.push(laneMsw); 11545 } 11546 11547 // Return final computed hash 11548 return new WordArray.init(hashWords, outputLengthBytes); 11549 }, 11550 11551 clone: function () { 11552 var clone = Hasher.clone.call(this); 11553 11554 var state = clone._state = this._state.slice(0); 11555 for (var i = 0; i < 25; i++) { 11556 state[i] = state[i].clone(); 11557 } 11558 11559 return clone; 11560 } 11561 }); 11562 11563 /** 11564 * Shortcut function to the hasher's object interface. 11565 * 11566 * @param {WordArray|string} message The message to hash. 11567 * 11568 * @return {WordArray} The hash. 11569 * 11570 * @static 11571 * 11572 * @example 11573 * 11574 * var hash = CryptoJS.SHA3('message'); 11575 * var hash = CryptoJS.SHA3(wordArray); 11576 */ 11577 C.SHA3 = Hasher._createHelper(SHA3); 11578 11579 /** 11580 * Shortcut function to the HMAC's object interface. 11581 * 11582 * @param {WordArray|string} message The message to hash. 11583 * @param {WordArray|string} key The secret key. 11584 * 11585 * @return {WordArray} The HMAC. 11586 * 11587 * @static 11588 * 11589 * @example 11590 * 11591 * var hmac = CryptoJS.HmacSHA3(message, key); 11592 */ 11593 C.HmacSHA3 = Hasher._createHmacHelper(SHA3); 11594 }(Math)); 11595 11596 11597 return CryptoJS.SHA3; 11598 11599 })); 11600 },{"./core":52,"./x64-core":83}],80:[function(require,module,exports){ 11601 ;(function (root, factory, undef) { 11602 if (typeof exports === "object") { 11603 // CommonJS 11604 module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512")); 11605 } 11606 else if (typeof define === "function" && define.amd) { 11607 // AMD 11608 define(["./core", "./x64-core", "./sha512"], factory); 11609 } 11610 else { 11611 // Global (browser) 11612 factory(root.CryptoJS); 11613 } 11614 }(this, function (CryptoJS) { 11615 11616 (function () { 11617 // Shortcuts 11618 var C = CryptoJS; 11619 var C_x64 = C.x64; 11620 var X64Word = C_x64.Word; 11621 var X64WordArray = C_x64.WordArray; 11622 var C_algo = C.algo; 11623 var SHA512 = C_algo.SHA512; 11624 11625 /** 11626 * SHA-384 hash algorithm. 11627 */ 11628 var SHA384 = C_algo.SHA384 = SHA512.extend({ 11629 _doReset: function () { 11630 this._hash = new X64WordArray.init([ 11631 new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), 11632 new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), 11633 new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), 11634 new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) 11635 ]); 11636 }, 11637 11638 _doFinalize: function () { 11639 var hash = SHA512._doFinalize.call(this); 11640 11641 hash.sigBytes -= 16; 11642 11643 return hash; 11644 } 11645 }); 11646 11647 /** 11648 * Shortcut function to the hasher's object interface. 11649 * 11650 * @param {WordArray|string} message The message to hash. 11651 * 11652 * @return {WordArray} The hash. 11653 * 11654 * @static 11655 * 11656 * @example 11657 * 11658 * var hash = CryptoJS.SHA384('message'); 11659 * var hash = CryptoJS.SHA384(wordArray); 11660 */ 11661 C.SHA384 = SHA512._createHelper(SHA384); 11662 11663 /** 11664 * Shortcut function to the HMAC's object interface. 11665 * 11666 * @param {WordArray|string} message The message to hash. 11667 * @param {WordArray|string} key The secret key. 11668 * 11669 * @return {WordArray} The HMAC. 11670 * 11671 * @static 11672 * 11673 * @example 11674 * 11675 * var hmac = CryptoJS.HmacSHA384(message, key); 11676 */ 11677 C.HmacSHA384 = SHA512._createHmacHelper(SHA384); 11678 }()); 11679 11680 11681 return CryptoJS.SHA384; 11682 11683 })); 11684 },{"./core":52,"./sha512":81,"./x64-core":83}],81:[function(require,module,exports){ 11685 ;(function (root, factory, undef) { 11686 if (typeof exports === "object") { 11687 // CommonJS 11688 module.exports = exports = factory(require("./core"), require("./x64-core")); 11689 } 11690 else if (typeof define === "function" && define.amd) { 11691 // AMD 11692 define(["./core", "./x64-core"], factory); 11693 } 11694 else { 11695 // Global (browser) 11696 factory(root.CryptoJS); 11697 } 11698 }(this, function (CryptoJS) { 11699 11700 (function () { 11701 // Shortcuts 11702 var C = CryptoJS; 11703 var C_lib = C.lib; 11704 var Hasher = C_lib.Hasher; 11705 var C_x64 = C.x64; 11706 var X64Word = C_x64.Word; 11707 var X64WordArray = C_x64.WordArray; 11708 var C_algo = C.algo; 11709 11710 function X64Word_create() { 11711 return X64Word.create.apply(X64Word, arguments); 11712 } 11713 11714 // Constants 11715 var K = [ 11716 X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), 11717 X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), 11718 X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), 11719 X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), 11720 X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), 11721 X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), 11722 X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), 11723 X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), 11724 X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), 11725 X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), 11726 X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), 11727 X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), 11728 X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), 11729 X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), 11730 X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), 11731 X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), 11732 X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), 11733 X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), 11734 X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), 11735 X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), 11736 X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), 11737 X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), 11738 X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), 11739 X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), 11740 X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), 11741 X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), 11742 X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), 11743 X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), 11744 X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), 11745 X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), 11746 X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), 11747 X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), 11748 X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), 11749 X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), 11750 X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), 11751 X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), 11752 X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), 11753 X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), 11754 X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), 11755 X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) 11756 ]; 11757 11758 // Reusable objects 11759 var W = []; 11760 (function () { 11761 for (var i = 0; i < 80; i++) { 11762 W[i] = X64Word_create(); 11763 } 11764 }()); 11765 11766 /** 11767 * SHA-512 hash algorithm. 11768 */ 11769 var SHA512 = C_algo.SHA512 = Hasher.extend({ 11770 _doReset: function () { 11771 this._hash = new X64WordArray.init([ 11772 new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), 11773 new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), 11774 new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), 11775 new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) 11776 ]); 11777 }, 11778 11779 _doProcessBlock: function (M, offset) { 11780 // Shortcuts 11781 var H = this._hash.words; 11782 11783 var H0 = H[0]; 11784 var H1 = H[1]; 11785 var H2 = H[2]; 11786 var H3 = H[3]; 11787 var H4 = H[4]; 11788 var H5 = H[5]; 11789 var H6 = H[6]; 11790 var H7 = H[7]; 11791 11792 var H0h = H0.high; 11793 var H0l = H0.low; 11794 var H1h = H1.high; 11795 var H1l = H1.low; 11796 var H2h = H2.high; 11797 var H2l = H2.low; 11798 var H3h = H3.high; 11799 var H3l = H3.low; 11800 var H4h = H4.high; 11801 var H4l = H4.low; 11802 var H5h = H5.high; 11803 var H5l = H5.low; 11804 var H6h = H6.high; 11805 var H6l = H6.low; 11806 var H7h = H7.high; 11807 var H7l = H7.low; 11808 11809 // Working variables 11810 var ah = H0h; 11811 var al = H0l; 11812 var bh = H1h; 11813 var bl = H1l; 11814 var ch = H2h; 11815 var cl = H2l; 11816 var dh = H3h; 11817 var dl = H3l; 11818 var eh = H4h; 11819 var el = H4l; 11820 var fh = H5h; 11821 var fl = H5l; 11822 var gh = H6h; 11823 var gl = H6l; 11824 var hh = H7h; 11825 var hl = H7l; 11826 11827 // Rounds 11828 for (var i = 0; i < 80; i++) { 11829 // Shortcut 11830 var Wi = W[i]; 11831 11832 // Extend message 11833 if (i < 16) { 11834 var Wih = Wi.high = M[offset + i * 2] | 0; 11835 var Wil = Wi.low = M[offset + i * 2 + 1] | 0; 11836 } else { 11837 // Gamma0 11838 var gamma0x = W[i - 15]; 11839 var gamma0xh = gamma0x.high; 11840 var gamma0xl = gamma0x.low; 11841 var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); 11842 var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); 11843 11844 // Gamma1 11845 var gamma1x = W[i - 2]; 11846 var gamma1xh = gamma1x.high; 11847 var gamma1xl = gamma1x.low; 11848 var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); 11849 var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); 11850 11851 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] 11852 var Wi7 = W[i - 7]; 11853 var Wi7h = Wi7.high; 11854 var Wi7l = Wi7.low; 11855 11856 var Wi16 = W[i - 16]; 11857 var Wi16h = Wi16.high; 11858 var Wi16l = Wi16.low; 11859 11860 var Wil = gamma0l + Wi7l; 11861 var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); 11862 var Wil = Wil + gamma1l; 11863 var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); 11864 var Wil = Wil + Wi16l; 11865 var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); 11866 11867 Wi.high = Wih; 11868 Wi.low = Wil; 11869 } 11870 11871 var chh = (eh & fh) ^ (~eh & gh); 11872 var chl = (el & fl) ^ (~el & gl); 11873 var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); 11874 var majl = (al & bl) ^ (al & cl) ^ (bl & cl); 11875 11876 var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); 11877 var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); 11878 var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); 11879 var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); 11880 11881 // t1 = h + sigma1 + ch + K[i] + W[i] 11882 var Ki = K[i]; 11883 var Kih = Ki.high; 11884 var Kil = Ki.low; 11885 11886 var t1l = hl + sigma1l; 11887 var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); 11888 var t1l = t1l + chl; 11889 var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); 11890 var t1l = t1l + Kil; 11891 var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); 11892 var t1l = t1l + Wil; 11893 var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); 11894 11895 // t2 = sigma0 + maj 11896 var t2l = sigma0l + majl; 11897 var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); 11898 11899 // Update working variables 11900 hh = gh; 11901 hl = gl; 11902 gh = fh; 11903 gl = fl; 11904 fh = eh; 11905 fl = el; 11906 el = (dl + t1l) | 0; 11907 eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; 11908 dh = ch; 11909 dl = cl; 11910 ch = bh; 11911 cl = bl; 11912 bh = ah; 11913 bl = al; 11914 al = (t1l + t2l) | 0; 11915 ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; 11916 } 11917 11918 // Intermediate hash value 11919 H0l = H0.low = (H0l + al); 11920 H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); 11921 H1l = H1.low = (H1l + bl); 11922 H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); 11923 H2l = H2.low = (H2l + cl); 11924 H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); 11925 H3l = H3.low = (H3l + dl); 11926 H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); 11927 H4l = H4.low = (H4l + el); 11928 H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); 11929 H5l = H5.low = (H5l + fl); 11930 H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); 11931 H6l = H6.low = (H6l + gl); 11932 H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); 11933 H7l = H7.low = (H7l + hl); 11934 H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); 11935 }, 11936 11937 _doFinalize: function () { 11938 // Shortcuts 11939 var data = this._data; 11940 var dataWords = data.words; 11941 11942 var nBitsTotal = this._nDataBytes * 8; 11943 var nBitsLeft = data.sigBytes * 8; 11944 11945 // Add padding 11946 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 11947 dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); 11948 dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; 11949 data.sigBytes = dataWords.length * 4; 11950 11951 // Hash final blocks 11952 this._process(); 11953 11954 // Convert hash to 32-bit word array before returning 11955 var hash = this._hash.toX32(); 11956 11957 // Return final computed hash 11958 return hash; 11959 }, 11960 11961 clone: function () { 11962 var clone = Hasher.clone.call(this); 11963 clone._hash = this._hash.clone(); 11964 11965 return clone; 11966 }, 11967 11968 blockSize: 1024/32 11969 }); 11970 11971 /** 11972 * Shortcut function to the hasher's object interface. 11973 * 11974 * @param {WordArray|string} message The message to hash. 11975 * 11976 * @return {WordArray} The hash. 11977 * 11978 * @static 11979 * 11980 * @example 11981 * 11982 * var hash = CryptoJS.SHA512('message'); 11983 * var hash = CryptoJS.SHA512(wordArray); 11984 */ 11985 C.SHA512 = Hasher._createHelper(SHA512); 11986 11987 /** 11988 * Shortcut function to the HMAC's object interface. 11989 * 11990 * @param {WordArray|string} message The message to hash. 11991 * @param {WordArray|string} key The secret key. 11992 * 11993 * @return {WordArray} The HMAC. 11994 * 11995 * @static 11996 * 11997 * @example 11998 * 11999 * var hmac = CryptoJS.HmacSHA512(message, key); 12000 */ 12001 C.HmacSHA512 = Hasher._createHmacHelper(SHA512); 12002 }()); 12003 12004 12005 return CryptoJS.SHA512; 12006 12007 })); 12008 },{"./core":52,"./x64-core":83}],82:[function(require,module,exports){ 12009 ;(function (root, factory, undef) { 12010 if (typeof exports === "object") { 12011 // CommonJS 12012 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 12013 } 12014 else if (typeof define === "function" && define.amd) { 12015 // AMD 12016 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 12017 } 12018 else { 12019 // Global (browser) 12020 factory(root.CryptoJS); 12021 } 12022 }(this, function (CryptoJS) { 12023 12024 (function () { 12025 // Shortcuts 12026 var C = CryptoJS; 12027 var C_lib = C.lib; 12028 var WordArray = C_lib.WordArray; 12029 var BlockCipher = C_lib.BlockCipher; 12030 var C_algo = C.algo; 12031 12032 // Permuted Choice 1 constants 12033 var PC1 = [ 12034 57, 49, 41, 33, 25, 17, 9, 1, 12035 58, 50, 42, 34, 26, 18, 10, 2, 12036 59, 51, 43, 35, 27, 19, 11, 3, 12037 60, 52, 44, 36, 63, 55, 47, 39, 12038 31, 23, 15, 7, 62, 54, 46, 38, 12039 30, 22, 14, 6, 61, 53, 45, 37, 12040 29, 21, 13, 5, 28, 20, 12, 4 12041 ]; 12042 12043 // Permuted Choice 2 constants 12044 var PC2 = [ 12045 14, 17, 11, 24, 1, 5, 12046 3, 28, 15, 6, 21, 10, 12047 23, 19, 12, 4, 26, 8, 12048 16, 7, 27, 20, 13, 2, 12049 41, 52, 31, 37, 47, 55, 12050 30, 40, 51, 45, 33, 48, 12051 44, 49, 39, 56, 34, 53, 12052 46, 42, 50, 36, 29, 32 12053 ]; 12054 12055 // Cumulative bit shift constants 12056 var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; 12057 12058 // SBOXes and round permutation constants 12059 var SBOX_P = [ 12060 { 12061 0x0: 0x808200, 12062 0x10000000: 0x8000, 12063 0x20000000: 0x808002, 12064 0x30000000: 0x2, 12065 0x40000000: 0x200, 12066 0x50000000: 0x808202, 12067 0x60000000: 0x800202, 12068 0x70000000: 0x800000, 12069 0x80000000: 0x202, 12070 0x90000000: 0x800200, 12071 0xa0000000: 0x8200, 12072 0xb0000000: 0x808000, 12073 0xc0000000: 0x8002, 12074 0xd0000000: 0x800002, 12075 0xe0000000: 0x0, 12076 0xf0000000: 0x8202, 12077 0x8000000: 0x0, 12078 0x18000000: 0x808202, 12079 0x28000000: 0x8202, 12080 0x38000000: 0x8000, 12081 0x48000000: 0x808200, 12082 0x58000000: 0x200, 12083 0x68000000: 0x808002, 12084 0x78000000: 0x2, 12085 0x88000000: 0x800200, 12086 0x98000000: 0x8200, 12087 0xa8000000: 0x808000, 12088 0xb8000000: 0x800202, 12089 0xc8000000: 0x800002, 12090 0xd8000000: 0x8002, 12091 0xe8000000: 0x202, 12092 0xf8000000: 0x800000, 12093 0x1: 0x8000, 12094 0x10000001: 0x2, 12095 0x20000001: 0x808200, 12096 0x30000001: 0x800000, 12097 0x40000001: 0x808002, 12098 0x50000001: 0x8200, 12099 0x60000001: 0x200, 12100 0x70000001: 0x800202, 12101 0x80000001: 0x808202, 12102 0x90000001: 0x808000, 12103 0xa0000001: 0x800002, 12104 0xb0000001: 0x8202, 12105 0xc0000001: 0x202, 12106 0xd0000001: 0x800200, 12107 0xe0000001: 0x8002, 12108 0xf0000001: 0x0, 12109 0x8000001: 0x808202, 12110 0x18000001: 0x808000, 12111 0x28000001: 0x800000, 12112 0x38000001: 0x200, 12113 0x48000001: 0x8000, 12114 0x58000001: 0x800002, 12115 0x68000001: 0x2, 12116 0x78000001: 0x8202, 12117 0x88000001: 0x8002, 12118 0x98000001: 0x800202, 12119 0xa8000001: 0x202, 12120 0xb8000001: 0x808200, 12121 0xc8000001: 0x800200, 12122 0xd8000001: 0x0, 12123 0xe8000001: 0x8200, 12124 0xf8000001: 0x808002 12125 }, 12126 { 12127 0x0: 0x40084010, 12128 0x1000000: 0x4000, 12129 0x2000000: 0x80000, 12130 0x3000000: 0x40080010, 12131 0x4000000: 0x40000010, 12132 0x5000000: 0x40084000, 12133 0x6000000: 0x40004000, 12134 0x7000000: 0x10, 12135 0x8000000: 0x84000, 12136 0x9000000: 0x40004010, 12137 0xa000000: 0x40000000, 12138 0xb000000: 0x84010, 12139 0xc000000: 0x80010, 12140 0xd000000: 0x0, 12141 0xe000000: 0x4010, 12142 0xf000000: 0x40080000, 12143 0x800000: 0x40004000, 12144 0x1800000: 0x84010, 12145 0x2800000: 0x10, 12146 0x3800000: 0x40004010, 12147 0x4800000: 0x40084010, 12148 0x5800000: 0x40000000, 12149 0x6800000: 0x80000, 12150 0x7800000: 0x40080010, 12151 0x8800000: 0x80010, 12152 0x9800000: 0x0, 12153 0xa800000: 0x4000, 12154 0xb800000: 0x40080000, 12155 0xc800000: 0x40000010, 12156 0xd800000: 0x84000, 12157 0xe800000: 0x40084000, 12158 0xf800000: 0x4010, 12159 0x10000000: 0x0, 12160 0x11000000: 0x40080010, 12161 0x12000000: 0x40004010, 12162 0x13000000: 0x40084000, 12163 0x14000000: 0x40080000, 12164 0x15000000: 0x10, 12165 0x16000000: 0x84010, 12166 0x17000000: 0x4000, 12167 0x18000000: 0x4010, 12168 0x19000000: 0x80000, 12169 0x1a000000: 0x80010, 12170 0x1b000000: 0x40000010, 12171 0x1c000000: 0x84000, 12172 0x1d000000: 0x40004000, 12173 0x1e000000: 0x40000000, 12174 0x1f000000: 0x40084010, 12175 0x10800000: 0x84010, 12176 0x11800000: 0x80000, 12177 0x12800000: 0x40080000, 12178 0x13800000: 0x4000, 12179 0x14800000: 0x40004000, 12180 0x15800000: 0x40084010, 12181 0x16800000: 0x10, 12182 0x17800000: 0x40000000, 12183 0x18800000: 0x40084000, 12184 0x19800000: 0x40000010, 12185 0x1a800000: 0x40004010, 12186 0x1b800000: 0x80010, 12187 0x1c800000: 0x0, 12188 0x1d800000: 0x4010, 12189 0x1e800000: 0x40080010, 12190 0x1f800000: 0x84000 12191 }, 12192 { 12193 0x0: 0x104, 12194 0x100000: 0x0, 12195 0x200000: 0x4000100, 12196 0x300000: 0x10104, 12197 0x400000: 0x10004, 12198 0x500000: 0x4000004, 12199 0x600000: 0x4010104, 12200 0x700000: 0x4010000, 12201 0x800000: 0x4000000, 12202 0x900000: 0x4010100, 12203 0xa00000: 0x10100, 12204 0xb00000: 0x4010004, 12205 0xc00000: 0x4000104, 12206 0xd00000: 0x10000, 12207 0xe00000: 0x4, 12208 0xf00000: 0x100, 12209 0x80000: 0x4010100, 12210 0x180000: 0x4010004, 12211 0x280000: 0x0, 12212 0x380000: 0x4000100, 12213 0x480000: 0x4000004, 12214 0x580000: 0x10000, 12215 0x680000: 0x10004, 12216 0x780000: 0x104, 12217 0x880000: 0x4, 12218 0x980000: 0x100, 12219 0xa80000: 0x4010000, 12220 0xb80000: 0x10104, 12221 0xc80000: 0x10100, 12222 0xd80000: 0x4000104, 12223 0xe80000: 0x4010104, 12224 0xf80000: 0x4000000, 12225 0x1000000: 0x4010100, 12226 0x1100000: 0x10004, 12227 0x1200000: 0x10000, 12228 0x1300000: 0x4000100, 12229 0x1400000: 0x100, 12230 0x1500000: 0x4010104, 12231 0x1600000: 0x4000004, 12232 0x1700000: 0x0, 12233 0x1800000: 0x4000104, 12234 0x1900000: 0x4000000, 12235 0x1a00000: 0x4, 12236 0x1b00000: 0x10100, 12237 0x1c00000: 0x4010000, 12238 0x1d00000: 0x104, 12239 0x1e00000: 0x10104, 12240 0x1f00000: 0x4010004, 12241 0x1080000: 0x4000000, 12242 0x1180000: 0x104, 12243 0x1280000: 0x4010100, 12244 0x1380000: 0x0, 12245 0x1480000: 0x10004, 12246 0x1580000: 0x4000100, 12247 0x1680000: 0x100, 12248 0x1780000: 0x4010004, 12249 0x1880000: 0x10000, 12250 0x1980000: 0x4010104, 12251 0x1a80000: 0x10104, 12252 0x1b80000: 0x4000004, 12253 0x1c80000: 0x4000104, 12254 0x1d80000: 0x4010000, 12255 0x1e80000: 0x4, 12256 0x1f80000: 0x10100 12257 }, 12258 { 12259 0x0: 0x80401000, 12260 0x10000: 0x80001040, 12261 0x20000: 0x401040, 12262 0x30000: 0x80400000, 12263 0x40000: 0x0, 12264 0x50000: 0x401000, 12265 0x60000: 0x80000040, 12266 0x70000: 0x400040, 12267 0x80000: 0x80000000, 12268 0x90000: 0x400000, 12269 0xa0000: 0x40, 12270 0xb0000: 0x80001000, 12271 0xc0000: 0x80400040, 12272 0xd0000: 0x1040, 12273 0xe0000: 0x1000, 12274 0xf0000: 0x80401040, 12275 0x8000: 0x80001040, 12276 0x18000: 0x40, 12277 0x28000: 0x80400040, 12278 0x38000: 0x80001000, 12279 0x48000: 0x401000, 12280 0x58000: 0x80401040, 12281 0x68000: 0x0, 12282 0x78000: 0x80400000, 12283 0x88000: 0x1000, 12284 0x98000: 0x80401000, 12285 0xa8000: 0x400000, 12286 0xb8000: 0x1040, 12287 0xc8000: 0x80000000, 12288 0xd8000: 0x400040, 12289 0xe8000: 0x401040, 12290 0xf8000: 0x80000040, 12291 0x100000: 0x400040, 12292 0x110000: 0x401000, 12293 0x120000: 0x80000040, 12294 0x130000: 0x0, 12295 0x140000: 0x1040, 12296 0x150000: 0x80400040, 12297 0x160000: 0x80401000, 12298 0x170000: 0x80001040, 12299 0x180000: 0x80401040, 12300 0x190000: 0x80000000, 12301 0x1a0000: 0x80400000, 12302 0x1b0000: 0x401040, 12303 0x1c0000: 0x80001000, 12304 0x1d0000: 0x400000, 12305 0x1e0000: 0x40, 12306 0x1f0000: 0x1000, 12307 0x108000: 0x80400000, 12308 0x118000: 0x80401040, 12309 0x128000: 0x0, 12310 0x138000: 0x401000, 12311 0x148000: 0x400040, 12312 0x158000: 0x80000000, 12313 0x168000: 0x80001040, 12314 0x178000: 0x40, 12315 0x188000: 0x80000040, 12316 0x198000: 0x1000, 12317 0x1a8000: 0x80001000, 12318 0x1b8000: 0x80400040, 12319 0x1c8000: 0x1040, 12320 0x1d8000: 0x80401000, 12321 0x1e8000: 0x400000, 12322 0x1f8000: 0x401040 12323 }, 12324 { 12325 0x0: 0x80, 12326 0x1000: 0x1040000, 12327 0x2000: 0x40000, 12328 0x3000: 0x20000000, 12329 0x4000: 0x20040080, 12330 0x5000: 0x1000080, 12331 0x6000: 0x21000080, 12332 0x7000: 0x40080, 12333 0x8000: 0x1000000, 12334 0x9000: 0x20040000, 12335 0xa000: 0x20000080, 12336 0xb000: 0x21040080, 12337 0xc000: 0x21040000, 12338 0xd000: 0x0, 12339 0xe000: 0x1040080, 12340 0xf000: 0x21000000, 12341 0x800: 0x1040080, 12342 0x1800: 0x21000080, 12343 0x2800: 0x80, 12344 0x3800: 0x1040000, 12345 0x4800: 0x40000, 12346 0x5800: 0x20040080, 12347 0x6800: 0x21040000, 12348 0x7800: 0x20000000, 12349 0x8800: 0x20040000, 12350 0x9800: 0x0, 12351 0xa800: 0x21040080, 12352 0xb800: 0x1000080, 12353 0xc800: 0x20000080, 12354 0xd800: 0x21000000, 12355 0xe800: 0x1000000, 12356 0xf800: 0x40080, 12357 0x10000: 0x40000, 12358 0x11000: 0x80, 12359 0x12000: 0x20000000, 12360 0x13000: 0x21000080, 12361 0x14000: 0x1000080, 12362 0x15000: 0x21040000, 12363 0x16000: 0x20040080, 12364 0x17000: 0x1000000, 12365 0x18000: 0x21040080, 12366 0x19000: 0x21000000, 12367 0x1a000: 0x1040000, 12368 0x1b000: 0x20040000, 12369 0x1c000: 0x40080, 12370 0x1d000: 0x20000080, 12371 0x1e000: 0x0, 12372 0x1f000: 0x1040080, 12373 0x10800: 0x21000080, 12374 0x11800: 0x1000000, 12375 0x12800: 0x1040000, 12376 0x13800: 0x20040080, 12377 0x14800: 0x20000000, 12378 0x15800: 0x1040080, 12379 0x16800: 0x80, 12380 0x17800: 0x21040000, 12381 0x18800: 0x40080, 12382 0x19800: 0x21040080, 12383 0x1a800: 0x0, 12384 0x1b800: 0x21000000, 12385 0x1c800: 0x1000080, 12386 0x1d800: 0x40000, 12387 0x1e800: 0x20040000, 12388 0x1f800: 0x20000080 12389 }, 12390 { 12391 0x0: 0x10000008, 12392 0x100: 0x2000, 12393 0x200: 0x10200000, 12394 0x300: 0x10202008, 12395 0x400: 0x10002000, 12396 0x500: 0x200000, 12397 0x600: 0x200008, 12398 0x700: 0x10000000, 12399 0x800: 0x0, 12400 0x900: 0x10002008, 12401 0xa00: 0x202000, 12402 0xb00: 0x8, 12403 0xc00: 0x10200008, 12404 0xd00: 0x202008, 12405 0xe00: 0x2008, 12406 0xf00: 0x10202000, 12407 0x80: 0x10200000, 12408 0x180: 0x10202008, 12409 0x280: 0x8, 12410 0x380: 0x200000, 12411 0x480: 0x202008, 12412 0x580: 0x10000008, 12413 0x680: 0x10002000, 12414 0x780: 0x2008, 12415 0x880: 0x200008, 12416 0x980: 0x2000, 12417 0xa80: 0x10002008, 12418 0xb80: 0x10200008, 12419 0xc80: 0x0, 12420 0xd80: 0x10202000, 12421 0xe80: 0x202000, 12422 0xf80: 0x10000000, 12423 0x1000: 0x10002000, 12424 0x1100: 0x10200008, 12425 0x1200: 0x10202008, 12426 0x1300: 0x2008, 12427 0x1400: 0x200000, 12428 0x1500: 0x10000000, 12429 0x1600: 0x10000008, 12430 0x1700: 0x202000, 12431 0x1800: 0x202008, 12432 0x1900: 0x0, 12433 0x1a00: 0x8, 12434 0x1b00: 0x10200000, 12435 0x1c00: 0x2000, 12436 0x1d00: 0x10002008, 12437 0x1e00: 0x10202000, 12438 0x1f00: 0x200008, 12439 0x1080: 0x8, 12440 0x1180: 0x202000, 12441 0x1280: 0x200000, 12442 0x1380: 0x10000008, 12443 0x1480: 0x10002000, 12444 0x1580: 0x2008, 12445 0x1680: 0x10202008, 12446 0x1780: 0x10200000, 12447 0x1880: 0x10202000, 12448 0x1980: 0x10200008, 12449 0x1a80: 0x2000, 12450 0x1b80: 0x202008, 12451 0x1c80: 0x200008, 12452 0x1d80: 0x0, 12453 0x1e80: 0x10000000, 12454 0x1f80: 0x10002008 12455 }, 12456 { 12457 0x0: 0x100000, 12458 0x10: 0x2000401, 12459 0x20: 0x400, 12460 0x30: 0x100401, 12461 0x40: 0x2100401, 12462 0x50: 0x0, 12463 0x60: 0x1, 12464 0x70: 0x2100001, 12465 0x80: 0x2000400, 12466 0x90: 0x100001, 12467 0xa0: 0x2000001, 12468 0xb0: 0x2100400, 12469 0xc0: 0x2100000, 12470 0xd0: 0x401, 12471 0xe0: 0x100400, 12472 0xf0: 0x2000000, 12473 0x8: 0x2100001, 12474 0x18: 0x0, 12475 0x28: 0x2000401, 12476 0x38: 0x2100400, 12477 0x48: 0x100000, 12478 0x58: 0x2000001, 12479 0x68: 0x2000000, 12480 0x78: 0x401, 12481 0x88: 0x100401, 12482 0x98: 0x2000400, 12483 0xa8: 0x2100000, 12484 0xb8: 0x100001, 12485 0xc8: 0x400, 12486 0xd8: 0x2100401, 12487 0xe8: 0x1, 12488 0xf8: 0x100400, 12489 0x100: 0x2000000, 12490 0x110: 0x100000, 12491 0x120: 0x2000401, 12492 0x130: 0x2100001, 12493 0x140: 0x100001, 12494 0x150: 0x2000400, 12495 0x160: 0x2100400, 12496 0x170: 0x100401, 12497 0x180: 0x401, 12498 0x190: 0x2100401, 12499 0x1a0: 0x100400, 12500 0x1b0: 0x1, 12501 0x1c0: 0x0, 12502 0x1d0: 0x2100000, 12503 0x1e0: 0x2000001, 12504 0x1f0: 0x400, 12505 0x108: 0x100400, 12506 0x118: 0x2000401, 12507 0x128: 0x2100001, 12508 0x138: 0x1, 12509 0x148: 0x2000000, 12510 0x158: 0x100000, 12511 0x168: 0x401, 12512 0x178: 0x2100400, 12513 0x188: 0x2000001, 12514 0x198: 0x2100000, 12515 0x1a8: 0x0, 12516 0x1b8: 0x2100401, 12517 0x1c8: 0x100401, 12518 0x1d8: 0x400, 12519 0x1e8: 0x2000400, 12520 0x1f8: 0x100001 12521 }, 12522 { 12523 0x0: 0x8000820, 12524 0x1: 0x20000, 12525 0x2: 0x8000000, 12526 0x3: 0x20, 12527 0x4: 0x20020, 12528 0x5: 0x8020820, 12529 0x6: 0x8020800, 12530 0x7: 0x800, 12531 0x8: 0x8020000, 12532 0x9: 0x8000800, 12533 0xa: 0x20800, 12534 0xb: 0x8020020, 12535 0xc: 0x820, 12536 0xd: 0x0, 12537 0xe: 0x8000020, 12538 0xf: 0x20820, 12539 0x80000000: 0x800, 12540 0x80000001: 0x8020820, 12541 0x80000002: 0x8000820, 12542 0x80000003: 0x8000000, 12543 0x80000004: 0x8020000, 12544 0x80000005: 0x20800, 12545 0x80000006: 0x20820, 12546 0x80000007: 0x20, 12547 0x80000008: 0x8000020, 12548 0x80000009: 0x820, 12549 0x8000000a: 0x20020, 12550 0x8000000b: 0x8020800, 12551 0x8000000c: 0x0, 12552 0x8000000d: 0x8020020, 12553 0x8000000e: 0x8000800, 12554 0x8000000f: 0x20000, 12555 0x10: 0x20820, 12556 0x11: 0x8020800, 12557 0x12: 0x20, 12558 0x13: 0x800, 12559 0x14: 0x8000800, 12560 0x15: 0x8000020, 12561 0x16: 0x8020020, 12562 0x17: 0x20000, 12563 0x18: 0x0, 12564 0x19: 0x20020, 12565 0x1a: 0x8020000, 12566 0x1b: 0x8000820, 12567 0x1c: 0x8020820, 12568 0x1d: 0x20800, 12569 0x1e: 0x820, 12570 0x1f: 0x8000000, 12571 0x80000010: 0x20000, 12572 0x80000011: 0x800, 12573 0x80000012: 0x8020020, 12574 0x80000013: 0x20820, 12575 0x80000014: 0x20, 12576 0x80000015: 0x8020000, 12577 0x80000016: 0x8000000, 12578 0x80000017: 0x8000820, 12579 0x80000018: 0x8020820, 12580 0x80000019: 0x8000020, 12581 0x8000001a: 0x8000800, 12582 0x8000001b: 0x0, 12583 0x8000001c: 0x20800, 12584 0x8000001d: 0x820, 12585 0x8000001e: 0x20020, 12586 0x8000001f: 0x8020800 12587 } 12588 ]; 12589 12590 // Masks that select the SBOX input 12591 var SBOX_MASK = [ 12592 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 12593 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f 12594 ]; 12595 12596 /** 12597 * DES block cipher algorithm. 12598 */ 12599 var DES = C_algo.DES = BlockCipher.extend({ 12600 _doReset: function () { 12601 // Shortcuts 12602 var key = this._key; 12603 var keyWords = key.words; 12604 12605 // Select 56 bits according to PC1 12606 var keyBits = []; 12607 for (var i = 0; i < 56; i++) { 12608 var keyBitPos = PC1[i] - 1; 12609 keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; 12610 } 12611 12612 // Assemble 16 subkeys 12613 var subKeys = this._subKeys = []; 12614 for (var nSubKey = 0; nSubKey < 16; nSubKey++) { 12615 // Create subkey 12616 var subKey = subKeys[nSubKey] = []; 12617 12618 // Shortcut 12619 var bitShift = BIT_SHIFTS[nSubKey]; 12620 12621 // Select 48 bits according to PC2 12622 for (var i = 0; i < 24; i++) { 12623 // Select from the left 28 key bits 12624 subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); 12625 12626 // Select from the right 28 key bits 12627 subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); 12628 } 12629 12630 // Since each subkey is applied to an expanded 32-bit input, 12631 // the subkey can be broken into 8 values scaled to 32-bits, 12632 // which allows the key to be used without expansion 12633 subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); 12634 for (var i = 1; i < 7; i++) { 12635 subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); 12636 } 12637 subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); 12638 } 12639 12640 // Compute inverse subkeys 12641 var invSubKeys = this._invSubKeys = []; 12642 for (var i = 0; i < 16; i++) { 12643 invSubKeys[i] = subKeys[15 - i]; 12644 } 12645 }, 12646 12647 encryptBlock: function (M, offset) { 12648 this._doCryptBlock(M, offset, this._subKeys); 12649 }, 12650 12651 decryptBlock: function (M, offset) { 12652 this._doCryptBlock(M, offset, this._invSubKeys); 12653 }, 12654 12655 _doCryptBlock: function (M, offset, subKeys) { 12656 // Get input 12657 this._lBlock = M[offset]; 12658 this._rBlock = M[offset + 1]; 12659 12660 // Initial permutation 12661 exchangeLR.call(this, 4, 0x0f0f0f0f); 12662 exchangeLR.call(this, 16, 0x0000ffff); 12663 exchangeRL.call(this, 2, 0x33333333); 12664 exchangeRL.call(this, 8, 0x00ff00ff); 12665 exchangeLR.call(this, 1, 0x55555555); 12666 12667 // Rounds 12668 for (var round = 0; round < 16; round++) { 12669 // Shortcuts 12670 var subKey = subKeys[round]; 12671 var lBlock = this._lBlock; 12672 var rBlock = this._rBlock; 12673 12674 // Feistel function 12675 var f = 0; 12676 for (var i = 0; i < 8; i++) { 12677 f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; 12678 } 12679 this._lBlock = rBlock; 12680 this._rBlock = lBlock ^ f; 12681 } 12682 12683 // Undo swap from last round 12684 var t = this._lBlock; 12685 this._lBlock = this._rBlock; 12686 this._rBlock = t; 12687 12688 // Final permutation 12689 exchangeLR.call(this, 1, 0x55555555); 12690 exchangeRL.call(this, 8, 0x00ff00ff); 12691 exchangeRL.call(this, 2, 0x33333333); 12692 exchangeLR.call(this, 16, 0x0000ffff); 12693 exchangeLR.call(this, 4, 0x0f0f0f0f); 12694 12695 // Set output 12696 M[offset] = this._lBlock; 12697 M[offset + 1] = this._rBlock; 12698 }, 12699 12700 keySize: 64/32, 12701 12702 ivSize: 64/32, 12703 12704 blockSize: 64/32 12705 }); 12706 12707 // Swap bits across the left and right words 12708 function exchangeLR(offset, mask) { 12709 var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; 12710 this._rBlock ^= t; 12711 this._lBlock ^= t << offset; 12712 } 12713 12714 function exchangeRL(offset, mask) { 12715 var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; 12716 this._lBlock ^= t; 12717 this._rBlock ^= t << offset; 12718 } 12719 12720 /** 12721 * Shortcut functions to the cipher's object interface. 12722 * 12723 * @example 12724 * 12725 * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); 12726 * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); 12727 */ 12728 C.DES = BlockCipher._createHelper(DES); 12729 12730 /** 12731 * Triple-DES block cipher algorithm. 12732 */ 12733 var TripleDES = C_algo.TripleDES = BlockCipher.extend({ 12734 _doReset: function () { 12735 // Shortcuts 12736 var key = this._key; 12737 var keyWords = key.words; 12738 12739 // Create DES instances 12740 this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); 12741 this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); 12742 this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); 12743 }, 12744 12745 encryptBlock: function (M, offset) { 12746 this._des1.encryptBlock(M, offset); 12747 this._des2.decryptBlock(M, offset); 12748 this._des3.encryptBlock(M, offset); 12749 }, 12750 12751 decryptBlock: function (M, offset) { 12752 this._des3.decryptBlock(M, offset); 12753 this._des2.encryptBlock(M, offset); 12754 this._des1.decryptBlock(M, offset); 12755 }, 12756 12757 keySize: 192/32, 12758 12759 ivSize: 64/32, 12760 12761 blockSize: 64/32 12762 }); 12763 12764 /** 12765 * Shortcut functions to the cipher's object interface. 12766 * 12767 * @example 12768 * 12769 * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); 12770 * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); 12771 */ 12772 C.TripleDES = BlockCipher._createHelper(TripleDES); 12773 }()); 12774 12775 12776 return CryptoJS.TripleDES; 12777 12778 })); 12779 },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],83:[function(require,module,exports){ 12780 ;(function (root, factory) { 12781 if (typeof exports === "object") { 12782 // CommonJS 12783 module.exports = exports = factory(require("./core")); 12784 } 12785 else if (typeof define === "function" && define.amd) { 12786 // AMD 12787 define(["./core"], factory); 12788 } 12789 else { 12790 // Global (browser) 12791 factory(root.CryptoJS); 12792 } 12793 }(this, function (CryptoJS) { 12794 12795 (function (undefined) { 12796 // Shortcuts 12797 var C = CryptoJS; 12798 var C_lib = C.lib; 12799 var Base = C_lib.Base; 12800 var X32WordArray = C_lib.WordArray; 12801 12802 /** 12803 * x64 namespace. 12804 */ 12805 var C_x64 = C.x64 = {}; 12806 12807 /** 12808 * A 64-bit word. 12809 */ 12810 var X64Word = C_x64.Word = Base.extend({ 12811 /** 12812 * Initializes a newly created 64-bit word. 12813 * 12814 * @param {number} high The high 32 bits. 12815 * @param {number} low The low 32 bits. 12816 * 12817 * @example 12818 * 12819 * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); 12820 */ 12821 init: function (high, low) { 12822 this.high = high; 12823 this.low = low; 12824 } 12825 12826 /** 12827 * Bitwise NOTs this word. 12828 * 12829 * @return {X64Word} A new x64-Word object after negating. 12830 * 12831 * @example 12832 * 12833 * var negated = x64Word.not(); 12834 */ 12835 // not: function () { 12836 // var high = ~this.high; 12837 // var low = ~this.low; 12838 12839 // return X64Word.create(high, low); 12840 // }, 12841 12842 /** 12843 * Bitwise ANDs this word with the passed word. 12844 * 12845 * @param {X64Word} word The x64-Word to AND with this word. 12846 * 12847 * @return {X64Word} A new x64-Word object after ANDing. 12848 * 12849 * @example 12850 * 12851 * var anded = x64Word.and(anotherX64Word); 12852 */ 12853 // and: function (word) { 12854 // var high = this.high & word.high; 12855 // var low = this.low & word.low; 12856 12857 // return X64Word.create(high, low); 12858 // }, 12859 12860 /** 12861 * Bitwise ORs this word with the passed word. 12862 * 12863 * @param {X64Word} word The x64-Word to OR with this word. 12864 * 12865 * @return {X64Word} A new x64-Word object after ORing. 12866 * 12867 * @example 12868 * 12869 * var ored = x64Word.or(anotherX64Word); 12870 */ 12871 // or: function (word) { 12872 // var high = this.high | word.high; 12873 // var low = this.low | word.low; 12874 12875 // return X64Word.create(high, low); 12876 // }, 12877 12878 /** 12879 * Bitwise XORs this word with the passed word. 12880 * 12881 * @param {X64Word} word The x64-Word to XOR with this word. 12882 * 12883 * @return {X64Word} A new x64-Word object after XORing. 12884 * 12885 * @example 12886 * 12887 * var xored = x64Word.xor(anotherX64Word); 12888 */ 12889 // xor: function (word) { 12890 // var high = this.high ^ word.high; 12891 // var low = this.low ^ word.low; 12892 12893 // return X64Word.create(high, low); 12894 // }, 12895 12896 /** 12897 * Shifts this word n bits to the left. 12898 * 12899 * @param {number} n The number of bits to shift. 12900 * 12901 * @return {X64Word} A new x64-Word object after shifting. 12902 * 12903 * @example 12904 * 12905 * var shifted = x64Word.shiftL(25); 12906 */ 12907 // shiftL: function (n) { 12908 // if (n < 32) { 12909 // var high = (this.high << n) | (this.low >>> (32 - n)); 12910 // var low = this.low << n; 12911 // } else { 12912 // var high = this.low << (n - 32); 12913 // var low = 0; 12914 // } 12915 12916 // return X64Word.create(high, low); 12917 // }, 12918 12919 /** 12920 * Shifts this word n bits to the right. 12921 * 12922 * @param {number} n The number of bits to shift. 12923 * 12924 * @return {X64Word} A new x64-Word object after shifting. 12925 * 12926 * @example 12927 * 12928 * var shifted = x64Word.shiftR(7); 12929 */ 12930 // shiftR: function (n) { 12931 // if (n < 32) { 12932 // var low = (this.low >>> n) | (this.high << (32 - n)); 12933 // var high = this.high >>> n; 12934 // } else { 12935 // var low = this.high >>> (n - 32); 12936 // var high = 0; 12937 // } 12938 12939 // return X64Word.create(high, low); 12940 // }, 12941 12942 /** 12943 * Rotates this word n bits to the left. 12944 * 12945 * @param {number} n The number of bits to rotate. 12946 * 12947 * @return {X64Word} A new x64-Word object after rotating. 12948 * 12949 * @example 12950 * 12951 * var rotated = x64Word.rotL(25); 12952 */ 12953 // rotL: function (n) { 12954 // return this.shiftL(n).or(this.shiftR(64 - n)); 12955 // }, 12956 12957 /** 12958 * Rotates this word n bits to the right. 12959 * 12960 * @param {number} n The number of bits to rotate. 12961 * 12962 * @return {X64Word} A new x64-Word object after rotating. 12963 * 12964 * @example 12965 * 12966 * var rotated = x64Word.rotR(7); 12967 */ 12968 // rotR: function (n) { 12969 // return this.shiftR(n).or(this.shiftL(64 - n)); 12970 // }, 12971 12972 /** 12973 * Adds this word with the passed word. 12974 * 12975 * @param {X64Word} word The x64-Word to add with this word. 12976 * 12977 * @return {X64Word} A new x64-Word object after adding. 12978 * 12979 * @example 12980 * 12981 * var added = x64Word.add(anotherX64Word); 12982 */ 12983 // add: function (word) { 12984 // var low = (this.low + word.low) | 0; 12985 // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; 12986 // var high = (this.high + word.high + carry) | 0; 12987 12988 // return X64Word.create(high, low); 12989 // } 12990 }); 12991 12992 /** 12993 * An array of 64-bit words. 12994 * 12995 * @property {Array} words The array of CryptoJS.x64.Word objects. 12996 * @property {number} sigBytes The number of significant bytes in this word array. 12997 */ 12998 var X64WordArray = C_x64.WordArray = Base.extend({ 12999 /** 13000 * Initializes a newly created word array. 13001 * 13002 * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. 13003 * @param {number} sigBytes (Optional) The number of significant bytes in the words. 13004 * 13005 * @example 13006 * 13007 * var wordArray = CryptoJS.x64.WordArray.create(); 13008 * 13009 * var wordArray = CryptoJS.x64.WordArray.create([ 13010 * CryptoJS.x64.Word.create(0x00010203, 0x04050607), 13011 * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) 13012 * ]); 13013 * 13014 * var wordArray = CryptoJS.x64.WordArray.create([ 13015 * CryptoJS.x64.Word.create(0x00010203, 0x04050607), 13016 * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) 13017 * ], 10); 13018 */ 13019 init: function (words, sigBytes) { 13020 words = this.words = words || []; 13021 13022 if (sigBytes != undefined) { 13023 this.sigBytes = sigBytes; 13024 } else { 13025 this.sigBytes = words.length * 8; 13026 } 13027 }, 13028 13029 /** 13030 * Converts this 64-bit word array to a 32-bit word array. 13031 * 13032 * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. 13033 * 13034 * @example 13035 * 13036 * var x32WordArray = x64WordArray.toX32(); 13037 */ 13038 toX32: function () { 13039 // Shortcuts 13040 var x64Words = this.words; 13041 var x64WordsLength = x64Words.length; 13042 13043 // Convert 13044 var x32Words = []; 13045 for (var i = 0; i < x64WordsLength; i++) { 13046 var x64Word = x64Words[i]; 13047 x32Words.push(x64Word.high); 13048 x32Words.push(x64Word.low); 13049 } 13050 13051 return X32WordArray.create(x32Words, this.sigBytes); 13052 }, 13053 13054 /** 13055 * Creates a copy of this word array. 13056 * 13057 * @return {X64WordArray} The clone. 13058 * 13059 * @example 13060 * 13061 * var clone = x64WordArray.clone(); 13062 */ 13063 clone: function () { 13064 var clone = Base.clone.call(this); 13065 13066 // Clone "words" array 13067 var words = clone.words = this.words.slice(0); 13068 13069 // Clone each X64Word object 13070 var wordsLength = words.length; 13071 for (var i = 0; i < wordsLength; i++) { 13072 words[i] = words[i].clone(); 13073 } 13074 13075 return clone; 13076 } 13077 }); 13078 }()); 13079 13080 13081 return CryptoJS; 13082 13083 })); 13084 },{"./core":52}],84:[function(require,module,exports){ 13085 /*! https://mths.be/utf8js v2.0.0 by @mathias */ 13086 ;(function(root) { 13087 13088 // Detect free variables exports 13089 var freeExports = typeof exports == 'object' && exports; 13090 13091 // Detect free variable module 13092 var freeModule = typeof module == 'object' && module && 13093 module.exports == freeExports && module; 13094 13095 // Detect free variable global, from Node.js or Browserified code, 13096 // and use it as root 13097 var freeGlobal = typeof global == 'object' && global; 13098 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { 13099 root = freeGlobal; 13100 } 13101 13102 /*--------------------------------------------------------------------------*/ 13103 13104 var stringFromCharCode = String.fromCharCode; 13105 13106 // Taken from https://mths.be/punycode 13107 function ucs2decode(string) { 13108 var output = []; 13109 var counter = 0; 13110 var length = string.length; 13111 var value; 13112 var extra; 13113 while (counter < length) { 13114 value = string.charCodeAt(counter++); 13115 if (value >= 0xD800 && value <= 0xDBFF && counter < length) { 13116 // high surrogate, and there is a next character 13117 extra = string.charCodeAt(counter++); 13118 if ((extra & 0xFC00) == 0xDC00) { // low surrogate 13119 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); 13120 } else { 13121 // unmatched surrogate; only append this code unit, in case the next 13122 // code unit is the high surrogate of a surrogate pair 13123 output.push(value); 13124 counter--; 13125 } 13126 } else { 13127 output.push(value); 13128 } 13129 } 13130 return output; 13131 } 13132 13133 // Taken from https://mths.be/punycode 13134 function ucs2encode(array) { 13135 var length = array.length; 13136 var index = -1; 13137 var value; 13138 var output = ''; 13139 while (++index < length) { 13140 value = array[index]; 13141 if (value > 0xFFFF) { 13142 value -= 0x10000; 13143 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); 13144 value = 0xDC00 | value & 0x3FF; 13145 } 13146 output += stringFromCharCode(value); 13147 } 13148 return output; 13149 } 13150 13151 function checkScalarValue(codePoint) { 13152 if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { 13153 throw Error( 13154 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + 13155 ' is not a scalar value' 13156 ); 13157 } 13158 } 13159 /*--------------------------------------------------------------------------*/ 13160 13161 function createByte(codePoint, shift) { 13162 return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); 13163 } 13164 13165 function encodeCodePoint(codePoint) { 13166 if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence 13167 return stringFromCharCode(codePoint); 13168 } 13169 var symbol = ''; 13170 if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence 13171 symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); 13172 } 13173 else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence 13174 checkScalarValue(codePoint); 13175 symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); 13176 symbol += createByte(codePoint, 6); 13177 } 13178 else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence 13179 symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); 13180 symbol += createByte(codePoint, 12); 13181 symbol += createByte(codePoint, 6); 13182 } 13183 symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); 13184 return symbol; 13185 } 13186 13187 function utf8encode(string) { 13188 var codePoints = ucs2decode(string); 13189 var length = codePoints.length; 13190 var index = -1; 13191 var codePoint; 13192 var byteString = ''; 13193 while (++index < length) { 13194 codePoint = codePoints[index]; 13195 byteString += encodeCodePoint(codePoint); 13196 } 13197 return byteString; 13198 } 13199 13200 /*--------------------------------------------------------------------------*/ 13201 13202 function readContinuationByte() { 13203 if (byteIndex >= byteCount) { 13204 throw Error('Invalid byte index'); 13205 } 13206 13207 var continuationByte = byteArray[byteIndex] & 0xFF; 13208 byteIndex++; 13209 13210 if ((continuationByte & 0xC0) == 0x80) { 13211 return continuationByte & 0x3F; 13212 } 13213 13214 // If we end up here, it’s not a continuation byte 13215 throw Error('Invalid continuation byte'); 13216 } 13217 13218 function decodeSymbol() { 13219 var byte1; 13220 var byte2; 13221 var byte3; 13222 var byte4; 13223 var codePoint; 13224 13225 if (byteIndex > byteCount) { 13226 throw Error('Invalid byte index'); 13227 } 13228 13229 if (byteIndex == byteCount) { 13230 return false; 13231 } 13232 13233 // Read first byte 13234 byte1 = byteArray[byteIndex] & 0xFF; 13235 byteIndex++; 13236 13237 // 1-byte sequence (no continuation bytes) 13238 if ((byte1 & 0x80) == 0) { 13239 return byte1; 13240 } 13241 13242 // 2-byte sequence 13243 if ((byte1 & 0xE0) == 0xC0) { 13244 var byte2 = readContinuationByte(); 13245 codePoint = ((byte1 & 0x1F) << 6) | byte2; 13246 if (codePoint >= 0x80) { 13247 return codePoint; 13248 } else { 13249 throw Error('Invalid continuation byte'); 13250 } 13251 } 13252 13253 // 3-byte sequence (may include unpaired surrogates) 13254 if ((byte1 & 0xF0) == 0xE0) { 13255 byte2 = readContinuationByte(); 13256 byte3 = readContinuationByte(); 13257 codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; 13258 if (codePoint >= 0x0800) { 13259 checkScalarValue(codePoint); 13260 return codePoint; 13261 } else { 13262 throw Error('Invalid continuation byte'); 13263 } 13264 } 13265 13266 // 4-byte sequence 13267 if ((byte1 & 0xF8) == 0xF0) { 13268 byte2 = readContinuationByte(); 13269 byte3 = readContinuationByte(); 13270 byte4 = readContinuationByte(); 13271 codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) | 13272 (byte3 << 0x06) | byte4; 13273 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { 13274 return codePoint; 13275 } 13276 } 13277 13278 throw Error('Invalid UTF-8 detected'); 13279 } 13280 13281 var byteArray; 13282 var byteCount; 13283 var byteIndex; 13284 function utf8decode(byteString) { 13285 byteArray = ucs2decode(byteString); 13286 byteCount = byteArray.length; 13287 byteIndex = 0; 13288 var codePoints = []; 13289 var tmp; 13290 while ((tmp = decodeSymbol()) !== false) { 13291 codePoints.push(tmp); 13292 } 13293 return ucs2encode(codePoints); 13294 } 13295 13296 /*--------------------------------------------------------------------------*/ 13297 13298 var utf8 = { 13299 'version': '2.0.0', 13300 'encode': utf8encode, 13301 'decode': utf8decode 13302 }; 13303 13304 // Some AMD build optimizers, like r.js, check for specific condition patterns 13305 // like the following: 13306 if ( 13307 typeof define == 'function' && 13308 typeof define.amd == 'object' && 13309 define.amd 13310 ) { 13311 define(function() { 13312 return utf8; 13313 }); 13314 } else if (freeExports && !freeExports.nodeType) { 13315 if (freeModule) { // in Node.js or RingoJS v0.8.0+ 13316 freeModule.exports = utf8; 13317 } else { // in Narwhal or RingoJS v0.7.0- 13318 var object = {}; 13319 var hasOwnProperty = object.hasOwnProperty; 13320 for (var key in utf8) { 13321 hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); 13322 } 13323 } 13324 } else { // in Rhino or a web browser 13325 root.utf8 = utf8; 13326 } 13327 13328 }(this)); 13329 13330 },{}],"bignumber.js":[function(require,module,exports){ 13331 /*! bignumber.js v2.0.7 https://github.com/MikeMcl/bignumber.js/LICENCE */ 13332 13333 ;(function (global) { 13334 'use strict'; 13335 13336 /* 13337 bignumber.js v2.0.7 13338 A JavaScript library for arbitrary-precision arithmetic. 13339 https://github.com/MikeMcl/bignumber.js 13340 Copyright (c) 2015 Michael Mclaughlin <M8ch88l@gmail.com> 13341 MIT Expat Licence 13342 */ 13343 13344 13345 var BigNumber, crypto, parseNumeric, 13346 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, 13347 mathceil = Math.ceil, 13348 mathfloor = Math.floor, 13349 notBool = ' not a boolean or binary digit', 13350 roundingMode = 'rounding mode', 13351 tooManyDigits = 'number type has more than 15 significant digits', 13352 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_', 13353 BASE = 1e14, 13354 LOG_BASE = 14, 13355 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 13356 // MAX_INT32 = 0x7fffffff, // 2^31 - 1 13357 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], 13358 SQRT_BASE = 1e7, 13359 13360 /* 13361 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and 13362 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an 13363 * exception is thrown (if ERRORS is true). 13364 */ 13365 MAX = 1E9; // 0 to MAX_INT32 13366 13367 13368 /* 13369 * Create and return a BigNumber constructor. 13370 */ 13371 function another(configObj) { 13372 var div, 13373 13374 // id tracks the caller function, so its name can be included in error messages. 13375 id = 0, 13376 P = BigNumber.prototype, 13377 ONE = new BigNumber(1), 13378 13379 13380 /********************************* EDITABLE DEFAULTS **********************************/ 13381 13382 13383 /* 13384 * The default values below must be integers within the inclusive ranges stated. 13385 * The values can also be changed at run-time using BigNumber.config. 13386 */ 13387 13388 // The maximum number of decimal places for operations involving division. 13389 DECIMAL_PLACES = 20, // 0 to MAX 13390 13391 /* 13392 * The rounding mode used when rounding to the above decimal places, and when using 13393 * toExponential, toFixed, toFormat and toPrecision, and round (default value). 13394 * UP 0 Away from zero. 13395 * DOWN 1 Towards zero. 13396 * CEIL 2 Towards +Infinity. 13397 * FLOOR 3 Towards -Infinity. 13398 * HALF_UP 4 Towards nearest neighbour. If equidistant, up. 13399 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. 13400 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. 13401 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. 13402 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. 13403 */ 13404 ROUNDING_MODE = 4, // 0 to 8 13405 13406 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] 13407 13408 // The exponent value at and beneath which toString returns exponential notation. 13409 // Number type: -7 13410 TO_EXP_NEG = -7, // 0 to -MAX 13411 13412 // The exponent value at and above which toString returns exponential notation. 13413 // Number type: 21 13414 TO_EXP_POS = 21, // 0 to MAX 13415 13416 // RANGE : [MIN_EXP, MAX_EXP] 13417 13418 // The minimum exponent value, beneath which underflow to zero occurs. 13419 // Number type: -324 (5e-324) 13420 MIN_EXP = -1e7, // -1 to -MAX 13421 13422 // The maximum exponent value, above which overflow to Infinity occurs. 13423 // Number type: 308 (1.7976931348623157e+308) 13424 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. 13425 MAX_EXP = 1e7, // 1 to MAX 13426 13427 // Whether BigNumber Errors are ever thrown. 13428 ERRORS = true, // true or false 13429 13430 // Change to intValidatorNoErrors if ERRORS is false. 13431 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors 13432 13433 // Whether to use cryptographically-secure random number generation, if available. 13434 CRYPTO = false, // true or false 13435 13436 /* 13437 * The modulo mode used when calculating the modulus: a mod n. 13438 * The quotient (q = a / n) is calculated according to the corresponding rounding mode. 13439 * The remainder (r) is calculated as: r = a - n * q. 13440 * 13441 * UP 0 The remainder is positive if the dividend is negative, else is negative. 13442 * DOWN 1 The remainder has the same sign as the dividend. 13443 * This modulo mode is commonly known as 'truncated division' and is 13444 * equivalent to (a % n) in JavaScript. 13445 * FLOOR 3 The remainder has the same sign as the divisor (Python %). 13446 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. 13447 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). 13448 * The remainder is always positive. 13449 * 13450 * The truncated division, floored division, Euclidian division and IEEE 754 remainder 13451 * modes are commonly used for the modulus operation. 13452 * Although the other rounding modes can also be used, they may not give useful results. 13453 */ 13454 MODULO_MODE = 1, // 0 to 9 13455 13456 // The maximum number of significant digits of the result of the toPower operation. 13457 // If POW_PRECISION is 0, there will be unlimited significant digits. 13458 POW_PRECISION = 100, // 0 to MAX 13459 13460 // The format specification used by the BigNumber.prototype.toFormat method. 13461 FORMAT = { 13462 decimalSeparator: '.', 13463 groupSeparator: ',', 13464 groupSize: 3, 13465 secondaryGroupSize: 0, 13466 fractionGroupSeparator: '\xA0', // non-breaking space 13467 fractionGroupSize: 0 13468 }; 13469 13470 13471 /******************************************************************************************/ 13472 13473 13474 // CONSTRUCTOR 13475 13476 13477 /* 13478 * The BigNumber constructor and exported function. 13479 * Create and return a new instance of a BigNumber object. 13480 * 13481 * n {number|string|BigNumber} A numeric value. 13482 * [b] {number} The base of n. Integer, 2 to 64 inclusive. 13483 */ 13484 function BigNumber( n, b ) { 13485 var c, e, i, num, len, str, 13486 x = this; 13487 13488 // Enable constructor usage without new. 13489 if ( !( x instanceof BigNumber ) ) { 13490 13491 // 'BigNumber() constructor call without new: {n}' 13492 if (ERRORS) raise( 26, 'constructor call without new', n ); 13493 return new BigNumber( n, b ); 13494 } 13495 13496 // 'new BigNumber() base not an integer: {b}' 13497 // 'new BigNumber() base out of range: {b}' 13498 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { 13499 13500 // Duplicate. 13501 if ( n instanceof BigNumber ) { 13502 x.s = n.s; 13503 x.e = n.e; 13504 x.c = ( n = n.c ) ? n.slice() : n; 13505 id = 0; 13506 return; 13507 } 13508 13509 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { 13510 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; 13511 13512 // Fast path for integers. 13513 if ( n === ~~n ) { 13514 for ( e = 0, i = n; i >= 10; i /= 10, e++ ); 13515 x.e = e; 13516 x.c = [n]; 13517 id = 0; 13518 return; 13519 } 13520 13521 str = n + ''; 13522 } else { 13523 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); 13524 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; 13525 } 13526 } else { 13527 b = b | 0; 13528 str = n + ''; 13529 13530 // Ensure return value is rounded to DECIMAL_PLACES as with other bases. 13531 // Allow exponential notation to be used with base 10 argument. 13532 if ( b == 10 ) { 13533 x = new BigNumber( n instanceof BigNumber ? n : str ); 13534 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); 13535 } 13536 13537 // Avoid potential interpretation of Infinity and NaN as base 44+ values. 13538 // Any number in exponential form will fail due to the [Ee][+-]. 13539 if ( ( num = typeof n == 'number' ) && n * 0 != 0 || 13540 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + 13541 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { 13542 return parseNumeric( x, str, num, b ); 13543 } 13544 13545 if (num) { 13546 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; 13547 13548 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { 13549 13550 // 'new BigNumber() number type has more than 15 significant digits: {n}' 13551 raise( id, tooManyDigits, n ); 13552 } 13553 13554 // Prevent later check for length on converted number. 13555 num = false; 13556 } else { 13557 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; 13558 } 13559 13560 str = convertBase( str, 10, b, x.s ); 13561 } 13562 13563 // Decimal point? 13564 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); 13565 13566 // Exponential form? 13567 if ( ( i = str.search( /e/i ) ) > 0 ) { 13568 13569 // Determine exponent. 13570 if ( e < 0 ) e = i; 13571 e += +str.slice( i + 1 ); 13572 str = str.substring( 0, i ); 13573 } else if ( e < 0 ) { 13574 13575 // Integer. 13576 e = str.length; 13577 } 13578 13579 // Determine leading zeros. 13580 for ( i = 0; str.charCodeAt(i) === 48; i++ ); 13581 13582 // Determine trailing zeros. 13583 for ( len = str.length; str.charCodeAt(--len) === 48; ); 13584 str = str.slice( i, len + 1 ); 13585 13586 if (str) { 13587 len = str.length; 13588 13589 // Disallow numbers with over 15 significant digits if number type. 13590 // 'new BigNumber() number type has more than 15 significant digits: {n}' 13591 if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n ); 13592 13593 e = e - i - 1; 13594 13595 // Overflow? 13596 if ( e > MAX_EXP ) { 13597 13598 // Infinity. 13599 x.c = x.e = null; 13600 13601 // Underflow? 13602 } else if ( e < MIN_EXP ) { 13603 13604 // Zero. 13605 x.c = [ x.e = 0 ]; 13606 } else { 13607 x.e = e; 13608 x.c = []; 13609 13610 // Transform base 13611 13612 // e is the base 10 exponent. 13613 // i is where to slice str to get the first element of the coefficient array. 13614 i = ( e + 1 ) % LOG_BASE; 13615 if ( e < 0 ) i += LOG_BASE; 13616 13617 if ( i < len ) { 13618 if (i) x.c.push( +str.slice( 0, i ) ); 13619 13620 for ( len -= LOG_BASE; i < len; ) { 13621 x.c.push( +str.slice( i, i += LOG_BASE ) ); 13622 } 13623 13624 str = str.slice(i); 13625 i = LOG_BASE - str.length; 13626 } else { 13627 i -= len; 13628 } 13629 13630 for ( ; i--; str += '0' ); 13631 x.c.push( +str ); 13632 } 13633 } else { 13634 13635 // Zero. 13636 x.c = [ x.e = 0 ]; 13637 } 13638 13639 id = 0; 13640 } 13641 13642 13643 // CONSTRUCTOR PROPERTIES 13644 13645 13646 BigNumber.another = another; 13647 13648 BigNumber.ROUND_UP = 0; 13649 BigNumber.ROUND_DOWN = 1; 13650 BigNumber.ROUND_CEIL = 2; 13651 BigNumber.ROUND_FLOOR = 3; 13652 BigNumber.ROUND_HALF_UP = 4; 13653 BigNumber.ROUND_HALF_DOWN = 5; 13654 BigNumber.ROUND_HALF_EVEN = 6; 13655 BigNumber.ROUND_HALF_CEIL = 7; 13656 BigNumber.ROUND_HALF_FLOOR = 8; 13657 BigNumber.EUCLID = 9; 13658 13659 13660 /* 13661 * Configure infrequently-changing library-wide settings. 13662 * 13663 * Accept an object or an argument list, with one or many of the following properties or 13664 * parameters respectively: 13665 * 13666 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive 13667 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive 13668 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or 13669 * [integer -MAX to 0 incl., 0 to MAX incl.] 13670 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or 13671 * [integer -MAX to -1 incl., integer 1 to MAX incl.] 13672 * ERRORS {boolean|number} true, false, 1 or 0 13673 * CRYPTO {boolean|number} true, false, 1 or 0 13674 * MODULO_MODE {number} 0 to 9 inclusive 13675 * POW_PRECISION {number} 0 to MAX inclusive 13676 * FORMAT {object} See BigNumber.prototype.toFormat 13677 * decimalSeparator {string} 13678 * groupSeparator {string} 13679 * groupSize {number} 13680 * secondaryGroupSize {number} 13681 * fractionGroupSeparator {string} 13682 * fractionGroupSize {number} 13683 * 13684 * (The values assigned to the above FORMAT object properties are not checked for validity.) 13685 * 13686 * E.g. 13687 * BigNumber.config(20, 4) is equivalent to 13688 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) 13689 * 13690 * Ignore properties/parameters set to null or undefined. 13691 * Return an object with the properties current values. 13692 */ 13693 BigNumber.config = function () { 13694 var v, p, 13695 i = 0, 13696 r = {}, 13697 a = arguments, 13698 o = a[0], 13699 has = o && typeof o == 'object' 13700 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; } 13701 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; }; 13702 13703 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. 13704 // 'config() DECIMAL_PLACES not an integer: {v}' 13705 // 'config() DECIMAL_PLACES out of range: {v}' 13706 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) { 13707 DECIMAL_PLACES = v | 0; 13708 } 13709 r[p] = DECIMAL_PLACES; 13710 13711 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. 13712 // 'config() ROUNDING_MODE not an integer: {v}' 13713 // 'config() ROUNDING_MODE out of range: {v}' 13714 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) { 13715 ROUNDING_MODE = v | 0; 13716 } 13717 r[p] = ROUNDING_MODE; 13718 13719 // EXPONENTIAL_AT {number|number[]} 13720 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive]. 13721 // 'config() EXPONENTIAL_AT not an integer: {v}' 13722 // 'config() EXPONENTIAL_AT out of range: {v}' 13723 if ( has( p = 'EXPONENTIAL_AT' ) ) { 13724 13725 if ( isArray(v) ) { 13726 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) { 13727 TO_EXP_NEG = v[0] | 0; 13728 TO_EXP_POS = v[1] | 0; 13729 } 13730 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { 13731 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); 13732 } 13733 } 13734 r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; 13735 13736 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or 13737 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. 13738 // 'config() RANGE not an integer: {v}' 13739 // 'config() RANGE cannot be zero: {v}' 13740 // 'config() RANGE out of range: {v}' 13741 if ( has( p = 'RANGE' ) ) { 13742 13743 if ( isArray(v) ) { 13744 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { 13745 MIN_EXP = v[0] | 0; 13746 MAX_EXP = v[1] | 0; 13747 } 13748 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { 13749 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 ); 13750 else if (ERRORS) raise( 2, p + ' cannot be zero', v ); 13751 } 13752 } 13753 r[p] = [ MIN_EXP, MAX_EXP ]; 13754 13755 // ERRORS {boolean|number} true, false, 1 or 0. 13756 // 'config() ERRORS not a boolean or binary digit: {v}' 13757 if ( has( p = 'ERRORS' ) ) { 13758 13759 if ( v === !!v || v === 1 || v === 0 ) { 13760 id = 0; 13761 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; 13762 } else if (ERRORS) { 13763 raise( 2, p + notBool, v ); 13764 } 13765 } 13766 r[p] = ERRORS; 13767 13768 // CRYPTO {boolean|number} true, false, 1 or 0. 13769 // 'config() CRYPTO not a boolean or binary digit: {v}' 13770 // 'config() crypto unavailable: {crypto}' 13771 if ( has( p = 'CRYPTO' ) ) { 13772 13773 if ( v === !!v || v === 1 || v === 0 ) { 13774 CRYPTO = !!( v && crypto && typeof crypto == 'object' ); 13775 if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', crypto ); 13776 } else if (ERRORS) { 13777 raise( 2, p + notBool, v ); 13778 } 13779 } 13780 r[p] = CRYPTO; 13781 13782 // MODULO_MODE {number} Integer, 0 to 9 inclusive. 13783 // 'config() MODULO_MODE not an integer: {v}' 13784 // 'config() MODULO_MODE out of range: {v}' 13785 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) { 13786 MODULO_MODE = v | 0; 13787 } 13788 r[p] = MODULO_MODE; 13789 13790 // POW_PRECISION {number} Integer, 0 to MAX inclusive. 13791 // 'config() POW_PRECISION not an integer: {v}' 13792 // 'config() POW_PRECISION out of range: {v}' 13793 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) { 13794 POW_PRECISION = v | 0; 13795 } 13796 r[p] = POW_PRECISION; 13797 13798 // FORMAT {object} 13799 // 'config() FORMAT not an object: {v}' 13800 if ( has( p = 'FORMAT' ) ) { 13801 13802 if ( typeof v == 'object' ) { 13803 FORMAT = v; 13804 } else if (ERRORS) { 13805 raise( 2, p + ' not an object', v ); 13806 } 13807 } 13808 r[p] = FORMAT; 13809 13810 return r; 13811 }; 13812 13813 13814 /* 13815 * Return a new BigNumber whose value is the maximum of the arguments. 13816 * 13817 * arguments {number|string|BigNumber} 13818 */ 13819 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); }; 13820 13821 13822 /* 13823 * Return a new BigNumber whose value is the minimum of the arguments. 13824 * 13825 * arguments {number|string|BigNumber} 13826 */ 13827 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); }; 13828 13829 13830 /* 13831 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, 13832 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing 13833 * zeros are produced). 13834 * 13835 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 13836 * 13837 * 'random() decimal places not an integer: {dp}' 13838 * 'random() decimal places out of range: {dp}' 13839 * 'random() crypto unavailable: {crypto}' 13840 */ 13841 BigNumber.random = (function () { 13842 var pow2_53 = 0x20000000000000; 13843 13844 // Return a 53 bit integer n, where 0 <= n < 9007199254740992. 13845 // Check if Math.random() produces more than 32 bits of randomness. 13846 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. 13847 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. 13848 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff 13849 ? function () { return mathfloor( Math.random() * pow2_53 ); } 13850 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + 13851 (Math.random() * 0x800000 | 0); }; 13852 13853 return function (dp) { 13854 var a, b, e, k, v, 13855 i = 0, 13856 c = [], 13857 rand = new BigNumber(ONE); 13858 13859 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; 13860 k = mathceil( dp / LOG_BASE ); 13861 13862 if (CRYPTO) { 13863 13864 // Browsers supporting crypto.getRandomValues. 13865 if ( crypto && crypto.getRandomValues ) { 13866 13867 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); 13868 13869 for ( ; i < k; ) { 13870 13871 // 53 bits: 13872 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) 13873 // 11111 11111111 11111111 11111111 11100000 00000000 00000000 13874 // ((Math.pow(2, 32) - 1) >>> 11).toString(2) 13875 // 11111 11111111 11111111 13876 // 0x20000 is 2^21. 13877 v = a[i] * 0x20000 + (a[i + 1] >>> 11); 13878 13879 // Rejection sampling: 13880 // 0 <= v < 9007199254740992 13881 // Probability that v >= 9e15, is 13882 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 13883 if ( v >= 9e15 ) { 13884 b = crypto.getRandomValues( new Uint32Array(2) ); 13885 a[i] = b[0]; 13886 a[i + 1] = b[1]; 13887 } else { 13888 13889 // 0 <= v <= 8999999999999999 13890 // 0 <= (v % 1e14) <= 99999999999999 13891 c.push( v % 1e14 ); 13892 i += 2; 13893 } 13894 } 13895 i = k / 2; 13896 13897 // Node.js supporting crypto.randomBytes. 13898 } else if ( crypto && crypto.randomBytes ) { 13899 13900 // buffer 13901 a = crypto.randomBytes( k *= 7 ); 13902 13903 for ( ; i < k; ) { 13904 13905 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 13906 // 0x100000000 is 2^32, 0x1000000 is 2^24 13907 // 11111 11111111 11111111 11111111 11111111 11111111 11111111 13908 // 0 <= v < 9007199254740992 13909 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + 13910 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + 13911 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; 13912 13913 if ( v >= 9e15 ) { 13914 crypto.randomBytes(7).copy( a, i ); 13915 } else { 13916 13917 // 0 <= (v % 1e14) <= 99999999999999 13918 c.push( v % 1e14 ); 13919 i += 7; 13920 } 13921 } 13922 i = k / 7; 13923 } else if (ERRORS) { 13924 raise( 14, 'crypto unavailable', crypto ); 13925 } 13926 } 13927 13928 // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false. 13929 if (!i) { 13930 13931 for ( ; i < k; ) { 13932 v = random53bitInt(); 13933 if ( v < 9e15 ) c[i++] = v % 1e14; 13934 } 13935 } 13936 13937 k = c[--i]; 13938 dp %= LOG_BASE; 13939 13940 // Convert trailing digits to zeros according to dp. 13941 if ( k && dp ) { 13942 v = POWS_TEN[LOG_BASE - dp]; 13943 c[i] = mathfloor( k / v ) * v; 13944 } 13945 13946 // Remove trailing elements which are zero. 13947 for ( ; c[i] === 0; c.pop(), i-- ); 13948 13949 // Zero? 13950 if ( i < 0 ) { 13951 c = [ e = 0 ]; 13952 } else { 13953 13954 // Remove leading elements which are zero and adjust exponent accordingly. 13955 for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE); 13956 13957 // Count the digits of the first element of c to determine leading zeros, and... 13958 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); 13959 13960 // adjust the exponent accordingly. 13961 if ( i < LOG_BASE ) e -= LOG_BASE - i; 13962 } 13963 13964 rand.e = e; 13965 rand.c = c; 13966 return rand; 13967 }; 13968 })(); 13969 13970 13971 // PRIVATE FUNCTIONS 13972 13973 13974 // Convert a numeric string of baseIn to a numeric string of baseOut. 13975 function convertBase( str, baseOut, baseIn, sign ) { 13976 var d, e, k, r, x, xc, y, 13977 i = str.indexOf( '.' ), 13978 dp = DECIMAL_PLACES, 13979 rm = ROUNDING_MODE; 13980 13981 if ( baseIn < 37 ) str = str.toLowerCase(); 13982 13983 // Non-integer. 13984 if ( i >= 0 ) { 13985 k = POW_PRECISION; 13986 13987 // Unlimited precision. 13988 POW_PRECISION = 0; 13989 str = str.replace( '.', '' ); 13990 y = new BigNumber(baseIn); 13991 x = y.pow( str.length - i ); 13992 POW_PRECISION = k; 13993 13994 // Convert str as if an integer, then restore the fraction part by dividing the 13995 // result by its base raised to a power. 13996 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut ); 13997 y.e = y.c.length; 13998 } 13999 14000 // Convert the number as integer. 14001 xc = toBaseOut( str, baseIn, baseOut ); 14002 e = k = xc.length; 14003 14004 // Remove trailing zeros. 14005 for ( ; xc[--k] == 0; xc.pop() ); 14006 if ( !xc[0] ) return '0'; 14007 14008 if ( i < 0 ) { 14009 --e; 14010 } else { 14011 x.c = xc; 14012 x.e = e; 14013 14014 // sign is needed for correct rounding. 14015 x.s = sign; 14016 x = div( x, y, dp, rm, baseOut ); 14017 xc = x.c; 14018 r = x.r; 14019 e = x.e; 14020 } 14021 14022 d = e + dp + 1; 14023 14024 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up. 14025 i = xc[d]; 14026 k = baseOut / 2; 14027 r = r || d < 0 || xc[d + 1] != null; 14028 14029 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) 14030 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || 14031 rm == ( x.s < 0 ? 8 : 7 ) ); 14032 14033 if ( d < 1 || !xc[0] ) { 14034 14035 // 1^-dp or 0. 14036 str = r ? toFixedPoint( '1', -dp ) : '0'; 14037 } else { 14038 xc.length = d; 14039 14040 if (r) { 14041 14042 // Rounding up may mean the previous digit has to be rounded up and so on. 14043 for ( --baseOut; ++xc[--d] > baseOut; ) { 14044 xc[d] = 0; 14045 14046 if ( !d ) { 14047 ++e; 14048 xc.unshift(1); 14049 } 14050 } 14051 } 14052 14053 // Determine trailing zeros. 14054 for ( k = xc.length; !xc[--k]; ); 14055 14056 // E.g. [4, 11, 15] becomes 4bf. 14057 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) ); 14058 str = toFixedPoint( str, e ); 14059 } 14060 14061 // The caller will add the sign. 14062 return str; 14063 } 14064 14065 14066 // Perform division in the specified base. Called by div and convertBase. 14067 div = (function () { 14068 14069 // Assume non-zero x and k. 14070 function multiply( x, k, base ) { 14071 var m, temp, xlo, xhi, 14072 carry = 0, 14073 i = x.length, 14074 klo = k % SQRT_BASE, 14075 khi = k / SQRT_BASE | 0; 14076 14077 for ( x = x.slice(); i--; ) { 14078 xlo = x[i] % SQRT_BASE; 14079 xhi = x[i] / SQRT_BASE | 0; 14080 m = khi * xlo + xhi * klo; 14081 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry; 14082 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi; 14083 x[i] = temp % base; 14084 } 14085 14086 if (carry) x.unshift(carry); 14087 14088 return x; 14089 } 14090 14091 function compare( a, b, aL, bL ) { 14092 var i, cmp; 14093 14094 if ( aL != bL ) { 14095 cmp = aL > bL ? 1 : -1; 14096 } else { 14097 14098 for ( i = cmp = 0; i < aL; i++ ) { 14099 14100 if ( a[i] != b[i] ) { 14101 cmp = a[i] > b[i] ? 1 : -1; 14102 break; 14103 } 14104 } 14105 } 14106 return cmp; 14107 } 14108 14109 function subtract( a, b, aL, base ) { 14110 var i = 0; 14111 14112 // Subtract b from a. 14113 for ( ; aL--; ) { 14114 a[aL] -= i; 14115 i = a[aL] < b[aL] ? 1 : 0; 14116 a[aL] = i * base + a[aL] - b[aL]; 14117 } 14118 14119 // Remove leading zeros. 14120 for ( ; !a[0] && a.length > 1; a.shift() ); 14121 } 14122 14123 // x: dividend, y: divisor. 14124 return function ( x, y, dp, rm, base ) { 14125 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, 14126 yL, yz, 14127 s = x.s == y.s ? 1 : -1, 14128 xc = x.c, 14129 yc = y.c; 14130 14131 // Either NaN, Infinity or 0? 14132 if ( !xc || !xc[0] || !yc || !yc[0] ) { 14133 14134 return new BigNumber( 14135 14136 // Return NaN if either NaN, or both Infinity or 0. 14137 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : 14138 14139 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. 14140 xc && xc[0] == 0 || !yc ? s * 0 : s / 0 14141 ); 14142 } 14143 14144 q = new BigNumber(s); 14145 qc = q.c = []; 14146 e = x.e - y.e; 14147 s = dp + e + 1; 14148 14149 if ( !base ) { 14150 base = BASE; 14151 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); 14152 s = s / LOG_BASE | 0; 14153 } 14154 14155 // Result exponent may be one less then the current value of e. 14156 // The coefficients of the BigNumbers from convertBase may have trailing zeros. 14157 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ ); 14158 if ( yc[i] > ( xc[i] || 0 ) ) e--; 14159 14160 if ( s < 0 ) { 14161 qc.push(1); 14162 more = true; 14163 } else { 14164 xL = xc.length; 14165 yL = yc.length; 14166 i = 0; 14167 s += 2; 14168 14169 // Normalise xc and yc so highest order digit of yc is >= base / 2. 14170 14171 n = mathfloor( base / ( yc[0] + 1 ) ); 14172 14173 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. 14174 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { 14175 if ( n > 1 ) { 14176 yc = multiply( yc, n, base ); 14177 xc = multiply( xc, n, base ); 14178 yL = yc.length; 14179 xL = xc.length; 14180 } 14181 14182 xi = yL; 14183 rem = xc.slice( 0, yL ); 14184 remL = rem.length; 14185 14186 // Add zeros to make remainder as long as divisor. 14187 for ( ; remL < yL; rem[remL++] = 0 ); 14188 yz = yc.slice(); 14189 yz.unshift(0); 14190 yc0 = yc[0]; 14191 if ( yc[1] >= base / 2 ) yc0++; 14192 // Not necessary, but to prevent trial digit n > base, when using base 3. 14193 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15; 14194 14195 do { 14196 n = 0; 14197 14198 // Compare divisor and remainder. 14199 cmp = compare( yc, rem, yL, remL ); 14200 14201 // If divisor < remainder. 14202 if ( cmp < 0 ) { 14203 14204 // Calculate trial digit, n. 14205 14206 rem0 = rem[0]; 14207 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); 14208 14209 // n is how many times the divisor goes into the current remainder. 14210 n = mathfloor( rem0 / yc0 ); 14211 14212 // Algorithm: 14213 // 1. product = divisor * trial digit (n) 14214 // 2. if product > remainder: product -= divisor, n-- 14215 // 3. remainder -= product 14216 // 4. if product was < remainder at 2: 14217 // 5. compare new remainder and divisor 14218 // 6. If remainder > divisor: remainder -= divisor, n++ 14219 14220 if ( n > 1 ) { 14221 14222 // n may be > base only when base is 3. 14223 if (n >= base) n = base - 1; 14224 14225 // product = divisor * trial digit. 14226 prod = multiply( yc, n, base ); 14227 prodL = prod.length; 14228 remL = rem.length; 14229 14230 // Compare product and remainder. 14231 // If product > remainder. 14232 // Trial digit n too high. 14233 // n is 1 too high about 5% of the time, and is not known to have 14234 // ever been more than 1 too high. 14235 while ( compare( prod, rem, prodL, remL ) == 1 ) { 14236 n--; 14237 14238 // Subtract divisor from product. 14239 subtract( prod, yL < prodL ? yz : yc, prodL, base ); 14240 prodL = prod.length; 14241 cmp = 1; 14242 } 14243 } else { 14244 14245 // n is 0 or 1, cmp is -1. 14246 // If n is 0, there is no need to compare yc and rem again below, 14247 // so change cmp to 1 to avoid it. 14248 // If n is 1, leave cmp as -1, so yc and rem are compared again. 14249 if ( n == 0 ) { 14250 14251 // divisor < remainder, so n must be at least 1. 14252 cmp = n = 1; 14253 } 14254 14255 // product = divisor 14256 prod = yc.slice(); 14257 prodL = prod.length; 14258 } 14259 14260 if ( prodL < remL ) prod.unshift(0); 14261 14262 // Subtract product from remainder. 14263 subtract( rem, prod, remL, base ); 14264 remL = rem.length; 14265 14266 // If product was < remainder. 14267 if ( cmp == -1 ) { 14268 14269 // Compare divisor and new remainder. 14270 // If divisor < new remainder, subtract divisor from remainder. 14271 // Trial digit n too low. 14272 // n is 1 too low about 5% of the time, and very rarely 2 too low. 14273 while ( compare( yc, rem, yL, remL ) < 1 ) { 14274 n++; 14275 14276 // Subtract divisor from remainder. 14277 subtract( rem, yL < remL ? yz : yc, remL, base ); 14278 remL = rem.length; 14279 } 14280 } 14281 } else if ( cmp === 0 ) { 14282 n++; 14283 rem = [0]; 14284 } // else cmp === 1 and n will be 0 14285 14286 // Add the next digit, n, to the result array. 14287 qc[i++] = n; 14288 14289 // Update the remainder. 14290 if ( rem[0] ) { 14291 rem[remL++] = xc[xi] || 0; 14292 } else { 14293 rem = [ xc[xi] ]; 14294 remL = 1; 14295 } 14296 } while ( ( xi++ < xL || rem[0] != null ) && s-- ); 14297 14298 more = rem[0] != null; 14299 14300 // Leading zero? 14301 if ( !qc[0] ) qc.shift(); 14302 } 14303 14304 if ( base == BASE ) { 14305 14306 // To calculate q.e, first get the number of digits of qc[0]. 14307 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ ); 14308 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more ); 14309 14310 // Caller is convertBase. 14311 } else { 14312 q.e = e; 14313 q.r = +more; 14314 } 14315 14316 return q; 14317 }; 14318 })(); 14319 14320 14321 /* 14322 * Return a string representing the value of BigNumber n in fixed-point or exponential 14323 * notation rounded to the specified decimal places or significant digits. 14324 * 14325 * n is a BigNumber. 14326 * i is the index of the last digit required (i.e. the digit that may be rounded up). 14327 * rm is the rounding mode. 14328 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24. 14329 */ 14330 function format( n, i, rm, caller ) { 14331 var c0, e, ne, len, str; 14332 14333 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode ) 14334 ? rm | 0 : ROUNDING_MODE; 14335 14336 if ( !n.c ) return n.toString(); 14337 c0 = n.c[0]; 14338 ne = n.e; 14339 14340 if ( i == null ) { 14341 str = coeffToString( n.c ); 14342 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG 14343 ? toExponential( str, ne ) 14344 : toFixedPoint( str, ne ); 14345 } else { 14346 n = round( new BigNumber(n), i, rm ); 14347 14348 // n.e may have changed if the value was rounded up. 14349 e = n.e; 14350 14351 str = coeffToString( n.c ); 14352 len = str.length; 14353 14354 // toPrecision returns exponential notation if the number of significant digits 14355 // specified is less than the number of digits necessary to represent the integer 14356 // part of the value in fixed-point notation. 14357 14358 // Exponential notation. 14359 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) { 14360 14361 // Append zeros? 14362 for ( ; len < i; str += '0', len++ ); 14363 str = toExponential( str, e ); 14364 14365 // Fixed-point notation. 14366 } else { 14367 i -= ne; 14368 str = toFixedPoint( str, e ); 14369 14370 // Append zeros? 14371 if ( e + 1 > len ) { 14372 if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); 14373 } else { 14374 i += e - len; 14375 if ( i > 0 ) { 14376 if ( e + 1 == len ) str += '.'; 14377 for ( ; i--; str += '0' ); 14378 } 14379 } 14380 } 14381 } 14382 14383 return n.s < 0 && c0 ? '-' + str : str; 14384 } 14385 14386 14387 // Handle BigNumber.max and BigNumber.min. 14388 function maxOrMin( args, method ) { 14389 var m, n, 14390 i = 0; 14391 14392 if ( isArray( args[0] ) ) args = args[0]; 14393 m = new BigNumber( args[0] ); 14394 14395 for ( ; ++i < args.length; ) { 14396 n = new BigNumber( args[i] ); 14397 14398 // If any number is NaN, return NaN. 14399 if ( !n.s ) { 14400 m = n; 14401 break; 14402 } else if ( method.call( m, n ) ) { 14403 m = n; 14404 } 14405 } 14406 14407 return m; 14408 } 14409 14410 14411 /* 14412 * Return true if n is an integer in range, otherwise throw. 14413 * Use for argument validation when ERRORS is true. 14414 */ 14415 function intValidatorWithErrors( n, min, max, caller, name ) { 14416 if ( n < min || n > max || n != truncate(n) ) { 14417 raise( caller, ( name || 'decimal places' ) + 14418 ( n < min || n > max ? ' out of range' : ' not an integer' ), n ); 14419 } 14420 14421 return true; 14422 } 14423 14424 14425 /* 14426 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. 14427 * Called by minus, plus and times. 14428 */ 14429 function normalise( n, c, e ) { 14430 var i = 1, 14431 j = c.length; 14432 14433 // Remove trailing zeros. 14434 for ( ; !c[--j]; c.pop() ); 14435 14436 // Calculate the base 10 exponent. First get the number of digits of c[0]. 14437 for ( j = c[0]; j >= 10; j /= 10, i++ ); 14438 14439 // Overflow? 14440 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { 14441 14442 // Infinity. 14443 n.c = n.e = null; 14444 14445 // Underflow? 14446 } else if ( e < MIN_EXP ) { 14447 14448 // Zero. 14449 n.c = [ n.e = 0 ]; 14450 } else { 14451 n.e = e; 14452 n.c = c; 14453 } 14454 14455 return n; 14456 } 14457 14458 14459 // Handle values that fail the validity test in BigNumber. 14460 parseNumeric = (function () { 14461 var basePrefix = /^(-?)0([xbo])/i, 14462 dotAfter = /^([^.]+)\.$/, 14463 dotBefore = /^\.([^.]+)$/, 14464 isInfinityOrNaN = /^-?(Infinity|NaN)$/, 14465 whitespaceOrPlus = /^\s*\+|^\s+|\s+$/g; 14466 14467 return function ( x, str, num, b ) { 14468 var base, 14469 s = num ? str : str.replace( whitespaceOrPlus, '' ); 14470 14471 // No exception on ±Infinity or NaN. 14472 if ( isInfinityOrNaN.test(s) ) { 14473 x.s = isNaN(s) ? null : s < 0 ? -1 : 1; 14474 } else { 14475 if ( !num ) { 14476 14477 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i 14478 s = s.replace( basePrefix, function ( m, p1, p2 ) { 14479 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8; 14480 return !b || b == base ? p1 : m; 14481 }); 14482 14483 if (b) { 14484 base = b; 14485 14486 // E.g. '1.' to '1', '.1' to '0.1' 14487 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); 14488 } 14489 14490 if ( str != s ) return new BigNumber( s, base ); 14491 } 14492 14493 // 'new BigNumber() not a number: {n}' 14494 // 'new BigNumber() not a base {b} number: {n}' 14495 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str ); 14496 x.s = null; 14497 } 14498 14499 x.c = x.e = null; 14500 id = 0; 14501 } 14502 })(); 14503 14504 14505 // Throw a BigNumber Error. 14506 function raise( caller, msg, val ) { 14507 var error = new Error( [ 14508 'new BigNumber', // 0 14509 'cmp', // 1 14510 'config', // 2 14511 'div', // 3 14512 'divToInt', // 4 14513 'eq', // 5 14514 'gt', // 6 14515 'gte', // 7 14516 'lt', // 8 14517 'lte', // 9 14518 'minus', // 10 14519 'mod', // 11 14520 'plus', // 12 14521 'precision', // 13 14522 'random', // 14 14523 'round', // 15 14524 'shift', // 16 14525 'times', // 17 14526 'toDigits', // 18 14527 'toExponential', // 19 14528 'toFixed', // 20 14529 'toFormat', // 21 14530 'toFraction', // 22 14531 'pow', // 23 14532 'toPrecision', // 24 14533 'toString', // 25 14534 'BigNumber' // 26 14535 ][caller] + '() ' + msg + ': ' + val ); 14536 14537 error.name = 'BigNumber Error'; 14538 id = 0; 14539 throw error; 14540 } 14541 14542 14543 /* 14544 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. 14545 * If r is truthy, it is known that there are more digits after the rounding digit. 14546 */ 14547 function round( x, sd, rm, r ) { 14548 var d, i, j, k, n, ni, rd, 14549 xc = x.c, 14550 pows10 = POWS_TEN; 14551 14552 // if x is not Infinity or NaN... 14553 if (xc) { 14554 14555 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. 14556 // n is a base 1e14 number, the value of the element of array x.c containing rd. 14557 // ni is the index of n within x.c. 14558 // d is the number of digits of n. 14559 // i is the index of rd within n including leading zeros. 14560 // j is the actual index of rd within n (if < 0, rd is a leading zero). 14561 out: { 14562 14563 // Get the number of digits of the first element of xc. 14564 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); 14565 i = sd - d; 14566 14567 // If the rounding digit is in the first element of xc... 14568 if ( i < 0 ) { 14569 i += LOG_BASE; 14570 j = sd; 14571 n = xc[ ni = 0 ]; 14572 14573 // Get the rounding digit at index j of n. 14574 rd = n / pows10[ d - j - 1 ] % 10 | 0; 14575 } else { 14576 ni = mathceil( ( i + 1 ) / LOG_BASE ); 14577 14578 if ( ni >= xc.length ) { 14579 14580 if (r) { 14581 14582 // Needed by sqrt. 14583 for ( ; xc.length <= ni; xc.push(0) ); 14584 n = rd = 0; 14585 d = 1; 14586 i %= LOG_BASE; 14587 j = i - LOG_BASE + 1; 14588 } else { 14589 break out; 14590 } 14591 } else { 14592 n = k = xc[ni]; 14593 14594 // Get the number of digits of n. 14595 for ( d = 1; k >= 10; k /= 10, d++ ); 14596 14597 // Get the index of rd within n. 14598 i %= LOG_BASE; 14599 14600 // Get the index of rd within n, adjusted for leading zeros. 14601 // The number of leading zeros of n is given by LOG_BASE - d. 14602 j = i - LOG_BASE + d; 14603 14604 // Get the rounding digit at index j of n. 14605 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; 14606 } 14607 } 14608 14609 r = r || sd < 0 || 14610 14611 // Are there any non-zero digits after the rounding digit? 14612 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right 14613 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. 14614 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] ); 14615 14616 r = rm < 4 14617 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) 14618 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && 14619 14620 // Check whether the digit to the left of the rounding digit is odd. 14621 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 || 14622 rm == ( x.s < 0 ? 8 : 7 ) ); 14623 14624 if ( sd < 1 || !xc[0] ) { 14625 xc.length = 0; 14626 14627 if (r) { 14628 14629 // Convert sd to decimal places. 14630 sd -= x.e + 1; 14631 14632 // 1, 0.1, 0.01, 0.001, 0.0001 etc. 14633 xc[0] = pows10[ sd % LOG_BASE ]; 14634 x.e = -sd || 0; 14635 } else { 14636 14637 // Zero. 14638 xc[0] = x.e = 0; 14639 } 14640 14641 return x; 14642 } 14643 14644 // Remove excess digits. 14645 if ( i == 0 ) { 14646 xc.length = ni; 14647 k = 1; 14648 ni--; 14649 } else { 14650 xc.length = ni + 1; 14651 k = pows10[ LOG_BASE - i ]; 14652 14653 // E.g. 56700 becomes 56000 if 7 is the rounding digit. 14654 // j > 0 means i > number of leading zeros of n. 14655 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0; 14656 } 14657 14658 // Round up? 14659 if (r) { 14660 14661 for ( ; ; ) { 14662 14663 // If the digit to be rounded up is in the first element of xc... 14664 if ( ni == 0 ) { 14665 14666 // i will be the length of xc[0] before k is added. 14667 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ ); 14668 j = xc[0] += k; 14669 for ( k = 1; j >= 10; j /= 10, k++ ); 14670 14671 // if i != k the length has increased. 14672 if ( i != k ) { 14673 x.e++; 14674 if ( xc[0] == BASE ) xc[0] = 1; 14675 } 14676 14677 break; 14678 } else { 14679 xc[ni] += k; 14680 if ( xc[ni] != BASE ) break; 14681 xc[ni--] = 0; 14682 k = 1; 14683 } 14684 } 14685 } 14686 14687 // Remove trailing zeros. 14688 for ( i = xc.length; xc[--i] === 0; xc.pop() ); 14689 } 14690 14691 // Overflow? Infinity. 14692 if ( x.e > MAX_EXP ) { 14693 x.c = x.e = null; 14694 14695 // Underflow? Zero. 14696 } else if ( x.e < MIN_EXP ) { 14697 x.c = [ x.e = 0 ]; 14698 } 14699 } 14700 14701 return x; 14702 } 14703 14704 14705 // PROTOTYPE/INSTANCE METHODS 14706 14707 14708 /* 14709 * Return a new BigNumber whose value is the absolute value of this BigNumber. 14710 */ 14711 P.absoluteValue = P.abs = function () { 14712 var x = new BigNumber(this); 14713 if ( x.s < 0 ) x.s = 1; 14714 return x; 14715 }; 14716 14717 14718 /* 14719 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole 14720 * number in the direction of Infinity. 14721 */ 14722 P.ceil = function () { 14723 return round( new BigNumber(this), this.e + 1, 2 ); 14724 }; 14725 14726 14727 /* 14728 * Return 14729 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), 14730 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), 14731 * 0 if they have the same value, 14732 * or null if the value of either is NaN. 14733 */ 14734 P.comparedTo = P.cmp = function ( y, b ) { 14735 id = 1; 14736 return compare( this, new BigNumber( y, b ) ); 14737 }; 14738 14739 14740 /* 14741 * Return the number of decimal places of the value of this BigNumber, or null if the value 14742 * of this BigNumber is ±Infinity or NaN. 14743 */ 14744 P.decimalPlaces = P.dp = function () { 14745 var n, v, 14746 c = this.c; 14747 14748 if ( !c ) return null; 14749 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; 14750 14751 // Subtract the number of trailing zeros of the last number. 14752 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); 14753 if ( n < 0 ) n = 0; 14754 14755 return n; 14756 }; 14757 14758 14759 /* 14760 * n / 0 = I 14761 * n / N = N 14762 * n / I = 0 14763 * 0 / n = 0 14764 * 0 / 0 = N 14765 * 0 / N = N 14766 * 0 / I = 0 14767 * N / n = N 14768 * N / 0 = N 14769 * N / N = N 14770 * N / I = N 14771 * I / n = I 14772 * I / 0 = I 14773 * I / N = N 14774 * I / I = N 14775 * 14776 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of 14777 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. 14778 */ 14779 P.dividedBy = P.div = function ( y, b ) { 14780 id = 3; 14781 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); 14782 }; 14783 14784 14785 /* 14786 * Return a new BigNumber whose value is the integer part of dividing the value of this 14787 * BigNumber by the value of BigNumber(y, b). 14788 */ 14789 P.dividedToIntegerBy = P.divToInt = function ( y, b ) { 14790 id = 4; 14791 return div( this, new BigNumber( y, b ), 0, 1 ); 14792 }; 14793 14794 14795 /* 14796 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), 14797 * otherwise returns false. 14798 */ 14799 P.equals = P.eq = function ( y, b ) { 14800 id = 5; 14801 return compare( this, new BigNumber( y, b ) ) === 0; 14802 }; 14803 14804 14805 /* 14806 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole 14807 * number in the direction of -Infinity. 14808 */ 14809 P.floor = function () { 14810 return round( new BigNumber(this), this.e + 1, 3 ); 14811 }; 14812 14813 14814 /* 14815 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), 14816 * otherwise returns false. 14817 */ 14818 P.greaterThan = P.gt = function ( y, b ) { 14819 id = 6; 14820 return compare( this, new BigNumber( y, b ) ) > 0; 14821 }; 14822 14823 14824 /* 14825 * Return true if the value of this BigNumber is greater than or equal to the value of 14826 * BigNumber(y, b), otherwise returns false. 14827 */ 14828 P.greaterThanOrEqualTo = P.gte = function ( y, b ) { 14829 id = 7; 14830 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; 14831 14832 }; 14833 14834 14835 /* 14836 * Return true if the value of this BigNumber is a finite number, otherwise returns false. 14837 */ 14838 P.isFinite = function () { 14839 return !!this.c; 14840 }; 14841 14842 14843 /* 14844 * Return true if the value of this BigNumber is an integer, otherwise return false. 14845 */ 14846 P.isInteger = P.isInt = function () { 14847 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; 14848 }; 14849 14850 14851 /* 14852 * Return true if the value of this BigNumber is NaN, otherwise returns false. 14853 */ 14854 P.isNaN = function () { 14855 return !this.s; 14856 }; 14857 14858 14859 /* 14860 * Return true if the value of this BigNumber is negative, otherwise returns false. 14861 */ 14862 P.isNegative = P.isNeg = function () { 14863 return this.s < 0; 14864 }; 14865 14866 14867 /* 14868 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false. 14869 */ 14870 P.isZero = function () { 14871 return !!this.c && this.c[0] == 0; 14872 }; 14873 14874 14875 /* 14876 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), 14877 * otherwise returns false. 14878 */ 14879 P.lessThan = P.lt = function ( y, b ) { 14880 id = 8; 14881 return compare( this, new BigNumber( y, b ) ) < 0; 14882 }; 14883 14884 14885 /* 14886 * Return true if the value of this BigNumber is less than or equal to the value of 14887 * BigNumber(y, b), otherwise returns false. 14888 */ 14889 P.lessThanOrEqualTo = P.lte = function ( y, b ) { 14890 id = 9; 14891 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; 14892 }; 14893 14894 14895 /* 14896 * n - 0 = n 14897 * n - N = N 14898 * n - I = -I 14899 * 0 - n = -n 14900 * 0 - 0 = 0 14901 * 0 - N = N 14902 * 0 - I = -I 14903 * N - n = N 14904 * N - 0 = N 14905 * N - N = N 14906 * N - I = N 14907 * I - n = I 14908 * I - 0 = I 14909 * I - N = N 14910 * I - I = N 14911 * 14912 * Return a new BigNumber whose value is the value of this BigNumber minus the value of 14913 * BigNumber(y, b). 14914 */ 14915 P.minus = P.sub = function ( y, b ) { 14916 var i, j, t, xLTy, 14917 x = this, 14918 a = x.s; 14919 14920 id = 10; 14921 y = new BigNumber( y, b ); 14922 b = y.s; 14923 14924 // Either NaN? 14925 if ( !a || !b ) return new BigNumber(NaN); 14926 14927 // Signs differ? 14928 if ( a != b ) { 14929 y.s = -b; 14930 return x.plus(y); 14931 } 14932 14933 var xe = x.e / LOG_BASE, 14934 ye = y.e / LOG_BASE, 14935 xc = x.c, 14936 yc = y.c; 14937 14938 if ( !xe || !ye ) { 14939 14940 // Either Infinity? 14941 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); 14942 14943 // Either zero? 14944 if ( !xc[0] || !yc[0] ) { 14945 14946 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. 14947 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : 14948 14949 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity 14950 ROUNDING_MODE == 3 ? -0 : 0 ); 14951 } 14952 } 14953 14954 xe = bitFloor(xe); 14955 ye = bitFloor(ye); 14956 xc = xc.slice(); 14957 14958 // Determine which is the bigger number. 14959 if ( a = xe - ye ) { 14960 14961 if ( xLTy = a < 0 ) { 14962 a = -a; 14963 t = xc; 14964 } else { 14965 ye = xe; 14966 t = yc; 14967 } 14968 14969 t.reverse(); 14970 14971 // Prepend zeros to equalise exponents. 14972 for ( b = a; b--; t.push(0) ); 14973 t.reverse(); 14974 } else { 14975 14976 // Exponents equal. Check digit by digit. 14977 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; 14978 14979 for ( a = b = 0; b < j; b++ ) { 14980 14981 if ( xc[b] != yc[b] ) { 14982 xLTy = xc[b] < yc[b]; 14983 break; 14984 } 14985 } 14986 } 14987 14988 // x < y? Point xc to the array of the bigger number. 14989 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; 14990 14991 b = ( j = yc.length ) - ( i = xc.length ); 14992 14993 // Append zeros to xc if shorter. 14994 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. 14995 if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); 14996 b = BASE - 1; 14997 14998 // Subtract yc from xc. 14999 for ( ; j > a; ) { 15000 15001 if ( xc[--j] < yc[j] ) { 15002 for ( i = j; i && !xc[--i]; xc[i] = b ); 15003 --xc[i]; 15004 xc[j] += BASE; 15005 } 15006 15007 xc[j] -= yc[j]; 15008 } 15009 15010 // Remove leading zeros and adjust exponent accordingly. 15011 for ( ; xc[0] == 0; xc.shift(), --ye ); 15012 15013 // Zero? 15014 if ( !xc[0] ) { 15015 15016 // Following IEEE 754 (2008) 6.3, 15017 // n - n = +0 but n - n = -0 when rounding towards -Infinity. 15018 y.s = ROUNDING_MODE == 3 ? -1 : 1; 15019 y.c = [ y.e = 0 ]; 15020 return y; 15021 } 15022 15023 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity 15024 // for finite x and y. 15025 return normalise( y, xc, ye ); 15026 }; 15027 15028 15029 /* 15030 * n % 0 = N 15031 * n % N = N 15032 * n % I = n 15033 * 0 % n = 0 15034 * -0 % n = -0 15035 * 0 % 0 = N 15036 * 0 % N = N 15037 * 0 % I = 0 15038 * N % n = N 15039 * N % 0 = N 15040 * N % N = N 15041 * N % I = N 15042 * I % n = N 15043 * I % 0 = N 15044 * I % N = N 15045 * I % I = N 15046 * 15047 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of 15048 * BigNumber(y, b). The result depends on the value of MODULO_MODE. 15049 */ 15050 P.modulo = P.mod = function ( y, b ) { 15051 var q, s, 15052 x = this; 15053 15054 id = 11; 15055 y = new BigNumber( y, b ); 15056 15057 // Return NaN if x is Infinity or NaN, or y is NaN or zero. 15058 if ( !x.c || !y.s || y.c && !y.c[0] ) { 15059 return new BigNumber(NaN); 15060 15061 // Return x if y is Infinity or x is zero. 15062 } else if ( !y.c || x.c && !x.c[0] ) { 15063 return new BigNumber(x); 15064 } 15065 15066 if ( MODULO_MODE == 9 ) { 15067 15068 // Euclidian division: q = sign(y) * floor(x / abs(y)) 15069 // r = x - qy where 0 <= r < abs(y) 15070 s = y.s; 15071 y.s = 1; 15072 q = div( x, y, 0, 3 ); 15073 y.s = s; 15074 q.s *= s; 15075 } else { 15076 q = div( x, y, 0, MODULO_MODE ); 15077 } 15078 15079 return x.minus( q.times(y) ); 15080 }; 15081 15082 15083 /* 15084 * Return a new BigNumber whose value is the value of this BigNumber negated, 15085 * i.e. multiplied by -1. 15086 */ 15087 P.negated = P.neg = function () { 15088 var x = new BigNumber(this); 15089 x.s = -x.s || null; 15090 return x; 15091 }; 15092 15093 15094 /* 15095 * n + 0 = n 15096 * n + N = N 15097 * n + I = I 15098 * 0 + n = n 15099 * 0 + 0 = 0 15100 * 0 + N = N 15101 * 0 + I = I 15102 * N + n = N 15103 * N + 0 = N 15104 * N + N = N 15105 * N + I = N 15106 * I + n = I 15107 * I + 0 = I 15108 * I + N = N 15109 * I + I = I 15110 * 15111 * Return a new BigNumber whose value is the value of this BigNumber plus the value of 15112 * BigNumber(y, b). 15113 */ 15114 P.plus = P.add = function ( y, b ) { 15115 var t, 15116 x = this, 15117 a = x.s; 15118 15119 id = 12; 15120 y = new BigNumber( y, b ); 15121 b = y.s; 15122 15123 // Either NaN? 15124 if ( !a || !b ) return new BigNumber(NaN); 15125 15126 // Signs differ? 15127 if ( a != b ) { 15128 y.s = -b; 15129 return x.minus(y); 15130 } 15131 15132 var xe = x.e / LOG_BASE, 15133 ye = y.e / LOG_BASE, 15134 xc = x.c, 15135 yc = y.c; 15136 15137 if ( !xe || !ye ) { 15138 15139 // Return ±Infinity if either ±Infinity. 15140 if ( !xc || !yc ) return new BigNumber( a / 0 ); 15141 15142 // Either zero? 15143 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. 15144 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); 15145 } 15146 15147 xe = bitFloor(xe); 15148 ye = bitFloor(ye); 15149 xc = xc.slice(); 15150 15151 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. 15152 if ( a = xe - ye ) { 15153 if ( a > 0 ) { 15154 ye = xe; 15155 t = yc; 15156 } else { 15157 a = -a; 15158 t = xc; 15159 } 15160 15161 t.reverse(); 15162 for ( ; a--; t.push(0) ); 15163 t.reverse(); 15164 } 15165 15166 a = xc.length; 15167 b = yc.length; 15168 15169 // Point xc to the longer array, and b to the shorter length. 15170 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; 15171 15172 // Only start adding at yc.length - 1 as the further digits of xc can be ignored. 15173 for ( a = 0; b; ) { 15174 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; 15175 xc[b] %= BASE; 15176 } 15177 15178 if (a) { 15179 xc.unshift(a); 15180 ++ye; 15181 } 15182 15183 // No need to check for zero, as +x + +y != 0 && -x + -y != 0 15184 // ye = MAX_EXP + 1 possible 15185 return normalise( y, xc, ye ); 15186 }; 15187 15188 15189 /* 15190 * Return the number of significant digits of the value of this BigNumber. 15191 * 15192 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. 15193 */ 15194 P.precision = P.sd = function (z) { 15195 var n, v, 15196 x = this, 15197 c = x.c; 15198 15199 // 'precision() argument not a boolean or binary digit: {z}' 15200 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { 15201 if (ERRORS) raise( 13, 'argument' + notBool, z ); 15202 if ( z != !!z ) z = null; 15203 } 15204 15205 if ( !c ) return null; 15206 v = c.length - 1; 15207 n = v * LOG_BASE + 1; 15208 15209 if ( v = c[v] ) { 15210 15211 // Subtract the number of trailing zeros of the last element. 15212 for ( ; v % 10 == 0; v /= 10, n-- ); 15213 15214 // Add the number of digits of the first element. 15215 for ( v = c[0]; v >= 10; v /= 10, n++ ); 15216 } 15217 15218 if ( z && x.e + 1 > n ) n = x.e + 1; 15219 15220 return n; 15221 }; 15222 15223 15224 /* 15225 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of 15226 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if 15227 * omitted. 15228 * 15229 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15230 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15231 * 15232 * 'round() decimal places out of range: {dp}' 15233 * 'round() decimal places not an integer: {dp}' 15234 * 'round() rounding mode not an integer: {rm}' 15235 * 'round() rounding mode out of range: {rm}' 15236 */ 15237 P.round = function ( dp, rm ) { 15238 var n = new BigNumber(this); 15239 15240 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) { 15241 round( n, ~~dp + this.e + 1, rm == null || 15242 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 ); 15243 } 15244 15245 return n; 15246 }; 15247 15248 15249 /* 15250 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places 15251 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. 15252 * 15253 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. 15254 * 15255 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity 15256 * otherwise. 15257 * 15258 * 'shift() argument not an integer: {k}' 15259 * 'shift() argument out of range: {k}' 15260 */ 15261 P.shift = function (k) { 15262 var n = this; 15263 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) 15264 15265 // k < 1e+21, or truncate(k) will produce exponential notation. 15266 ? n.times( '1e' + truncate(k) ) 15267 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER ) 15268 ? n.s * ( k < 0 ? 0 : 1 / 0 ) 15269 : n ); 15270 }; 15271 15272 15273 /* 15274 * sqrt(-n) = N 15275 * sqrt( N) = N 15276 * sqrt(-I) = N 15277 * sqrt( I) = I 15278 * sqrt( 0) = 0 15279 * sqrt(-0) = -0 15280 * 15281 * Return a new BigNumber whose value is the square root of the value of this BigNumber, 15282 * rounded according to DECIMAL_PLACES and ROUNDING_MODE. 15283 */ 15284 P.squareRoot = P.sqrt = function () { 15285 var m, n, r, rep, t, 15286 x = this, 15287 c = x.c, 15288 s = x.s, 15289 e = x.e, 15290 dp = DECIMAL_PLACES + 4, 15291 half = new BigNumber('0.5'); 15292 15293 // Negative/NaN/Infinity/zero? 15294 if ( s !== 1 || !c || !c[0] ) { 15295 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); 15296 } 15297 15298 // Initial estimate. 15299 s = Math.sqrt( +x ); 15300 15301 // Math.sqrt underflow/overflow? 15302 // Pass x to Math.sqrt as integer, then adjust the exponent of the result. 15303 if ( s == 0 || s == 1 / 0 ) { 15304 n = coeffToString(c); 15305 if ( ( n.length + e ) % 2 == 0 ) n += '0'; 15306 s = Math.sqrt(n); 15307 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); 15308 15309 if ( s == 1 / 0 ) { 15310 n = '1e' + e; 15311 } else { 15312 n = s.toExponential(); 15313 n = n.slice( 0, n.indexOf('e') + 1 ) + e; 15314 } 15315 15316 r = new BigNumber(n); 15317 } else { 15318 r = new BigNumber( s + '' ); 15319 } 15320 15321 // Check for zero. 15322 // r could be zero if MIN_EXP is changed after the this value was created. 15323 // This would cause a division by zero (x/t) and hence Infinity below, which would cause 15324 // coeffToString to throw. 15325 if ( r.c[0] ) { 15326 e = r.e; 15327 s = e + dp; 15328 if ( s < 3 ) s = 0; 15329 15330 // Newton-Raphson iteration. 15331 for ( ; ; ) { 15332 t = r; 15333 r = half.times( t.plus( div( x, t, dp, 1 ) ) ); 15334 15335 if ( coeffToString( t.c ).slice( 0, s ) === ( n = 15336 coeffToString( r.c ) ).slice( 0, s ) ) { 15337 15338 // The exponent of r may here be one less than the final result exponent, 15339 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits 15340 // are indexed correctly. 15341 if ( r.e < e ) --s; 15342 n = n.slice( s - 3, s + 1 ); 15343 15344 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits 15345 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the 15346 // iteration. 15347 if ( n == '9999' || !rep && n == '4999' ) { 15348 15349 // On the first iteration only, check to see if rounding up gives the 15350 // exact result as the nines may infinitely repeat. 15351 if ( !rep ) { 15352 round( t, t.e + DECIMAL_PLACES + 2, 0 ); 15353 15354 if ( t.times(t).eq(x) ) { 15355 r = t; 15356 break; 15357 } 15358 } 15359 15360 dp += 4; 15361 s += 4; 15362 rep = 1; 15363 } else { 15364 15365 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact 15366 // result. If not, then there are further digits and m will be truthy. 15367 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { 15368 15369 // Truncate to the first rounding digit. 15370 round( r, r.e + DECIMAL_PLACES + 2, 1 ); 15371 m = !r.times(r).eq(x); 15372 } 15373 15374 break; 15375 } 15376 } 15377 } 15378 } 15379 15380 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); 15381 }; 15382 15383 15384 /* 15385 * n * 0 = 0 15386 * n * N = N 15387 * n * I = I 15388 * 0 * n = 0 15389 * 0 * 0 = 0 15390 * 0 * N = N 15391 * 0 * I = N 15392 * N * n = N 15393 * N * 0 = N 15394 * N * N = N 15395 * N * I = N 15396 * I * n = I 15397 * I * 0 = N 15398 * I * N = N 15399 * I * I = I 15400 * 15401 * Return a new BigNumber whose value is the value of this BigNumber times the value of 15402 * BigNumber(y, b). 15403 */ 15404 P.times = P.mul = function ( y, b ) { 15405 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, 15406 base, sqrtBase, 15407 x = this, 15408 xc = x.c, 15409 yc = ( id = 17, y = new BigNumber( y, b ) ).c; 15410 15411 // Either NaN, ±Infinity or ±0? 15412 if ( !xc || !yc || !xc[0] || !yc[0] ) { 15413 15414 // Return NaN if either is NaN, or one is 0 and the other is Infinity. 15415 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { 15416 y.c = y.e = y.s = null; 15417 } else { 15418 y.s *= x.s; 15419 15420 // Return ±Infinity if either is ±Infinity. 15421 if ( !xc || !yc ) { 15422 y.c = y.e = null; 15423 15424 // Return ±0 if either is ±0. 15425 } else { 15426 y.c = [0]; 15427 y.e = 0; 15428 } 15429 } 15430 15431 return y; 15432 } 15433 15434 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); 15435 y.s *= x.s; 15436 xcL = xc.length; 15437 ycL = yc.length; 15438 15439 // Ensure xc points to longer array and xcL to its length. 15440 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; 15441 15442 // Initialise the result array with zeros. 15443 for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); 15444 15445 base = BASE; 15446 sqrtBase = SQRT_BASE; 15447 15448 for ( i = ycL; --i >= 0; ) { 15449 c = 0; 15450 ylo = yc[i] % sqrtBase; 15451 yhi = yc[i] / sqrtBase | 0; 15452 15453 for ( k = xcL, j = i + k; j > i; ) { 15454 xlo = xc[--k] % sqrtBase; 15455 xhi = xc[k] / sqrtBase | 0; 15456 m = yhi * xlo + xhi * ylo; 15457 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; 15458 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; 15459 zc[j--] = xlo % base; 15460 } 15461 15462 zc[j] = c; 15463 } 15464 15465 if (c) { 15466 ++e; 15467 } else { 15468 zc.shift(); 15469 } 15470 15471 return normalise( y, zc, e ); 15472 }; 15473 15474 15475 /* 15476 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of 15477 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted. 15478 * 15479 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. 15480 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15481 * 15482 * 'toDigits() precision out of range: {sd}' 15483 * 'toDigits() precision not an integer: {sd}' 15484 * 'toDigits() rounding mode not an integer: {rm}' 15485 * 'toDigits() rounding mode out of range: {rm}' 15486 */ 15487 P.toDigits = function ( sd, rm ) { 15488 var n = new BigNumber(this); 15489 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0; 15490 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0; 15491 return sd ? round( n, sd, rm ) : n; 15492 }; 15493 15494 15495 /* 15496 * Return a string representing the value of this BigNumber in exponential notation and 15497 * rounded using ROUNDING_MODE to dp fixed decimal places. 15498 * 15499 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15500 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15501 * 15502 * 'toExponential() decimal places not an integer: {dp}' 15503 * 'toExponential() decimal places out of range: {dp}' 15504 * 'toExponential() rounding mode not an integer: {rm}' 15505 * 'toExponential() rounding mode out of range: {rm}' 15506 */ 15507 P.toExponential = function ( dp, rm ) { 15508 return format( this, 15509 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); 15510 }; 15511 15512 15513 /* 15514 * Return a string representing the value of this BigNumber in fixed-point notation rounding 15515 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. 15516 * 15517 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', 15518 * but e.g. (-0.00001).toFixed(0) is '-0'. 15519 * 15520 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15521 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15522 * 15523 * 'toFixed() decimal places not an integer: {dp}' 15524 * 'toFixed() decimal places out of range: {dp}' 15525 * 'toFixed() rounding mode not an integer: {rm}' 15526 * 'toFixed() rounding mode out of range: {rm}' 15527 */ 15528 P.toFixed = function ( dp, rm ) { 15529 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 ) 15530 ? ~~dp + this.e + 1 : null, rm, 20 ); 15531 }; 15532 15533 15534 /* 15535 * Return a string representing the value of this BigNumber in fixed-point notation rounded 15536 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties 15537 * of the FORMAT object (see BigNumber.config). 15538 * 15539 * FORMAT = { 15540 * decimalSeparator : '.', 15541 * groupSeparator : ',', 15542 * groupSize : 3, 15543 * secondaryGroupSize : 0, 15544 * fractionGroupSeparator : '\xA0', // non-breaking space 15545 * fractionGroupSize : 0 15546 * }; 15547 * 15548 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15549 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15550 * 15551 * 'toFormat() decimal places not an integer: {dp}' 15552 * 'toFormat() decimal places out of range: {dp}' 15553 * 'toFormat() rounding mode not an integer: {rm}' 15554 * 'toFormat() rounding mode out of range: {rm}' 15555 */ 15556 P.toFormat = function ( dp, rm ) { 15557 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 ) 15558 ? ~~dp + this.e + 1 : null, rm, 21 ); 15559 15560 if ( this.c ) { 15561 var i, 15562 arr = str.split('.'), 15563 g1 = +FORMAT.groupSize, 15564 g2 = +FORMAT.secondaryGroupSize, 15565 groupSeparator = FORMAT.groupSeparator, 15566 intPart = arr[0], 15567 fractionPart = arr[1], 15568 isNeg = this.s < 0, 15569 intDigits = isNeg ? intPart.slice(1) : intPart, 15570 len = intDigits.length; 15571 15572 if (g2) i = g1, g1 = g2, g2 = i, len -= i; 15573 15574 if ( g1 > 0 && len > 0 ) { 15575 i = len % g1 || g1; 15576 intPart = intDigits.substr( 0, i ); 15577 15578 for ( ; i < len; i += g1 ) { 15579 intPart += groupSeparator + intDigits.substr( i, g1 ); 15580 } 15581 15582 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); 15583 if (isNeg) intPart = '-' + intPart; 15584 } 15585 15586 str = fractionPart 15587 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) 15588 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), 15589 '$&' + FORMAT.fractionGroupSeparator ) 15590 : fractionPart ) 15591 : intPart; 15592 } 15593 15594 return str; 15595 }; 15596 15597 15598 /* 15599 * Return a string array representing the value of this BigNumber as a simple fraction with 15600 * an integer numerator and an integer denominator. The denominator will be a positive 15601 * non-zero value less than or equal to the specified maximum denominator. If a maximum 15602 * denominator is not specified, the denominator will be the lowest value necessary to 15603 * represent the number exactly. 15604 * 15605 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. 15606 * 15607 * 'toFraction() max denominator not an integer: {md}' 15608 * 'toFraction() max denominator out of range: {md}' 15609 */ 15610 P.toFraction = function (md) { 15611 var arr, d0, d2, e, exp, n, n0, q, s, 15612 k = ERRORS, 15613 x = this, 15614 xc = x.c, 15615 d = new BigNumber(ONE), 15616 n1 = d0 = new BigNumber(ONE), 15617 d1 = n0 = new BigNumber(ONE); 15618 15619 if ( md != null ) { 15620 ERRORS = false; 15621 n = new BigNumber(md); 15622 ERRORS = k; 15623 15624 if ( !( k = n.isInt() ) || n.lt(ONE) ) { 15625 15626 if (ERRORS) { 15627 raise( 22, 15628 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); 15629 } 15630 15631 // ERRORS is false: 15632 // If md is a finite non-integer >= 1, round it to an integer and use it. 15633 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null; 15634 } 15635 } 15636 15637 if ( !xc ) return x.toString(); 15638 s = coeffToString(xc); 15639 15640 // Determine initial denominator. 15641 // d is a power of 10 and the minimum max denominator that specifies the value exactly. 15642 e = d.e = s.length - x.e - 1; 15643 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; 15644 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n; 15645 15646 exp = MAX_EXP; 15647 MAX_EXP = 1 / 0; 15648 n = new BigNumber(s); 15649 15650 // n0 = d1 = 0 15651 n0.c[0] = 0; 15652 15653 for ( ; ; ) { 15654 q = div( n, d, 0, 1 ); 15655 d2 = d0.plus( q.times(d1) ); 15656 if ( d2.cmp(md) == 1 ) break; 15657 d0 = d1; 15658 d1 = d2; 15659 n1 = n0.plus( q.times( d2 = n1 ) ); 15660 n0 = d2; 15661 d = n.minus( q.times( d2 = d ) ); 15662 n = d2; 15663 } 15664 15665 d2 = div( md.minus(d0), d1, 0, 1 ); 15666 n0 = n0.plus( d2.times(n1) ); 15667 d0 = d0.plus( d2.times(d1) ); 15668 n0.s = n1.s = x.s; 15669 e *= 2; 15670 15671 // Determine which fraction is closer to x, n0/d0 or n1/d1 15672 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp( 15673 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 15674 ? [ n1.toString(), d1.toString() ] 15675 : [ n0.toString(), d0.toString() ]; 15676 15677 MAX_EXP = exp; 15678 return arr; 15679 }; 15680 15681 15682 /* 15683 * Return the value of this BigNumber converted to a number primitive. 15684 */ 15685 P.toNumber = function () { 15686 var x = this; 15687 15688 // Ensure zero has correct sign. 15689 return +x || ( x.s ? x.s * 0 : NaN ); 15690 }; 15691 15692 15693 /* 15694 * Return a BigNumber whose value is the value of this BigNumber raised to the power n. 15695 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. 15696 * If POW_PRECISION is not 0, round to POW_PRECISION using ROUNDING_MODE. 15697 * 15698 * n {number} Integer, -9007199254740992 to 9007199254740992 inclusive. 15699 * (Performs 54 loop iterations for n of 9007199254740992.) 15700 * 15701 * 'pow() exponent not an integer: {n}' 15702 * 'pow() exponent out of range: {n}' 15703 */ 15704 P.toPower = P.pow = function (n) { 15705 var k, y, 15706 i = mathfloor( n < 0 ? -n : +n ), 15707 x = this; 15708 15709 // Pass ±Infinity to Math.pow if exponent is out of range. 15710 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && 15711 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || 15712 parseFloat(n) != n && !( n = NaN ) ) ) { 15713 return new BigNumber( Math.pow( +x, n ) ); 15714 } 15715 15716 // Truncating each coefficient array to a length of k after each multiplication equates 15717 // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a 15718 // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.) 15719 k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0; 15720 y = new BigNumber(ONE); 15721 15722 for ( ; ; ) { 15723 15724 if ( i % 2 ) { 15725 y = y.times(x); 15726 if ( !y.c ) break; 15727 if ( k && y.c.length > k ) y.c.length = k; 15728 } 15729 15730 i = mathfloor( i / 2 ); 15731 if ( !i ) break; 15732 15733 x = x.times(x); 15734 if ( k && x.c && x.c.length > k ) x.c.length = k; 15735 } 15736 15737 if ( n < 0 ) y = ONE.div(y); 15738 return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; 15739 }; 15740 15741 15742 /* 15743 * Return a string representing the value of this BigNumber rounded to sd significant digits 15744 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits 15745 * necessary to represent the integer part of the value in fixed-point notation, then use 15746 * exponential notation. 15747 * 15748 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. 15749 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15750 * 15751 * 'toPrecision() precision not an integer: {sd}' 15752 * 'toPrecision() precision out of range: {sd}' 15753 * 'toPrecision() rounding mode not an integer: {rm}' 15754 * 'toPrecision() rounding mode out of range: {rm}' 15755 */ 15756 P.toPrecision = function ( sd, rm ) { 15757 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) 15758 ? sd | 0 : null, rm, 24 ); 15759 }; 15760 15761 15762 /* 15763 * Return a string representing the value of this BigNumber in base b, or base 10 if b is 15764 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and 15765 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent 15766 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than 15767 * TO_EXP_NEG, return exponential notation. 15768 * 15769 * [b] {number} Integer, 2 to 64 inclusive. 15770 * 15771 * 'toString() base not an integer: {b}' 15772 * 'toString() base out of range: {b}' 15773 */ 15774 P.toString = function (b) { 15775 var str, 15776 n = this, 15777 s = n.s, 15778 e = n.e; 15779 15780 // Infinity or NaN? 15781 if ( e === null ) { 15782 15783 if (s) { 15784 str = 'Infinity'; 15785 if ( s < 0 ) str = '-' + str; 15786 } else { 15787 str = 'NaN'; 15788 } 15789 } else { 15790 str = coeffToString( n.c ); 15791 15792 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) { 15793 str = e <= TO_EXP_NEG || e >= TO_EXP_POS 15794 ? toExponential( str, e ) 15795 : toFixedPoint( str, e ); 15796 } else { 15797 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); 15798 } 15799 15800 if ( s < 0 && n.c[0] ) str = '-' + str; 15801 } 15802 15803 return str; 15804 }; 15805 15806 15807 /* 15808 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole 15809 * number. 15810 */ 15811 P.truncated = P.trunc = function () { 15812 return round( new BigNumber(this), this.e + 1, 1 ); 15813 }; 15814 15815 15816 15817 /* 15818 * Return as toString, but do not accept a base argument. 15819 */ 15820 P.valueOf = P.toJSON = function () { 15821 return this.toString(); 15822 }; 15823 15824 15825 // Aliases for BigDecimal methods. 15826 //P.add = P.plus; // P.add included above 15827 //P.subtract = P.minus; // P.sub included above 15828 //P.multiply = P.times; // P.mul included above 15829 //P.divide = P.div; 15830 //P.remainder = P.mod; 15831 //P.compareTo = P.cmp; 15832 //P.negate = P.neg; 15833 15834 15835 if ( configObj != null ) BigNumber.config(configObj); 15836 15837 return BigNumber; 15838 } 15839 15840 15841 // PRIVATE HELPER FUNCTIONS 15842 15843 15844 function bitFloor(n) { 15845 var i = n | 0; 15846 return n > 0 || n === i ? i : i - 1; 15847 } 15848 15849 15850 // Return a coefficient array as a string of base 10 digits. 15851 function coeffToString(a) { 15852 var s, z, 15853 i = 1, 15854 j = a.length, 15855 r = a[0] + ''; 15856 15857 for ( ; i < j; ) { 15858 s = a[i++] + ''; 15859 z = LOG_BASE - s.length; 15860 for ( ; z--; s = '0' + s ); 15861 r += s; 15862 } 15863 15864 // Determine trailing zeros. 15865 for ( j = r.length; r.charCodeAt(--j) === 48; ); 15866 return r.slice( 0, j + 1 || 1 ); 15867 } 15868 15869 15870 // Compare the value of BigNumbers x and y. 15871 function compare( x, y ) { 15872 var a, b, 15873 xc = x.c, 15874 yc = y.c, 15875 i = x.s, 15876 j = y.s, 15877 k = x.e, 15878 l = y.e; 15879 15880 // Either NaN? 15881 if ( !i || !j ) return null; 15882 15883 a = xc && !xc[0]; 15884 b = yc && !yc[0]; 15885 15886 // Either zero? 15887 if ( a || b ) return a ? b ? 0 : -j : i; 15888 15889 // Signs differ? 15890 if ( i != j ) return i; 15891 15892 a = i < 0; 15893 b = k == l; 15894 15895 // Either Infinity? 15896 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; 15897 15898 // Compare exponents. 15899 if ( !b ) return k > l ^ a ? 1 : -1; 15900 15901 j = ( k = xc.length ) < ( l = yc.length ) ? k : l; 15902 15903 // Compare digit by digit. 15904 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1; 15905 15906 // Compare lengths. 15907 return k == l ? 0 : k > l ^ a ? 1 : -1; 15908 } 15909 15910 15911 /* 15912 * Return true if n is a valid number in range, otherwise false. 15913 * Use for argument validation when ERRORS is false. 15914 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10. 15915 */ 15916 function intValidatorNoErrors( n, min, max ) { 15917 return ( n = truncate(n) ) >= min && n <= max; 15918 } 15919 15920 15921 function isArray(obj) { 15922 return Object.prototype.toString.call(obj) == '[object Array]'; 15923 } 15924 15925 15926 /* 15927 * Convert string of baseIn to an array of numbers of baseOut. 15928 * Eg. convertBase('255', 10, 16) returns [15, 15]. 15929 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. 15930 */ 15931 function toBaseOut( str, baseIn, baseOut ) { 15932 var j, 15933 arr = [0], 15934 arrL, 15935 i = 0, 15936 len = str.length; 15937 15938 for ( ; i < len; ) { 15939 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); 15940 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) ); 15941 15942 for ( ; j < arr.length; j++ ) { 15943 15944 if ( arr[j] > baseOut - 1 ) { 15945 if ( arr[j + 1] == null ) arr[j + 1] = 0; 15946 arr[j + 1] += arr[j] / baseOut | 0; 15947 arr[j] %= baseOut; 15948 } 15949 } 15950 } 15951 15952 return arr.reverse(); 15953 } 15954 15955 15956 function toExponential( str, e ) { 15957 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + 15958 ( e < 0 ? 'e' : 'e+' ) + e; 15959 } 15960 15961 15962 function toFixedPoint( str, e ) { 15963 var len, z; 15964 15965 // Negative exponent? 15966 if ( e < 0 ) { 15967 15968 // Prepend zeros. 15969 for ( z = '0.'; ++e; z += '0' ); 15970 str = z + str; 15971 15972 // Positive exponent 15973 } else { 15974 len = str.length; 15975 15976 // Append zeros. 15977 if ( ++e > len ) { 15978 for ( z = '0', e -= len; --e; z += '0' ); 15979 str += z; 15980 } else if ( e < len ) { 15981 str = str.slice( 0, e ) + '.' + str.slice(e); 15982 } 15983 } 15984 15985 return str; 15986 } 15987 15988 15989 function truncate(n) { 15990 n = parseFloat(n); 15991 return n < 0 ? mathceil(n) : mathfloor(n); 15992 } 15993 15994 15995 // EXPORT 15996 15997 15998 BigNumber = another(); 15999 16000 // AMD. 16001 if ( typeof define == 'function' && define.amd ) { 16002 define( function () { return BigNumber; } ); 16003 16004 // Node and other environments that support module.exports. 16005 } else if ( typeof module != 'undefined' && module.exports ) { 16006 module.exports = BigNumber; 16007 if ( !crypto ) try { crypto = require('crypto'); } catch (e) {} 16008 16009 // Browser. 16010 } else { 16011 global.BigNumber = BigNumber; 16012 } 16013 })(this); 16014 16015 },{"crypto":49}],"web3":[function(require,module,exports){ 16016 var Web3 = require('./lib/web3'); 16017 16018 // dont override global variable 16019 if (typeof window !== 'undefined' && typeof window.Web3 === 'undefined') { 16020 window.Web3 = Web3; 16021 } 16022 16023 module.exports = Web3; 16024 16025 },{"./lib/web3":22}]},{},["web3"]) 16026 //# sourceMappingURL=web3.js.map 16027 `