github.com/waltonchain/waltonchain_gwtc_src@v1.1.4-0.20201225072101-8a298c95a819/internal/jsre/deps/web3.js (about) 1 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){ 2 module.exports=[ 3 { 4 "constant": true, 5 "inputs": [ 6 { 7 "name": "_owner", 8 "type": "address" 9 } 10 ], 11 "name": "name", 12 "outputs": [ 13 { 14 "name": "o_name", 15 "type": "bytes32" 16 } 17 ], 18 "type": "function" 19 }, 20 { 21 "constant": true, 22 "inputs": [ 23 { 24 "name": "_name", 25 "type": "bytes32" 26 } 27 ], 28 "name": "owner", 29 "outputs": [ 30 { 31 "name": "", 32 "type": "address" 33 } 34 ], 35 "type": "function" 36 }, 37 { 38 "constant": true, 39 "inputs": [ 40 { 41 "name": "_name", 42 "type": "bytes32" 43 } 44 ], 45 "name": "content", 46 "outputs": [ 47 { 48 "name": "", 49 "type": "bytes32" 50 } 51 ], 52 "type": "function" 53 }, 54 { 55 "constant": true, 56 "inputs": [ 57 { 58 "name": "_name", 59 "type": "bytes32" 60 } 61 ], 62 "name": "addr", 63 "outputs": [ 64 { 65 "name": "", 66 "type": "address" 67 } 68 ], 69 "type": "function" 70 }, 71 { 72 "constant": false, 73 "inputs": [ 74 { 75 "name": "_name", 76 "type": "bytes32" 77 } 78 ], 79 "name": "reserve", 80 "outputs": [], 81 "type": "function" 82 }, 83 { 84 "constant": true, 85 "inputs": [ 86 { 87 "name": "_name", 88 "type": "bytes32" 89 } 90 ], 91 "name": "subRegistrar", 92 "outputs": [ 93 { 94 "name": "", 95 "type": "address" 96 } 97 ], 98 "type": "function" 99 }, 100 { 101 "constant": false, 102 "inputs": [ 103 { 104 "name": "_name", 105 "type": "bytes32" 106 }, 107 { 108 "name": "_newOwner", 109 "type": "address" 110 } 111 ], 112 "name": "transfer", 113 "outputs": [], 114 "type": "function" 115 }, 116 { 117 "constant": false, 118 "inputs": [ 119 { 120 "name": "_name", 121 "type": "bytes32" 122 }, 123 { 124 "name": "_registrar", 125 "type": "address" 126 } 127 ], 128 "name": "setSubRegistrar", 129 "outputs": [], 130 "type": "function" 131 }, 132 { 133 "constant": false, 134 "inputs": [], 135 "name": "Registrar", 136 "outputs": [], 137 "type": "function" 138 }, 139 { 140 "constant": false, 141 "inputs": [ 142 { 143 "name": "_name", 144 "type": "bytes32" 145 }, 146 { 147 "name": "_a", 148 "type": "address" 149 }, 150 { 151 "name": "_primary", 152 "type": "bool" 153 } 154 ], 155 "name": "setAddress", 156 "outputs": [], 157 "type": "function" 158 }, 159 { 160 "constant": false, 161 "inputs": [ 162 { 163 "name": "_name", 164 "type": "bytes32" 165 }, 166 { 167 "name": "_content", 168 "type": "bytes32" 169 } 170 ], 171 "name": "setContent", 172 "outputs": [], 173 "type": "function" 174 }, 175 { 176 "constant": false, 177 "inputs": [ 178 { 179 "name": "_name", 180 "type": "bytes32" 181 } 182 ], 183 "name": "disown", 184 "outputs": [], 185 "type": "function" 186 }, 187 { 188 "anonymous": false, 189 "inputs": [ 190 { 191 "indexed": true, 192 "name": "_name", 193 "type": "bytes32" 194 }, 195 { 196 "indexed": false, 197 "name": "_winner", 198 "type": "address" 199 } 200 ], 201 "name": "AuctionEnded", 202 "type": "event" 203 }, 204 { 205 "anonymous": false, 206 "inputs": [ 207 { 208 "indexed": true, 209 "name": "_name", 210 "type": "bytes32" 211 }, 212 { 213 "indexed": false, 214 "name": "_bidder", 215 "type": "address" 216 }, 217 { 218 "indexed": false, 219 "name": "_value", 220 "type": "uint256" 221 } 222 ], 223 "name": "NewBid", 224 "type": "event" 225 }, 226 { 227 "anonymous": false, 228 "inputs": [ 229 { 230 "indexed": true, 231 "name": "name", 232 "type": "bytes32" 233 } 234 ], 235 "name": "Changed", 236 "type": "event" 237 }, 238 { 239 "anonymous": false, 240 "inputs": [ 241 { 242 "indexed": true, 243 "name": "name", 244 "type": "bytes32" 245 }, 246 { 247 "indexed": true, 248 "name": "addr", 249 "type": "address" 250 } 251 ], 252 "name": "PrimaryChanged", 253 "type": "event" 254 } 255 ] 256 257 },{}],2:[function(require,module,exports){ 258 module.exports=[ 259 { 260 "constant": true, 261 "inputs": [ 262 { 263 "name": "_name", 264 "type": "bytes32" 265 } 266 ], 267 "name": "owner", 268 "outputs": [ 269 { 270 "name": "", 271 "type": "address" 272 } 273 ], 274 "type": "function" 275 }, 276 { 277 "constant": false, 278 "inputs": [ 279 { 280 "name": "_name", 281 "type": "bytes32" 282 }, 283 { 284 "name": "_refund", 285 "type": "address" 286 } 287 ], 288 "name": "disown", 289 "outputs": [], 290 "type": "function" 291 }, 292 { 293 "constant": true, 294 "inputs": [ 295 { 296 "name": "_name", 297 "type": "bytes32" 298 } 299 ], 300 "name": "addr", 301 "outputs": [ 302 { 303 "name": "", 304 "type": "address" 305 } 306 ], 307 "type": "function" 308 }, 309 { 310 "constant": false, 311 "inputs": [ 312 { 313 "name": "_name", 314 "type": "bytes32" 315 } 316 ], 317 "name": "reserve", 318 "outputs": [], 319 "type": "function" 320 }, 321 { 322 "constant": false, 323 "inputs": [ 324 { 325 "name": "_name", 326 "type": "bytes32" 327 }, 328 { 329 "name": "_newOwner", 330 "type": "address" 331 } 332 ], 333 "name": "transfer", 334 "outputs": [], 335 "type": "function" 336 }, 337 { 338 "constant": false, 339 "inputs": [ 340 { 341 "name": "_name", 342 "type": "bytes32" 343 }, 344 { 345 "name": "_a", 346 "type": "address" 347 } 348 ], 349 "name": "setAddr", 350 "outputs": [], 351 "type": "function" 352 }, 353 { 354 "anonymous": false, 355 "inputs": [ 356 { 357 "indexed": true, 358 "name": "name", 359 "type": "bytes32" 360 } 361 ], 362 "name": "Changed", 363 "type": "event" 364 } 365 ] 366 367 },{}],3:[function(require,module,exports){ 368 module.exports=[ 369 { 370 "constant": false, 371 "inputs": [ 372 { 373 "name": "from", 374 "type": "bytes32" 375 }, 376 { 377 "name": "to", 378 "type": "address" 379 }, 380 { 381 "name": "value", 382 "type": "uint256" 383 } 384 ], 385 "name": "transfer", 386 "outputs": [], 387 "type": "function" 388 }, 389 { 390 "constant": false, 391 "inputs": [ 392 { 393 "name": "from", 394 "type": "bytes32" 395 }, 396 { 397 "name": "to", 398 "type": "address" 399 }, 400 { 401 "name": "indirectId", 402 "type": "bytes32" 403 }, 404 { 405 "name": "value", 406 "type": "uint256" 407 } 408 ], 409 "name": "icapTransfer", 410 "outputs": [], 411 "type": "function" 412 }, 413 { 414 "constant": false, 415 "inputs": [ 416 { 417 "name": "to", 418 "type": "bytes32" 419 } 420 ], 421 "name": "deposit", 422 "outputs": [], 423 "payable": true, 424 "type": "function" 425 }, 426 { 427 "anonymous": false, 428 "inputs": [ 429 { 430 "indexed": true, 431 "name": "from", 432 "type": "address" 433 }, 434 { 435 "indexed": false, 436 "name": "value", 437 "type": "uint256" 438 } 439 ], 440 "name": "AnonymousDeposit", 441 "type": "event" 442 }, 443 { 444 "anonymous": false, 445 "inputs": [ 446 { 447 "indexed": true, 448 "name": "from", 449 "type": "address" 450 }, 451 { 452 "indexed": true, 453 "name": "to", 454 "type": "bytes32" 455 }, 456 { 457 "indexed": false, 458 "name": "value", 459 "type": "uint256" 460 } 461 ], 462 "name": "Deposit", 463 "type": "event" 464 }, 465 { 466 "anonymous": false, 467 "inputs": [ 468 { 469 "indexed": true, 470 "name": "from", 471 "type": "bytes32" 472 }, 473 { 474 "indexed": true, 475 "name": "to", 476 "type": "address" 477 }, 478 { 479 "indexed": false, 480 "name": "value", 481 "type": "uint256" 482 } 483 ], 484 "name": "Transfer", 485 "type": "event" 486 }, 487 { 488 "anonymous": false, 489 "inputs": [ 490 { 491 "indexed": true, 492 "name": "from", 493 "type": "bytes32" 494 }, 495 { 496 "indexed": true, 497 "name": "to", 498 "type": "address" 499 }, 500 { 501 "indexed": false, 502 "name": "indirectId", 503 "type": "bytes32" 504 }, 505 { 506 "indexed": false, 507 "name": "value", 508 "type": "uint256" 509 } 510 ], 511 "name": "IcapTransfer", 512 "type": "event" 513 } 514 ] 515 516 },{}],4:[function(require,module,exports){ 517 var f = require('./formatters'); 518 var SolidityType = require('./type'); 519 520 /** 521 * SolidityTypeAddress is a prootype that represents address type 522 * It matches: 523 * address 524 * address[] 525 * address[4] 526 * address[][] 527 * address[3][] 528 * address[][6][], ... 529 */ 530 var SolidityTypeAddress = function () { 531 this._inputFormatter = f.formatInputInt; 532 this._outputFormatter = f.formatOutputAddress; 533 }; 534 535 SolidityTypeAddress.prototype = new SolidityType({}); 536 SolidityTypeAddress.prototype.constructor = SolidityTypeAddress; 537 538 SolidityTypeAddress.prototype.isType = function (name) { 539 return !!name.match(/address(\[([0-9]*)\])?/); 540 }; 541 542 module.exports = SolidityTypeAddress; 543 544 },{"./formatters":9,"./type":14}],5:[function(require,module,exports){ 545 var f = require('./formatters'); 546 var SolidityType = require('./type'); 547 548 /** 549 * SolidityTypeBool is a prootype that represents bool type 550 * It matches: 551 * bool 552 * bool[] 553 * bool[4] 554 * bool[][] 555 * bool[3][] 556 * bool[][6][], ... 557 */ 558 var SolidityTypeBool = function () { 559 this._inputFormatter = f.formatInputBool; 560 this._outputFormatter = f.formatOutputBool; 561 }; 562 563 SolidityTypeBool.prototype = new SolidityType({}); 564 SolidityTypeBool.prototype.constructor = SolidityTypeBool; 565 566 SolidityTypeBool.prototype.isType = function (name) { 567 return !!name.match(/^bool(\[([0-9]*)\])*$/); 568 }; 569 570 module.exports = SolidityTypeBool; 571 572 },{"./formatters":9,"./type":14}],6:[function(require,module,exports){ 573 var f = require('./formatters'); 574 var SolidityType = require('./type'); 575 576 /** 577 * SolidityTypeBytes is a prototype that represents the bytes type. 578 * It matches: 579 * bytes 580 * bytes[] 581 * bytes[4] 582 * bytes[][] 583 * bytes[3][] 584 * bytes[][6][], ... 585 * bytes32 586 * bytes8[4] 587 * bytes[3][] 588 */ 589 var SolidityTypeBytes = function () { 590 this._inputFormatter = f.formatInputBytes; 591 this._outputFormatter = f.formatOutputBytes; 592 }; 593 594 SolidityTypeBytes.prototype = new SolidityType({}); 595 SolidityTypeBytes.prototype.constructor = SolidityTypeBytes; 596 597 SolidityTypeBytes.prototype.isType = function (name) { 598 return !!name.match(/^bytes([0-9]{1,})(\[([0-9]*)\])*$/); 599 }; 600 601 module.exports = SolidityTypeBytes; 602 603 },{"./formatters":9,"./type":14}],7:[function(require,module,exports){ 604 /* 605 This file is part of web3.js. 606 607 web3.js is free software: you can redistribute it and/or modify 608 it under the terms of the GNU Lesser General Public License as published by 609 the Free Software Foundation, either version 3 of the License, or 610 (at your option) any later version. 611 612 web3.js is distributed in the hope that it will be useful, 613 but WITHOUT ANY WARRANTY; without even the implied warranty of 614 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 615 GNU Lesser General Public License for more details. 616 617 You should have received a copy of the GNU Lesser General Public License 618 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 619 */ 620 /** 621 * @file coder.js 622 * @author Marek Kotewicz <marek@ethdev.com> 623 * @date 2015 624 */ 625 626 var f = require('./formatters'); 627 628 var SolidityTypeAddress = require('./address'); 629 var SolidityTypeBool = require('./bool'); 630 var SolidityTypeInt = require('./int'); 631 var SolidityTypeUInt = require('./uint'); 632 var SolidityTypeDynamicBytes = require('./dynamicbytes'); 633 var SolidityTypeString = require('./string'); 634 var SolidityTypeReal = require('./real'); 635 var SolidityTypeUReal = require('./ureal'); 636 var SolidityTypeBytes = require('./bytes'); 637 638 var isDynamic = function (solidityType, type) { 639 return solidityType.isDynamicType(type) || 640 solidityType.isDynamicArray(type); 641 }; 642 643 /** 644 * SolidityCoder prototype should be used to encode/decode solidity params of any type 645 */ 646 var SolidityCoder = function (types) { 647 this._types = types; 648 }; 649 650 /** 651 * This method should be used to transform type to SolidityType 652 * 653 * @method _requireType 654 * @param {String} type 655 * @returns {SolidityType} 656 * @throws {Error} throws if no matching type is found 657 */ 658 SolidityCoder.prototype._requireType = function (type) { 659 var solidityType = this._types.filter(function (t) { 660 return t.isType(type); 661 })[0]; 662 663 if (!solidityType) { 664 throw Error('invalid solidity type!: ' + type); 665 } 666 667 return solidityType; 668 }; 669 670 /** 671 * Should be used to encode plain param 672 * 673 * @method encodeParam 674 * @param {String} type 675 * @param {Object} plain param 676 * @return {String} encoded plain param 677 */ 678 SolidityCoder.prototype.encodeParam = function (type, param) { 679 return this.encodeParams([type], [param]); 680 }; 681 682 /** 683 * Should be used to encode list of params 684 * 685 * @method encodeParams 686 * @param {Array} types 687 * @param {Array} params 688 * @return {String} encoded list of params 689 */ 690 SolidityCoder.prototype.encodeParams = function (types, params) { 691 var solidityTypes = this.getSolidityTypes(types); 692 693 var encodeds = solidityTypes.map(function (solidityType, index) { 694 return solidityType.encode(params[index], types[index]); 695 }); 696 697 var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) { 698 var staticPartLength = solidityType.staticPartLength(types[index]); 699 var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32; 700 701 return acc + (isDynamic(solidityTypes[index], types[index]) ? 702 32 : 703 roundedStaticPartLength); 704 }, 0); 705 706 var result = this.encodeMultiWithOffset(types, solidityTypes, encodeds, dynamicOffset); 707 708 return result; 709 }; 710 711 SolidityCoder.prototype.encodeMultiWithOffset = function (types, solidityTypes, encodeds, dynamicOffset) { 712 var result = ""; 713 var self = this; 714 715 types.forEach(function (type, i) { 716 if (isDynamic(solidityTypes[i], types[i])) { 717 result += f.formatInputInt(dynamicOffset).encode(); 718 var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); 719 dynamicOffset += e.length / 2; 720 } else { 721 // don't add length to dynamicOffset. it's already counted 722 result += self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); 723 } 724 725 // TODO: figure out nested arrays 726 }); 727 728 types.forEach(function (type, i) { 729 if (isDynamic(solidityTypes[i], types[i])) { 730 var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); 731 dynamicOffset += e.length / 2; 732 result += e; 733 } 734 }); 735 return result; 736 }; 737 738 // TODO: refactor whole encoding! 739 SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded, offset) { 740 var self = this; 741 if (solidityType.isDynamicArray(type)) { 742 return (function () { 743 // offset was already set 744 var nestedName = solidityType.nestedName(type); 745 var nestedStaticPartLength = solidityType.staticPartLength(nestedName); 746 var result = encoded[0]; 747 748 (function () { 749 var previousLength = 2; // in int 750 if (solidityType.isDynamicArray(nestedName)) { 751 for (var i = 1; i < encoded.length; i++) { 752 previousLength += +(encoded[i - 1])[0] || 0; 753 result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode(); 754 } 755 } 756 })(); 757 758 // first element is length, skip it 759 (function () { 760 for (var i = 0; i < encoded.length - 1; i++) { 761 var additionalOffset = result / 2; 762 result += self.encodeWithOffset(nestedName, solidityType, encoded[i + 1], offset + additionalOffset); 763 } 764 })(); 765 766 return result; 767 })(); 768 769 } else if (solidityType.isStaticArray(type)) { 770 return (function () { 771 var nestedName = solidityType.nestedName(type); 772 var nestedStaticPartLength = solidityType.staticPartLength(nestedName); 773 var result = ""; 774 775 776 if (solidityType.isDynamicArray(nestedName)) { 777 (function () { 778 var previousLength = 0; // in int 779 for (var i = 0; i < encoded.length; i++) { 780 // calculate length of previous item 781 previousLength += +(encoded[i - 1] || [])[0] || 0; 782 result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode(); 783 } 784 })(); 785 } 786 787 (function () { 788 for (var i = 0; i < encoded.length; i++) { 789 var additionalOffset = result / 2; 790 result += self.encodeWithOffset(nestedName, solidityType, encoded[i], offset + additionalOffset); 791 } 792 })(); 793 794 return result; 795 })(); 796 } 797 798 return encoded; 799 }; 800 801 /** 802 * Should be used to decode bytes to plain param 803 * 804 * @method decodeParam 805 * @param {String} type 806 * @param {String} bytes 807 * @return {Object} plain param 808 */ 809 SolidityCoder.prototype.decodeParam = function (type, bytes) { 810 return this.decodeParams([type], bytes)[0]; 811 }; 812 813 /** 814 * Should be used to decode list of params 815 * 816 * @method decodeParam 817 * @param {Array} types 818 * @param {String} bytes 819 * @return {Array} array of plain params 820 */ 821 SolidityCoder.prototype.decodeParams = function (types, bytes) { 822 var solidityTypes = this.getSolidityTypes(types); 823 var offsets = this.getOffsets(types, solidityTypes); 824 825 return solidityTypes.map(function (solidityType, index) { 826 return solidityType.decode(bytes, offsets[index], types[index], index); 827 }); 828 }; 829 830 SolidityCoder.prototype.getOffsets = function (types, solidityTypes) { 831 var lengths = solidityTypes.map(function (solidityType, index) { 832 return solidityType.staticPartLength(types[index]); 833 }); 834 835 for (var i = 1; i < lengths.length; i++) { 836 // sum with length of previous element 837 lengths[i] += lengths[i - 1]; 838 } 839 840 return lengths.map(function (length, index) { 841 // remove the current length, so the length is sum of previous elements 842 var staticPartLength = solidityTypes[index].staticPartLength(types[index]); 843 return length - staticPartLength; 844 }); 845 }; 846 847 SolidityCoder.prototype.getSolidityTypes = function (types) { 848 var self = this; 849 return types.map(function (type) { 850 return self._requireType(type); 851 }); 852 }; 853 854 var coder = new SolidityCoder([ 855 new SolidityTypeAddress(), 856 new SolidityTypeBool(), 857 new SolidityTypeInt(), 858 new SolidityTypeUInt(), 859 new SolidityTypeDynamicBytes(), 860 new SolidityTypeBytes(), 861 new SolidityTypeString(), 862 new SolidityTypeReal(), 863 new SolidityTypeUReal() 864 ]); 865 866 module.exports = coder; 867 868 },{"./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){ 869 var f = require('./formatters'); 870 var SolidityType = require('./type'); 871 872 var SolidityTypeDynamicBytes = function () { 873 this._inputFormatter = f.formatInputDynamicBytes; 874 this._outputFormatter = f.formatOutputDynamicBytes; 875 }; 876 877 SolidityTypeDynamicBytes.prototype = new SolidityType({}); 878 SolidityTypeDynamicBytes.prototype.constructor = SolidityTypeDynamicBytes; 879 880 SolidityTypeDynamicBytes.prototype.isType = function (name) { 881 return !!name.match(/^bytes(\[([0-9]*)\])*$/); 882 }; 883 884 SolidityTypeDynamicBytes.prototype.isDynamicType = function () { 885 return true; 886 }; 887 888 module.exports = SolidityTypeDynamicBytes; 889 890 },{"./formatters":9,"./type":14}],9:[function(require,module,exports){ 891 /* 892 This file is part of web3.js. 893 894 web3.js is free software: you can redistribute it and/or modify 895 it under the terms of the GNU Lesser General Public License as published by 896 the Free Software Foundation, either version 3 of the License, or 897 (at your option) any later version. 898 899 web3.js is distributed in the hope that it will be useful, 900 but WITHOUT ANY WARRANTY; without even the implied warranty of 901 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 902 GNU Lesser General Public License for more details. 903 904 You should have received a copy of the GNU Lesser General Public License 905 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 906 */ 907 /** 908 * @file formatters.js 909 * @author Marek Kotewicz <marek@ethdev.com> 910 * @date 2015 911 */ 912 913 var BigNumber = require('bignumber.js'); 914 var utils = require('../utils/utils'); 915 var c = require('../utils/config'); 916 var SolidityParam = require('./param'); 917 918 919 /** 920 * Formats input value to byte representation of int 921 * If value is negative, return it's two's complement 922 * If the value is floating point, round it down 923 * 924 * @method formatInputInt 925 * @param {String|Number|BigNumber} value that needs to be formatted 926 * @returns {SolidityParam} 927 */ 928 var formatInputInt = function (value) { 929 BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE); 930 var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64); 931 return new SolidityParam(result); 932 }; 933 934 /** 935 * Formats input bytes 936 * 937 * @method formatInputBytes 938 * @param {String} 939 * @returns {SolidityParam} 940 */ 941 var formatInputBytes = function (value) { 942 var result = utils.toHex(value).substr(2); 943 var l = Math.floor((result.length + 63) / 64); 944 result = utils.padRight(result, l * 64); 945 return new SolidityParam(result); 946 }; 947 948 /** 949 * Formats input bytes 950 * 951 * @method formatDynamicInputBytes 952 * @param {String} 953 * @returns {SolidityParam} 954 */ 955 var formatInputDynamicBytes = function (value) { 956 var result = utils.toHex(value).substr(2); 957 var length = result.length / 2; 958 var l = Math.floor((result.length + 63) / 64); 959 result = utils.padRight(result, l * 64); 960 return new SolidityParam(formatInputInt(length).value + result); 961 }; 962 963 /** 964 * Formats input value to byte representation of string 965 * 966 * @method formatInputString 967 * @param {String} 968 * @returns {SolidityParam} 969 */ 970 var formatInputString = function (value) { 971 var result = utils.fromUtf8(value).substr(2); 972 var length = result.length / 2; 973 var l = Math.floor((result.length + 63) / 64); 974 result = utils.padRight(result, l * 64); 975 return new SolidityParam(formatInputInt(length).value + result); 976 }; 977 978 /** 979 * Formats input value to byte representation of bool 980 * 981 * @method formatInputBool 982 * @param {Boolean} 983 * @returns {SolidityParam} 984 */ 985 var formatInputBool = function (value) { 986 var result = '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0'); 987 return new SolidityParam(result); 988 }; 989 990 /** 991 * Formats input value to byte representation of real 992 * Values are multiplied by 2^m and encoded as integers 993 * 994 * @method formatInputReal 995 * @param {String|Number|BigNumber} 996 * @returns {SolidityParam} 997 */ 998 var formatInputReal = function (value) { 999 return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128))); 1000 }; 1001 1002 /** 1003 * Check if input value is negative 1004 * 1005 * @method signedIsNegative 1006 * @param {String} value is hex format 1007 * @returns {Boolean} true if it is negative, otherwise false 1008 */ 1009 var signedIsNegative = function (value) { 1010 return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1'; 1011 }; 1012 1013 /** 1014 * Formats right-aligned output bytes to int 1015 * 1016 * @method formatOutputInt 1017 * @param {SolidityParam} param 1018 * @returns {BigNumber} right-aligned output bytes formatted to big number 1019 */ 1020 var formatOutputInt = function (param) { 1021 var value = param.staticPart() || "0"; 1022 1023 // check if it's negative number 1024 // it it is, return two's complement 1025 if (signedIsNegative(value)) { 1026 return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1); 1027 } 1028 return new BigNumber(value, 16); 1029 }; 1030 1031 /** 1032 * Formats right-aligned output bytes to uint 1033 * 1034 * @method formatOutputUInt 1035 * @param {SolidityParam} 1036 * @returns {BigNumeber} right-aligned output bytes formatted to uint 1037 */ 1038 var formatOutputUInt = function (param) { 1039 var value = param.staticPart() || "0"; 1040 return new BigNumber(value, 16); 1041 }; 1042 1043 /** 1044 * Formats right-aligned output bytes to real 1045 * 1046 * @method formatOutputReal 1047 * @param {SolidityParam} 1048 * @returns {BigNumber} input bytes formatted to real 1049 */ 1050 var formatOutputReal = function (param) { 1051 return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128)); 1052 }; 1053 1054 /** 1055 * Formats right-aligned output bytes to ureal 1056 * 1057 * @method formatOutputUReal 1058 * @param {SolidityParam} 1059 * @returns {BigNumber} input bytes formatted to ureal 1060 */ 1061 var formatOutputUReal = function (param) { 1062 return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128)); 1063 }; 1064 1065 /** 1066 * Should be used to format output bool 1067 * 1068 * @method formatOutputBool 1069 * @param {SolidityParam} 1070 * @returns {Boolean} right-aligned input bytes formatted to bool 1071 */ 1072 var formatOutputBool = function (param) { 1073 return param.staticPart() === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false; 1074 }; 1075 1076 /** 1077 * Should be used to format output bytes 1078 * 1079 * @method formatOutputBytes 1080 * @param {SolidityParam} left-aligned hex representation of string 1081 * @param {String} name type name 1082 * @returns {String} hex string 1083 */ 1084 var formatOutputBytes = function (param, name) { 1085 var matches = name.match(/^bytes([0-9]*)/); 1086 var size = parseInt(matches[1]); 1087 return '0x' + param.staticPart().slice(0, 2 * size); 1088 }; 1089 1090 /** 1091 * Should be used to format output bytes 1092 * 1093 * @method formatOutputDynamicBytes 1094 * @param {SolidityParam} left-aligned hex representation of string 1095 * @returns {String} hex string 1096 */ 1097 var formatOutputDynamicBytes = function (param) { 1098 var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2; 1099 return '0x' + param.dynamicPart().substr(64, length); 1100 }; 1101 1102 /** 1103 * Should be used to format output string 1104 * 1105 * @method formatOutputString 1106 * @param {SolidityParam} left-aligned hex representation of string 1107 * @returns {String} ascii string 1108 */ 1109 var formatOutputString = function (param) { 1110 var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2; 1111 return utils.toUtf8(param.dynamicPart().substr(64, length)); 1112 }; 1113 1114 /** 1115 * Should be used to format output address 1116 * 1117 * @method formatOutputAddress 1118 * @param {SolidityParam} right-aligned input bytes 1119 * @returns {String} address 1120 */ 1121 var formatOutputAddress = function (param) { 1122 var value = param.staticPart(); 1123 return "0x" + value.slice(value.length - 40, value.length); 1124 }; 1125 1126 module.exports = { 1127 formatInputInt: formatInputInt, 1128 formatInputBytes: formatInputBytes, 1129 formatInputDynamicBytes: formatInputDynamicBytes, 1130 formatInputString: formatInputString, 1131 formatInputBool: formatInputBool, 1132 formatInputReal: formatInputReal, 1133 formatOutputInt: formatOutputInt, 1134 formatOutputUInt: formatOutputUInt, 1135 formatOutputReal: formatOutputReal, 1136 formatOutputUReal: formatOutputUReal, 1137 formatOutputBool: formatOutputBool, 1138 formatOutputBytes: formatOutputBytes, 1139 formatOutputDynamicBytes: formatOutputDynamicBytes, 1140 formatOutputString: formatOutputString, 1141 formatOutputAddress: formatOutputAddress 1142 }; 1143 1144 },{"../utils/config":18,"../utils/utils":20,"./param":11,"bignumber.js":"bignumber.js"}],10:[function(require,module,exports){ 1145 var f = require('./formatters'); 1146 var SolidityType = require('./type'); 1147 1148 /** 1149 * SolidityTypeInt is a prootype that represents int type 1150 * It matches: 1151 * int 1152 * int[] 1153 * int[4] 1154 * int[][] 1155 * int[3][] 1156 * int[][6][], ... 1157 * int32 1158 * int64[] 1159 * int8[4] 1160 * int256[][] 1161 * int[3][] 1162 * int64[][6][], ... 1163 */ 1164 var SolidityTypeInt = function () { 1165 this._inputFormatter = f.formatInputInt; 1166 this._outputFormatter = f.formatOutputInt; 1167 }; 1168 1169 SolidityTypeInt.prototype = new SolidityType({}); 1170 SolidityTypeInt.prototype.constructor = SolidityTypeInt; 1171 1172 SolidityTypeInt.prototype.isType = function (name) { 1173 return !!name.match(/^int([0-9]*)?(\[([0-9]*)\])*$/); 1174 }; 1175 1176 module.exports = SolidityTypeInt; 1177 1178 },{"./formatters":9,"./type":14}],11:[function(require,module,exports){ 1179 /* 1180 This file is part of web3.js. 1181 1182 web3.js is free software: you can redistribute it and/or modify 1183 it under the terms of the GNU Lesser General Public License as published by 1184 the Free Software Foundation, either version 3 of the License, or 1185 (at your option) any later version. 1186 1187 web3.js is distributed in the hope that it will be useful, 1188 but WITHOUT ANY WARRANTY; without even the implied warranty of 1189 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1190 GNU Lesser General Public License for more details. 1191 1192 You should have received a copy of the GNU Lesser General Public License 1193 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1194 */ 1195 /** 1196 * @file param.js 1197 * @author Marek Kotewicz <marek@ethdev.com> 1198 * @date 2015 1199 */ 1200 1201 var utils = require('../utils/utils'); 1202 1203 /** 1204 * SolidityParam object prototype. 1205 * Should be used when encoding, decoding solidity bytes 1206 */ 1207 var SolidityParam = function (value, offset) { 1208 this.value = value || ''; 1209 this.offset = offset; // offset in bytes 1210 }; 1211 1212 /** 1213 * This method should be used to get length of params's dynamic part 1214 * 1215 * @method dynamicPartLength 1216 * @returns {Number} length of dynamic part (in bytes) 1217 */ 1218 SolidityParam.prototype.dynamicPartLength = function () { 1219 return this.dynamicPart().length / 2; 1220 }; 1221 1222 /** 1223 * This method should be used to create copy of solidity param with different offset 1224 * 1225 * @method withOffset 1226 * @param {Number} offset length in bytes 1227 * @returns {SolidityParam} new solidity param with applied offset 1228 */ 1229 SolidityParam.prototype.withOffset = function (offset) { 1230 return new SolidityParam(this.value, offset); 1231 }; 1232 1233 /** 1234 * This method should be used to combine solidity params together 1235 * eg. when appending an array 1236 * 1237 * @method combine 1238 * @param {SolidityParam} param with which we should combine 1239 * @param {SolidityParam} result of combination 1240 */ 1241 SolidityParam.prototype.combine = function (param) { 1242 return new SolidityParam(this.value + param.value); 1243 }; 1244 1245 /** 1246 * This method should be called to check if param has dynamic size. 1247 * If it has, it returns true, otherwise false 1248 * 1249 * @method isDynamic 1250 * @returns {Boolean} 1251 */ 1252 SolidityParam.prototype.isDynamic = function () { 1253 return this.offset !== undefined; 1254 }; 1255 1256 /** 1257 * This method should be called to transform offset to bytes 1258 * 1259 * @method offsetAsBytes 1260 * @returns {String} bytes representation of offset 1261 */ 1262 SolidityParam.prototype.offsetAsBytes = function () { 1263 return !this.isDynamic() ? '' : utils.padLeft(utils.toTwosComplement(this.offset).toString(16), 64); 1264 }; 1265 1266 /** 1267 * This method should be called to get static part of param 1268 * 1269 * @method staticPart 1270 * @returns {String} offset if it is a dynamic param, otherwise value 1271 */ 1272 SolidityParam.prototype.staticPart = function () { 1273 if (!this.isDynamic()) { 1274 return this.value; 1275 } 1276 return this.offsetAsBytes(); 1277 }; 1278 1279 /** 1280 * This method should be called to get dynamic part of param 1281 * 1282 * @method dynamicPart 1283 * @returns {String} returns a value if it is a dynamic param, otherwise empty string 1284 */ 1285 SolidityParam.prototype.dynamicPart = function () { 1286 return this.isDynamic() ? this.value : ''; 1287 }; 1288 1289 /** 1290 * This method should be called to encode param 1291 * 1292 * @method encode 1293 * @returns {String} 1294 */ 1295 SolidityParam.prototype.encode = function () { 1296 return this.staticPart() + this.dynamicPart(); 1297 }; 1298 1299 /** 1300 * This method should be called to encode array of params 1301 * 1302 * @method encodeList 1303 * @param {Array[SolidityParam]} params 1304 * @returns {String} 1305 */ 1306 SolidityParam.encodeList = function (params) { 1307 1308 // updating offsets 1309 var totalOffset = params.length * 32; 1310 var offsetParams = params.map(function (param) { 1311 if (!param.isDynamic()) { 1312 return param; 1313 } 1314 var offset = totalOffset; 1315 totalOffset += param.dynamicPartLength(); 1316 return param.withOffset(offset); 1317 }); 1318 1319 // encode everything! 1320 return offsetParams.reduce(function (result, param) { 1321 return result + param.dynamicPart(); 1322 }, offsetParams.reduce(function (result, param) { 1323 return result + param.staticPart(); 1324 }, '')); 1325 }; 1326 1327 1328 1329 module.exports = SolidityParam; 1330 1331 1332 },{"../utils/utils":20}],12:[function(require,module,exports){ 1333 var f = require('./formatters'); 1334 var SolidityType = require('./type'); 1335 1336 /** 1337 * SolidityTypeReal is a prootype that represents real type 1338 * It matches: 1339 * real 1340 * real[] 1341 * real[4] 1342 * real[][] 1343 * real[3][] 1344 * real[][6][], ... 1345 * real32 1346 * real64[] 1347 * real8[4] 1348 * real256[][] 1349 * real[3][] 1350 * real64[][6][], ... 1351 */ 1352 var SolidityTypeReal = function () { 1353 this._inputFormatter = f.formatInputReal; 1354 this._outputFormatter = f.formatOutputReal; 1355 }; 1356 1357 SolidityTypeReal.prototype = new SolidityType({}); 1358 SolidityTypeReal.prototype.constructor = SolidityTypeReal; 1359 1360 SolidityTypeReal.prototype.isType = function (name) { 1361 return !!name.match(/real([0-9]*)?(\[([0-9]*)\])?/); 1362 }; 1363 1364 module.exports = SolidityTypeReal; 1365 1366 },{"./formatters":9,"./type":14}],13:[function(require,module,exports){ 1367 var f = require('./formatters'); 1368 var SolidityType = require('./type'); 1369 1370 var SolidityTypeString = function () { 1371 this._inputFormatter = f.formatInputString; 1372 this._outputFormatter = f.formatOutputString; 1373 }; 1374 1375 SolidityTypeString.prototype = new SolidityType({}); 1376 SolidityTypeString.prototype.constructor = SolidityTypeString; 1377 1378 SolidityTypeString.prototype.isType = function (name) { 1379 return !!name.match(/^string(\[([0-9]*)\])*$/); 1380 }; 1381 1382 SolidityTypeString.prototype.isDynamicType = function () { 1383 return true; 1384 }; 1385 1386 module.exports = SolidityTypeString; 1387 1388 },{"./formatters":9,"./type":14}],14:[function(require,module,exports){ 1389 var f = require('./formatters'); 1390 var SolidityParam = require('./param'); 1391 1392 /** 1393 * SolidityType prototype is used to encode/decode solidity params of certain type 1394 */ 1395 var SolidityType = function (config) { 1396 this._inputFormatter = config.inputFormatter; 1397 this._outputFormatter = config.outputFormatter; 1398 }; 1399 1400 /** 1401 * Should be used to determine if this SolidityType do match given name 1402 * 1403 * @method isType 1404 * @param {String} name 1405 * @return {Bool} true if type match this SolidityType, otherwise false 1406 */ 1407 SolidityType.prototype.isType = function (name) { 1408 throw "this method should be overrwritten for type " + name; 1409 }; 1410 1411 /** 1412 * Should be used to determine what is the length of static part in given type 1413 * 1414 * @method staticPartLength 1415 * @param {String} name 1416 * @return {Number} length of static part in bytes 1417 */ 1418 SolidityType.prototype.staticPartLength = function (name) { 1419 // If name isn't an array then treat it like a single element array. 1420 return (this.nestedTypes(name) || ['[1]']) 1421 .map(function (type) { 1422 // the length of the nested array 1423 return parseInt(type.slice(1, -1), 10) || 1; 1424 }) 1425 .reduce(function (previous, current) { 1426 return previous * current; 1427 // all basic types are 32 bytes long 1428 }, 32); 1429 }; 1430 1431 /** 1432 * Should be used to determine if type is dynamic array 1433 * eg: 1434 * "type[]" => true 1435 * "type[4]" => false 1436 * 1437 * @method isDynamicArray 1438 * @param {String} name 1439 * @return {Bool} true if the type is dynamic array 1440 */ 1441 SolidityType.prototype.isDynamicArray = function (name) { 1442 var nestedTypes = this.nestedTypes(name); 1443 return !!nestedTypes && !nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g); 1444 }; 1445 1446 /** 1447 * Should be used to determine if type is static array 1448 * eg: 1449 * "type[]" => false 1450 * "type[4]" => true 1451 * 1452 * @method isStaticArray 1453 * @param {String} name 1454 * @return {Bool} true if the type is static array 1455 */ 1456 SolidityType.prototype.isStaticArray = function (name) { 1457 var nestedTypes = this.nestedTypes(name); 1458 return !!nestedTypes && !!nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g); 1459 }; 1460 1461 /** 1462 * Should return length of static array 1463 * eg. 1464 * "int[32]" => 32 1465 * "int256[14]" => 14 1466 * "int[2][3]" => 3 1467 * "int" => 1 1468 * "int[1]" => 1 1469 * "int[]" => 1 1470 * 1471 * @method staticArrayLength 1472 * @param {String} name 1473 * @return {Number} static array length 1474 */ 1475 SolidityType.prototype.staticArrayLength = function (name) { 1476 var nestedTypes = this.nestedTypes(name); 1477 if (nestedTypes) { 1478 return parseInt(nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g) || 1); 1479 } 1480 return 1; 1481 }; 1482 1483 /** 1484 * Should return nested type 1485 * eg. 1486 * "int[32]" => "int" 1487 * "int256[14]" => "int256" 1488 * "int[2][3]" => "int[2]" 1489 * "int" => "int" 1490 * "int[]" => "int" 1491 * 1492 * @method nestedName 1493 * @param {String} name 1494 * @return {String} nested name 1495 */ 1496 SolidityType.prototype.nestedName = function (name) { 1497 // remove last [] in name 1498 var nestedTypes = this.nestedTypes(name); 1499 if (!nestedTypes) { 1500 return name; 1501 } 1502 1503 return name.substr(0, name.length - nestedTypes[nestedTypes.length - 1].length); 1504 }; 1505 1506 /** 1507 * Should return true if type has dynamic size by default 1508 * such types are "string", "bytes" 1509 * 1510 * @method isDynamicType 1511 * @param {String} name 1512 * @return {Bool} true if is dynamic, otherwise false 1513 */ 1514 SolidityType.prototype.isDynamicType = function () { 1515 return false; 1516 }; 1517 1518 /** 1519 * Should return array of nested types 1520 * eg. 1521 * "int[2][3][]" => ["[2]", "[3]", "[]"] 1522 * "int[] => ["[]"] 1523 * "int" => null 1524 * 1525 * @method nestedTypes 1526 * @param {String} name 1527 * @return {Array} array of nested types 1528 */ 1529 SolidityType.prototype.nestedTypes = function (name) { 1530 // return list of strings eg. "[]", "[3]", "[]", "[2]" 1531 return name.match(/(\[[0-9]*\])/g); 1532 }; 1533 1534 /** 1535 * Should be used to encode the value 1536 * 1537 * @method encode 1538 * @param {Object} value 1539 * @param {String} name 1540 * @return {String} encoded value 1541 */ 1542 SolidityType.prototype.encode = function (value, name) { 1543 var self = this; 1544 if (this.isDynamicArray(name)) { 1545 1546 return (function () { 1547 var length = value.length; // in int 1548 var nestedName = self.nestedName(name); 1549 1550 var result = []; 1551 result.push(f.formatInputInt(length).encode()); 1552 1553 value.forEach(function (v) { 1554 result.push(self.encode(v, nestedName)); 1555 }); 1556 1557 return result; 1558 })(); 1559 1560 } else if (this.isStaticArray(name)) { 1561 1562 return (function () { 1563 var length = self.staticArrayLength(name); // in int 1564 var nestedName = self.nestedName(name); 1565 1566 var result = []; 1567 for (var i = 0; i < length; i++) { 1568 result.push(self.encode(value[i], nestedName)); 1569 } 1570 1571 return result; 1572 })(); 1573 1574 } 1575 1576 return this._inputFormatter(value, name).encode(); 1577 }; 1578 1579 /** 1580 * Should be used to decode value from bytes 1581 * 1582 * @method decode 1583 * @param {String} bytes 1584 * @param {Number} offset in bytes 1585 * @param {String} name type name 1586 * @returns {Object} decoded value 1587 */ 1588 SolidityType.prototype.decode = function (bytes, offset, name) { 1589 var self = this; 1590 1591 if (this.isDynamicArray(name)) { 1592 1593 return (function () { 1594 var arrayOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes 1595 var length = parseInt('0x' + bytes.substr(arrayOffset * 2, 64)); // in int 1596 var arrayStart = arrayOffset + 32; // array starts after length; // in bytes 1597 1598 var nestedName = self.nestedName(name); 1599 var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes 1600 var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32; 1601 var result = []; 1602 1603 for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) { 1604 result.push(self.decode(bytes, arrayStart + i, nestedName)); 1605 } 1606 1607 return result; 1608 })(); 1609 1610 } else if (this.isStaticArray(name)) { 1611 1612 return (function () { 1613 var length = self.staticArrayLength(name); // in int 1614 var arrayStart = offset; // in bytes 1615 1616 var nestedName = self.nestedName(name); 1617 var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes 1618 var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32; 1619 var result = []; 1620 1621 for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) { 1622 result.push(self.decode(bytes, arrayStart + i, nestedName)); 1623 } 1624 1625 return result; 1626 })(); 1627 } else if (this.isDynamicType(name)) { 1628 1629 return (function () { 1630 var dynamicOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes 1631 var length = parseInt('0x' + bytes.substr(dynamicOffset * 2, 64)); // in bytes 1632 var roundedLength = Math.floor((length + 31) / 32); // in int 1633 var param = new SolidityParam(bytes.substr(dynamicOffset * 2, ( 1 + roundedLength) * 64), 0); 1634 return self._outputFormatter(param, name); 1635 })(); 1636 } 1637 1638 var length = this.staticPartLength(name); 1639 var param = new SolidityParam(bytes.substr(offset * 2, length * 2)); 1640 return this._outputFormatter(param, name); 1641 }; 1642 1643 module.exports = SolidityType; 1644 1645 },{"./formatters":9,"./param":11}],15:[function(require,module,exports){ 1646 var f = require('./formatters'); 1647 var SolidityType = require('./type'); 1648 1649 /** 1650 * SolidityTypeUInt is a prootype that represents uint type 1651 * It matches: 1652 * uint 1653 * uint[] 1654 * uint[4] 1655 * uint[][] 1656 * uint[3][] 1657 * uint[][6][], ... 1658 * uint32 1659 * uint64[] 1660 * uint8[4] 1661 * uint256[][] 1662 * uint[3][] 1663 * uint64[][6][], ... 1664 */ 1665 var SolidityTypeUInt = function () { 1666 this._inputFormatter = f.formatInputInt; 1667 this._outputFormatter = f.formatOutputUInt; 1668 }; 1669 1670 SolidityTypeUInt.prototype = new SolidityType({}); 1671 SolidityTypeUInt.prototype.constructor = SolidityTypeUInt; 1672 1673 SolidityTypeUInt.prototype.isType = function (name) { 1674 return !!name.match(/^uint([0-9]*)?(\[([0-9]*)\])*$/); 1675 }; 1676 1677 module.exports = SolidityTypeUInt; 1678 1679 },{"./formatters":9,"./type":14}],16:[function(require,module,exports){ 1680 var f = require('./formatters'); 1681 var SolidityType = require('./type'); 1682 1683 /** 1684 * SolidityTypeUReal is a prootype that represents ureal type 1685 * It matches: 1686 * ureal 1687 * ureal[] 1688 * ureal[4] 1689 * ureal[][] 1690 * ureal[3][] 1691 * ureal[][6][], ... 1692 * ureal32 1693 * ureal64[] 1694 * ureal8[4] 1695 * ureal256[][] 1696 * ureal[3][] 1697 * ureal64[][6][], ... 1698 */ 1699 var SolidityTypeUReal = function () { 1700 this._inputFormatter = f.formatInputReal; 1701 this._outputFormatter = f.formatOutputUReal; 1702 }; 1703 1704 SolidityTypeUReal.prototype = new SolidityType({}); 1705 SolidityTypeUReal.prototype.constructor = SolidityTypeUReal; 1706 1707 SolidityTypeUReal.prototype.isType = function (name) { 1708 return !!name.match(/^ureal([0-9]*)?(\[([0-9]*)\])*$/); 1709 }; 1710 1711 module.exports = SolidityTypeUReal; 1712 1713 },{"./formatters":9,"./type":14}],17:[function(require,module,exports){ 1714 'use strict'; 1715 1716 // go env doesn't have and need XMLHttpRequest 1717 if (typeof XMLHttpRequest === 'undefined') { 1718 exports.XMLHttpRequest = {}; 1719 } else { 1720 exports.XMLHttpRequest = XMLHttpRequest; // jshint ignore:line 1721 } 1722 1723 1724 },{}],18:[function(require,module,exports){ 1725 /* 1726 This file is part of web3.js. 1727 1728 web3.js is free software: you can redistribute it and/or modify 1729 it under the terms of the GNU Lesser General Public License as published by 1730 the Free Software Foundation, either version 3 of the License, or 1731 (at your option) any later version. 1732 1733 web3.js is distributed in the hope that it will be useful, 1734 but WITHOUT ANY WARRANTY; without even the implied warranty of 1735 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1736 GNU Lesser General Public License for more details. 1737 1738 You should have received a copy of the GNU Lesser General Public License 1739 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1740 */ 1741 /** @file config.js 1742 * @authors: 1743 * Marek Kotewicz <marek@ethdev.com> 1744 * @date 2015 1745 */ 1746 1747 /** 1748 * Utils 1749 * 1750 * @module utils 1751 */ 1752 1753 /** 1754 * Utility functions 1755 * 1756 * @class [utils] config 1757 * @constructor 1758 */ 1759 1760 1761 /// required to define ETH_BIGNUMBER_ROUNDING_MODE 1762 var BigNumber = require('bignumber.js'); 1763 1764 var ETH_UNITS = [ 1765 'wei', 1766 'kwei', 1767 'Mwei', 1768 'Gwei', 1769 'szabo', 1770 'finney', 1771 'femtoether', 1772 'picoether', 1773 'nanoether', 1774 'microether', 1775 'milliether', 1776 'nano', 1777 'micro', 1778 'milli', 1779 'ether', 1780 'grand', 1781 'Mether', 1782 'Gwtcer', 1783 'Tether', 1784 'Pether', 1785 'Eether', 1786 'Zether', 1787 'Yether', 1788 'Nether', 1789 'Dether', 1790 'Vether', 1791 'Uether' 1792 ]; 1793 1794 module.exports = { 1795 ETH_PADDING: 32, 1796 ETH_SIGNATURE_LENGTH: 4, 1797 ETH_UNITS: ETH_UNITS, 1798 ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN }, 1799 ETH_POLLING_TIMEOUT: 1000/2, 1800 defaultBlock: 'latest', 1801 defaultAccount: undefined 1802 }; 1803 1804 1805 },{"bignumber.js":"bignumber.js"}],19:[function(require,module,exports){ 1806 /* 1807 This file is part of web3.js. 1808 1809 web3.js is free software: you can redistribute it and/or modify 1810 it under the terms of the GNU Lesser General Public License as published by 1811 the Free Software Foundation, either version 3 of the License, or 1812 (at your option) any later version. 1813 1814 web3.js is distributed in the hope that it will be useful, 1815 but WITHOUT ANY WARRANTY; without even the implied warranty of 1816 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1817 GNU Lesser General Public License for more details. 1818 1819 You should have received a copy of the GNU Lesser General Public License 1820 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1821 */ 1822 /** 1823 * @file sha3.js 1824 * @author Marek Kotewicz <marek@ethdev.com> 1825 * @date 2015 1826 */ 1827 1828 var CryptoJS = require('crypto-js'); 1829 var sha3 = require('crypto-js/sha3'); 1830 1831 module.exports = function (value, options) { 1832 if (options && options.encoding === 'hex') { 1833 if (value.length > 2 && value.substr(0, 2) === '0x') { 1834 value = value.substr(2); 1835 } 1836 value = CryptoJS.enc.Hex.parse(value); 1837 } 1838 1839 return sha3(value, { 1840 outputLength: 256 1841 }).toString(); 1842 }; 1843 1844 1845 },{"crypto-js":59,"crypto-js/sha3":80}],20:[function(require,module,exports){ 1846 /* 1847 This file is part of web3.js. 1848 1849 web3.js is free software: you can redistribute it and/or modify 1850 it under the terms of the GNU Lesser General Public License as published by 1851 the Free Software Foundation, either version 3 of the License, or 1852 (at your option) any later version. 1853 1854 web3.js is distributed in the hope that it will be useful, 1855 but WITHOUT ANY WARRANTY; without even the implied warranty of 1856 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1857 GNU Lesser General Public License for more details. 1858 1859 You should have received a copy of the GNU Lesser General Public License 1860 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1861 */ 1862 /** 1863 * @file utils.js 1864 * @author Marek Kotewicz <marek@ethdev.com> 1865 * @date 2015 1866 */ 1867 1868 /** 1869 * Utils 1870 * 1871 * @module utils 1872 */ 1873 1874 /** 1875 * Utility functions 1876 * 1877 * @class [utils] utils 1878 * @constructor 1879 */ 1880 1881 1882 var BigNumber = require('bignumber.js'); 1883 var sha3 = require('./sha3.js'); 1884 var utf8 = require('utf8'); 1885 1886 var unitMap = { 1887 'noether': '0', 1888 'wei': '1', 1889 'kwei': '1000', 1890 'Kwei': '1000', 1891 'babbage': '1000', 1892 'femtoether': '1000', 1893 'mwei': '1000000', 1894 'Mwei': '1000000', 1895 'lovelace': '1000000', 1896 'picoether': '1000000', 1897 'gwei': '1000000000', 1898 'Gwei': '1000000000', 1899 'shannon': '1000000000', 1900 'nanoether': '1000000000', 1901 'nano': '1000000000', 1902 'szabo': '1000000000000', 1903 'microether': '1000000000000', 1904 'micro': '1000000000000', 1905 'finney': '1000000000000000', 1906 'milliether': '1000000000000000', 1907 'milli': '1000000000000000', 1908 'ether': '1000000000000000000', 1909 'kether': '1000000000000000000000', 1910 'grand': '1000000000000000000000', 1911 'mether': '1000000000000000000000000', 1912 'gwtcer': '1000000000000000000000000000', 1913 'tether': '1000000000000000000000000000000' 1914 }; 1915 1916 /** 1917 * Should be called to pad string to expected length 1918 * 1919 * @method padLeft 1920 * @param {String} string to be padded 1921 * @param {Number} characters that result string should have 1922 * @param {String} sign, by default 0 1923 * @returns {String} right aligned string 1924 */ 1925 var padLeft = function (string, chars, sign) { 1926 return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; 1927 }; 1928 1929 /** 1930 * Should be called to pad string to expected length 1931 * 1932 * @method padRight 1933 * @param {String} string to be padded 1934 * @param {Number} characters that result string should have 1935 * @param {String} sign, by default 0 1936 * @returns {String} right aligned string 1937 */ 1938 var padRight = function (string, chars, sign) { 1939 return string + (new Array(chars - string.length + 1).join(sign ? sign : "0")); 1940 }; 1941 1942 /** 1943 * Should be called to get utf8 from it's hex representation 1944 * 1945 * @method toUtf8 1946 * @param {String} string in hex 1947 * @returns {String} ascii string representation of hex value 1948 */ 1949 var toUtf8 = function(hex) { 1950 // Find termination 1951 var str = ""; 1952 var i = 0, l = hex.length; 1953 if (hex.substring(0, 2) === '0x') { 1954 i = 2; 1955 } 1956 for (; i < l; i+=2) { 1957 var code = parseInt(hex.substr(i, 2), 16); 1958 if (code === 0) 1959 break; 1960 str += String.fromCharCode(code); 1961 } 1962 1963 return utf8.decode(str); 1964 }; 1965 1966 /** 1967 * Should be called to get ascii from it's hex representation 1968 * 1969 * @method toAscii 1970 * @param {String} string in hex 1971 * @returns {String} ascii string representation of hex value 1972 */ 1973 var toAscii = function(hex) { 1974 // Find termination 1975 var str = ""; 1976 var i = 0, l = hex.length; 1977 if (hex.substring(0, 2) === '0x') { 1978 i = 2; 1979 } 1980 for (; i < l; i+=2) { 1981 var code = parseInt(hex.substr(i, 2), 16); 1982 str += String.fromCharCode(code); 1983 } 1984 1985 return str; 1986 }; 1987 1988 /** 1989 * Should be called to get hex representation (prefixed by 0x) of utf8 string 1990 * 1991 * @method fromUtf8 1992 * @param {String} string 1993 * @param {Number} optional padding 1994 * @returns {String} hex representation of input string 1995 */ 1996 var fromUtf8 = function(str) { 1997 str = utf8.encode(str); 1998 var hex = ""; 1999 for(var i = 0; i < str.length; i++) { 2000 var code = str.charCodeAt(i); 2001 if (code === 0) 2002 break; 2003 var n = code.toString(16); 2004 hex += n.length < 2 ? '0' + n : n; 2005 } 2006 2007 return "0x" + hex; 2008 }; 2009 2010 /** 2011 * Should be called to get hex representation (prefixed by 0x) of ascii string 2012 * 2013 * @method fromAscii 2014 * @param {String} string 2015 * @param {Number} optional padding 2016 * @returns {String} hex representation of input string 2017 */ 2018 var fromAscii = function(str) { 2019 var hex = ""; 2020 for(var i = 0; i < str.length; i++) { 2021 var code = str.charCodeAt(i); 2022 var n = code.toString(16); 2023 hex += n.length < 2 ? '0' + n : n; 2024 } 2025 2026 return "0x" + hex; 2027 }; 2028 2029 /** 2030 * Should be used to create full function/event name from json abi 2031 * 2032 * @method transformToFullName 2033 * @param {Object} json-abi 2034 * @return {String} full fnction/event name 2035 */ 2036 var transformToFullName = function (json) { 2037 if (json.name.indexOf('(') !== -1) { 2038 return json.name; 2039 } 2040 2041 var typeName = json.inputs.map(function(i){return i.type; }).join(); 2042 return json.name + '(' + typeName + ')'; 2043 }; 2044 2045 /** 2046 * Should be called to get display name of contract function 2047 * 2048 * @method extractDisplayName 2049 * @param {String} name of function/event 2050 * @returns {String} display name for function/event eg. multiply(uint256) -> multiply 2051 */ 2052 var extractDisplayName = function (name) { 2053 var length = name.indexOf('('); 2054 return length !== -1 ? name.substr(0, length) : name; 2055 }; 2056 2057 /// @returns overloaded part of function/event name 2058 var extractTypeName = function (name) { 2059 /// TODO: make it invulnerable 2060 var length = name.indexOf('('); 2061 return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : ""; 2062 }; 2063 2064 /** 2065 * Converts value to it's decimal representation in string 2066 * 2067 * @method toDecimal 2068 * @param {String|Number|BigNumber} 2069 * @return {String} 2070 */ 2071 var toDecimal = function (value) { 2072 return toBigNumber(value).toNumber(); 2073 }; 2074 2075 /** 2076 * Converts value to it's hex representation 2077 * 2078 * @method fromDecimal 2079 * @param {String|Number|BigNumber} 2080 * @return {String} 2081 */ 2082 var fromDecimal = function (value) { 2083 var number = toBigNumber(value); 2084 var result = number.toString(16); 2085 2086 return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result; 2087 }; 2088 2089 /** 2090 * Auto converts any given value into it's hex representation. 2091 * 2092 * And even stringifys objects before. 2093 * 2094 * @method toHex 2095 * @param {String|Number|BigNumber|Object} 2096 * @return {String} 2097 */ 2098 var toHex = function (val) { 2099 /*jshint maxcomplexity: 8 */ 2100 2101 if (isBoolean(val)) 2102 return fromDecimal(+val); 2103 2104 if (isBigNumber(val)) 2105 return fromDecimal(val); 2106 2107 if (isObject(val)) 2108 return fromUtf8(JSON.stringify(val)); 2109 2110 // if its a negative number, pass it through fromDecimal 2111 if (isString(val)) { 2112 if (val.indexOf('-0x') === 0) 2113 return fromDecimal(val); 2114 else if(val.indexOf('0x') === 0) 2115 return val; 2116 else if (!isFinite(val)) 2117 return fromAscii(val); 2118 } 2119 2120 return fromDecimal(val); 2121 }; 2122 2123 /** 2124 * Returns value of unit in Wei 2125 * 2126 * @method getValueOfUnit 2127 * @param {String} unit the unit to convert to, default ether 2128 * @returns {BigNumber} value of the unit (in Wei) 2129 * @throws error if the unit is not correct:w 2130 */ 2131 var getValueOfUnit = function (unit) { 2132 unit = unit ? unit.toLowerCase() : 'ether'; 2133 var unitValue = unitMap[unit]; 2134 if (unitValue === undefined) { 2135 throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2)); 2136 } 2137 return new BigNumber(unitValue, 10); 2138 }; 2139 2140 /** 2141 * Takes a number of wei and converts it to any other ether unit. 2142 * 2143 * Possible units are: 2144 * SI Short SI Full Effigy Other 2145 * - kwei femtoether babbage 2146 * - mwei picoether lovelace 2147 * - gwei nanoether shannon nano 2148 * - -- microether szabo micro 2149 * - -- milliether finney milli 2150 * - ether -- -- 2151 * - kether -- grand 2152 * - mether 2153 * - gwtcer 2154 * - tether 2155 * 2156 * @method fromWei 2157 * @param {Number|String} number can be a number, number string or a HEX of a decimal 2158 * @param {String} unit the unit to convert to, default ether 2159 * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number 2160 */ 2161 var fromWei = function(number, unit) { 2162 var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); 2163 2164 return isBigNumber(number) ? returnValue : returnValue.toString(10); 2165 }; 2166 2167 /** 2168 * Takes a number of a unit and converts it to wei. 2169 * 2170 * Possible units are: 2171 * SI Short SI Full Effigy Other 2172 * - kwei femtoether babbage 2173 * - mwei picoether lovelace 2174 * - gwei nanoether shannon nano 2175 * - -- microether szabo micro 2176 * - -- microether szabo micro 2177 * - -- milliether finney milli 2178 * - ether -- -- 2179 * - kether -- grand 2180 * - mether 2181 * - gwtcer 2182 * - tether 2183 * 2184 * @method toWei 2185 * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal 2186 * @param {String} unit the unit to convert from, default ether 2187 * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number 2188 */ 2189 var toWei = function(number, unit) { 2190 var returnValue = toBigNumber(number).times(getValueOfUnit(unit)); 2191 2192 return isBigNumber(number) ? returnValue : returnValue.toString(10); 2193 }; 2194 2195 /** 2196 * Takes an input and transforms it into an bignumber 2197 * 2198 * @method toBigNumber 2199 * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber 2200 * @return {BigNumber} BigNumber 2201 */ 2202 var toBigNumber = function(number) { 2203 /*jshint maxcomplexity:5 */ 2204 number = number || 0; 2205 if (isBigNumber(number)) 2206 return number; 2207 2208 if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) { 2209 return new BigNumber(number.replace('0x',''), 16); 2210 } 2211 2212 return new BigNumber(number.toString(10), 10); 2213 }; 2214 2215 /** 2216 * Takes and input transforms it into bignumber and if it is negative value, into two's complement 2217 * 2218 * @method toTwosComplement 2219 * @param {Number|String|BigNumber} 2220 * @return {BigNumber} 2221 */ 2222 var toTwosComplement = function (number) { 2223 var bigNumber = toBigNumber(number).round(); 2224 if (bigNumber.lessThan(0)) { 2225 return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1); 2226 } 2227 return bigNumber; 2228 }; 2229 2230 /** 2231 * Checks if the given string is strictly an address 2232 * 2233 * @method isStrictAddress 2234 * @param {String} address the given HEX adress 2235 * @return {Boolean} 2236 */ 2237 var isStrictAddress = function (address) { 2238 return /^0x[0-9a-f]{40}$/i.test(address); 2239 }; 2240 2241 /** 2242 * Checks if the given string is an address 2243 * 2244 * @method isAddress 2245 * @param {String} address the given HEX adress 2246 * @return {Boolean} 2247 */ 2248 var isAddress = function (address) { 2249 if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { 2250 // check if it has the basic requirements of an address 2251 return false; 2252 } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { 2253 // If it's all small caps or all all caps, return true 2254 return true; 2255 } else { 2256 // Otherwise check each case 2257 return isChecksumAddress(address); 2258 } 2259 }; 2260 2261 2262 2263 /** 2264 * Checks if the given string is a checksummed address 2265 * 2266 * @method isChecksumAddress 2267 * @param {String} address the given HEX adress 2268 * @return {Boolean} 2269 */ 2270 var isChecksumAddress = function (address) { 2271 // Check each case 2272 address = address.replace('0x',''); 2273 var addressHash = sha3(address.toLowerCase()); 2274 2275 for (var i = 0; i < 40; i++ ) { 2276 // the nth letter should be uppercase if the nth digit of casemap is 1 2277 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { 2278 return false; 2279 } 2280 } 2281 return true; 2282 }; 2283 2284 2285 2286 /** 2287 * Makes a checksum address 2288 * 2289 * @method toChecksumAddress 2290 * @param {String} address the given HEX adress 2291 * @return {String} 2292 */ 2293 var toChecksumAddress = function (address) { 2294 if (typeof address === 'undefined') return ''; 2295 2296 address = address.toLowerCase().replace('0x',''); 2297 var addressHash = sha3(address); 2298 var checksumAddress = '0x'; 2299 2300 for (var i = 0; i < address.length; i++ ) { 2301 // If ith character is 9 to f then make it uppercase 2302 if (parseInt(addressHash[i], 16) > 7) { 2303 checksumAddress += address[i].toUpperCase(); 2304 } else { 2305 checksumAddress += address[i]; 2306 } 2307 } 2308 return checksumAddress; 2309 }; 2310 2311 /** 2312 * Transforms given string to valid 20 bytes-length addres with 0x prefix 2313 * 2314 * @method toAddress 2315 * @param {String} address 2316 * @return {String} formatted address 2317 */ 2318 var toAddress = function (address) { 2319 if (isStrictAddress(address)) { 2320 return address; 2321 } 2322 2323 if (/^[0-9a-f]{40}$/.test(address)) { 2324 return '0x' + address; 2325 } 2326 2327 return '0x' + padLeft(toHex(address).substr(2), 40); 2328 }; 2329 2330 /** 2331 * Returns true if object is BigNumber, otherwise false 2332 * 2333 * @method isBigNumber 2334 * @param {Object} 2335 * @return {Boolean} 2336 */ 2337 var isBigNumber = function (object) { 2338 return object instanceof BigNumber || 2339 (object && object.constructor && object.constructor.name === 'BigNumber'); 2340 }; 2341 2342 /** 2343 * Returns true if object is string, otherwise false 2344 * 2345 * @method isString 2346 * @param {Object} 2347 * @return {Boolean} 2348 */ 2349 var isString = function (object) { 2350 return typeof object === 'string' || 2351 (object && object.constructor && object.constructor.name === 'String'); 2352 }; 2353 2354 /** 2355 * Returns true if object is function, otherwise false 2356 * 2357 * @method isFunction 2358 * @param {Object} 2359 * @return {Boolean} 2360 */ 2361 var isFunction = function (object) { 2362 return typeof object === 'function'; 2363 }; 2364 2365 /** 2366 * Returns true if object is Objet, otherwise false 2367 * 2368 * @method isObject 2369 * @param {Object} 2370 * @return {Boolean} 2371 */ 2372 var isObject = function (object) { 2373 return typeof object === 'object'; 2374 }; 2375 2376 /** 2377 * Returns true if object is boolean, otherwise false 2378 * 2379 * @method isBoolean 2380 * @param {Object} 2381 * @return {Boolean} 2382 */ 2383 var isBoolean = function (object) { 2384 return typeof object === 'boolean'; 2385 }; 2386 2387 /** 2388 * Returns true if object is array, otherwise false 2389 * 2390 * @method isArray 2391 * @param {Object} 2392 * @return {Boolean} 2393 */ 2394 var isArray = function (object) { 2395 return object instanceof Array; 2396 }; 2397 2398 /** 2399 * Returns true if given string is valid json object 2400 * 2401 * @method isJson 2402 * @param {String} 2403 * @return {Boolean} 2404 */ 2405 var isJson = function (str) { 2406 try { 2407 return !!JSON.parse(str); 2408 } catch (e) { 2409 return false; 2410 } 2411 }; 2412 2413 module.exports = { 2414 padLeft: padLeft, 2415 padRight: padRight, 2416 toHex: toHex, 2417 toDecimal: toDecimal, 2418 fromDecimal: fromDecimal, 2419 toUtf8: toUtf8, 2420 toAscii: toAscii, 2421 fromUtf8: fromUtf8, 2422 fromAscii: fromAscii, 2423 transformToFullName: transformToFullName, 2424 extractDisplayName: extractDisplayName, 2425 extractTypeName: extractTypeName, 2426 toWei: toWei, 2427 fromWei: fromWei, 2428 toBigNumber: toBigNumber, 2429 toTwosComplement: toTwosComplement, 2430 toAddress: toAddress, 2431 isBigNumber: isBigNumber, 2432 isStrictAddress: isStrictAddress, 2433 isAddress: isAddress, 2434 isChecksumAddress: isChecksumAddress, 2435 toChecksumAddress: toChecksumAddress, 2436 isFunction: isFunction, 2437 isString: isString, 2438 isObject: isObject, 2439 isBoolean: isBoolean, 2440 isArray: isArray, 2441 isJson: isJson 2442 }; 2443 2444 },{"./sha3.js":19,"bignumber.js":"bignumber.js","utf8":85}],21:[function(require,module,exports){ 2445 module.exports={ 2446 "version": "0.18.1" 2447 } 2448 2449 },{}],22:[function(require,module,exports){ 2450 /* 2451 This file is part of web3.js. 2452 2453 web3.js is free software: you can redistribute it and/or modify 2454 it under the terms of the GNU Lesser General Public License as published by 2455 the Free Software Foundation, either version 3 of the License, or 2456 (at your option) any later version. 2457 2458 web3.js is distributed in the hope that it will be useful, 2459 but WITHOUT ANY WARRANTY; without even the implied warranty of 2460 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2461 GNU Lesser General Public License for more details. 2462 2463 You should have received a copy of the GNU Lesser General Public License 2464 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2465 */ 2466 /** 2467 * @file web3.js 2468 * @authors: 2469 * Jeffrey Wilcke <jeff@ethdev.com> 2470 * Marek Kotewicz <marek@ethdev.com> 2471 * Marian Oancea <marian@ethdev.com> 2472 * Fabian Vogelsteller <fabian@ethdev.com> 2473 * Gav Wood <g@ethdev.com> 2474 * @date 2014 2475 */ 2476 2477 var RequestManager = require('./web3/requestmanager'); 2478 var Iban = require('./web3/iban'); 2479 var Eth = require('./web3/methods/eth'); 2480 var DB = require('./web3/methods/db'); 2481 var Shh = require('./web3/methods/shh'); 2482 var Net = require('./web3/methods/net'); 2483 var Personal = require('./web3/methods/personal'); 2484 var Swarm = require('./web3/methods/swarm'); 2485 var Settings = require('./web3/settings'); 2486 var version = require('./version.json'); 2487 var utils = require('./utils/utils'); 2488 var sha3 = require('./utils/sha3'); 2489 var extend = require('./web3/extend'); 2490 var Batch = require('./web3/batch'); 2491 var Property = require('./web3/property'); 2492 var HttpProvider = require('./web3/httpprovider'); 2493 var IpcProvider = require('./web3/ipcprovider'); 2494 var BigNumber = require('bignumber.js'); 2495 2496 2497 2498 function Web3 (provider) { 2499 this._requestManager = new RequestManager(provider); 2500 this.currentProvider = provider; 2501 this.eth = new Eth(this); 2502 this.db = new DB(this); 2503 this.shh = new Shh(this); 2504 this.net = new Net(this); 2505 this.personal = new Personal(this); 2506 this.bzz = new Swarm(this); 2507 this.settings = new Settings(); 2508 this.version = { 2509 api: version.version 2510 }; 2511 this.providers = { 2512 HttpProvider: HttpProvider, 2513 IpcProvider: IpcProvider 2514 }; 2515 this._extend = extend(this); 2516 this._extend({ 2517 properties: properties() 2518 }); 2519 } 2520 2521 // expose providers on the class 2522 Web3.providers = { 2523 HttpProvider: HttpProvider, 2524 IpcProvider: IpcProvider 2525 }; 2526 2527 Web3.prototype.setProvider = function (provider) { 2528 this._requestManager.setProvider(provider); 2529 this.currentProvider = provider; 2530 }; 2531 2532 Web3.prototype.reset = function (keepIsSyncing) { 2533 this._requestManager.reset(keepIsSyncing); 2534 this.settings = new Settings(); 2535 }; 2536 2537 Web3.prototype.BigNumber = BigNumber; 2538 Web3.prototype.toHex = utils.toHex; 2539 Web3.prototype.toAscii = utils.toAscii; 2540 Web3.prototype.toUtf8 = utils.toUtf8; 2541 Web3.prototype.fromAscii = utils.fromAscii; 2542 Web3.prototype.fromUtf8 = utils.fromUtf8; 2543 Web3.prototype.toDecimal = utils.toDecimal; 2544 Web3.prototype.fromDecimal = utils.fromDecimal; 2545 Web3.prototype.toBigNumber = utils.toBigNumber; 2546 Web3.prototype.toWei = utils.toWei; 2547 Web3.prototype.fromWei = utils.fromWei; 2548 Web3.prototype.isAddress = utils.isAddress; 2549 Web3.prototype.isChecksumAddress = utils.isChecksumAddress; 2550 Web3.prototype.toChecksumAddress = utils.toChecksumAddress; 2551 Web3.prototype.isIBAN = utils.isIBAN; 2552 2553 2554 Web3.prototype.sha3 = function(string, options) { 2555 return '0x' + sha3(string, options); 2556 }; 2557 2558 /** 2559 * Transforms direct icap to address 2560 */ 2561 Web3.prototype.fromICAP = function (icap) { 2562 var iban = new Iban(icap); 2563 return iban.address(); 2564 }; 2565 2566 var properties = function () { 2567 return [ 2568 new Property({ 2569 name: 'version.node', 2570 getter: 'web3_clientVersion' 2571 }), 2572 new Property({ 2573 name: 'version.network', 2574 getter: 'net_version', 2575 inputFormatter: utils.toDecimal 2576 }), 2577 new Property({ 2578 name: 'version.wtc', 2579 getter: 'eth_protocolVersion', 2580 inputFormatter: utils.toDecimal 2581 }), 2582 new Property({ 2583 name: 'version.whisper', 2584 getter: 'shh_version', 2585 inputFormatter: utils.toDecimal 2586 }) 2587 ]; 2588 }; 2589 2590 Web3.prototype.isConnected = function(){ 2591 return (this.currentProvider && this.currentProvider.isConnected()); 2592 }; 2593 2594 Web3.prototype.createBatch = function () { 2595 return new Batch(this); 2596 }; 2597 2598 module.exports = Web3; 2599 2600 2601 },{"./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/methods/swarm":42,"./web3/property":45,"./web3/requestmanager":46,"./web3/settings":47,"bignumber.js":"bignumber.js"}],23:[function(require,module,exports){ 2602 /* 2603 This file is part of web3.js. 2604 2605 web3.js is free software: you can redistribute it and/or modify 2606 it under the terms of the GNU Lesser General Public License as published by 2607 the Free Software Foundation, either version 3 of the License, or 2608 (at your option) any later version. 2609 2610 web3.js is distributed in the hope that it will be useful, 2611 but WITHOUT ANY WARRANTY; without even the implied warranty of 2612 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2613 GNU Lesser General Public License for more details. 2614 2615 You should have received a copy of the GNU Lesser General Public License 2616 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2617 */ 2618 /** 2619 * @file allevents.js 2620 * @author Marek Kotewicz <marek@ethdev.com> 2621 * @date 2014 2622 */ 2623 2624 var sha3 = require('../utils/sha3'); 2625 var SolidityEvent = require('./event'); 2626 var formatters = require('./formatters'); 2627 var utils = require('../utils/utils'); 2628 var Filter = require('./filter'); 2629 var watches = require('./methods/watches'); 2630 2631 var AllSolidityEvents = function (requestManager, json, address) { 2632 this._requestManager = requestManager; 2633 this._json = json; 2634 this._address = address; 2635 }; 2636 2637 AllSolidityEvents.prototype.encode = function (options) { 2638 options = options || {}; 2639 var result = {}; 2640 2641 ['fromBlock', 'toBlock'].filter(function (f) { 2642 return options[f] !== undefined; 2643 }).forEach(function (f) { 2644 result[f] = formatters.inputBlockNumberFormatter(options[f]); 2645 }); 2646 2647 result.address = this._address; 2648 2649 return result; 2650 }; 2651 2652 AllSolidityEvents.prototype.decode = function (data) { 2653 data.data = data.data || ''; 2654 data.topics = data.topics || []; 2655 2656 var eventTopic = data.topics[0].slice(2); 2657 var match = this._json.filter(function (j) { 2658 return eventTopic === sha3(utils.transformToFullName(j)); 2659 })[0]; 2660 2661 if (!match) { // cannot find matching event? 2662 console.warn('cannot find event for log'); 2663 return data; 2664 } 2665 2666 var event = new SolidityEvent(this._requestManager, match, this._address); 2667 return event.decode(data); 2668 }; 2669 2670 AllSolidityEvents.prototype.execute = function (options, callback) { 2671 2672 if (utils.isFunction(arguments[arguments.length - 1])) { 2673 callback = arguments[arguments.length - 1]; 2674 if(arguments.length === 1) 2675 options = null; 2676 } 2677 2678 var o = this.encode(options); 2679 var formatter = this.decode.bind(this); 2680 return new Filter(this._requestManager, o, watches.eth(), formatter, callback); 2681 }; 2682 2683 AllSolidityEvents.prototype.attachToContract = function (contract) { 2684 var execute = this.execute.bind(this); 2685 contract.allEvents = execute; 2686 }; 2687 2688 module.exports = AllSolidityEvents; 2689 2690 2691 },{"../utils/sha3":19,"../utils/utils":20,"./event":27,"./filter":29,"./formatters":30,"./methods/watches":43}],24:[function(require,module,exports){ 2692 /* 2693 This file is part of web3.js. 2694 2695 web3.js is free software: you can redistribute it and/or modify 2696 it under the terms of the GNU Lesser General Public License as published by 2697 the Free Software Foundation, either version 3 of the License, or 2698 (at your option) any later version. 2699 2700 web3.js is distributed in the hope that it will be useful, 2701 but WITHOUT ANY WARRANTY; without even the implied warranty of 2702 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2703 GNU Lesser General Public License for more details. 2704 2705 You should have received a copy of the GNU Lesser General Public License 2706 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2707 */ 2708 /** 2709 * @file batch.js 2710 * @author Marek Kotewicz <marek@ethdev.com> 2711 * @date 2015 2712 */ 2713 2714 var Jsonrpc = require('./jsonrpc'); 2715 var errors = require('./errors'); 2716 2717 var Batch = function (web3) { 2718 this.requestManager = web3._requestManager; 2719 this.requests = []; 2720 }; 2721 2722 /** 2723 * Should be called to add create new request to batch request 2724 * 2725 * @method add 2726 * @param {Object} jsonrpc requet object 2727 */ 2728 Batch.prototype.add = function (request) { 2729 this.requests.push(request); 2730 }; 2731 2732 /** 2733 * Should be called to execute batch request 2734 * 2735 * @method execute 2736 */ 2737 Batch.prototype.execute = function () { 2738 var requests = this.requests; 2739 this.requestManager.sendBatch(requests, function (err, results) { 2740 results = results || []; 2741 requests.map(function (request, index) { 2742 return results[index] || {}; 2743 }).forEach(function (result, index) { 2744 if (requests[index].callback) { 2745 2746 if (!Jsonrpc.isValidResponse(result)) { 2747 return requests[index].callback(errors.InvalidResponse(result)); 2748 } 2749 2750 requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result)); 2751 } 2752 }); 2753 }); 2754 }; 2755 2756 module.exports = Batch; 2757 2758 2759 },{"./errors":26,"./jsonrpc":35}],25:[function(require,module,exports){ 2760 /* 2761 This file is part of web3.js. 2762 2763 web3.js is free software: you can redistribute it and/or modify 2764 it under the terms of the GNU Lesser General Public License as published by 2765 the Free Software Foundation, either version 3 of the License, or 2766 (at your option) any later version. 2767 2768 web3.js is distributed in the hope that it will be useful, 2769 but WITHOUT ANY WARRANTY; without even the implied warranty of 2770 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2771 GNU Lesser General Public License for more details. 2772 2773 You should have received a copy of the GNU Lesser General Public License 2774 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2775 */ 2776 /** 2777 * @file contract.js 2778 * @author Marek Kotewicz <marek@ethdev.com> 2779 * @date 2014 2780 */ 2781 2782 var utils = require('../utils/utils'); 2783 var coder = require('../solidity/coder'); 2784 var SolidityEvent = require('./event'); 2785 var SolidityFunction = require('./function'); 2786 var AllEvents = require('./allevents'); 2787 2788 /** 2789 * Should be called to encode constructor params 2790 * 2791 * @method encodeConstructorParams 2792 * @param {Array} abi 2793 * @param {Array} constructor params 2794 */ 2795 var encodeConstructorParams = function (abi, params) { 2796 return abi.filter(function (json) { 2797 return json.type === 'constructor' && json.inputs.length === params.length; 2798 }).map(function (json) { 2799 return json.inputs.map(function (input) { 2800 return input.type; 2801 }); 2802 }).map(function (types) { 2803 return coder.encodeParams(types, params); 2804 })[0] || ''; 2805 }; 2806 2807 /** 2808 * Should be called to add functions to contract object 2809 * 2810 * @method addFunctionsToContract 2811 * @param {Contract} contract 2812 * @param {Array} abi 2813 */ 2814 var addFunctionsToContract = function (contract) { 2815 contract.abi.filter(function (json) { 2816 return json.type === 'function'; 2817 }).map(function (json) { 2818 return new SolidityFunction(contract._eth, json, contract.address); 2819 }).forEach(function (f) { 2820 f.attachToContract(contract); 2821 }); 2822 }; 2823 2824 /** 2825 * Should be called to add events to contract object 2826 * 2827 * @method addEventsToContract 2828 * @param {Contract} contract 2829 * @param {Array} abi 2830 */ 2831 var addEventsToContract = function (contract) { 2832 var events = contract.abi.filter(function (json) { 2833 return json.type === 'event'; 2834 }); 2835 2836 var All = new AllEvents(contract._eth._requestManager, events, contract.address); 2837 All.attachToContract(contract); 2838 2839 events.map(function (json) { 2840 return new SolidityEvent(contract._eth._requestManager, json, contract.address); 2841 }).forEach(function (e) { 2842 e.attachToContract(contract); 2843 }); 2844 }; 2845 2846 2847 /** 2848 * Should be called to check if the contract gets properly deployed on the blockchain. 2849 * 2850 * @method checkForContractAddress 2851 * @param {Object} contract 2852 * @param {Function} callback 2853 * @returns {Undefined} 2854 */ 2855 var checkForContractAddress = function(contract, callback){ 2856 var count = 0, 2857 callbackFired = false; 2858 2859 // wait for receipt 2860 var filter = contract._eth.filter('latest', function(e){ 2861 if (!e && !callbackFired) { 2862 count++; 2863 2864 // stop watching after 50 blocks (timeout) 2865 if (count > 50) { 2866 2867 filter.stopWatching(function() {}); 2868 callbackFired = true; 2869 2870 if (callback) 2871 callback(new Error('Contract transaction couldn\'t be found after 50 blocks')); 2872 else 2873 throw new Error('Contract transaction couldn\'t be found after 50 blocks'); 2874 2875 2876 } else { 2877 2878 contract._eth.getTransactionReceipt(contract.transactionHash, function(e, receipt){ 2879 if(receipt && !callbackFired) { 2880 2881 contract._eth.getCode(receipt.contractAddress, function(e, code){ 2882 /*jshint maxcomplexity: 6 */ 2883 2884 if(callbackFired || !code) 2885 return; 2886 2887 filter.stopWatching(function() {}); 2888 callbackFired = true; 2889 2890 if(code.length > 3) { 2891 2892 // console.log('Contract code deployed!'); 2893 2894 contract.address = receipt.contractAddress; 2895 2896 // attach events and methods again after we have 2897 addFunctionsToContract(contract); 2898 addEventsToContract(contract); 2899 2900 // call callback for the second time 2901 if(callback) 2902 callback(null, contract); 2903 2904 } else { 2905 if(callback) 2906 callback(new Error('The contract code couldn\'t be stored, please check your gas amount.')); 2907 else 2908 throw new Error('The contract code couldn\'t be stored, please check your gas amount.'); 2909 } 2910 }); 2911 } 2912 }); 2913 } 2914 } 2915 }); 2916 }; 2917 2918 /** 2919 * Should be called to create new ContractFactory instance 2920 * 2921 * @method ContractFactory 2922 * @param {Array} abi 2923 */ 2924 var ContractFactory = function (eth, abi) { 2925 this.eth = eth; 2926 this.abi = abi; 2927 2928 /** 2929 * Should be called to create new contract on a blockchain 2930 * 2931 * @method new 2932 * @param {Any} contract constructor param1 (optional) 2933 * @param {Any} contract constructor param2 (optional) 2934 * @param {Object} contract transaction object (required) 2935 * @param {Function} callback 2936 * @returns {Contract} returns contract instance 2937 */ 2938 this.new = function () { 2939 var contract = new Contract(this.eth, this.abi); 2940 2941 // parse arguments 2942 var options = {}; // required! 2943 var callback; 2944 2945 var args = Array.prototype.slice.call(arguments); 2946 if (utils.isFunction(args[args.length - 1])) { 2947 callback = args.pop(); 2948 } 2949 2950 var last = args[args.length - 1]; 2951 if (utils.isObject(last) && !utils.isArray(last)) { 2952 options = args.pop(); 2953 } 2954 2955 if (options.value > 0) { 2956 var constructorAbi = abi.filter(function (json) { 2957 return json.type === 'constructor' && json.inputs.length === args.length; 2958 })[0] || {}; 2959 2960 if (!constructorAbi.payable) { 2961 throw new Error('Cannot send value to non-payable constructor'); 2962 } 2963 } 2964 2965 var bytes = encodeConstructorParams(this.abi, args); 2966 options.data += bytes; 2967 2968 if (callback) { 2969 2970 // wait for the contract address adn check if the code was deployed 2971 this.eth.sendTransaction(options, function (err, hash) { 2972 if (err) { 2973 callback(err); 2974 } else { 2975 // add the transaction hash 2976 contract.transactionHash = hash; 2977 2978 // call callback for the first time 2979 callback(null, contract); 2980 2981 checkForContractAddress(contract, callback); 2982 } 2983 }); 2984 } else { 2985 var hash = this.eth.sendTransaction(options); 2986 // add the transaction hash 2987 contract.transactionHash = hash; 2988 checkForContractAddress(contract); 2989 } 2990 2991 return contract; 2992 }; 2993 2994 this.new.getData = this.getData.bind(this); 2995 }; 2996 2997 /** 2998 * Should be called to create new ContractFactory 2999 * 3000 * @method contract 3001 * @param {Array} abi 3002 * @returns {ContractFactory} new contract factory 3003 */ 3004 //var contract = function (abi) { 3005 //return new ContractFactory(abi); 3006 //}; 3007 3008 3009 3010 /** 3011 * Should be called to get access to existing contract on a blockchain 3012 * 3013 * @method at 3014 * @param {Address} contract address (required) 3015 * @param {Function} callback {optional) 3016 * @returns {Contract} returns contract if no callback was passed, 3017 * otherwise calls callback function (err, contract) 3018 */ 3019 ContractFactory.prototype.at = function (address, callback) { 3020 var contract = new Contract(this.eth, this.abi, address); 3021 3022 // this functions are not part of prototype, 3023 // because we dont want to spoil the interface 3024 addFunctionsToContract(contract); 3025 addEventsToContract(contract); 3026 3027 if (callback) { 3028 callback(null, contract); 3029 } 3030 return contract; 3031 }; 3032 3033 /** 3034 * Gets the data, which is data to deploy plus constructor params 3035 * 3036 * @method getData 3037 */ 3038 ContractFactory.prototype.getData = function () { 3039 var options = {}; // required! 3040 var args = Array.prototype.slice.call(arguments); 3041 3042 var last = args[args.length - 1]; 3043 if (utils.isObject(last) && !utils.isArray(last)) { 3044 options = args.pop(); 3045 } 3046 3047 var bytes = encodeConstructorParams(this.abi, args); 3048 options.data += bytes; 3049 3050 return options.data; 3051 }; 3052 3053 /** 3054 * Should be called to create new contract instance 3055 * 3056 * @method Contract 3057 * @param {Array} abi 3058 * @param {Address} contract address 3059 */ 3060 var Contract = function (eth, abi, address) { 3061 this._eth = eth; 3062 this.transactionHash = null; 3063 this.address = address; 3064 this.abi = abi; 3065 }; 3066 3067 module.exports = ContractFactory; 3068 3069 },{"../solidity/coder":7,"../utils/utils":20,"./allevents":23,"./event":27,"./function":31}],26:[function(require,module,exports){ 3070 /* 3071 This file is part of web3.js. 3072 3073 web3.js is free software: you can redistribute it and/or modify 3074 it under the terms of the GNU Lesser General Public License as published by 3075 the Free Software Foundation, either version 3 of the License, or 3076 (at your option) any later version. 3077 3078 web3.js is distributed in the hope that it will be useful, 3079 but WITHOUT ANY WARRANTY; without even the implied warranty of 3080 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3081 GNU Lesser General Public License for more details. 3082 3083 You should have received a copy of the GNU Lesser General Public License 3084 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3085 */ 3086 /** 3087 * @file errors.js 3088 * @author Marek Kotewicz <marek@ethdev.com> 3089 * @date 2015 3090 */ 3091 3092 module.exports = { 3093 InvalidNumberOfParams: function () { 3094 return new Error('Invalid number of input parameters'); 3095 }, 3096 InvalidConnection: function (host){ 3097 return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.'); 3098 }, 3099 InvalidProvider: function () { 3100 return new Error('Provider not set or invalid'); 3101 }, 3102 InvalidResponse: function (result){ 3103 var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); 3104 return new Error(message); 3105 }, 3106 ConnectionTimeout: function (ms){ 3107 return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived'); 3108 } 3109 }; 3110 3111 },{}],27:[function(require,module,exports){ 3112 /* 3113 This file is part of web3.js. 3114 3115 web3.js is free software: you can redistribute it and/or modify 3116 it under the terms of the GNU Lesser General Public License as published by 3117 the Free Software Foundation, either version 3 of the License, or 3118 (at your option) any later version. 3119 3120 web3.js is distributed in the hope that it will be useful, 3121 but WITHOUT ANY WARRANTY; without even the implied warranty of 3122 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3123 GNU Lesser General Public License for more details. 3124 3125 You should have received a copy of the GNU Lesser General Public License 3126 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3127 */ 3128 /** 3129 * @file event.js 3130 * @author Marek Kotewicz <marek@ethdev.com> 3131 * @date 2014 3132 */ 3133 3134 var utils = require('../utils/utils'); 3135 var coder = require('../solidity/coder'); 3136 var formatters = require('./formatters'); 3137 var sha3 = require('../utils/sha3'); 3138 var Filter = require('./filter'); 3139 var watches = require('./methods/watches'); 3140 3141 /** 3142 * This prototype should be used to create event filters 3143 */ 3144 var SolidityEvent = function (requestManager, json, address) { 3145 this._requestManager = requestManager; 3146 this._params = json.inputs; 3147 this._name = utils.transformToFullName(json); 3148 this._address = address; 3149 this._anonymous = json.anonymous; 3150 }; 3151 3152 /** 3153 * Should be used to get filtered param types 3154 * 3155 * @method types 3156 * @param {Bool} decide if returned typed should be indexed 3157 * @return {Array} array of types 3158 */ 3159 SolidityEvent.prototype.types = function (indexed) { 3160 return this._params.filter(function (i) { 3161 return i.indexed === indexed; 3162 }).map(function (i) { 3163 return i.type; 3164 }); 3165 }; 3166 3167 /** 3168 * Should be used to get event display name 3169 * 3170 * @method displayName 3171 * @return {String} event display name 3172 */ 3173 SolidityEvent.prototype.displayName = function () { 3174 return utils.extractDisplayName(this._name); 3175 }; 3176 3177 /** 3178 * Should be used to get event type name 3179 * 3180 * @method typeName 3181 * @return {String} event type name 3182 */ 3183 SolidityEvent.prototype.typeName = function () { 3184 return utils.extractTypeName(this._name); 3185 }; 3186 3187 /** 3188 * Should be used to get event signature 3189 * 3190 * @method signature 3191 * @return {String} event signature 3192 */ 3193 SolidityEvent.prototype.signature = function () { 3194 return sha3(this._name); 3195 }; 3196 3197 /** 3198 * Should be used to encode indexed params and options to one final object 3199 * 3200 * @method encode 3201 * @param {Object} indexed 3202 * @param {Object} options 3203 * @return {Object} everything combined together and encoded 3204 */ 3205 SolidityEvent.prototype.encode = function (indexed, options) { 3206 indexed = indexed || {}; 3207 options = options || {}; 3208 var result = {}; 3209 3210 ['fromBlock', 'toBlock'].filter(function (f) { 3211 return options[f] !== undefined; 3212 }).forEach(function (f) { 3213 result[f] = formatters.inputBlockNumberFormatter(options[f]); 3214 }); 3215 3216 result.topics = []; 3217 3218 result.address = this._address; 3219 if (!this._anonymous) { 3220 result.topics.push('0x' + this.signature()); 3221 } 3222 3223 var indexedTopics = this._params.filter(function (i) { 3224 return i.indexed === true; 3225 }).map(function (i) { 3226 var value = indexed[i.name]; 3227 if (value === undefined || value === null) { 3228 return null; 3229 } 3230 3231 if (utils.isArray(value)) { 3232 return value.map(function (v) { 3233 return '0x' + coder.encodeParam(i.type, v); 3234 }); 3235 } 3236 return '0x' + coder.encodeParam(i.type, value); 3237 }); 3238 3239 result.topics = result.topics.concat(indexedTopics); 3240 3241 return result; 3242 }; 3243 3244 /** 3245 * Should be used to decode indexed params and options 3246 * 3247 * @method decode 3248 * @param {Object} data 3249 * @return {Object} result object with decoded indexed && not indexed params 3250 */ 3251 SolidityEvent.prototype.decode = function (data) { 3252 3253 data.data = data.data || ''; 3254 data.topics = data.topics || []; 3255 3256 var argTopics = this._anonymous ? data.topics : data.topics.slice(1); 3257 var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join(""); 3258 var indexedParams = coder.decodeParams(this.types(true), indexedData); 3259 3260 var notIndexedData = data.data.slice(2); 3261 var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData); 3262 3263 var result = formatters.outputLogFormatter(data); 3264 result.event = this.displayName(); 3265 result.address = data.address; 3266 3267 result.args = this._params.reduce(function (acc, current) { 3268 acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift(); 3269 return acc; 3270 }, {}); 3271 3272 delete result.data; 3273 delete result.topics; 3274 3275 return result; 3276 }; 3277 3278 /** 3279 * Should be used to create new filter object from event 3280 * 3281 * @method execute 3282 * @param {Object} indexed 3283 * @param {Object} options 3284 * @return {Object} filter object 3285 */ 3286 SolidityEvent.prototype.execute = function (indexed, options, callback) { 3287 3288 if (utils.isFunction(arguments[arguments.length - 1])) { 3289 callback = arguments[arguments.length - 1]; 3290 if(arguments.length === 2) 3291 options = null; 3292 if(arguments.length === 1) { 3293 options = null; 3294 indexed = {}; 3295 } 3296 } 3297 3298 var o = this.encode(indexed, options); 3299 var formatter = this.decode.bind(this); 3300 return new Filter(this._requestManager, o, watches.eth(), formatter, callback); 3301 }; 3302 3303 /** 3304 * Should be used to attach event to contract object 3305 * 3306 * @method attachToContract 3307 * @param {Contract} 3308 */ 3309 SolidityEvent.prototype.attachToContract = function (contract) { 3310 var execute = this.execute.bind(this); 3311 var displayName = this.displayName(); 3312 if (!contract[displayName]) { 3313 contract[displayName] = execute; 3314 } 3315 contract[displayName][this.typeName()] = this.execute.bind(this, contract); 3316 }; 3317 3318 module.exports = SolidityEvent; 3319 3320 3321 },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters":30,"./methods/watches":43}],28:[function(require,module,exports){ 3322 var formatters = require('./formatters'); 3323 var utils = require('./../utils/utils'); 3324 var Method = require('./method'); 3325 var Property = require('./property'); 3326 3327 // TODO: refactor, so the input params are not altered. 3328 // it's necessary to make same 'extension' work with multiple providers 3329 var extend = function (web3) { 3330 /* jshint maxcomplexity:5 */ 3331 var ex = function (extension) { 3332 3333 var extendedObject; 3334 if (extension.property) { 3335 if (!web3[extension.property]) { 3336 web3[extension.property] = {}; 3337 } 3338 extendedObject = web3[extension.property]; 3339 } else { 3340 extendedObject = web3; 3341 } 3342 3343 if (extension.methods) { 3344 extension.methods.forEach(function (method) { 3345 method.attachToObject(extendedObject); 3346 method.setRequestManager(web3._requestManager); 3347 }); 3348 } 3349 3350 if (extension.properties) { 3351 extension.properties.forEach(function (property) { 3352 property.attachToObject(extendedObject); 3353 property.setRequestManager(web3._requestManager); 3354 }); 3355 } 3356 }; 3357 3358 ex.formatters = formatters; 3359 ex.utils = utils; 3360 ex.Method = Method; 3361 ex.Property = Property; 3362 3363 return ex; 3364 }; 3365 3366 3367 3368 module.exports = extend; 3369 3370 3371 },{"./../utils/utils":20,"./formatters":30,"./method":36,"./property":45}],29:[function(require,module,exports){ 3372 /* 3373 This file is part of web3.js. 3374 3375 web3.js is free software: you can redistribute it and/or modify 3376 it under the terms of the GNU Lesser General Public License as published by 3377 the Free Software Foundation, either version 3 of the License, or 3378 (at your option) any later version. 3379 3380 web3.js is distributed in the hope that it will be useful, 3381 but WITHOUT ANY WARRANTY; without even the implied warranty of 3382 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3383 GNU Lesser General Public License for more details. 3384 3385 You should have received a copy of the GNU Lesser General Public License 3386 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3387 */ 3388 /** @file filter.js 3389 * @authors: 3390 * Jeffrey Wilcke <jeff@ethdev.com> 3391 * Marek Kotewicz <marek@ethdev.com> 3392 * Marian Oancea <marian@ethdev.com> 3393 * Fabian Vogelsteller <fabian@ethdev.com> 3394 * Gav Wood <g@ethdev.com> 3395 * @date 2014 3396 */ 3397 3398 var formatters = require('./formatters'); 3399 var utils = require('../utils/utils'); 3400 3401 /** 3402 * Converts a given topic to a hex string, but also allows null values. 3403 * 3404 * @param {Mixed} value 3405 * @return {String} 3406 */ 3407 var toTopic = function(value){ 3408 3409 if(value === null || typeof value === 'undefined') 3410 return null; 3411 3412 value = String(value); 3413 3414 if(value.indexOf('0x') === 0) 3415 return value; 3416 else 3417 return utils.fromUtf8(value); 3418 }; 3419 3420 /// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones 3421 /// @param should be string or object 3422 /// @returns options string or object 3423 var getOptions = function (options) { 3424 3425 if (utils.isString(options)) { 3426 return options; 3427 } 3428 3429 options = options || {}; 3430 3431 // make sure topics, get converted to hex 3432 options.topics = options.topics || []; 3433 options.topics = options.topics.map(function(topic){ 3434 return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic); 3435 }); 3436 3437 return { 3438 topics: options.topics, 3439 from: options.from, 3440 to: options.to, 3441 address: options.address, 3442 fromBlock: formatters.inputBlockNumberFormatter(options.fromBlock), 3443 toBlock: formatters.inputBlockNumberFormatter(options.toBlock) 3444 }; 3445 }; 3446 3447 /** 3448 Adds the callback and sets up the methods, to iterate over the results. 3449 3450 @method getLogsAtStart 3451 @param {Object} self 3452 @param {funciton} 3453 */ 3454 var getLogsAtStart = function(self, callback){ 3455 // call getFilterLogs for the first watch callback start 3456 if (!utils.isString(self.options)) { 3457 self.get(function (err, messages) { 3458 // don't send all the responses to all the watches again... just to self one 3459 if (err) { 3460 callback(err); 3461 } 3462 3463 if(utils.isArray(messages)) { 3464 messages.forEach(function (message) { 3465 callback(null, message); 3466 }); 3467 } 3468 }); 3469 } 3470 }; 3471 3472 /** 3473 Adds the callback and sets up the methods, to iterate over the results. 3474 3475 @method pollFilter 3476 @param {Object} self 3477 */ 3478 var pollFilter = function(self) { 3479 3480 var onMessage = function (error, messages) { 3481 if (error) { 3482 return self.callbacks.forEach(function (callback) { 3483 callback(error); 3484 }); 3485 } 3486 3487 if(utils.isArray(messages)) { 3488 messages.forEach(function (message) { 3489 message = self.formatter ? self.formatter(message) : message; 3490 self.callbacks.forEach(function (callback) { 3491 callback(null, message); 3492 }); 3493 }); 3494 } 3495 }; 3496 3497 self.requestManager.startPolling({ 3498 method: self.implementation.poll.call, 3499 params: [self.filterId], 3500 }, self.filterId, onMessage, self.stopWatching.bind(self)); 3501 3502 }; 3503 3504 var Filter = function (requestManager, options, methods, formatter, callback, filterCreationErrorCallback) { 3505 var self = this; 3506 var implementation = {}; 3507 methods.forEach(function (method) { 3508 method.setRequestManager(requestManager); 3509 method.attachToObject(implementation); 3510 }); 3511 this.requestManager = requestManager; 3512 this.options = getOptions(options); 3513 this.implementation = implementation; 3514 this.filterId = null; 3515 this.callbacks = []; 3516 this.getLogsCallbacks = []; 3517 this.pollFilters = []; 3518 this.formatter = formatter; 3519 this.implementation.newFilter(this.options, function(error, id){ 3520 if(error) { 3521 self.callbacks.forEach(function(cb){ 3522 cb(error); 3523 }); 3524 filterCreationErrorCallback(error); 3525 } else { 3526 self.filterId = id; 3527 3528 // check if there are get pending callbacks as a consequence 3529 // of calling get() with filterId unassigned. 3530 self.getLogsCallbacks.forEach(function (cb){ 3531 self.get(cb); 3532 }); 3533 self.getLogsCallbacks = []; 3534 3535 // get filter logs for the already existing watch calls 3536 self.callbacks.forEach(function(cb){ 3537 getLogsAtStart(self, cb); 3538 }); 3539 if(self.callbacks.length > 0) 3540 pollFilter(self); 3541 3542 // start to watch immediately 3543 if(typeof callback === 'function') { 3544 return self.watch(callback); 3545 } 3546 } 3547 }); 3548 3549 return this; 3550 }; 3551 3552 Filter.prototype.watch = function (callback) { 3553 this.callbacks.push(callback); 3554 3555 if(this.filterId) { 3556 getLogsAtStart(this, callback); 3557 pollFilter(this); 3558 } 3559 3560 return this; 3561 }; 3562 3563 Filter.prototype.stopWatching = function (callback) { 3564 this.requestManager.stopPolling(this.filterId); 3565 this.callbacks = []; 3566 // remove filter async 3567 if (callback) { 3568 this.implementation.uninstallFilter(this.filterId, callback); 3569 } else { 3570 return this.implementation.uninstallFilter(this.filterId); 3571 } 3572 }; 3573 3574 Filter.prototype.get = function (callback) { 3575 var self = this; 3576 if (utils.isFunction(callback)) { 3577 if (this.filterId === null) { 3578 // If filterId is not set yet, call it back 3579 // when newFilter() assigns it. 3580 this.getLogsCallbacks.push(callback); 3581 } else { 3582 this.implementation.getLogs(this.filterId, function(err, res){ 3583 if (err) { 3584 callback(err); 3585 } else { 3586 callback(null, res.map(function (log) { 3587 return self.formatter ? self.formatter(log) : log; 3588 })); 3589 } 3590 }); 3591 } 3592 } else { 3593 if (this.filterId === null) { 3594 throw new Error('Filter ID Error: filter().get() can\'t be chained synchronous, please provide a callback for the get() method.'); 3595 } 3596 var logs = this.implementation.getLogs(this.filterId); 3597 return logs.map(function (log) { 3598 return self.formatter ? self.formatter(log) : log; 3599 }); 3600 } 3601 3602 return this; 3603 }; 3604 3605 module.exports = Filter; 3606 3607 3608 },{"../utils/utils":20,"./formatters":30}],30:[function(require,module,exports){ 3609 /* 3610 This file is part of web3.js. 3611 3612 web3.js is free software: you can redistribute it and/or modify 3613 it under the terms of the GNU Lesser General Public License as published by 3614 the Free Software Foundation, either version 3 of the License, or 3615 (at your option) any later version. 3616 3617 web3.js is distributed in the hope that it will be useful, 3618 but WITHOUT ANY WARRANTY; without even the implied warranty of 3619 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3620 GNU Lesser General Public License for more details. 3621 3622 You should have received a copy of the GNU Lesser General Public License 3623 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3624 */ 3625 /** 3626 * @file formatters.js 3627 * @author Marek Kotewicz <marek@ethdev.com> 3628 * @author Fabian Vogelsteller <fabian@ethdev.com> 3629 * @date 2015 3630 */ 3631 3632 var utils = require('../utils/utils'); 3633 var config = require('../utils/config'); 3634 var Iban = require('./iban'); 3635 3636 /** 3637 * Should the format output to a big number 3638 * 3639 * @method outputBigNumberFormatter 3640 * @param {String|Number|BigNumber} 3641 * @returns {BigNumber} object 3642 */ 3643 var outputBigNumberFormatter = function (number) { 3644 return utils.toBigNumber(number); 3645 }; 3646 3647 var isPredefinedBlockNumber = function (blockNumber) { 3648 return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest'; 3649 }; 3650 3651 var inputDefaultBlockNumberFormatter = function (blockNumber) { 3652 if (blockNumber === undefined) { 3653 return config.defaultBlock; 3654 } 3655 return inputBlockNumberFormatter(blockNumber); 3656 }; 3657 3658 var inputBlockNumberFormatter = function (blockNumber) { 3659 if (blockNumber === undefined) { 3660 return undefined; 3661 } else if (isPredefinedBlockNumber(blockNumber)) { 3662 return blockNumber; 3663 } 3664 return utils.toHex(blockNumber); 3665 }; 3666 3667 /** 3668 * Formats the input of a transaction and converts all values to HEX 3669 * 3670 * @method inputCallFormatter 3671 * @param {Object} transaction options 3672 * @returns object 3673 */ 3674 var inputCallFormatter = function (options){ 3675 3676 options.from = options.from || config.defaultAccount; 3677 3678 if (options.from) { 3679 options.from = inputAddressFormatter(options.from); 3680 } 3681 3682 if (options.to) { // it might be contract creation 3683 options.to = inputAddressFormatter(options.to); 3684 } 3685 3686 ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { 3687 return options[key] !== undefined; 3688 }).forEach(function(key){ 3689 options[key] = utils.fromDecimal(options[key]); 3690 }); 3691 3692 return options; 3693 }; 3694 3695 /** 3696 * Formats the input of a transaction and converts all values to HEX 3697 * 3698 * @method inputTransactionFormatter 3699 * @param {Object} transaction options 3700 * @returns object 3701 */ 3702 var inputTransactionFormatter = function (options){ 3703 3704 options.from = options.from || config.defaultAccount; 3705 options.from = inputAddressFormatter(options.from); 3706 3707 if (options.to) { // it might be contract creation 3708 options.to = inputAddressFormatter(options.to); 3709 } 3710 3711 ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { 3712 return options[key] !== undefined; 3713 }).forEach(function(key){ 3714 options[key] = utils.fromDecimal(options[key]); 3715 }); 3716 3717 return options; 3718 }; 3719 3720 /** 3721 * Formats the output of a transaction to its proper values 3722 * 3723 * @method outputTransactionFormatter 3724 * @param {Object} tx 3725 * @returns {Object} 3726 */ 3727 var outputTransactionFormatter = function (tx){ 3728 if(tx.blockNumber !== null) 3729 tx.blockNumber = utils.toDecimal(tx.blockNumber); 3730 if(tx.transactionIndex !== null) 3731 tx.transactionIndex = utils.toDecimal(tx.transactionIndex); 3732 tx.nonce = utils.toDecimal(tx.nonce); 3733 tx.gas = utils.toDecimal(tx.gas); 3734 tx.gasPrice = utils.toBigNumber(tx.gasPrice); 3735 tx.value = utils.toBigNumber(tx.value); 3736 return tx; 3737 }; 3738 3739 /** 3740 * Formats the output of a transaction receipt to its proper values 3741 * 3742 * @method outputTransactionReceiptFormatter 3743 * @param {Object} receipt 3744 * @returns {Object} 3745 */ 3746 var outputTransactionReceiptFormatter = function (receipt){ 3747 if(receipt.blockNumber !== null) 3748 receipt.blockNumber = utils.toDecimal(receipt.blockNumber); 3749 if(receipt.transactionIndex !== null) 3750 receipt.transactionIndex = utils.toDecimal(receipt.transactionIndex); 3751 receipt.cumulativeGasUsed = utils.toDecimal(receipt.cumulativeGasUsed); 3752 receipt.gasUsed = utils.toDecimal(receipt.gasUsed); 3753 3754 if(utils.isArray(receipt.logs)) { 3755 receipt.logs = receipt.logs.map(function(log){ 3756 return outputLogFormatter(log); 3757 }); 3758 } 3759 3760 return receipt; 3761 }; 3762 3763 /** 3764 * Formats the output of a block to its proper values 3765 * 3766 * @method outputBlockFormatter 3767 * @param {Object} block 3768 * @returns {Object} 3769 */ 3770 var outputBlockFormatter = function(block) { 3771 3772 // transform to number 3773 block.gasLimit = utils.toDecimal(block.gasLimit); 3774 block.gasUsed = utils.toDecimal(block.gasUsed); 3775 block.size = utils.toDecimal(block.size); 3776 block.timestamp = utils.toDecimal(block.timestamp); 3777 if(block.number !== null) 3778 block.number = utils.toDecimal(block.number); 3779 3780 block.difficulty = utils.toBigNumber(block.difficulty); 3781 block.totalDifficulty = utils.toBigNumber(block.totalDifficulty); 3782 3783 if (utils.isArray(block.transactions)) { 3784 block.transactions.forEach(function(item){ 3785 if(!utils.isString(item)) 3786 return outputTransactionFormatter(item); 3787 }); 3788 } 3789 3790 return block; 3791 }; 3792 3793 /** 3794 * Formats the output of a log 3795 * 3796 * @method outputLogFormatter 3797 * @param {Object} log object 3798 * @returns {Object} log 3799 */ 3800 var outputLogFormatter = function(log) { 3801 if(log.blockNumber !== null) 3802 log.blockNumber = utils.toDecimal(log.blockNumber); 3803 if(log.transactionIndex !== null) 3804 log.transactionIndex = utils.toDecimal(log.transactionIndex); 3805 if(log.logIndex !== null) 3806 log.logIndex = utils.toDecimal(log.logIndex); 3807 3808 return log; 3809 }; 3810 3811 /** 3812 * Formats the input of a whisper post and converts all values to HEX 3813 * 3814 * @method inputPostFormatter 3815 * @param {Object} transaction object 3816 * @returns {Object} 3817 */ 3818 var inputPostFormatter = function(post) { 3819 3820 // post.payload = utils.toHex(post.payload); 3821 post.ttl = utils.fromDecimal(post.ttl); 3822 post.workToProve = utils.fromDecimal(post.workToProve); 3823 post.priority = utils.fromDecimal(post.priority); 3824 3825 // fallback 3826 if (!utils.isArray(post.topics)) { 3827 post.topics = post.topics ? [post.topics] : []; 3828 } 3829 3830 // format the following options 3831 post.topics = post.topics.map(function(topic){ 3832 // convert only if not hex 3833 return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); 3834 }); 3835 3836 return post; 3837 }; 3838 3839 /** 3840 * Formats the output of a received post message 3841 * 3842 * @method outputPostFormatter 3843 * @param {Object} 3844 * @returns {Object} 3845 */ 3846 var outputPostFormatter = function(post){ 3847 3848 post.expiry = utils.toDecimal(post.expiry); 3849 post.sent = utils.toDecimal(post.sent); 3850 post.ttl = utils.toDecimal(post.ttl); 3851 post.workProved = utils.toDecimal(post.workProved); 3852 // post.payloadRaw = post.payload; 3853 // post.payload = utils.toAscii(post.payload); 3854 3855 // if (utils.isJson(post.payload)) { 3856 // post.payload = JSON.parse(post.payload); 3857 // } 3858 3859 // format the following options 3860 if (!post.topics) { 3861 post.topics = []; 3862 } 3863 post.topics = post.topics.map(function(topic){ 3864 return utils.toAscii(topic); 3865 }); 3866 3867 return post; 3868 }; 3869 3870 var inputAddressFormatter = function (address) { 3871 var iban = new Iban(address); 3872 if (iban.isValid() && iban.isDirect()) { 3873 return '0x' + iban.address(); 3874 } else if (utils.isStrictAddress(address)) { 3875 return address; 3876 } else if (utils.isAddress(address)) { 3877 return '0x' + address; 3878 } 3879 throw new Error('invalid address'); 3880 }; 3881 3882 3883 var outputSyncingFormatter = function(result) { 3884 3885 result.startingBlock = utils.toDecimal(result.startingBlock); 3886 result.currentBlock = utils.toDecimal(result.currentBlock); 3887 result.highestBlock = utils.toDecimal(result.highestBlock); 3888 if (result.knownStates) { 3889 result.knownStates = utils.toDecimal(result.knownStates); 3890 result.pulledStates = utils.toDecimal(result.pulledStates); 3891 } 3892 3893 return result; 3894 }; 3895 3896 module.exports = { 3897 inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, 3898 inputBlockNumberFormatter: inputBlockNumberFormatter, 3899 inputCallFormatter: inputCallFormatter, 3900 inputTransactionFormatter: inputTransactionFormatter, 3901 inputAddressFormatter: inputAddressFormatter, 3902 inputPostFormatter: inputPostFormatter, 3903 outputBigNumberFormatter: outputBigNumberFormatter, 3904 outputTransactionFormatter: outputTransactionFormatter, 3905 outputTransactionReceiptFormatter: outputTransactionReceiptFormatter, 3906 outputBlockFormatter: outputBlockFormatter, 3907 outputLogFormatter: outputLogFormatter, 3908 outputPostFormatter: outputPostFormatter, 3909 outputSyncingFormatter: outputSyncingFormatter 3910 }; 3911 3912 3913 },{"../utils/config":18,"../utils/utils":20,"./iban":33}],31:[function(require,module,exports){ 3914 /* 3915 This file is part of web3.js. 3916 3917 web3.js is free software: you can redistribute it and/or modify 3918 it under the terms of the GNU Lesser General Public License as published by 3919 the Free Software Foundation, either version 3 of the License, or 3920 (at your option) any later version. 3921 3922 web3.js is distributed in the hope that it will be useful, 3923 but WITHOUT ANY WARRANTY; without even the implied warranty of 3924 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3925 GNU Lesser General Public License for more details. 3926 3927 You should have received a copy of the GNU Lesser General Public License 3928 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3929 */ 3930 /** 3931 * @file function.js 3932 * @author Marek Kotewicz <marek@ethdev.com> 3933 * @date 2015 3934 */ 3935 3936 var coder = require('../solidity/coder'); 3937 var utils = require('../utils/utils'); 3938 var formatters = require('./formatters'); 3939 var sha3 = require('../utils/sha3'); 3940 3941 /** 3942 * This prototype should be used to call/sendTransaction to solidity functions 3943 */ 3944 var SolidityFunction = function (eth, json, address) { 3945 this._eth = eth; 3946 this._inputTypes = json.inputs.map(function (i) { 3947 return i.type; 3948 }); 3949 this._outputTypes = json.outputs.map(function (i) { 3950 return i.type; 3951 }); 3952 this._constant = json.constant; 3953 this._payable = json.payable; 3954 this._name = utils.transformToFullName(json); 3955 this._address = address; 3956 }; 3957 3958 SolidityFunction.prototype.extractCallback = function (args) { 3959 if (utils.isFunction(args[args.length - 1])) { 3960 return args.pop(); // modify the args array! 3961 } 3962 }; 3963 3964 SolidityFunction.prototype.extractDefaultBlock = function (args) { 3965 if (args.length > this._inputTypes.length && !utils.isObject(args[args.length -1])) { 3966 return formatters.inputDefaultBlockNumberFormatter(args.pop()); // modify the args array! 3967 } 3968 }; 3969 3970 /** 3971 * Should be used to create payload from arguments 3972 * 3973 * @method toPayload 3974 * @param {Array} solidity function params 3975 * @param {Object} optional payload options 3976 */ 3977 SolidityFunction.prototype.toPayload = function (args) { 3978 var options = {}; 3979 if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) { 3980 options = args[args.length - 1]; 3981 } 3982 options.to = this._address; 3983 options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args); 3984 return options; 3985 }; 3986 3987 /** 3988 * Should be used to get function signature 3989 * 3990 * @method signature 3991 * @return {String} function signature 3992 */ 3993 SolidityFunction.prototype.signature = function () { 3994 return sha3(this._name).slice(0, 8); 3995 }; 3996 3997 3998 SolidityFunction.prototype.unpackOutput = function (output) { 3999 if (!output) { 4000 return; 4001 } 4002 4003 output = output.length >= 2 ? output.slice(2) : output; 4004 var result = coder.decodeParams(this._outputTypes, output); 4005 return result.length === 1 ? result[0] : result; 4006 }; 4007 4008 /** 4009 * Calls a contract function. 4010 * 4011 * @method call 4012 * @param {...Object} Contract function arguments 4013 * @param {function} If the last argument is a function, the contract function 4014 * call will be asynchronous, and the callback will be passed the 4015 * error and result. 4016 * @return {String} output bytes 4017 */ 4018 SolidityFunction.prototype.call = function () { 4019 var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); 4020 var callback = this.extractCallback(args); 4021 var defaultBlock = this.extractDefaultBlock(args); 4022 var payload = this.toPayload(args); 4023 4024 4025 if (!callback) { 4026 var output = this._eth.call(payload, defaultBlock); 4027 return this.unpackOutput(output); 4028 } 4029 4030 var self = this; 4031 this._eth.call(payload, defaultBlock, function (error, output) { 4032 if (error) return callback(error, null); 4033 4034 var unpacked = null; 4035 try { 4036 unpacked = self.unpackOutput(output); 4037 } 4038 catch (e) { 4039 error = e; 4040 } 4041 4042 callback(error, unpacked); 4043 }); 4044 }; 4045 4046 /** 4047 * Should be used to sendTransaction to solidity function 4048 * 4049 * @method sendTransaction 4050 */ 4051 SolidityFunction.prototype.sendTransaction = function () { 4052 var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); 4053 var callback = this.extractCallback(args); 4054 var payload = this.toPayload(args); 4055 4056 if (payload.value > 0 && !this._payable) { 4057 throw new Error('Cannot send value to non-payable function'); 4058 } 4059 4060 if (!callback) { 4061 return this._eth.sendTransaction(payload); 4062 } 4063 4064 this._eth.sendTransaction(payload, callback); 4065 }; 4066 4067 /** 4068 * Should be used to estimateGas of solidity function 4069 * 4070 * @method estimateGas 4071 */ 4072 SolidityFunction.prototype.estimateGas = function () { 4073 var args = Array.prototype.slice.call(arguments); 4074 var callback = this.extractCallback(args); 4075 var payload = this.toPayload(args); 4076 4077 if (!callback) { 4078 return this._eth.estimateGas(payload); 4079 } 4080 4081 this._eth.estimateGas(payload, callback); 4082 }; 4083 4084 /** 4085 * Return the encoded data of the call 4086 * 4087 * @method getData 4088 * @return {String} the encoded data 4089 */ 4090 SolidityFunction.prototype.getData = function () { 4091 var args = Array.prototype.slice.call(arguments); 4092 var payload = this.toPayload(args); 4093 4094 return payload.data; 4095 }; 4096 4097 /** 4098 * Should be used to get function display name 4099 * 4100 * @method displayName 4101 * @return {String} display name of the function 4102 */ 4103 SolidityFunction.prototype.displayName = function () { 4104 return utils.extractDisplayName(this._name); 4105 }; 4106 4107 /** 4108 * Should be used to get function type name 4109 * 4110 * @method typeName 4111 * @return {String} type name of the function 4112 */ 4113 SolidityFunction.prototype.typeName = function () { 4114 return utils.extractTypeName(this._name); 4115 }; 4116 4117 /** 4118 * Should be called to get rpc requests from solidity function 4119 * 4120 * @method request 4121 * @returns {Object} 4122 */ 4123 SolidityFunction.prototype.request = function () { 4124 var args = Array.prototype.slice.call(arguments); 4125 var callback = this.extractCallback(args); 4126 var payload = this.toPayload(args); 4127 var format = this.unpackOutput.bind(this); 4128 4129 return { 4130 method: this._constant ? 'eth_call' : 'eth_sendTransaction', 4131 callback: callback, 4132 params: [payload], 4133 format: format 4134 }; 4135 }; 4136 4137 /** 4138 * Should be called to execute function 4139 * 4140 * @method execute 4141 */ 4142 SolidityFunction.prototype.execute = function () { 4143 var transaction = !this._constant; 4144 4145 // send transaction 4146 if (transaction) { 4147 return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments)); 4148 } 4149 4150 // call 4151 return this.call.apply(this, Array.prototype.slice.call(arguments)); 4152 }; 4153 4154 /** 4155 * Should be called to attach function to contract 4156 * 4157 * @method attachToContract 4158 * @param {Contract} 4159 */ 4160 SolidityFunction.prototype.attachToContract = function (contract) { 4161 var execute = this.execute.bind(this); 4162 execute.request = this.request.bind(this); 4163 execute.call = this.call.bind(this); 4164 execute.sendTransaction = this.sendTransaction.bind(this); 4165 execute.estimateGas = this.estimateGas.bind(this); 4166 execute.getData = this.getData.bind(this); 4167 var displayName = this.displayName(); 4168 if (!contract[displayName]) { 4169 contract[displayName] = execute; 4170 } 4171 contract[displayName][this.typeName()] = execute; // circular!!!! 4172 }; 4173 4174 module.exports = SolidityFunction; 4175 4176 4177 },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./formatters":30}],32:[function(require,module,exports){ 4178 /* 4179 This file is part of web3.js. 4180 4181 web3.js is free software: you can redistribute it and/or modify 4182 it under the terms of the GNU Lesser General Public License as published by 4183 the Free Software Foundation, either version 3 of the License, or 4184 (at your option) any later version. 4185 4186 web3.js is distributed in the hope that it will be useful, 4187 but WITHOUT ANY WARRANTY; without even the implied warranty of 4188 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4189 GNU Lesser General Public License for more details. 4190 4191 You should have received a copy of the GNU Lesser General Public License 4192 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4193 */ 4194 /** @file httpprovider.js 4195 * @authors: 4196 * Marek Kotewicz <marek@ethdev.com> 4197 * Marian Oancea <marian@ethdev.com> 4198 * Fabian Vogelsteller <fabian@ethdev.com> 4199 * @date 2015 4200 */ 4201 4202 "use strict"; 4203 4204 var errors = require('./errors'); 4205 4206 // workaround to use httpprovider in different envs 4207 // var XMLHttpRequest; // jshint ignore: line 4208 4209 // browser 4210 if (typeof window !== 'undefined' && window.XMLHttpRequest) { 4211 XMLHttpRequest = window.XMLHttpRequest; // jshint ignore: line 4212 // node 4213 } else { 4214 XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line 4215 } 4216 4217 var XHR2 = require('xhr2'); // jshint ignore: line 4218 4219 /** 4220 * HttpProvider should be used to send rpc calls over http 4221 */ 4222 var HttpProvider = function (host, timeout) { 4223 this.host = host || 'http://localhost:8545'; 4224 this.timeout = timeout || 0; 4225 }; 4226 4227 /** 4228 * Should be called to prepare new XMLHttpRequest 4229 * 4230 * @method prepareRequest 4231 * @param {Boolean} true if request should be async 4232 * @return {XMLHttpRequest} object 4233 */ 4234 HttpProvider.prototype.prepareRequest = function (async) { 4235 var request; 4236 4237 if (async) { 4238 request = new XHR2(); 4239 request.timeout = this.timeout; 4240 }else { 4241 request = new XMLHttpRequest(); 4242 } 4243 4244 request.open('POST', this.host, async); 4245 request.setRequestHeader('Content-Type','application/json'); 4246 return request; 4247 }; 4248 4249 /** 4250 * Should be called to make sync request 4251 * 4252 * @method send 4253 * @param {Object} payload 4254 * @return {Object} result 4255 */ 4256 HttpProvider.prototype.send = function (payload) { 4257 var request = this.prepareRequest(false); 4258 4259 try { 4260 request.send(JSON.stringify(payload)); 4261 } catch(error) { 4262 throw errors.InvalidConnection(this.host); 4263 } 4264 4265 var result = request.responseText; 4266 4267 try { 4268 result = JSON.parse(result); 4269 } catch(e) { 4270 throw errors.InvalidResponse(request.responseText); 4271 } 4272 4273 return result; 4274 }; 4275 4276 /** 4277 * Should be used to make async request 4278 * 4279 * @method sendAsync 4280 * @param {Object} payload 4281 * @param {Function} callback triggered on end with (err, result) 4282 */ 4283 HttpProvider.prototype.sendAsync = function (payload, callback) { 4284 var request = this.prepareRequest(true); 4285 4286 request.onreadystatechange = function() { 4287 if (request.readyState === 4 && request.timeout !== 1) { 4288 var result = request.responseText; 4289 var error = null; 4290 4291 try { 4292 result = JSON.parse(result); 4293 } catch(e) { 4294 error = errors.InvalidResponse(request.responseText); 4295 } 4296 4297 callback(error, result); 4298 } 4299 }; 4300 4301 request.ontimeout = function() { 4302 callback(errors.ConnectionTimeout(this.timeout)); 4303 }; 4304 4305 try { 4306 request.send(JSON.stringify(payload)); 4307 } catch(error) { 4308 callback(errors.InvalidConnection(this.host)); 4309 } 4310 }; 4311 4312 /** 4313 * Synchronously tries to make Http request 4314 * 4315 * @method isConnected 4316 * @return {Boolean} returns true if request haven't failed. Otherwise false 4317 */ 4318 HttpProvider.prototype.isConnected = function() { 4319 try { 4320 this.send({ 4321 id: 9999999999, 4322 jsonrpc: '2.0', 4323 method: 'net_listening', 4324 params: [] 4325 }); 4326 return true; 4327 } catch(e) { 4328 return false; 4329 } 4330 }; 4331 4332 module.exports = HttpProvider; 4333 4334 },{"./errors":26,"xhr2":86,"xmlhttprequest":17}],33:[function(require,module,exports){ 4335 /* 4336 This file is part of web3.js. 4337 4338 web3.js is free software: you can redistribute it and/or modify 4339 it under the terms of the GNU Lesser General Public License as published by 4340 the Free Software Foundation, either version 3 of the License, or 4341 (at your option) any later version. 4342 4343 web3.js is distributed in the hope that it will be useful, 4344 but WITHOUT ANY WARRANTY; without even the implied warranty of 4345 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4346 GNU Lesser General Public License for more details. 4347 4348 You should have received a copy of the GNU Lesser General Public License 4349 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4350 */ 4351 /** 4352 * @file iban.js 4353 * @author Marek Kotewicz <marek@ethdev.com> 4354 * @date 2015 4355 */ 4356 4357 var BigNumber = require('bignumber.js'); 4358 4359 var padLeft = function (string, bytes) { 4360 var result = string; 4361 while (result.length < bytes * 2) { 4362 result = '0' + result; 4363 } 4364 return result; 4365 }; 4366 4367 /** 4368 * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to 4369 * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. 4370 * 4371 * @method iso13616Prepare 4372 * @param {String} iban the IBAN 4373 * @returns {String} the prepared IBAN 4374 */ 4375 var iso13616Prepare = function (iban) { 4376 var A = 'A'.charCodeAt(0); 4377 var Z = 'Z'.charCodeAt(0); 4378 4379 iban = iban.toUpperCase(); 4380 iban = iban.substr(4) + iban.substr(0,4); 4381 4382 return iban.split('').map(function(n){ 4383 var code = n.charCodeAt(0); 4384 if (code >= A && code <= Z){ 4385 // A = 10, B = 11, ... Z = 35 4386 return code - A + 10; 4387 } else { 4388 return n; 4389 } 4390 }).join(''); 4391 }; 4392 4393 /** 4394 * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. 4395 * 4396 * @method mod9710 4397 * @param {String} iban 4398 * @returns {Number} 4399 */ 4400 var mod9710 = function (iban) { 4401 var remainder = iban, 4402 block; 4403 4404 while (remainder.length > 2){ 4405 block = remainder.slice(0, 9); 4406 remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); 4407 } 4408 4409 return parseInt(remainder, 10) % 97; 4410 }; 4411 4412 /** 4413 * This prototype should be used to create iban object from iban correct string 4414 * 4415 * @param {String} iban 4416 */ 4417 var Iban = function (iban) { 4418 this._iban = iban; 4419 }; 4420 4421 /** 4422 * This method should be used to create iban object from wtc address 4423 * 4424 * @method fromAddress 4425 * @param {String} address 4426 * @return {Iban} the IBAN object 4427 */ 4428 Iban.fromAddress = function (address) { 4429 var asBn = new BigNumber(address, 16); 4430 var base36 = asBn.toString(36); 4431 var padded = padLeft(base36, 15); 4432 return Iban.fromBban(padded.toUpperCase()); 4433 }; 4434 4435 /** 4436 * Convert the passed BBAN to an IBAN for this country specification. 4437 * Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. 4438 * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits 4439 * 4440 * @method fromBban 4441 * @param {String} bban the BBAN to convert to IBAN 4442 * @returns {Iban} the IBAN object 4443 */ 4444 Iban.fromBban = function (bban) { 4445 var countryCode = 'XE'; 4446 4447 var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); 4448 var checkDigit = ('0' + (98 - remainder)).slice(-2); 4449 4450 return new Iban(countryCode + checkDigit + bban); 4451 }; 4452 4453 /** 4454 * Should be used to create IBAN object for given institution and identifier 4455 * 4456 * @method createIndirect 4457 * @param {Object} options, required options are "institution" and "identifier" 4458 * @return {Iban} the IBAN object 4459 */ 4460 Iban.createIndirect = function (options) { 4461 return Iban.fromBban('ETH' + options.institution + options.identifier); 4462 }; 4463 4464 /** 4465 * Thos method should be used to check if given string is valid iban object 4466 * 4467 * @method isValid 4468 * @param {String} iban string 4469 * @return {Boolean} true if it is valid IBAN 4470 */ 4471 Iban.isValid = function (iban) { 4472 var i = new Iban(iban); 4473 return i.isValid(); 4474 }; 4475 4476 /** 4477 * Should be called to check if iban is correct 4478 * 4479 * @method isValid 4480 * @returns {Boolean} true if it is, otherwise false 4481 */ 4482 Iban.prototype.isValid = function () { 4483 return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && 4484 mod9710(iso13616Prepare(this._iban)) === 1; 4485 }; 4486 4487 /** 4488 * Should be called to check if iban number is direct 4489 * 4490 * @method isDirect 4491 * @returns {Boolean} true if it is, otherwise false 4492 */ 4493 Iban.prototype.isDirect = function () { 4494 return this._iban.length === 34 || this._iban.length === 35; 4495 }; 4496 4497 /** 4498 * Should be called to check if iban number if indirect 4499 * 4500 * @method isIndirect 4501 * @returns {Boolean} true if it is, otherwise false 4502 */ 4503 Iban.prototype.isIndirect = function () { 4504 return this._iban.length === 20; 4505 }; 4506 4507 /** 4508 * Should be called to get iban checksum 4509 * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) 4510 * 4511 * @method checksum 4512 * @returns {String} checksum 4513 */ 4514 Iban.prototype.checksum = function () { 4515 return this._iban.substr(2, 2); 4516 }; 4517 4518 /** 4519 * Should be called to get institution identifier 4520 * eg. XREG 4521 * 4522 * @method institution 4523 * @returns {String} institution identifier 4524 */ 4525 Iban.prototype.institution = function () { 4526 return this.isIndirect() ? this._iban.substr(7, 4) : ''; 4527 }; 4528 4529 /** 4530 * Should be called to get client identifier within institution 4531 * eg. GAVOFYORK 4532 * 4533 * @method client 4534 * @returns {String} client identifier 4535 */ 4536 Iban.prototype.client = function () { 4537 return this.isIndirect() ? this._iban.substr(11) : ''; 4538 }; 4539 4540 /** 4541 * Should be called to get client direct address 4542 * 4543 * @method address 4544 * @returns {String} client direct address 4545 */ 4546 Iban.prototype.address = function () { 4547 if (this.isDirect()) { 4548 var base36 = this._iban.substr(4); 4549 var asBn = new BigNumber(base36, 36); 4550 return padLeft(asBn.toString(16), 20); 4551 } 4552 4553 return ''; 4554 }; 4555 4556 Iban.prototype.toString = function () { 4557 return this._iban; 4558 }; 4559 4560 module.exports = Iban; 4561 4562 4563 },{"bignumber.js":"bignumber.js"}],34:[function(require,module,exports){ 4564 /* 4565 This file is part of web3.js. 4566 4567 web3.js is free software: you can redistribute it and/or modify 4568 it under the terms of the GNU Lesser General Public License as published by 4569 the Free Software Foundation, either version 3 of the License, or 4570 (at your option) any later version. 4571 4572 web3.js is distributed in the hope that it will be useful, 4573 but WITHOUT ANY WARRANTY; without even the implied warranty of 4574 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4575 GNU Lesser General Public License for more details. 4576 4577 You should have received a copy of the GNU Lesser General Public License 4578 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4579 */ 4580 /** @file ipcprovider.js 4581 * @authors: 4582 * Fabian Vogelsteller <fabian@ethdev.com> 4583 * @date 2015 4584 */ 4585 4586 "use strict"; 4587 4588 var utils = require('../utils/utils'); 4589 var errors = require('./errors'); 4590 4591 4592 var IpcProvider = function (path, net) { 4593 var _this = this; 4594 this.responseCallbacks = {}; 4595 this.path = path; 4596 4597 this.connection = net.connect({path: this.path}); 4598 4599 this.connection.on('error', function(e){ 4600 console.error('IPC Connection Error', e); 4601 _this._timeout(); 4602 }); 4603 4604 this.connection.on('end', function(){ 4605 _this._timeout(); 4606 }); 4607 4608 4609 // LISTEN FOR CONNECTION RESPONSES 4610 this.connection.on('data', function(data) { 4611 /*jshint maxcomplexity: 6 */ 4612 4613 _this._parseResponse(data.toString()).forEach(function(result){ 4614 4615 var id = null; 4616 4617 // get the id which matches the returned id 4618 if(utils.isArray(result)) { 4619 result.forEach(function(load){ 4620 if(_this.responseCallbacks[load.id]) 4621 id = load.id; 4622 }); 4623 } else { 4624 id = result.id; 4625 } 4626 4627 // fire the callback 4628 if(_this.responseCallbacks[id]) { 4629 _this.responseCallbacks[id](null, result); 4630 delete _this.responseCallbacks[id]; 4631 } 4632 }); 4633 }); 4634 }; 4635 4636 /** 4637 Will parse the response and make an array out of it. 4638 4639 @method _parseResponse 4640 @param {String} data 4641 */ 4642 IpcProvider.prototype._parseResponse = function(data) { 4643 var _this = this, 4644 returnValues = []; 4645 4646 // DE-CHUNKER 4647 var dechunkedData = data 4648 .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ 4649 .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ 4650 .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ 4651 .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ 4652 .split('|--|'); 4653 4654 dechunkedData.forEach(function(data){ 4655 4656 // prepend the last chunk 4657 if(_this.lastChunk) 4658 data = _this.lastChunk + data; 4659 4660 var result = null; 4661 4662 try { 4663 result = JSON.parse(data); 4664 4665 } catch(e) { 4666 4667 _this.lastChunk = data; 4668 4669 // start timeout to cancel all requests 4670 clearTimeout(_this.lastChunkTimeout); 4671 _this.lastChunkTimeout = setTimeout(function(){ 4672 _this._timeout(); 4673 throw errors.InvalidResponse(data); 4674 }, 1000 * 15); 4675 4676 return; 4677 } 4678 4679 // cancel timeout and set chunk to null 4680 clearTimeout(_this.lastChunkTimeout); 4681 _this.lastChunk = null; 4682 4683 if(result) 4684 returnValues.push(result); 4685 }); 4686 4687 return returnValues; 4688 }; 4689 4690 4691 /** 4692 Get the adds a callback to the responseCallbacks object, 4693 which will be called if a response matching the response Id will arrive. 4694 4695 @method _addResponseCallback 4696 */ 4697 IpcProvider.prototype._addResponseCallback = function(payload, callback) { 4698 var id = payload.id || payload[0].id; 4699 var method = payload.method || payload[0].method; 4700 4701 this.responseCallbacks[id] = callback; 4702 this.responseCallbacks[id].method = method; 4703 }; 4704 4705 /** 4706 Timeout all requests when the end/error event is fired 4707 4708 @method _timeout 4709 */ 4710 IpcProvider.prototype._timeout = function() { 4711 for(var key in this.responseCallbacks) { 4712 if(this.responseCallbacks.hasOwnProperty(key)){ 4713 this.responseCallbacks[key](errors.InvalidConnection('on IPC')); 4714 delete this.responseCallbacks[key]; 4715 } 4716 } 4717 }; 4718 4719 4720 /** 4721 Check if the current connection is still valid. 4722 4723 @method isConnected 4724 */ 4725 IpcProvider.prototype.isConnected = function() { 4726 var _this = this; 4727 4728 // try reconnect, when connection is gone 4729 if(!_this.connection.writable) 4730 _this.connection.connect({path: _this.path}); 4731 4732 return !!this.connection.writable; 4733 }; 4734 4735 IpcProvider.prototype.send = function (payload) { 4736 4737 if(this.connection.writeSync) { 4738 var result; 4739 4740 // try reconnect, when connection is gone 4741 if(!this.connection.writable) 4742 this.connection.connect({path: this.path}); 4743 4744 var data = this.connection.writeSync(JSON.stringify(payload)); 4745 4746 try { 4747 result = JSON.parse(data); 4748 } catch(e) { 4749 throw errors.InvalidResponse(data); 4750 } 4751 4752 return result; 4753 4754 } else { 4755 throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported by the IPC provider.'); 4756 } 4757 }; 4758 4759 IpcProvider.prototype.sendAsync = function (payload, callback) { 4760 // try reconnect, when connection is gone 4761 if(!this.connection.writable) 4762 this.connection.connect({path: this.path}); 4763 4764 4765 this.connection.write(JSON.stringify(payload)); 4766 this._addResponseCallback(payload, callback); 4767 }; 4768 4769 module.exports = IpcProvider; 4770 4771 4772 },{"../utils/utils":20,"./errors":26}],35:[function(require,module,exports){ 4773 /* 4774 This file is part of web3.js. 4775 4776 web3.js is free software: you can redistribute it and/or modify 4777 it under the terms of the GNU Lesser General Public License as published by 4778 the Free Software Foundation, either version 3 of the License, or 4779 (at your option) any later version. 4780 4781 web3.js is distributed in the hope that it will be useful, 4782 but WITHOUT ANY WARRANTY; without even the implied warranty of 4783 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4784 GNU Lesser General Public License for more details. 4785 4786 You should have received a copy of the GNU Lesser General Public License 4787 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4788 */ 4789 /** @file jsonrpc.js 4790 * @authors: 4791 * Marek Kotewicz <marek@ethdev.com> 4792 * Aaron Kumavis <aaron@kumavis.me> 4793 * @date 2015 4794 */ 4795 4796 // Initialize Jsonrpc as a simple object with utility functions. 4797 var Jsonrpc = { 4798 messageId: 0 4799 }; 4800 4801 /** 4802 * Should be called to valid json create payload object 4803 * 4804 * @method toPayload 4805 * @param {Function} method of jsonrpc call, required 4806 * @param {Array} params, an array of method params, optional 4807 * @returns {Object} valid jsonrpc payload object 4808 */ 4809 Jsonrpc.toPayload = function (method, params) { 4810 if (!method) 4811 console.error('jsonrpc method should be specified!'); 4812 4813 // advance message ID 4814 Jsonrpc.messageId++; 4815 4816 return { 4817 jsonrpc: '2.0', 4818 id: Jsonrpc.messageId, 4819 method: method, 4820 params: params || [] 4821 }; 4822 }; 4823 4824 /** 4825 * Should be called to check if jsonrpc response is valid 4826 * 4827 * @method isValidResponse 4828 * @param {Object} 4829 * @returns {Boolean} true if response is valid, otherwise false 4830 */ 4831 Jsonrpc.isValidResponse = function (response) { 4832 return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); 4833 4834 function validateSingleMessage(message){ 4835 return !!message && 4836 !message.error && 4837 message.jsonrpc === '2.0' && 4838 typeof message.id === 'number' && 4839 message.result !== undefined; // only undefined is not valid json object 4840 } 4841 }; 4842 4843 /** 4844 * Should be called to create batch payload object 4845 * 4846 * @method toBatchPayload 4847 * @param {Array} messages, an array of objects with method (required) and params (optional) fields 4848 * @returns {Array} batch payload 4849 */ 4850 Jsonrpc.toBatchPayload = function (messages) { 4851 return messages.map(function (message) { 4852 return Jsonrpc.toPayload(message.method, message.params); 4853 }); 4854 }; 4855 4856 module.exports = Jsonrpc; 4857 4858 4859 },{}],36:[function(require,module,exports){ 4860 /* 4861 This file is part of web3.js. 4862 4863 web3.js is free software: you can redistribute it and/or modify 4864 it under the terms of the GNU Lesser General Public License as published by 4865 the Free Software Foundation, either version 3 of the License, or 4866 (at your option) any later version. 4867 4868 web3.js is distributed in the hope that it will be useful, 4869 but WITHOUT ANY WARRANTY; without even the implied warranty of 4870 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4871 GNU Lesser General Public License for more details. 4872 4873 You should have received a copy of the GNU Lesser General Public License 4874 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4875 */ 4876 /** 4877 * @file method.js 4878 * @author Marek Kotewicz <marek@ethdev.com> 4879 * @date 2015 4880 */ 4881 4882 var utils = require('../utils/utils'); 4883 var errors = require('./errors'); 4884 4885 var Method = function (options) { 4886 this.name = options.name; 4887 this.call = options.call; 4888 this.params = options.params || 0; 4889 this.inputFormatter = options.inputFormatter; 4890 this.outputFormatter = options.outputFormatter; 4891 this.requestManager = null; 4892 }; 4893 4894 Method.prototype.setRequestManager = function (rm) { 4895 this.requestManager = rm; 4896 }; 4897 4898 /** 4899 * Should be used to determine name of the jsonrpc method based on arguments 4900 * 4901 * @method getCall 4902 * @param {Array} arguments 4903 * @return {String} name of jsonrpc method 4904 */ 4905 Method.prototype.getCall = function (args) { 4906 return utils.isFunction(this.call) ? this.call(args) : this.call; 4907 }; 4908 4909 /** 4910 * Should be used to extract callback from array of arguments. Modifies input param 4911 * 4912 * @method extractCallback 4913 * @param {Array} arguments 4914 * @return {Function|Null} callback, if exists 4915 */ 4916 Method.prototype.extractCallback = function (args) { 4917 if (utils.isFunction(args[args.length - 1])) { 4918 return args.pop(); // modify the args array! 4919 } 4920 }; 4921 4922 /** 4923 * Should be called to check if the number of arguments is correct 4924 * 4925 * @method validateArgs 4926 * @param {Array} arguments 4927 * @throws {Error} if it is not 4928 */ 4929 Method.prototype.validateArgs = function (args) { 4930 if (args.length !== this.params) { 4931 throw errors.InvalidNumberOfParams(); 4932 } 4933 }; 4934 4935 /** 4936 * Should be called to format input args of method 4937 * 4938 * @method formatInput 4939 * @param {Array} 4940 * @return {Array} 4941 */ 4942 Method.prototype.formatInput = function (args) { 4943 if (!this.inputFormatter) { 4944 return args; 4945 } 4946 4947 return this.inputFormatter.map(function (formatter, index) { 4948 return formatter ? formatter(args[index]) : args[index]; 4949 }); 4950 }; 4951 4952 /** 4953 * Should be called to format output(result) of method 4954 * 4955 * @method formatOutput 4956 * @param {Object} 4957 * @return {Object} 4958 */ 4959 Method.prototype.formatOutput = function (result) { 4960 return this.outputFormatter && result ? this.outputFormatter(result) : result; 4961 }; 4962 4963 /** 4964 * Should create payload from given input args 4965 * 4966 * @method toPayload 4967 * @param {Array} args 4968 * @return {Object} 4969 */ 4970 Method.prototype.toPayload = function (args) { 4971 var call = this.getCall(args); 4972 var callback = this.extractCallback(args); 4973 var params = this.formatInput(args); 4974 this.validateArgs(params); 4975 4976 return { 4977 method: call, 4978 params: params, 4979 callback: callback 4980 }; 4981 }; 4982 4983 Method.prototype.attachToObject = function (obj) { 4984 var func = this.buildCall(); 4985 func.call = this.call; // TODO!!! that's ugly. filter.js uses it 4986 var name = this.name.split('.'); 4987 if (name.length > 1) { 4988 obj[name[0]] = obj[name[0]] || {}; 4989 obj[name[0]][name[1]] = func; 4990 } else { 4991 obj[name[0]] = func; 4992 } 4993 }; 4994 4995 Method.prototype.buildCall = function() { 4996 var method = this; 4997 var send = function () { 4998 var payload = method.toPayload(Array.prototype.slice.call(arguments)); 4999 if (payload.callback) { 5000 return method.requestManager.sendAsync(payload, function (err, result) { 5001 payload.callback(err, method.formatOutput(result)); 5002 }); 5003 } 5004 return method.formatOutput(method.requestManager.send(payload)); 5005 }; 5006 send.request = this.request.bind(this); 5007 return send; 5008 }; 5009 5010 /** 5011 * Should be called to create pure JSONRPC request which can be used in batch request 5012 * 5013 * @method request 5014 * @param {...} params 5015 * @return {Object} jsonrpc request 5016 */ 5017 Method.prototype.request = function () { 5018 var payload = this.toPayload(Array.prototype.slice.call(arguments)); 5019 payload.format = this.formatOutput.bind(this); 5020 return payload; 5021 }; 5022 5023 module.exports = Method; 5024 5025 5026 },{"../utils/utils":20,"./errors":26}],37:[function(require,module,exports){ 5027 /* 5028 This file is part of web3.js. 5029 5030 web3.js is free software: you can redistribute it and/or modify 5031 it under the terms of the GNU Lesser General Public License as published by 5032 the Free Software Foundation, either version 3 of the License, or 5033 (at your option) any later version. 5034 5035 web3.js is distributed in the hope that it will be useful, 5036 but WITHOUT ANY WARRANTY; without even the implied warranty of 5037 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5038 GNU Lesser General Public License for more details. 5039 5040 You should have received a copy of the GNU Lesser General Public License 5041 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5042 */ 5043 /** @file db.js 5044 * @authors: 5045 * Marek Kotewicz <marek@ethdev.com> 5046 * @date 2015 5047 */ 5048 5049 var Method = require('../method'); 5050 5051 var DB = function (web3) { 5052 this._requestManager = web3._requestManager; 5053 5054 var self = this; 5055 5056 methods().forEach(function(method) { 5057 method.attachToObject(self); 5058 method.setRequestManager(web3._requestManager); 5059 }); 5060 }; 5061 5062 var methods = function () { 5063 var putString = new Method({ 5064 name: 'putString', 5065 call: 'db_putString', 5066 params: 3 5067 }); 5068 5069 var getString = new Method({ 5070 name: 'getString', 5071 call: 'db_getString', 5072 params: 2 5073 }); 5074 5075 var putHex = new Method({ 5076 name: 'putHex', 5077 call: 'db_putHex', 5078 params: 3 5079 }); 5080 5081 var getHex = new Method({ 5082 name: 'getHex', 5083 call: 'db_getHex', 5084 params: 2 5085 }); 5086 5087 return [ 5088 putString, getString, putHex, getHex 5089 ]; 5090 }; 5091 5092 module.exports = DB; 5093 5094 },{"../method":36}],38:[function(require,module,exports){ 5095 /* 5096 This file is part of web3.js. 5097 5098 web3.js is free software: you can redistribute it and/or modify 5099 it under the terms of the GNU Lesser General Public License as published by 5100 the Free Software Foundation, either version 3 of the License, or 5101 (at your option) any later version. 5102 5103 web3.js is distributed in the hope that it will be useful, 5104 but WITHOUT ANY WARRANTY; without even the implied warranty of 5105 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5106 GNU Lesser General Public License for more details. 5107 5108 You should have received a copy of the GNU Lesser General Public License 5109 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5110 */ 5111 /** 5112 * @file eth.js 5113 * @author Marek Kotewicz <marek@ethdev.com> 5114 * @author Fabian Vogelsteller <fabian@ethdev.com> 5115 * @date 2015 5116 */ 5117 5118 "use strict"; 5119 5120 var formatters = require('../formatters'); 5121 var utils = require('../../utils/utils'); 5122 var Method = require('../method'); 5123 var Property = require('../property'); 5124 var c = require('../../utils/config'); 5125 var Contract = require('../contract'); 5126 var watches = require('./watches'); 5127 var Filter = require('../filter'); 5128 var IsSyncing = require('../syncing'); 5129 var namereg = require('../namereg'); 5130 var Iban = require('../iban'); 5131 var transfer = require('../transfer'); 5132 5133 var blockCall = function (args) { 5134 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber"; 5135 }; 5136 5137 var transactionFromBlockCall = function (args) { 5138 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex'; 5139 }; 5140 5141 var uncleCall = function (args) { 5142 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex'; 5143 }; 5144 5145 var getBlockTransactionCountCall = function (args) { 5146 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber'; 5147 }; 5148 5149 var uncleCountCall = function (args) { 5150 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber'; 5151 }; 5152 5153 function Eth(web3) { 5154 this._requestManager = web3._requestManager; 5155 5156 var self = this; 5157 5158 methods().forEach(function(method) { 5159 method.attachToObject(self); 5160 method.setRequestManager(self._requestManager); 5161 }); 5162 5163 properties().forEach(function(p) { 5164 p.attachToObject(self); 5165 p.setRequestManager(self._requestManager); 5166 }); 5167 5168 5169 this.iban = Iban; 5170 this.sendIBANTransaction = transfer.bind(null, this); 5171 } 5172 5173 Object.defineProperty(Eth.prototype, 'defaultBlock', { 5174 get: function () { 5175 return c.defaultBlock; 5176 }, 5177 set: function (val) { 5178 c.defaultBlock = val; 5179 return val; 5180 } 5181 }); 5182 5183 Object.defineProperty(Eth.prototype, 'defaultAccount', { 5184 get: function () { 5185 return c.defaultAccount; 5186 }, 5187 set: function (val) { 5188 c.defaultAccount = val; 5189 return val; 5190 } 5191 }); 5192 5193 var methods = function () { 5194 var getBalance = new Method({ 5195 name: 'getBalance', 5196 call: 'eth_getBalance', 5197 params: 2, 5198 inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter], 5199 outputFormatter: formatters.outputBigNumberFormatter 5200 }); 5201 5202 var getStorageAt = new Method({ 5203 name: 'getStorageAt', 5204 call: 'eth_getStorageAt', 5205 params: 3, 5206 inputFormatter: [null, utils.toHex, formatters.inputDefaultBlockNumberFormatter] 5207 }); 5208 5209 var getCode = new Method({ 5210 name: 'getCode', 5211 call: 'eth_getCode', 5212 params: 2, 5213 inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter] 5214 }); 5215 5216 var getBlock = new Method({ 5217 name: 'getBlock', 5218 call: blockCall, 5219 params: 2, 5220 inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }], 5221 outputFormatter: formatters.outputBlockFormatter 5222 }); 5223 5224 var getUncle = new Method({ 5225 name: 'getUncle', 5226 call: uncleCall, 5227 params: 2, 5228 inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex], 5229 outputFormatter: formatters.outputBlockFormatter, 5230 5231 }); 5232 5233 var getCompilers = new Method({ 5234 name: 'getCompilers', 5235 call: 'eth_getCompilers', 5236 params: 0 5237 }); 5238 5239 var getBlockTransactionCount = new Method({ 5240 name: 'getBlockTransactionCount', 5241 call: getBlockTransactionCountCall, 5242 params: 1, 5243 inputFormatter: [formatters.inputBlockNumberFormatter], 5244 outputFormatter: utils.toDecimal 5245 }); 5246 5247 var getBlockUncleCount = new Method({ 5248 name: 'getBlockUncleCount', 5249 call: uncleCountCall, 5250 params: 1, 5251 inputFormatter: [formatters.inputBlockNumberFormatter], 5252 outputFormatter: utils.toDecimal 5253 }); 5254 5255 var getTransaction = new Method({ 5256 name: 'getTransaction', 5257 call: 'eth_getTransactionByHash', 5258 params: 1, 5259 outputFormatter: formatters.outputTransactionFormatter 5260 }); 5261 5262 var getTransactionFromBlock = new Method({ 5263 name: 'getTransactionFromBlock', 5264 call: transactionFromBlockCall, 5265 params: 2, 5266 inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex], 5267 outputFormatter: formatters.outputTransactionFormatter 5268 }); 5269 5270 var getTransactionReceipt = new Method({ 5271 name: 'getTransactionReceipt', 5272 call: 'eth_getTransactionReceipt', 5273 params: 1, 5274 outputFormatter: formatters.outputTransactionReceiptFormatter 5275 }); 5276 5277 var getTransactionCount = new Method({ 5278 name: 'getTransactionCount', 5279 call: 'eth_getTransactionCount', 5280 params: 2, 5281 inputFormatter: [null, formatters.inputDefaultBlockNumberFormatter], 5282 outputFormatter: utils.toDecimal 5283 }); 5284 5285 var sendRawTransaction = new Method({ 5286 name: 'sendRawTransaction', 5287 call: 'eth_sendRawTransaction', 5288 params: 1, 5289 inputFormatter: [null] 5290 }); 5291 5292 var sendTransaction = new Method({ 5293 name: 'sendTransaction', 5294 call: 'eth_sendTransaction', 5295 params: 1, 5296 inputFormatter: [formatters.inputTransactionFormatter] 5297 }); 5298 5299 var sign = new Method({ 5300 name: 'sign', 5301 call: 'eth_sign', 5302 params: 2, 5303 inputFormatter: [formatters.inputAddressFormatter, null] 5304 }); 5305 5306 var call = new Method({ 5307 name: 'call', 5308 call: 'eth_call', 5309 params: 2, 5310 inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter] 5311 }); 5312 5313 var estimateGas = new Method({ 5314 name: 'estimateGas', 5315 call: 'eth_estimateGas', 5316 params: 1, 5317 inputFormatter: [formatters.inputCallFormatter], 5318 outputFormatter: utils.toDecimal 5319 }); 5320 5321 var compileSolidity = new Method({ 5322 name: 'compile.solidity', 5323 call: 'eth_compileSolidity', 5324 params: 1 5325 }); 5326 5327 var compileLLL = new Method({ 5328 name: 'compile.lll', 5329 call: 'eth_compileLLL', 5330 params: 1 5331 }); 5332 5333 var compileSerpent = new Method({ 5334 name: 'compile.serpent', 5335 call: 'eth_compileSerpent', 5336 params: 1 5337 }); 5338 5339 var submitWork = new Method({ 5340 name: 'submitWork', 5341 call: 'eth_submitWork', 5342 params: 3 5343 }); 5344 5345 var posShareCheck = new Method({ 5346 name: 'posShareCheck', 5347 call: 'eth_posShareCheck', 5348 params: 4 5349 }); 5350 5351 var getWork = new Method({ 5352 name: 'getWork', 5353 call: 'eth_getWork', 5354 params: 0 5355 }); 5356 5357 return [ 5358 getBalance, 5359 getStorageAt, 5360 getCode, 5361 getBlock, 5362 getUncle, 5363 getCompilers, 5364 getBlockTransactionCount, 5365 getBlockUncleCount, 5366 getTransaction, 5367 getTransactionFromBlock, 5368 getTransactionReceipt, 5369 getTransactionCount, 5370 call, 5371 estimateGas, 5372 sendRawTransaction, 5373 sendTransaction, 5374 sign, 5375 compileSolidity, 5376 compileLLL, 5377 compileSerpent, 5378 submitWork, 5379 posShareCheck, 5380 getWork 5381 ]; 5382 }; 5383 5384 5385 var properties = function () { 5386 return [ 5387 new Property({ 5388 name: 'coinbase', 5389 getter: 'eth_coinbase' 5390 }), 5391 new Property({ 5392 name: 'mining', 5393 getter: 'eth_mining' 5394 }), 5395 new Property({ 5396 name: 'hashrate', 5397 getter: 'eth_hashrate', 5398 outputFormatter: utils.toDecimal 5399 }), 5400 new Property({ 5401 name: 'syncing', 5402 getter: 'eth_syncing', 5403 outputFormatter: formatters.outputSyncingFormatter 5404 }), 5405 new Property({ 5406 name: 'gasPrice', 5407 getter: 'eth_gasPrice', 5408 outputFormatter: formatters.outputBigNumberFormatter 5409 }), 5410 new Property({ 5411 name: 'accounts', 5412 getter: 'eth_accounts' 5413 }), 5414 new Property({ 5415 name: 'blockNumber', 5416 getter: 'eth_blockNumber', 5417 outputFormatter: utils.toDecimal 5418 }), 5419 new Property({ 5420 name: 'protocolVersion', 5421 getter: 'eth_protocolVersion' 5422 }) 5423 ]; 5424 }; 5425 5426 Eth.prototype.contract = function (abi) { 5427 var factory = new Contract(this, abi); 5428 return factory; 5429 }; 5430 5431 Eth.prototype.filter = function (fil, callback) { 5432 return new Filter(this._requestManager, fil, watches.eth(), formatters.outputLogFormatter, callback); 5433 }; 5434 5435 Eth.prototype.namereg = function () { 5436 return this.contract(namereg.global.abi).at(namereg.global.address); 5437 }; 5438 5439 Eth.prototype.icapNamereg = function () { 5440 return this.contract(namereg.icap.abi).at(namereg.icap.address); 5441 }; 5442 5443 Eth.prototype.isSyncing = function (callback) { 5444 return new IsSyncing(this._requestManager, callback); 5445 }; 5446 5447 module.exports = Eth; 5448 5449 5450 },{"../../utils/config":18,"../../utils/utils":20,"../contract":25,"../filter":29,"../formatters":30,"../iban":33,"../method":36,"../namereg":44,"../property":45,"../syncing":48,"../transfer":49,"./watches":43}],39:[function(require,module,exports){ 5451 /* 5452 This file is part of web3.js. 5453 5454 web3.js is free software: you can redistribute it and/or modify 5455 it under the terms of the GNU Lesser General Public License as published by 5456 the Free Software Foundation, either version 3 of the License, or 5457 (at your option) any later version. 5458 5459 web3.js is distributed in the hope that it will be useful, 5460 but WITHOUT ANY WARRANTY; without even the implied warranty of 5461 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5462 GNU Lesser General Public License for more details. 5463 5464 You should have received a copy of the GNU Lesser General Public License 5465 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5466 */ 5467 /** @file eth.js 5468 * @authors: 5469 * Marek Kotewicz <marek@ethdev.com> 5470 * @date 2015 5471 */ 5472 5473 var utils = require('../../utils/utils'); 5474 var Property = require('../property'); 5475 5476 var Net = function (web3) { 5477 this._requestManager = web3._requestManager; 5478 5479 var self = this; 5480 5481 properties().forEach(function(p) { 5482 p.attachToObject(self); 5483 p.setRequestManager(web3._requestManager); 5484 }); 5485 }; 5486 5487 /// @returns an array of objects describing web3.eth api properties 5488 var properties = function () { 5489 return [ 5490 new Property({ 5491 name: 'listening', 5492 getter: 'net_listening' 5493 }), 5494 new Property({ 5495 name: 'peerCount', 5496 getter: 'net_peerCount', 5497 outputFormatter: utils.toDecimal 5498 }) 5499 ]; 5500 }; 5501 5502 module.exports = Net; 5503 5504 },{"../../utils/utils":20,"../property":45}],40:[function(require,module,exports){ 5505 /* 5506 This file is part of web3.js. 5507 5508 web3.js is free software: you can redistribute it and/or modify 5509 it under the terms of the GNU Lesser General Public License as published by 5510 the Free Software Foundation, either version 3 of the License, or 5511 (at your option) any later version. 5512 5513 web3.js is distributed in the hope that it will be useful, 5514 but WITHOUT ANY WARRANTY; without even the implied warranty of 5515 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5516 GNU Lesser General Public License for more details. 5517 5518 You should have received a copy of the GNU Lesser General Public License 5519 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5520 */ 5521 /** 5522 * @file eth.js 5523 * @author Marek Kotewicz <marek@ethdev.com> 5524 * @author Fabian Vogelsteller <fabian@ethdev.com> 5525 * @date 2015 5526 */ 5527 5528 "use strict"; 5529 5530 var Method = require('../method'); 5531 var Property = require('../property'); 5532 var formatters = require('../formatters'); 5533 5534 function Personal(web3) { 5535 this._requestManager = web3._requestManager; 5536 5537 var self = this; 5538 5539 methods().forEach(function(method) { 5540 method.attachToObject(self); 5541 method.setRequestManager(self._requestManager); 5542 }); 5543 5544 properties().forEach(function(p) { 5545 p.attachToObject(self); 5546 p.setRequestManager(self._requestManager); 5547 }); 5548 } 5549 5550 var methods = function () { 5551 var newAccount = new Method({ 5552 name: 'newAccount', 5553 call: 'personal_newAccount', 5554 params: 1, 5555 inputFormatter: [null] 5556 }); 5557 5558 var unlockAccount = new Method({ 5559 name: 'unlockAccount', 5560 call: 'personal_unlockAccount', 5561 params: 3, 5562 inputFormatter: [formatters.inputAddressFormatter, null, null] 5563 }); 5564 5565 var sendTransaction = new Method({ 5566 name: 'sendTransaction', 5567 call: 'personal_sendTransaction', 5568 params: 2, 5569 inputFormatter: [formatters.inputTransactionFormatter, null] 5570 }); 5571 5572 var lockAccount = new Method({ 5573 name: 'lockAccount', 5574 call: 'personal_lockAccount', 5575 params: 1, 5576 inputFormatter: [formatters.inputAddressFormatter] 5577 }); 5578 5579 return [ 5580 newAccount, 5581 unlockAccount, 5582 sendTransaction, 5583 lockAccount 5584 ]; 5585 }; 5586 5587 var properties = function () { 5588 return [ 5589 new Property({ 5590 name: 'listAccounts', 5591 getter: 'personal_listAccounts' 5592 }) 5593 ]; 5594 }; 5595 5596 5597 module.exports = Personal; 5598 5599 },{"../formatters":30,"../method":36,"../property":45}],41:[function(require,module,exports){ 5600 /* 5601 This file is part of web3.js. 5602 5603 web3.js is free software: you can redistribute it and/or modify 5604 it under the terms of the GNU Lesser General Public License as published by 5605 the Free Software Foundation, either version 3 of the License, or 5606 (at your option) any later version. 5607 5608 web3.js is distributed in the hope that it will be useful, 5609 but WITHOUT ANY WARRANTY; without even the implied warranty of 5610 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5611 GNU Lesser General Public License for more details. 5612 5613 You should have received a copy of the GNU Lesser General Public License 5614 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5615 */ 5616 /** @file shh.js 5617 * @authors: 5618 * Marek Kotewicz <marek@ethdev.com> 5619 * @date 2015 5620 */ 5621 5622 var Method = require('../method'); 5623 var formatters = require('../formatters'); 5624 var Filter = require('../filter'); 5625 var watches = require('./watches'); 5626 5627 var Shh = function (web3) { 5628 this._requestManager = web3._requestManager; 5629 5630 var self = this; 5631 5632 methods().forEach(function(method) { 5633 method.attachToObject(self); 5634 method.setRequestManager(self._requestManager); 5635 }); 5636 }; 5637 5638 Shh.prototype.filter = function (fil, callback) { 5639 return new Filter(this._requestManager, fil, watches.shh(), formatters.outputPostFormatter, callback); 5640 }; 5641 5642 var methods = function () { 5643 5644 var post = new Method({ 5645 name: 'post', 5646 call: 'shh_post', 5647 params: 1, 5648 inputFormatter: [formatters.inputPostFormatter] 5649 }); 5650 5651 var newIdentity = new Method({ 5652 name: 'newIdentity', 5653 call: 'shh_newIdentity', 5654 params: 0 5655 }); 5656 5657 var hasIdentity = new Method({ 5658 name: 'hasIdentity', 5659 call: 'shh_hasIdentity', 5660 params: 1 5661 }); 5662 5663 var newGroup = new Method({ 5664 name: 'newGroup', 5665 call: 'shh_newGroup', 5666 params: 0 5667 }); 5668 5669 var addToGroup = new Method({ 5670 name: 'addToGroup', 5671 call: 'shh_addToGroup', 5672 params: 0 5673 }); 5674 5675 return [ 5676 post, 5677 newIdentity, 5678 hasIdentity, 5679 newGroup, 5680 addToGroup 5681 ]; 5682 }; 5683 5684 module.exports = Shh; 5685 5686 5687 },{"../filter":29,"../formatters":30,"../method":36,"./watches":43}],42:[function(require,module,exports){ 5688 /* 5689 This file is part of web3.js. 5690 5691 web3.js is free software: you can redistribute it and/or modify 5692 it under the terms of the GNU Lesser General Public License as published by 5693 the Free Software Foundation, either version 3 of the License, or 5694 (at your option) any later version. 5695 5696 web3.js is distributed in the hope that it will be useful, 5697 but WITHOUT ANY WARRANTY; without even the implied warranty of 5698 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5699 GNU Lesser General Public License for more details. 5700 5701 You should have received a copy of the GNU Lesser General Public License 5702 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5703 */ 5704 /** 5705 * @file bzz.js 5706 * @author Alex Beregszaszi <alex@rtfs.hu> 5707 * @date 2016 5708 * 5709 * Reference: https://github.com/wtc/go-wtc/blob/swarm/internal/web3ext/web3ext.go#L33 5710 */ 5711 5712 "use strict"; 5713 5714 var Method = require('../method'); 5715 var Property = require('../property'); 5716 5717 function Swarm(web3) { 5718 this._requestManager = web3._requestManager; 5719 5720 var self = this; 5721 5722 methods().forEach(function(method) { 5723 method.attachToObject(self); 5724 method.setRequestManager(self._requestManager); 5725 }); 5726 5727 properties().forEach(function(p) { 5728 p.attachToObject(self); 5729 p.setRequestManager(self._requestManager); 5730 }); 5731 } 5732 5733 var methods = function () { 5734 var blockNetworkRead = new Method({ 5735 name: 'blockNetworkRead', 5736 call: 'bzz_blockNetworkRead', 5737 params: 1, 5738 inputFormatter: [null] 5739 }); 5740 5741 var syncEnabled = new Method({ 5742 name: 'syncEnabled', 5743 call: 'bzz_syncEnabled', 5744 params: 1, 5745 inputFormatter: [null] 5746 }); 5747 5748 var swapEnabled = new Method({ 5749 name: 'swapEnabled', 5750 call: 'bzz_swapEnabled', 5751 params: 1, 5752 inputFormatter: [null] 5753 }); 5754 5755 var download = new Method({ 5756 name: 'download', 5757 call: 'bzz_download', 5758 params: 2, 5759 inputFormatter: [null, null] 5760 }); 5761 5762 var upload = new Method({ 5763 name: 'upload', 5764 call: 'bzz_upload', 5765 params: 2, 5766 inputFormatter: [null, null] 5767 }); 5768 5769 var retrieve = new Method({ 5770 name: 'retrieve', 5771 call: 'bzz_retrieve', 5772 params: 1, 5773 inputFormatter: [null] 5774 }); 5775 5776 var store = new Method({ 5777 name: 'store', 5778 call: 'bzz_store', 5779 params: 2, 5780 inputFormatter: [null, null] 5781 }); 5782 5783 var get = new Method({ 5784 name: 'get', 5785 call: 'bzz_get', 5786 params: 1, 5787 inputFormatter: [null] 5788 }); 5789 5790 var put = new Method({ 5791 name: 'put', 5792 call: 'bzz_put', 5793 params: 2, 5794 inputFormatter: [null, null] 5795 }); 5796 5797 var modify = new Method({ 5798 name: 'modify', 5799 call: 'bzz_modify', 5800 params: 4, 5801 inputFormatter: [null, null, null, null] 5802 }); 5803 5804 return [ 5805 blockNetworkRead, 5806 syncEnabled, 5807 swapEnabled, 5808 download, 5809 upload, 5810 retrieve, 5811 store, 5812 get, 5813 put, 5814 modify 5815 ]; 5816 }; 5817 5818 var properties = function () { 5819 return [ 5820 new Property({ 5821 name: 'hive', 5822 getter: 'bzz_hive' 5823 }), 5824 new Property({ 5825 name: 'info', 5826 getter: 'bzz_info' 5827 }) 5828 ]; 5829 }; 5830 5831 5832 module.exports = Swarm; 5833 5834 },{"../method":36,"../property":45}],43:[function(require,module,exports){ 5835 /* 5836 This file is part of web3.js. 5837 5838 web3.js is free software: you can redistribute it and/or modify 5839 it under the terms of the GNU Lesser General Public License as published by 5840 the Free Software Foundation, either version 3 of the License, or 5841 (at your option) any later version. 5842 5843 web3.js is distributed in the hope that it will be useful, 5844 but WITHOUT ANY WARRANTY; without even the implied warranty of 5845 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5846 GNU Lesser General Public License for more details. 5847 5848 You should have received a copy of the GNU Lesser General Public License 5849 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5850 */ 5851 /** @file watches.js 5852 * @authors: 5853 * Marek Kotewicz <marek@ethdev.com> 5854 * @date 2015 5855 */ 5856 5857 var Method = require('../method'); 5858 5859 /// @returns an array of objects describing web3.eth.filter api methods 5860 var eth = function () { 5861 var newFilterCall = function (args) { 5862 var type = args[0]; 5863 5864 switch(type) { 5865 case 'latest': 5866 args.shift(); 5867 this.params = 0; 5868 return 'eth_newBlockFilter'; 5869 case 'pending': 5870 args.shift(); 5871 this.params = 0; 5872 return 'eth_newPendingTransactionFilter'; 5873 default: 5874 return 'eth_newFilter'; 5875 } 5876 }; 5877 5878 var newFilter = new Method({ 5879 name: 'newFilter', 5880 call: newFilterCall, 5881 params: 1 5882 }); 5883 5884 var uninstallFilter = new Method({ 5885 name: 'uninstallFilter', 5886 call: 'eth_uninstallFilter', 5887 params: 1 5888 }); 5889 5890 var getLogs = new Method({ 5891 name: 'getLogs', 5892 call: 'eth_getFilterLogs', 5893 params: 1 5894 }); 5895 5896 var poll = new Method({ 5897 name: 'poll', 5898 call: 'eth_getFilterChanges', 5899 params: 1 5900 }); 5901 5902 return [ 5903 newFilter, 5904 uninstallFilter, 5905 getLogs, 5906 poll 5907 ]; 5908 }; 5909 5910 /// @returns an array of objects describing web3.shh.watch api methods 5911 var shh = function () { 5912 var newFilter = new Method({ 5913 name: 'newFilter', 5914 call: 'shh_newFilter', 5915 params: 1 5916 }); 5917 5918 var uninstallFilter = new Method({ 5919 name: 'uninstallFilter', 5920 call: 'shh_uninstallFilter', 5921 params: 1 5922 }); 5923 5924 var getLogs = new Method({ 5925 name: 'getLogs', 5926 call: 'shh_getMessages', 5927 params: 1 5928 }); 5929 5930 var poll = new Method({ 5931 name: 'poll', 5932 call: 'shh_getFilterChanges', 5933 params: 1 5934 }); 5935 5936 return [ 5937 newFilter, 5938 uninstallFilter, 5939 getLogs, 5940 poll 5941 ]; 5942 }; 5943 5944 module.exports = { 5945 eth: eth, 5946 shh: shh 5947 }; 5948 5949 5950 },{"../method":36}],44:[function(require,module,exports){ 5951 /* 5952 This file is part of web3.js. 5953 5954 web3.js is free software: you can redistribute it and/or modify 5955 it under the terms of the GNU Lesser General Public License as published by 5956 the Free Software Foundation, either version 3 of the License, or 5957 (at your option) any later version. 5958 5959 web3.js is distributed in the hope that it will be useful, 5960 but WITHOUT ANY WARRANTY; without even the implied warranty of 5961 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5962 GNU Lesser General Public License for more details. 5963 5964 You should have received a copy of the GNU Lesser General Public License 5965 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5966 */ 5967 /** 5968 * @file namereg.js 5969 * @author Marek Kotewicz <marek@ethdev.com> 5970 * @date 2015 5971 */ 5972 5973 var globalRegistrarAbi = require('../contracts/GlobalRegistrar.json'); 5974 var icapRegistrarAbi= require('../contracts/ICAPRegistrar.json'); 5975 5976 var globalNameregAddress = '0xc6d9d2cd449a754c494264e1809c50e34d64562b'; 5977 var icapNameregAddress = '0xa1a111bc074c9cfa781f0c38e63bd51c91b8af00'; 5978 5979 module.exports = { 5980 global: { 5981 abi: globalRegistrarAbi, 5982 address: globalNameregAddress 5983 }, 5984 icap: { 5985 abi: icapRegistrarAbi, 5986 address: icapNameregAddress 5987 } 5988 }; 5989 5990 5991 },{"../contracts/GlobalRegistrar.json":1,"../contracts/ICAPRegistrar.json":2}],45:[function(require,module,exports){ 5992 /* 5993 This file is part of web3.js. 5994 5995 web3.js is free software: you can redistribute it and/or modify 5996 it under the terms of the GNU Lesser General Public License as published by 5997 the Free Software Foundation, either version 3 of the License, or 5998 (at your option) any later version. 5999 6000 web3.js is distributed in the hope that it will be useful, 6001 but WITHOUT ANY WARRANTY; without even the implied warranty of 6002 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6003 GNU Lesser General Public License for more details. 6004 6005 You should have received a copy of the GNU Lesser General Public License 6006 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6007 */ 6008 /** 6009 * @file property.js 6010 * @author Fabian Vogelsteller <fabian@frozeman.de> 6011 * @author Marek Kotewicz <marek@ethdev.com> 6012 * @date 2015 6013 */ 6014 6015 var utils = require('../utils/utils'); 6016 6017 var Property = function (options) { 6018 this.name = options.name; 6019 this.getter = options.getter; 6020 this.setter = options.setter; 6021 this.outputFormatter = options.outputFormatter; 6022 this.inputFormatter = options.inputFormatter; 6023 this.requestManager = null; 6024 }; 6025 6026 Property.prototype.setRequestManager = function (rm) { 6027 this.requestManager = rm; 6028 }; 6029 6030 /** 6031 * Should be called to format input args of method 6032 * 6033 * @method formatInput 6034 * @param {Array} 6035 * @return {Array} 6036 */ 6037 Property.prototype.formatInput = function (arg) { 6038 return this.inputFormatter ? this.inputFormatter(arg) : arg; 6039 }; 6040 6041 /** 6042 * Should be called to format output(result) of method 6043 * 6044 * @method formatOutput 6045 * @param {Object} 6046 * @return {Object} 6047 */ 6048 Property.prototype.formatOutput = function (result) { 6049 return this.outputFormatter && result !== null && result !== undefined ? this.outputFormatter(result) : result; 6050 }; 6051 6052 /** 6053 * Should be used to extract callback from array of arguments. Modifies input param 6054 * 6055 * @method extractCallback 6056 * @param {Array} arguments 6057 * @return {Function|Null} callback, if exists 6058 */ 6059 Property.prototype.extractCallback = function (args) { 6060 if (utils.isFunction(args[args.length - 1])) { 6061 return args.pop(); // modify the args array! 6062 } 6063 }; 6064 6065 6066 /** 6067 * Should attach function to method 6068 * 6069 * @method attachToObject 6070 * @param {Object} 6071 * @param {Function} 6072 */ 6073 Property.prototype.attachToObject = function (obj) { 6074 var proto = { 6075 get: this.buildGet(), 6076 enumerable: true 6077 }; 6078 6079 var names = this.name.split('.'); 6080 var name = names[0]; 6081 if (names.length > 1) { 6082 obj[names[0]] = obj[names[0]] || {}; 6083 obj = obj[names[0]]; 6084 name = names[1]; 6085 } 6086 6087 Object.defineProperty(obj, name, proto); 6088 obj[asyncGetterName(name)] = this.buildAsyncGet(); 6089 }; 6090 6091 var asyncGetterName = function (name) { 6092 return 'get' + name.charAt(0).toUpperCase() + name.slice(1); 6093 }; 6094 6095 Property.prototype.buildGet = function () { 6096 var property = this; 6097 return function get() { 6098 return property.formatOutput(property.requestManager.send({ 6099 method: property.getter 6100 })); 6101 }; 6102 }; 6103 6104 Property.prototype.buildAsyncGet = function () { 6105 var property = this; 6106 var get = function (callback) { 6107 property.requestManager.sendAsync({ 6108 method: property.getter 6109 }, function (err, result) { 6110 callback(err, property.formatOutput(result)); 6111 }); 6112 }; 6113 get.request = this.request.bind(this); 6114 return get; 6115 }; 6116 6117 /** 6118 * Should be called to create pure JSONRPC request which can be used in batch request 6119 * 6120 * @method request 6121 * @param {...} params 6122 * @return {Object} jsonrpc request 6123 */ 6124 Property.prototype.request = function () { 6125 var payload = { 6126 method: this.getter, 6127 params: [], 6128 callback: this.extractCallback(Array.prototype.slice.call(arguments)) 6129 }; 6130 payload.format = this.formatOutput.bind(this); 6131 return payload; 6132 }; 6133 6134 module.exports = Property; 6135 6136 6137 },{"../utils/utils":20}],46:[function(require,module,exports){ 6138 /* 6139 This file is part of web3.js. 6140 6141 web3.js is free software: you can redistribute it and/or modify 6142 it under the terms of the GNU Lesser General Public License as published by 6143 the Free Software Foundation, either version 3 of the License, or 6144 (at your option) any later version. 6145 6146 web3.js is distributed in the hope that it will be useful, 6147 but WITHOUT ANY WARRANTY; without even the implied warranty of 6148 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6149 GNU Lesser General Public License for more details. 6150 6151 You should have received a copy of the GNU Lesser General Public License 6152 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6153 */ 6154 /** 6155 * @file requestmanager.js 6156 * @author Jeffrey Wilcke <jeff@ethdev.com> 6157 * @author Marek Kotewicz <marek@ethdev.com> 6158 * @author Marian Oancea <marian@ethdev.com> 6159 * @author Fabian Vogelsteller <fabian@ethdev.com> 6160 * @author Gav Wood <g@ethdev.com> 6161 * @date 2014 6162 */ 6163 6164 var Jsonrpc = require('./jsonrpc'); 6165 var utils = require('../utils/utils'); 6166 var c = require('../utils/config'); 6167 var errors = require('./errors'); 6168 6169 /** 6170 * It's responsible for passing messages to providers 6171 * It's also responsible for polling the wtc node for incoming messages 6172 * Default poll timeout is 1 second 6173 * Singleton 6174 */ 6175 var RequestManager = function (provider) { 6176 this.provider = provider; 6177 this.polls = {}; 6178 this.timeout = null; 6179 }; 6180 6181 /** 6182 * Should be used to synchronously send request 6183 * 6184 * @method send 6185 * @param {Object} data 6186 * @return {Object} 6187 */ 6188 RequestManager.prototype.send = function (data) { 6189 if (!this.provider) { 6190 console.error(errors.InvalidProvider()); 6191 return null; 6192 } 6193 6194 var payload = Jsonrpc.toPayload(data.method, data.params); 6195 var result = this.provider.send(payload); 6196 6197 if (!Jsonrpc.isValidResponse(result)) { 6198 throw errors.InvalidResponse(result); 6199 } 6200 6201 return result.result; 6202 }; 6203 6204 /** 6205 * Should be used to asynchronously send request 6206 * 6207 * @method sendAsync 6208 * @param {Object} data 6209 * @param {Function} callback 6210 */ 6211 RequestManager.prototype.sendAsync = function (data, callback) { 6212 if (!this.provider) { 6213 return callback(errors.InvalidProvider()); 6214 } 6215 6216 var payload = Jsonrpc.toPayload(data.method, data.params); 6217 this.provider.sendAsync(payload, function (err, result) { 6218 if (err) { 6219 return callback(err); 6220 } 6221 6222 if (!Jsonrpc.isValidResponse(result)) { 6223 return callback(errors.InvalidResponse(result)); 6224 } 6225 6226 callback(null, result.result); 6227 }); 6228 }; 6229 6230 /** 6231 * Should be called to asynchronously send batch request 6232 * 6233 * @method sendBatch 6234 * @param {Array} batch data 6235 * @param {Function} callback 6236 */ 6237 RequestManager.prototype.sendBatch = function (data, callback) { 6238 if (!this.provider) { 6239 return callback(errors.InvalidProvider()); 6240 } 6241 6242 var payload = Jsonrpc.toBatchPayload(data); 6243 6244 this.provider.sendAsync(payload, function (err, results) { 6245 if (err) { 6246 return callback(err); 6247 } 6248 6249 if (!utils.isArray(results)) { 6250 return callback(errors.InvalidResponse(results)); 6251 } 6252 6253 callback(err, results); 6254 }); 6255 }; 6256 6257 /** 6258 * Should be used to set provider of request manager 6259 * 6260 * @method setProvider 6261 * @param {Object} 6262 */ 6263 RequestManager.prototype.setProvider = function (p) { 6264 this.provider = p; 6265 }; 6266 6267 /** 6268 * Should be used to start polling 6269 * 6270 * @method startPolling 6271 * @param {Object} data 6272 * @param {Number} pollId 6273 * @param {Function} callback 6274 * @param {Function} uninstall 6275 * 6276 * @todo cleanup number of params 6277 */ 6278 RequestManager.prototype.startPolling = function (data, pollId, callback, uninstall) { 6279 this.polls[pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall}; 6280 6281 6282 // start polling 6283 if (!this.timeout) { 6284 this.poll(); 6285 } 6286 }; 6287 6288 /** 6289 * Should be used to stop polling for filter with given id 6290 * 6291 * @method stopPolling 6292 * @param {Number} pollId 6293 */ 6294 RequestManager.prototype.stopPolling = function (pollId) { 6295 delete this.polls[pollId]; 6296 6297 // stop polling 6298 if(Object.keys(this.polls).length === 0 && this.timeout) { 6299 clearTimeout(this.timeout); 6300 this.timeout = null; 6301 } 6302 }; 6303 6304 /** 6305 * Should be called to reset the polling mechanism of the request manager 6306 * 6307 * @method reset 6308 */ 6309 RequestManager.prototype.reset = function (keepIsSyncing) { 6310 /*jshint maxcomplexity:5 */ 6311 6312 for (var key in this.polls) { 6313 // remove all polls, except sync polls, 6314 // they need to be removed manually by calling syncing.stopWatching() 6315 if(!keepIsSyncing || key.indexOf('syncPoll_') === -1) { 6316 this.polls[key].uninstall(); 6317 delete this.polls[key]; 6318 } 6319 } 6320 6321 // stop polling 6322 if(Object.keys(this.polls).length === 0 && this.timeout) { 6323 clearTimeout(this.timeout); 6324 this.timeout = null; 6325 } 6326 }; 6327 6328 /** 6329 * Should be called to poll for changes on filter with given id 6330 * 6331 * @method poll 6332 */ 6333 RequestManager.prototype.poll = function () { 6334 /*jshint maxcomplexity: 6 */ 6335 this.timeout = setTimeout(this.poll.bind(this), c.ETH_POLLING_TIMEOUT); 6336 6337 if (Object.keys(this.polls).length === 0) { 6338 return; 6339 } 6340 6341 if (!this.provider) { 6342 console.error(errors.InvalidProvider()); 6343 return; 6344 } 6345 6346 var pollsData = []; 6347 var pollsIds = []; 6348 for (var key in this.polls) { 6349 pollsData.push(this.polls[key].data); 6350 pollsIds.push(key); 6351 } 6352 6353 if (pollsData.length === 0) { 6354 return; 6355 } 6356 6357 var payload = Jsonrpc.toBatchPayload(pollsData); 6358 6359 // map the request id to they poll id 6360 var pollsIdMap = {}; 6361 payload.forEach(function(load, index){ 6362 pollsIdMap[load.id] = pollsIds[index]; 6363 }); 6364 6365 6366 var self = this; 6367 this.provider.sendAsync(payload, function (error, results) { 6368 6369 6370 // TODO: console log? 6371 if (error) { 6372 return; 6373 } 6374 6375 if (!utils.isArray(results)) { 6376 throw errors.InvalidResponse(results); 6377 } 6378 results.map(function (result) { 6379 var id = pollsIdMap[result.id]; 6380 6381 // make sure the filter is still installed after arrival of the request 6382 if (self.polls[id]) { 6383 result.callback = self.polls[id].callback; 6384 return result; 6385 } else 6386 return false; 6387 }).filter(function (result) { 6388 return !!result; 6389 }).filter(function (result) { 6390 var valid = Jsonrpc.isValidResponse(result); 6391 if (!valid) { 6392 result.callback(errors.InvalidResponse(result)); 6393 } 6394 return valid; 6395 }).forEach(function (result) { 6396 result.callback(null, result.result); 6397 }); 6398 }); 6399 }; 6400 6401 module.exports = RequestManager; 6402 6403 6404 },{"../utils/config":18,"../utils/utils":20,"./errors":26,"./jsonrpc":35}],47:[function(require,module,exports){ 6405 6406 6407 var Settings = function () { 6408 this.defaultBlock = 'latest'; 6409 this.defaultAccount = undefined; 6410 }; 6411 6412 module.exports = Settings; 6413 6414 6415 },{}],48:[function(require,module,exports){ 6416 /* 6417 This file is part of web3.js. 6418 6419 web3.js is free software: you can redistribute it and/or modify 6420 it under the terms of the GNU Lesser General Public License as published by 6421 the Free Software Foundation, either version 3 of the License, or 6422 (at your option) any later version. 6423 6424 web3.js is distributed in the hope that it will be useful, 6425 but WITHOUT ANY WARRANTY; without even the implied warranty of 6426 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6427 GNU Lesser General Public License for more details. 6428 6429 You should have received a copy of the GNU Lesser General Public License 6430 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6431 */ 6432 /** @file syncing.js 6433 * @authors: 6434 * Fabian Vogelsteller <fabian@ethdev.com> 6435 * @date 2015 6436 */ 6437 6438 var formatters = require('./formatters'); 6439 var utils = require('../utils/utils'); 6440 6441 var count = 1; 6442 6443 /** 6444 Adds the callback and sets up the methods, to iterate over the results. 6445 6446 @method pollSyncing 6447 @param {Object} self 6448 */ 6449 var pollSyncing = function(self) { 6450 6451 var onMessage = function (error, sync) { 6452 if (error) { 6453 return self.callbacks.forEach(function (callback) { 6454 callback(error); 6455 }); 6456 } 6457 6458 if(utils.isObject(sync) && sync.startingBlock) 6459 sync = formatters.outputSyncingFormatter(sync); 6460 6461 self.callbacks.forEach(function (callback) { 6462 if (self.lastSyncState !== sync) { 6463 6464 // call the callback with true first so the app can stop anything, before receiving the sync data 6465 if(!self.lastSyncState && utils.isObject(sync)) 6466 callback(null, true); 6467 6468 // call on the next CPU cycle, so the actions of the sync stop can be processes first 6469 setTimeout(function() { 6470 callback(null, sync); 6471 }, 0); 6472 6473 self.lastSyncState = sync; 6474 } 6475 }); 6476 }; 6477 6478 self.requestManager.startPolling({ 6479 method: 'eth_syncing', 6480 params: [], 6481 }, self.pollId, onMessage, self.stopWatching.bind(self)); 6482 6483 }; 6484 6485 var IsSyncing = function (requestManager, callback) { 6486 this.requestManager = requestManager; 6487 this.pollId = 'syncPoll_'+ count++; 6488 this.callbacks = []; 6489 this.addCallback(callback); 6490 this.lastSyncState = false; 6491 pollSyncing(this); 6492 6493 return this; 6494 }; 6495 6496 IsSyncing.prototype.addCallback = function (callback) { 6497 if(callback) 6498 this.callbacks.push(callback); 6499 return this; 6500 }; 6501 6502 IsSyncing.prototype.stopWatching = function () { 6503 this.requestManager.stopPolling(this.pollId); 6504 this.callbacks = []; 6505 }; 6506 6507 module.exports = IsSyncing; 6508 6509 6510 },{"../utils/utils":20,"./formatters":30}],49:[function(require,module,exports){ 6511 /* 6512 This file is part of web3.js. 6513 6514 web3.js is free software: you can redistribute it and/or modify 6515 it under the terms of the GNU Lesser General Public License as published by 6516 the Free Software Foundation, either version 3 of the License, or 6517 (at your option) any later version. 6518 6519 web3.js is distributed in the hope that it will be useful, 6520 but WITHOUT ANY WARRANTY; without even the implied warranty of 6521 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6522 GNU Lesser General Public License for more details. 6523 6524 You should have received a copy of the GNU Lesser General Public License 6525 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6526 */ 6527 /** 6528 * @file transfer.js 6529 * @author Marek Kotewicz <marek@ethdev.com> 6530 * @date 2015 6531 */ 6532 6533 var Iban = require('./iban'); 6534 var exchangeAbi = require('../contracts/SmartExchange.json'); 6535 6536 /** 6537 * Should be used to make Iban transfer 6538 * 6539 * @method transfer 6540 * @param {String} from 6541 * @param {String} to iban 6542 * @param {Value} value to be tranfered 6543 * @param {Function} callback, callback 6544 */ 6545 var transfer = function (eth, from, to, value, callback) { 6546 var iban = new Iban(to); 6547 if (!iban.isValid()) { 6548 throw new Error('invalid iban address'); 6549 } 6550 6551 if (iban.isDirect()) { 6552 return transferToAddress(eth, from, iban.address(), value, callback); 6553 } 6554 6555 if (!callback) { 6556 var address = eth.icapNamereg().addr(iban.institution()); 6557 return deposit(eth, from, address, value, iban.client()); 6558 } 6559 6560 eth.icapNamereg().addr(iban.institution(), function (err, address) { 6561 return deposit(eth, from, address, value, iban.client(), callback); 6562 }); 6563 6564 }; 6565 6566 /** 6567 * Should be used to transfer funds to certain address 6568 * 6569 * @method transferToAddress 6570 * @param {String} from 6571 * @param {String} to 6572 * @param {Value} value to be tranfered 6573 * @param {Function} callback, callback 6574 */ 6575 var transferToAddress = function (eth, from, to, value, callback) { 6576 return eth.sendTransaction({ 6577 address: to, 6578 from: from, 6579 value: value 6580 }, callback); 6581 }; 6582 6583 /** 6584 * Should be used to deposit funds to generic Exchange contract (must implement deposit(bytes32) method!) 6585 * 6586 * @method deposit 6587 * @param {String} from 6588 * @param {String} to 6589 * @param {Value} value to be transfered 6590 * @param {String} client unique identifier 6591 * @param {Function} callback, callback 6592 */ 6593 var deposit = function (eth, from, to, value, client, callback) { 6594 var abi = exchangeAbi; 6595 return eth.contract(abi).at(to).deposit(client, { 6596 from: from, 6597 value: value 6598 }, callback); 6599 }; 6600 6601 module.exports = transfer; 6602 6603 6604 },{"../contracts/SmartExchange.json":3,"./iban":33}],50:[function(require,module,exports){ 6605 6606 },{}],51:[function(require,module,exports){ 6607 ;(function (root, factory, undef) { 6608 if (typeof exports === "object") { 6609 // CommonJS 6610 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 6611 } 6612 else if (typeof define === "function" && define.amd) { 6613 // AMD 6614 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 6615 } 6616 else { 6617 // Global (browser) 6618 factory(root.CryptoJS); 6619 } 6620 }(this, function (CryptoJS) { 6621 6622 (function () { 6623 // Shortcuts 6624 var C = CryptoJS; 6625 var C_lib = C.lib; 6626 var BlockCipher = C_lib.BlockCipher; 6627 var C_algo = C.algo; 6628 6629 // Lookup tables 6630 var SBOX = []; 6631 var INV_SBOX = []; 6632 var SUB_MIX_0 = []; 6633 var SUB_MIX_1 = []; 6634 var SUB_MIX_2 = []; 6635 var SUB_MIX_3 = []; 6636 var INV_SUB_MIX_0 = []; 6637 var INV_SUB_MIX_1 = []; 6638 var INV_SUB_MIX_2 = []; 6639 var INV_SUB_MIX_3 = []; 6640 6641 // Compute lookup tables 6642 (function () { 6643 // Compute double table 6644 var d = []; 6645 for (var i = 0; i < 256; i++) { 6646 if (i < 128) { 6647 d[i] = i << 1; 6648 } else { 6649 d[i] = (i << 1) ^ 0x11b; 6650 } 6651 } 6652 6653 // Walk GF(2^8) 6654 var x = 0; 6655 var xi = 0; 6656 for (var i = 0; i < 256; i++) { 6657 // Compute sbox 6658 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); 6659 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; 6660 SBOX[x] = sx; 6661 INV_SBOX[sx] = x; 6662 6663 // Compute multiplication 6664 var x2 = d[x]; 6665 var x4 = d[x2]; 6666 var x8 = d[x4]; 6667 6668 // Compute sub bytes, mix columns tables 6669 var t = (d[sx] * 0x101) ^ (sx * 0x1010100); 6670 SUB_MIX_0[x] = (t << 24) | (t >>> 8); 6671 SUB_MIX_1[x] = (t << 16) | (t >>> 16); 6672 SUB_MIX_2[x] = (t << 8) | (t >>> 24); 6673 SUB_MIX_3[x] = t; 6674 6675 // Compute inv sub bytes, inv mix columns tables 6676 var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); 6677 INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); 6678 INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); 6679 INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); 6680 INV_SUB_MIX_3[sx] = t; 6681 6682 // Compute next counter 6683 if (!x) { 6684 x = xi = 1; 6685 } else { 6686 x = x2 ^ d[d[d[x8 ^ x2]]]; 6687 xi ^= d[d[xi]]; 6688 } 6689 } 6690 }()); 6691 6692 // Precomputed Rcon lookup 6693 var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; 6694 6695 /** 6696 * AES block cipher algorithm. 6697 */ 6698 var AES = C_algo.AES = BlockCipher.extend({ 6699 _doReset: function () { 6700 // Skip reset of nRounds has been set before and key did not change 6701 if (this._nRounds && this._keyPriorReset === this._key) { 6702 return; 6703 } 6704 6705 // Shortcuts 6706 var key = this._keyPriorReset = this._key; 6707 var keyWords = key.words; 6708 var keySize = key.sigBytes / 4; 6709 6710 // Compute number of rounds 6711 var nRounds = this._nRounds = keySize + 6; 6712 6713 // Compute number of key schedule rows 6714 var ksRows = (nRounds + 1) * 4; 6715 6716 // Compute key schedule 6717 var keySchedule = this._keySchedule = []; 6718 for (var ksRow = 0; ksRow < ksRows; ksRow++) { 6719 if (ksRow < keySize) { 6720 keySchedule[ksRow] = keyWords[ksRow]; 6721 } else { 6722 var t = keySchedule[ksRow - 1]; 6723 6724 if (!(ksRow % keySize)) { 6725 // Rot word 6726 t = (t << 8) | (t >>> 24); 6727 6728 // Sub word 6729 t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; 6730 6731 // Mix Rcon 6732 t ^= RCON[(ksRow / keySize) | 0] << 24; 6733 } else if (keySize > 6 && ksRow % keySize == 4) { 6734 // Sub word 6735 t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; 6736 } 6737 6738 keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; 6739 } 6740 } 6741 6742 // Compute inv key schedule 6743 var invKeySchedule = this._invKeySchedule = []; 6744 for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { 6745 var ksRow = ksRows - invKsRow; 6746 6747 if (invKsRow % 4) { 6748 var t = keySchedule[ksRow]; 6749 } else { 6750 var t = keySchedule[ksRow - 4]; 6751 } 6752 6753 if (invKsRow < 4 || ksRow <= 4) { 6754 invKeySchedule[invKsRow] = t; 6755 } else { 6756 invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ 6757 INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; 6758 } 6759 } 6760 }, 6761 6762 encryptBlock: function (M, offset) { 6763 this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); 6764 }, 6765 6766 decryptBlock: function (M, offset) { 6767 // Swap 2nd and 4th rows 6768 var t = M[offset + 1]; 6769 M[offset + 1] = M[offset + 3]; 6770 M[offset + 3] = t; 6771 6772 this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); 6773 6774 // Inv swap 2nd and 4th rows 6775 var t = M[offset + 1]; 6776 M[offset + 1] = M[offset + 3]; 6777 M[offset + 3] = t; 6778 }, 6779 6780 _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { 6781 // Shortcut 6782 var nRounds = this._nRounds; 6783 6784 // Get input, add round key 6785 var s0 = M[offset] ^ keySchedule[0]; 6786 var s1 = M[offset + 1] ^ keySchedule[1]; 6787 var s2 = M[offset + 2] ^ keySchedule[2]; 6788 var s3 = M[offset + 3] ^ keySchedule[3]; 6789 6790 // Key schedule row counter 6791 var ksRow = 4; 6792 6793 // Rounds 6794 for (var round = 1; round < nRounds; round++) { 6795 // Shift rows, sub bytes, mix columns, add round key 6796 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++]; 6797 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++]; 6798 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++]; 6799 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++]; 6800 6801 // Update state 6802 s0 = t0; 6803 s1 = t1; 6804 s2 = t2; 6805 s3 = t3; 6806 } 6807 6808 // Shift rows, sub bytes, add round key 6809 var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; 6810 var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; 6811 var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; 6812 var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; 6813 6814 // Set output 6815 M[offset] = t0; 6816 M[offset + 1] = t1; 6817 M[offset + 2] = t2; 6818 M[offset + 3] = t3; 6819 }, 6820 6821 keySize: 256/32 6822 }); 6823 6824 /** 6825 * Shortcut functions to the cipher's object interface. 6826 * 6827 * @example 6828 * 6829 * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); 6830 * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); 6831 */ 6832 C.AES = BlockCipher._createHelper(AES); 6833 }()); 6834 6835 6836 return CryptoJS.AES; 6837 6838 })); 6839 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],52:[function(require,module,exports){ 6840 ;(function (root, factory) { 6841 if (typeof exports === "object") { 6842 // CommonJS 6843 module.exports = exports = factory(require("./core")); 6844 } 6845 else if (typeof define === "function" && define.amd) { 6846 // AMD 6847 define(["./core"], factory); 6848 } 6849 else { 6850 // Global (browser) 6851 factory(root.CryptoJS); 6852 } 6853 }(this, function (CryptoJS) { 6854 6855 /** 6856 * Cipher core components. 6857 */ 6858 CryptoJS.lib.Cipher || (function (undefined) { 6859 // Shortcuts 6860 var C = CryptoJS; 6861 var C_lib = C.lib; 6862 var Base = C_lib.Base; 6863 var WordArray = C_lib.WordArray; 6864 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; 6865 var C_enc = C.enc; 6866 var Utf8 = C_enc.Utf8; 6867 var Base64 = C_enc.Base64; 6868 var C_algo = C.algo; 6869 var EvpKDF = C_algo.EvpKDF; 6870 6871 /** 6872 * Abstract base cipher template. 6873 * 6874 * @property {number} keySize This cipher's key size. Default: 4 (128 bits) 6875 * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) 6876 * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. 6877 * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. 6878 */ 6879 var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ 6880 /** 6881 * Configuration options. 6882 * 6883 * @property {WordArray} iv The IV to use for this operation. 6884 */ 6885 cfg: Base.extend(), 6886 6887 /** 6888 * Creates this cipher in encryption mode. 6889 * 6890 * @param {WordArray} key The key. 6891 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6892 * 6893 * @return {Cipher} A cipher instance. 6894 * 6895 * @static 6896 * 6897 * @example 6898 * 6899 * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); 6900 */ 6901 createEncryptor: function (key, cfg) { 6902 return this.create(this._ENC_XFORM_MODE, key, cfg); 6903 }, 6904 6905 /** 6906 * Creates this cipher in decryption mode. 6907 * 6908 * @param {WordArray} key The key. 6909 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6910 * 6911 * @return {Cipher} A cipher instance. 6912 * 6913 * @static 6914 * 6915 * @example 6916 * 6917 * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); 6918 */ 6919 createDecryptor: function (key, cfg) { 6920 return this.create(this._DEC_XFORM_MODE, key, cfg); 6921 }, 6922 6923 /** 6924 * Initializes a newly created cipher. 6925 * 6926 * @param {number} xformMode Either the encryption or decryption transormation mode constant. 6927 * @param {WordArray} key The key. 6928 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6929 * 6930 * @example 6931 * 6932 * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); 6933 */ 6934 init: function (xformMode, key, cfg) { 6935 // Apply config defaults 6936 this.cfg = this.cfg.extend(cfg); 6937 6938 // Store transform mode and key 6939 this._xformMode = xformMode; 6940 this._key = key; 6941 6942 // Set initial values 6943 this.reset(); 6944 }, 6945 6946 /** 6947 * Resets this cipher to its initial state. 6948 * 6949 * @example 6950 * 6951 * cipher.reset(); 6952 */ 6953 reset: function () { 6954 // Reset data buffer 6955 BufferedBlockAlgorithm.reset.call(this); 6956 6957 // Perform concrete-cipher logic 6958 this._doReset(); 6959 }, 6960 6961 /** 6962 * Adds data to be encrypted or decrypted. 6963 * 6964 * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. 6965 * 6966 * @return {WordArray} The data after processing. 6967 * 6968 * @example 6969 * 6970 * var encrypted = cipher.process('data'); 6971 * var encrypted = cipher.process(wordArray); 6972 */ 6973 process: function (dataUpdate) { 6974 // Append 6975 this._append(dataUpdate); 6976 6977 // Process available blocks 6978 return this._process(); 6979 }, 6980 6981 /** 6982 * Finalizes the encryption or decryption process. 6983 * Note that the finalize operation is effectively a destructive, read-once operation. 6984 * 6985 * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. 6986 * 6987 * @return {WordArray} The data after final processing. 6988 * 6989 * @example 6990 * 6991 * var encrypted = cipher.finalize(); 6992 * var encrypted = cipher.finalize('data'); 6993 * var encrypted = cipher.finalize(wordArray); 6994 */ 6995 finalize: function (dataUpdate) { 6996 // Final data update 6997 if (dataUpdate) { 6998 this._append(dataUpdate); 6999 } 7000 7001 // Perform concrete-cipher logic 7002 var finalProcessedData = this._doFinalize(); 7003 7004 return finalProcessedData; 7005 }, 7006 7007 keySize: 128/32, 7008 7009 ivSize: 128/32, 7010 7011 _ENC_XFORM_MODE: 1, 7012 7013 _DEC_XFORM_MODE: 2, 7014 7015 /** 7016 * Creates shortcut functions to a cipher's object interface. 7017 * 7018 * @param {Cipher} cipher The cipher to create a helper for. 7019 * 7020 * @return {Object} An object with encrypt and decrypt shortcut functions. 7021 * 7022 * @static 7023 * 7024 * @example 7025 * 7026 * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); 7027 */ 7028 _createHelper: (function () { 7029 function selectCipherStrategy(key) { 7030 if (typeof key == 'string') { 7031 return PasswordBasedCipher; 7032 } else { 7033 return SerializableCipher; 7034 } 7035 } 7036 7037 return function (cipher) { 7038 return { 7039 encrypt: function (message, key, cfg) { 7040 return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); 7041 }, 7042 7043 decrypt: function (ciphertext, key, cfg) { 7044 return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); 7045 } 7046 }; 7047 }; 7048 }()) 7049 }); 7050 7051 /** 7052 * Abstract base stream cipher template. 7053 * 7054 * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) 7055 */ 7056 var StreamCipher = C_lib.StreamCipher = Cipher.extend({ 7057 _doFinalize: function () { 7058 // Process partial blocks 7059 var finalProcessedBlocks = this._process(!!'flush'); 7060 7061 return finalProcessedBlocks; 7062 }, 7063 7064 blockSize: 1 7065 }); 7066 7067 /** 7068 * Mode namespace. 7069 */ 7070 var C_mode = C.mode = {}; 7071 7072 /** 7073 * Abstract base block cipher mode template. 7074 */ 7075 var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ 7076 /** 7077 * Creates this mode for encryption. 7078 * 7079 * @param {Cipher} cipher A block cipher instance. 7080 * @param {Array} iv The IV words. 7081 * 7082 * @static 7083 * 7084 * @example 7085 * 7086 * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); 7087 */ 7088 createEncryptor: function (cipher, iv) { 7089 return this.Encryptor.create(cipher, iv); 7090 }, 7091 7092 /** 7093 * Creates this mode for decryption. 7094 * 7095 * @param {Cipher} cipher A block cipher instance. 7096 * @param {Array} iv The IV words. 7097 * 7098 * @static 7099 * 7100 * @example 7101 * 7102 * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); 7103 */ 7104 createDecryptor: function (cipher, iv) { 7105 return this.Decryptor.create(cipher, iv); 7106 }, 7107 7108 /** 7109 * Initializes a newly created mode. 7110 * 7111 * @param {Cipher} cipher A block cipher instance. 7112 * @param {Array} iv The IV words. 7113 * 7114 * @example 7115 * 7116 * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); 7117 */ 7118 init: function (cipher, iv) { 7119 this._cipher = cipher; 7120 this._iv = iv; 7121 } 7122 }); 7123 7124 /** 7125 * Cipher Block Chaining mode. 7126 */ 7127 var CBC = C_mode.CBC = (function () { 7128 /** 7129 * Abstract base CBC mode. 7130 */ 7131 var CBC = BlockCipherMode.extend(); 7132 7133 /** 7134 * CBC encryptor. 7135 */ 7136 CBC.Encryptor = CBC.extend({ 7137 /** 7138 * Processes the data block at offset. 7139 * 7140 * @param {Array} words The data words to operate on. 7141 * @param {number} offset The offset where the block starts. 7142 * 7143 * @example 7144 * 7145 * mode.processBlock(data.words, offset); 7146 */ 7147 processBlock: function (words, offset) { 7148 // Shortcuts 7149 var cipher = this._cipher; 7150 var blockSize = cipher.blockSize; 7151 7152 // XOR and encrypt 7153 xorBlock.call(this, words, offset, blockSize); 7154 cipher.encryptBlock(words, offset); 7155 7156 // Remember this block to use with next block 7157 this._prevBlock = words.slice(offset, offset + blockSize); 7158 } 7159 }); 7160 7161 /** 7162 * CBC decryptor. 7163 */ 7164 CBC.Decryptor = CBC.extend({ 7165 /** 7166 * Processes the data block at offset. 7167 * 7168 * @param {Array} words The data words to operate on. 7169 * @param {number} offset The offset where the block starts. 7170 * 7171 * @example 7172 * 7173 * mode.processBlock(data.words, offset); 7174 */ 7175 processBlock: function (words, offset) { 7176 // Shortcuts 7177 var cipher = this._cipher; 7178 var blockSize = cipher.blockSize; 7179 7180 // Remember this block to use with next block 7181 var thisBlock = words.slice(offset, offset + blockSize); 7182 7183 // Decrypt and XOR 7184 cipher.decryptBlock(words, offset); 7185 xorBlock.call(this, words, offset, blockSize); 7186 7187 // This block becomes the previous block 7188 this._prevBlock = thisBlock; 7189 } 7190 }); 7191 7192 function xorBlock(words, offset, blockSize) { 7193 // Shortcut 7194 var iv = this._iv; 7195 7196 // Choose mixing block 7197 if (iv) { 7198 var block = iv; 7199 7200 // Remove IV for subsequent blocks 7201 this._iv = undefined; 7202 } else { 7203 var block = this._prevBlock; 7204 } 7205 7206 // XOR blocks 7207 for (var i = 0; i < blockSize; i++) { 7208 words[offset + i] ^= block[i]; 7209 } 7210 } 7211 7212 return CBC; 7213 }()); 7214 7215 /** 7216 * Padding namespace. 7217 */ 7218 var C_pad = C.pad = {}; 7219 7220 /** 7221 * PKCS #5/7 padding strategy. 7222 */ 7223 var Pkcs7 = C_pad.Pkcs7 = { 7224 /** 7225 * Pads data using the algorithm defined in PKCS #5/7. 7226 * 7227 * @param {WordArray} data The data to pad. 7228 * @param {number} blockSize The multiple that the data should be padded to. 7229 * 7230 * @static 7231 * 7232 * @example 7233 * 7234 * CryptoJS.pad.Pkcs7.pad(wordArray, 4); 7235 */ 7236 pad: function (data, blockSize) { 7237 // Shortcut 7238 var blockSizeBytes = blockSize * 4; 7239 7240 // Count padding bytes 7241 var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; 7242 7243 // Create padding word 7244 var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; 7245 7246 // Create padding 7247 var paddingWords = []; 7248 for (var i = 0; i < nPaddingBytes; i += 4) { 7249 paddingWords.push(paddingWord); 7250 } 7251 var padding = WordArray.create(paddingWords, nPaddingBytes); 7252 7253 // Add padding 7254 data.concat(padding); 7255 }, 7256 7257 /** 7258 * Unpads data that had been padded using the algorithm defined in PKCS #5/7. 7259 * 7260 * @param {WordArray} data The data to unpad. 7261 * 7262 * @static 7263 * 7264 * @example 7265 * 7266 * CryptoJS.pad.Pkcs7.unpad(wordArray); 7267 */ 7268 unpad: function (data) { 7269 // Get number of padding bytes from last byte 7270 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 7271 7272 // Remove padding 7273 data.sigBytes -= nPaddingBytes; 7274 } 7275 }; 7276 7277 /** 7278 * Abstract base block cipher template. 7279 * 7280 * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) 7281 */ 7282 var BlockCipher = C_lib.BlockCipher = Cipher.extend({ 7283 /** 7284 * Configuration options. 7285 * 7286 * @property {Mode} mode The block mode to use. Default: CBC 7287 * @property {Padding} padding The padding strategy to use. Default: Pkcs7 7288 */ 7289 cfg: Cipher.cfg.extend({ 7290 mode: CBC, 7291 padding: Pkcs7 7292 }), 7293 7294 reset: function () { 7295 // Reset cipher 7296 Cipher.reset.call(this); 7297 7298 // Shortcuts 7299 var cfg = this.cfg; 7300 var iv = cfg.iv; 7301 var mode = cfg.mode; 7302 7303 // Reset block mode 7304 if (this._xformMode == this._ENC_XFORM_MODE) { 7305 var modeCreator = mode.createEncryptor; 7306 } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { 7307 var modeCreator = mode.createDecryptor; 7308 7309 // Keep at least one block in the buffer for unpadding 7310 this._minBufferSize = 1; 7311 } 7312 this._mode = modeCreator.call(mode, this, iv && iv.words); 7313 }, 7314 7315 _doProcessBlock: function (words, offset) { 7316 this._mode.processBlock(words, offset); 7317 }, 7318 7319 _doFinalize: function () { 7320 // Shortcut 7321 var padding = this.cfg.padding; 7322 7323 // Finalize 7324 if (this._xformMode == this._ENC_XFORM_MODE) { 7325 // Pad data 7326 padding.pad(this._data, this.blockSize); 7327 7328 // Process final blocks 7329 var finalProcessedBlocks = this._process(!!'flush'); 7330 } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { 7331 // Process final blocks 7332 var finalProcessedBlocks = this._process(!!'flush'); 7333 7334 // Unpad data 7335 padding.unpad(finalProcessedBlocks); 7336 } 7337 7338 return finalProcessedBlocks; 7339 }, 7340 7341 blockSize: 128/32 7342 }); 7343 7344 /** 7345 * A collection of cipher parameters. 7346 * 7347 * @property {WordArray} ciphertext The raw ciphertext. 7348 * @property {WordArray} key The key to this ciphertext. 7349 * @property {WordArray} iv The IV used in the ciphering operation. 7350 * @property {WordArray} salt The salt used with a key derivation function. 7351 * @property {Cipher} algorithm The cipher algorithm. 7352 * @property {Mode} mode The block mode used in the ciphering operation. 7353 * @property {Padding} padding The padding scheme used in the ciphering operation. 7354 * @property {number} blockSize The block size of the cipher. 7355 * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. 7356 */ 7357 var CipherParams = C_lib.CipherParams = Base.extend({ 7358 /** 7359 * Initializes a newly created cipher params object. 7360 * 7361 * @param {Object} cipherParams An object with any of the possible cipher parameters. 7362 * 7363 * @example 7364 * 7365 * var cipherParams = CryptoJS.lib.CipherParams.create({ 7366 * ciphertext: ciphertextWordArray, 7367 * key: keyWordArray, 7368 * iv: ivWordArray, 7369 * salt: saltWordArray, 7370 * algorithm: CryptoJS.algo.AES, 7371 * mode: CryptoJS.mode.CBC, 7372 * padding: CryptoJS.pad.PKCS7, 7373 * blockSize: 4, 7374 * formatter: CryptoJS.format.OpenSSL 7375 * }); 7376 */ 7377 init: function (cipherParams) { 7378 this.mixIn(cipherParams); 7379 }, 7380 7381 /** 7382 * Converts this cipher params object to a string. 7383 * 7384 * @param {Format} formatter (Optional) The formatting strategy to use. 7385 * 7386 * @return {string} The stringified cipher params. 7387 * 7388 * @throws Error If neither the formatter nor the default formatter is set. 7389 * 7390 * @example 7391 * 7392 * var string = cipherParams + ''; 7393 * var string = cipherParams.toString(); 7394 * var string = cipherParams.toString(CryptoJS.format.OpenSSL); 7395 */ 7396 toString: function (formatter) { 7397 return (formatter || this.formatter).stringify(this); 7398 } 7399 }); 7400 7401 /** 7402 * Format namespace. 7403 */ 7404 var C_format = C.format = {}; 7405 7406 /** 7407 * OpenSSL formatting strategy. 7408 */ 7409 var OpenSSLFormatter = C_format.OpenSSL = { 7410 /** 7411 * Converts a cipher params object to an OpenSSL-compatible string. 7412 * 7413 * @param {CipherParams} cipherParams The cipher params object. 7414 * 7415 * @return {string} The OpenSSL-compatible string. 7416 * 7417 * @static 7418 * 7419 * @example 7420 * 7421 * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); 7422 */ 7423 stringify: function (cipherParams) { 7424 // Shortcuts 7425 var ciphertext = cipherParams.ciphertext; 7426 var salt = cipherParams.salt; 7427 7428 // Format 7429 if (salt) { 7430 var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); 7431 } else { 7432 var wordArray = ciphertext; 7433 } 7434 7435 return wordArray.toString(Base64); 7436 }, 7437 7438 /** 7439 * Converts an OpenSSL-compatible string to a cipher params object. 7440 * 7441 * @param {string} openSSLStr The OpenSSL-compatible string. 7442 * 7443 * @return {CipherParams} The cipher params object. 7444 * 7445 * @static 7446 * 7447 * @example 7448 * 7449 * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); 7450 */ 7451 parse: function (openSSLStr) { 7452 // Parse base64 7453 var ciphertext = Base64.parse(openSSLStr); 7454 7455 // Shortcut 7456 var ciphertextWords = ciphertext.words; 7457 7458 // Test for salt 7459 if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { 7460 // Extract salt 7461 var salt = WordArray.create(ciphertextWords.slice(2, 4)); 7462 7463 // Remove salt from ciphertext 7464 ciphertextWords.splice(0, 4); 7465 ciphertext.sigBytes -= 16; 7466 } 7467 7468 return CipherParams.create({ ciphertext: ciphertext, salt: salt }); 7469 } 7470 }; 7471 7472 /** 7473 * A cipher wrapper that returns ciphertext as a serializable cipher params object. 7474 */ 7475 var SerializableCipher = C_lib.SerializableCipher = Base.extend({ 7476 /** 7477 * Configuration options. 7478 * 7479 * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL 7480 */ 7481 cfg: Base.extend({ 7482 format: OpenSSLFormatter 7483 }), 7484 7485 /** 7486 * Encrypts a message. 7487 * 7488 * @param {Cipher} cipher The cipher algorithm to use. 7489 * @param {WordArray|string} message The message to encrypt. 7490 * @param {WordArray} key The key. 7491 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7492 * 7493 * @return {CipherParams} A cipher params object. 7494 * 7495 * @static 7496 * 7497 * @example 7498 * 7499 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); 7500 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); 7501 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7502 */ 7503 encrypt: function (cipher, message, key, cfg) { 7504 // Apply config defaults 7505 cfg = this.cfg.extend(cfg); 7506 7507 // Encrypt 7508 var encryptor = cipher.createEncryptor(key, cfg); 7509 var ciphertext = encryptor.finalize(message); 7510 7511 // Shortcut 7512 var cipherCfg = encryptor.cfg; 7513 7514 // Create and return serializable cipher params 7515 return CipherParams.create({ 7516 ciphertext: ciphertext, 7517 key: key, 7518 iv: cipherCfg.iv, 7519 algorithm: cipher, 7520 mode: cipherCfg.mode, 7521 padding: cipherCfg.padding, 7522 blockSize: cipher.blockSize, 7523 formatter: cfg.format 7524 }); 7525 }, 7526 7527 /** 7528 * Decrypts serialized ciphertext. 7529 * 7530 * @param {Cipher} cipher The cipher algorithm to use. 7531 * @param {CipherParams|string} ciphertext The ciphertext to decrypt. 7532 * @param {WordArray} key The key. 7533 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7534 * 7535 * @return {WordArray} The plaintext. 7536 * 7537 * @static 7538 * 7539 * @example 7540 * 7541 * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7542 * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7543 */ 7544 decrypt: function (cipher, ciphertext, key, cfg) { 7545 // Apply config defaults 7546 cfg = this.cfg.extend(cfg); 7547 7548 // Convert string to CipherParams 7549 ciphertext = this._parse(ciphertext, cfg.format); 7550 7551 // Decrypt 7552 var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); 7553 7554 return plaintext; 7555 }, 7556 7557 /** 7558 * Converts serialized ciphertext to CipherParams, 7559 * else assumed CipherParams already and returns ciphertext unchanged. 7560 * 7561 * @param {CipherParams|string} ciphertext The ciphertext. 7562 * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. 7563 * 7564 * @return {CipherParams} The unserialized ciphertext. 7565 * 7566 * @static 7567 * 7568 * @example 7569 * 7570 * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); 7571 */ 7572 _parse: function (ciphertext, format) { 7573 if (typeof ciphertext == 'string') { 7574 return format.parse(ciphertext, this); 7575 } else { 7576 return ciphertext; 7577 } 7578 } 7579 }); 7580 7581 /** 7582 * Key derivation function namespace. 7583 */ 7584 var C_kdf = C.kdf = {}; 7585 7586 /** 7587 * OpenSSL key derivation function. 7588 */ 7589 var OpenSSLKdf = C_kdf.OpenSSL = { 7590 /** 7591 * Derives a key and IV from a password. 7592 * 7593 * @param {string} password The password to derive from. 7594 * @param {number} keySize The size in words of the key to generate. 7595 * @param {number} ivSize The size in words of the IV to generate. 7596 * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. 7597 * 7598 * @return {CipherParams} A cipher params object with the key, IV, and salt. 7599 * 7600 * @static 7601 * 7602 * @example 7603 * 7604 * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); 7605 * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); 7606 */ 7607 execute: function (password, keySize, ivSize, salt) { 7608 // Generate random salt 7609 if (!salt) { 7610 salt = WordArray.random(64/8); 7611 } 7612 7613 // Derive key and IV 7614 var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); 7615 7616 // Separate key and IV 7617 var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); 7618 key.sigBytes = keySize * 4; 7619 7620 // Return params 7621 return CipherParams.create({ key: key, iv: iv, salt: salt }); 7622 } 7623 }; 7624 7625 /** 7626 * A serializable cipher wrapper that derives the key from a password, 7627 * and returns ciphertext as a serializable cipher params object. 7628 */ 7629 var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ 7630 /** 7631 * Configuration options. 7632 * 7633 * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL 7634 */ 7635 cfg: SerializableCipher.cfg.extend({ 7636 kdf: OpenSSLKdf 7637 }), 7638 7639 /** 7640 * Encrypts a message using a password. 7641 * 7642 * @param {Cipher} cipher The cipher algorithm to use. 7643 * @param {WordArray|string} message The message to encrypt. 7644 * @param {string} password The password. 7645 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7646 * 7647 * @return {CipherParams} A cipher params object. 7648 * 7649 * @static 7650 * 7651 * @example 7652 * 7653 * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); 7654 * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); 7655 */ 7656 encrypt: function (cipher, message, password, cfg) { 7657 // Apply config defaults 7658 cfg = this.cfg.extend(cfg); 7659 7660 // Derive key and other params 7661 var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); 7662 7663 // Add IV to config 7664 cfg.iv = derivedParams.iv; 7665 7666 // Encrypt 7667 var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); 7668 7669 // Mix in derived params 7670 ciphertext.mixIn(derivedParams); 7671 7672 return ciphertext; 7673 }, 7674 7675 /** 7676 * Decrypts serialized ciphertext using a password. 7677 * 7678 * @param {Cipher} cipher The cipher algorithm to use. 7679 * @param {CipherParams|string} ciphertext The ciphertext to decrypt. 7680 * @param {string} password The password. 7681 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7682 * 7683 * @return {WordArray} The plaintext. 7684 * 7685 * @static 7686 * 7687 * @example 7688 * 7689 * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); 7690 * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); 7691 */ 7692 decrypt: function (cipher, ciphertext, password, cfg) { 7693 // Apply config defaults 7694 cfg = this.cfg.extend(cfg); 7695 7696 // Convert string to CipherParams 7697 ciphertext = this._parse(ciphertext, cfg.format); 7698 7699 // Derive key and other params 7700 var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); 7701 7702 // Add IV to config 7703 cfg.iv = derivedParams.iv; 7704 7705 // Decrypt 7706 var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); 7707 7708 return plaintext; 7709 } 7710 }); 7711 }()); 7712 7713 7714 })); 7715 },{"./core":53}],53:[function(require,module,exports){ 7716 ;(function (root, factory) { 7717 if (typeof exports === "object") { 7718 // CommonJS 7719 module.exports = exports = factory(); 7720 } 7721 else if (typeof define === "function" && define.amd) { 7722 // AMD 7723 define([], factory); 7724 } 7725 else { 7726 // Global (browser) 7727 root.CryptoJS = factory(); 7728 } 7729 }(this, function () { 7730 7731 /** 7732 * CryptoJS core components. 7733 */ 7734 var CryptoJS = CryptoJS || (function (Math, undefined) { 7735 /* 7736 * Local polyfil of Object.create 7737 */ 7738 var create = Object.create || (function () { 7739 function F() {}; 7740 7741 return function (obj) { 7742 var subtype; 7743 7744 F.prototype = obj; 7745 7746 subtype = new F(); 7747 7748 F.prototype = null; 7749 7750 return subtype; 7751 }; 7752 }()) 7753 7754 /** 7755 * CryptoJS namespace. 7756 */ 7757 var C = {}; 7758 7759 /** 7760 * Library namespace. 7761 */ 7762 var C_lib = C.lib = {}; 7763 7764 /** 7765 * Base object for prototypal inheritance. 7766 */ 7767 var Base = C_lib.Base = (function () { 7768 7769 7770 return { 7771 /** 7772 * Creates a new object that inherits from this object. 7773 * 7774 * @param {Object} overrides Properties to copy into the new object. 7775 * 7776 * @return {Object} The new object. 7777 * 7778 * @static 7779 * 7780 * @example 7781 * 7782 * var MyType = CryptoJS.lib.Base.extend({ 7783 * field: 'value', 7784 * 7785 * method: function () { 7786 * } 7787 * }); 7788 */ 7789 extend: function (overrides) { 7790 // Spawn 7791 var subtype = create(this); 7792 7793 // Augment 7794 if (overrides) { 7795 subtype.mixIn(overrides); 7796 } 7797 7798 // Create default initializer 7799 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { 7800 subtype.init = function () { 7801 subtype.$super.init.apply(this, arguments); 7802 }; 7803 } 7804 7805 // Initializer's prototype is the subtype object 7806 subtype.init.prototype = subtype; 7807 7808 // Reference supertype 7809 subtype.$super = this; 7810 7811 return subtype; 7812 }, 7813 7814 /** 7815 * Extends this object and runs the init method. 7816 * Arguments to create() will be passed to init(). 7817 * 7818 * @return {Object} The new object. 7819 * 7820 * @static 7821 * 7822 * @example 7823 * 7824 * var instance = MyType.create(); 7825 */ 7826 create: function () { 7827 var instance = this.extend(); 7828 instance.init.apply(instance, arguments); 7829 7830 return instance; 7831 }, 7832 7833 /** 7834 * Initializes a newly created object. 7835 * Override this method to add some logic when your objects are created. 7836 * 7837 * @example 7838 * 7839 * var MyType = CryptoJS.lib.Base.extend({ 7840 * init: function () { 7841 * // ... 7842 * } 7843 * }); 7844 */ 7845 init: function () { 7846 }, 7847 7848 /** 7849 * Copies properties into this object. 7850 * 7851 * @param {Object} properties The properties to mix in. 7852 * 7853 * @example 7854 * 7855 * MyType.mixIn({ 7856 * field: 'value' 7857 * }); 7858 */ 7859 mixIn: function (properties) { 7860 for (var propertyName in properties) { 7861 if (properties.hasOwnProperty(propertyName)) { 7862 this[propertyName] = properties[propertyName]; 7863 } 7864 } 7865 7866 // IE won't copy toString using the loop above 7867 if (properties.hasOwnProperty('toString')) { 7868 this.toString = properties.toString; 7869 } 7870 }, 7871 7872 /** 7873 * Creates a copy of this object. 7874 * 7875 * @return {Object} The clone. 7876 * 7877 * @example 7878 * 7879 * var clone = instance.clone(); 7880 */ 7881 clone: function () { 7882 return this.init.prototype.extend(this); 7883 } 7884 }; 7885 }()); 7886 7887 /** 7888 * An array of 32-bit words. 7889 * 7890 * @property {Array} words The array of 32-bit words. 7891 * @property {number} sigBytes The number of significant bytes in this word array. 7892 */ 7893 var WordArray = C_lib.WordArray = Base.extend({ 7894 /** 7895 * Initializes a newly created word array. 7896 * 7897 * @param {Array} words (Optional) An array of 32-bit words. 7898 * @param {number} sigBytes (Optional) The number of significant bytes in the words. 7899 * 7900 * @example 7901 * 7902 * var wordArray = CryptoJS.lib.WordArray.create(); 7903 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); 7904 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); 7905 */ 7906 init: function (words, sigBytes) { 7907 words = this.words = words || []; 7908 7909 if (sigBytes != undefined) { 7910 this.sigBytes = sigBytes; 7911 } else { 7912 this.sigBytes = words.length * 4; 7913 } 7914 }, 7915 7916 /** 7917 * Converts this word array to a string. 7918 * 7919 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex 7920 * 7921 * @return {string} The stringified word array. 7922 * 7923 * @example 7924 * 7925 * var string = wordArray + ''; 7926 * var string = wordArray.toString(); 7927 * var string = wordArray.toString(CryptoJS.enc.Utf8); 7928 */ 7929 toString: function (encoder) { 7930 return (encoder || Hex).stringify(this); 7931 }, 7932 7933 /** 7934 * Concatenates a word array to this word array. 7935 * 7936 * @param {WordArray} wordArray The word array to append. 7937 * 7938 * @return {WordArray} This word array. 7939 * 7940 * @example 7941 * 7942 * wordArray1.concat(wordArray2); 7943 */ 7944 concat: function (wordArray) { 7945 // Shortcuts 7946 var thisWords = this.words; 7947 var thatWords = wordArray.words; 7948 var thisSigBytes = this.sigBytes; 7949 var thatSigBytes = wordArray.sigBytes; 7950 7951 // Clamp excess bits 7952 this.clamp(); 7953 7954 // Concat 7955 if (thisSigBytes % 4) { 7956 // Copy one byte at a time 7957 for (var i = 0; i < thatSigBytes; i++) { 7958 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 7959 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); 7960 } 7961 } else { 7962 // Copy one word at a time 7963 for (var i = 0; i < thatSigBytes; i += 4) { 7964 thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; 7965 } 7966 } 7967 this.sigBytes += thatSigBytes; 7968 7969 // Chainable 7970 return this; 7971 }, 7972 7973 /** 7974 * Removes insignificant bits. 7975 * 7976 * @example 7977 * 7978 * wordArray.clamp(); 7979 */ 7980 clamp: function () { 7981 // Shortcuts 7982 var words = this.words; 7983 var sigBytes = this.sigBytes; 7984 7985 // Clamp 7986 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); 7987 words.length = Math.ceil(sigBytes / 4); 7988 }, 7989 7990 /** 7991 * Creates a copy of this word array. 7992 * 7993 * @return {WordArray} The clone. 7994 * 7995 * @example 7996 * 7997 * var clone = wordArray.clone(); 7998 */ 7999 clone: function () { 8000 var clone = Base.clone.call(this); 8001 clone.words = this.words.slice(0); 8002 8003 return clone; 8004 }, 8005 8006 /** 8007 * Creates a word array filled with random bytes. 8008 * 8009 * @param {number} nBytes The number of random bytes to generate. 8010 * 8011 * @return {WordArray} The random word array. 8012 * 8013 * @static 8014 * 8015 * @example 8016 * 8017 * var wordArray = CryptoJS.lib.WordArray.random(16); 8018 */ 8019 random: function (nBytes) { 8020 var words = []; 8021 8022 var r = (function (m_w) { 8023 var m_w = m_w; 8024 var m_z = 0x3ade68b1; 8025 var mask = 0xffffffff; 8026 8027 return function () { 8028 m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; 8029 m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; 8030 var result = ((m_z << 0x10) + m_w) & mask; 8031 result /= 0x100000000; 8032 result += 0.5; 8033 return result * (Math.random() > .5 ? 1 : -1); 8034 } 8035 }); 8036 8037 for (var i = 0, rcache; i < nBytes; i += 4) { 8038 var _r = r((rcache || Math.random()) * 0x100000000); 8039 8040 rcache = _r() * 0x3ade67b7; 8041 words.push((_r() * 0x100000000) | 0); 8042 } 8043 8044 return new WordArray.init(words, nBytes); 8045 } 8046 }); 8047 8048 /** 8049 * Encoder namespace. 8050 */ 8051 var C_enc = C.enc = {}; 8052 8053 /** 8054 * Hex encoding strategy. 8055 */ 8056 var Hex = C_enc.Hex = { 8057 /** 8058 * Converts a word array to a hex string. 8059 * 8060 * @param {WordArray} wordArray The word array. 8061 * 8062 * @return {string} The hex string. 8063 * 8064 * @static 8065 * 8066 * @example 8067 * 8068 * var hexString = CryptoJS.enc.Hex.stringify(wordArray); 8069 */ 8070 stringify: function (wordArray) { 8071 // Shortcuts 8072 var words = wordArray.words; 8073 var sigBytes = wordArray.sigBytes; 8074 8075 // Convert 8076 var hexChars = []; 8077 for (var i = 0; i < sigBytes; i++) { 8078 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 8079 hexChars.push((bite >>> 4).toString(16)); 8080 hexChars.push((bite & 0x0f).toString(16)); 8081 } 8082 8083 return hexChars.join(''); 8084 }, 8085 8086 /** 8087 * Converts a hex string to a word array. 8088 * 8089 * @param {string} hexStr The hex string. 8090 * 8091 * @return {WordArray} The word array. 8092 * 8093 * @static 8094 * 8095 * @example 8096 * 8097 * var wordArray = CryptoJS.enc.Hex.parse(hexString); 8098 */ 8099 parse: function (hexStr) { 8100 // Shortcut 8101 var hexStrLength = hexStr.length; 8102 8103 // Convert 8104 var words = []; 8105 for (var i = 0; i < hexStrLength; i += 2) { 8106 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); 8107 } 8108 8109 return new WordArray.init(words, hexStrLength / 2); 8110 } 8111 }; 8112 8113 /** 8114 * Latin1 encoding strategy. 8115 */ 8116 var Latin1 = C_enc.Latin1 = { 8117 /** 8118 * Converts a word array to a Latin1 string. 8119 * 8120 * @param {WordArray} wordArray The word array. 8121 * 8122 * @return {string} The Latin1 string. 8123 * 8124 * @static 8125 * 8126 * @example 8127 * 8128 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); 8129 */ 8130 stringify: function (wordArray) { 8131 // Shortcuts 8132 var words = wordArray.words; 8133 var sigBytes = wordArray.sigBytes; 8134 8135 // Convert 8136 var latin1Chars = []; 8137 for (var i = 0; i < sigBytes; i++) { 8138 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 8139 latin1Chars.push(String.fromCharCode(bite)); 8140 } 8141 8142 return latin1Chars.join(''); 8143 }, 8144 8145 /** 8146 * Converts a Latin1 string to a word array. 8147 * 8148 * @param {string} latin1Str The Latin1 string. 8149 * 8150 * @return {WordArray} The word array. 8151 * 8152 * @static 8153 * 8154 * @example 8155 * 8156 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); 8157 */ 8158 parse: function (latin1Str) { 8159 // Shortcut 8160 var latin1StrLength = latin1Str.length; 8161 8162 // Convert 8163 var words = []; 8164 for (var i = 0; i < latin1StrLength; i++) { 8165 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); 8166 } 8167 8168 return new WordArray.init(words, latin1StrLength); 8169 } 8170 }; 8171 8172 /** 8173 * UTF-8 encoding strategy. 8174 */ 8175 var Utf8 = C_enc.Utf8 = { 8176 /** 8177 * Converts a word array to a UTF-8 string. 8178 * 8179 * @param {WordArray} wordArray The word array. 8180 * 8181 * @return {string} The UTF-8 string. 8182 * 8183 * @static 8184 * 8185 * @example 8186 * 8187 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); 8188 */ 8189 stringify: function (wordArray) { 8190 try { 8191 return decodeURIComponent(escape(Latin1.stringify(wordArray))); 8192 } catch (e) { 8193 throw new Error('Malformed UTF-8 data'); 8194 } 8195 }, 8196 8197 /** 8198 * Converts a UTF-8 string to a word array. 8199 * 8200 * @param {string} utf8Str The UTF-8 string. 8201 * 8202 * @return {WordArray} The word array. 8203 * 8204 * @static 8205 * 8206 * @example 8207 * 8208 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); 8209 */ 8210 parse: function (utf8Str) { 8211 return Latin1.parse(unescape(encodeURIComponent(utf8Str))); 8212 } 8213 }; 8214 8215 /** 8216 * Abstract buffered block algorithm template. 8217 * 8218 * The property blockSize must be implemented in a concrete subtype. 8219 * 8220 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 8221 */ 8222 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ 8223 /** 8224 * Resets this block algorithm's data buffer to its initial state. 8225 * 8226 * @example 8227 * 8228 * bufferedBlockAlgorithm.reset(); 8229 */ 8230 reset: function () { 8231 // Initial values 8232 this._data = new WordArray.init(); 8233 this._nDataBytes = 0; 8234 }, 8235 8236 /** 8237 * Adds new data to this block algorithm's buffer. 8238 * 8239 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. 8240 * 8241 * @example 8242 * 8243 * bufferedBlockAlgorithm._append('data'); 8244 * bufferedBlockAlgorithm._append(wordArray); 8245 */ 8246 _append: function (data) { 8247 // Convert string to WordArray, else assume WordArray already 8248 if (typeof data == 'string') { 8249 data = Utf8.parse(data); 8250 } 8251 8252 // Append 8253 this._data.concat(data); 8254 this._nDataBytes += data.sigBytes; 8255 }, 8256 8257 /** 8258 * Processes available data blocks. 8259 * 8260 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. 8261 * 8262 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. 8263 * 8264 * @return {WordArray} The processed data. 8265 * 8266 * @example 8267 * 8268 * var processedData = bufferedBlockAlgorithm._process(); 8269 * var processedData = bufferedBlockAlgorithm._process(!!'flush'); 8270 */ 8271 _process: function (doFlush) { 8272 // Shortcuts 8273 var data = this._data; 8274 var dataWords = data.words; 8275 var dataSigBytes = data.sigBytes; 8276 var blockSize = this.blockSize; 8277 var blockSizeBytes = blockSize * 4; 8278 8279 // Count blocks ready 8280 var nBlocksReady = dataSigBytes / blockSizeBytes; 8281 if (doFlush) { 8282 // Round up to include partial blocks 8283 nBlocksReady = Math.ceil(nBlocksReady); 8284 } else { 8285 // Round down to include only full blocks, 8286 // less the number of blocks that must remain in the buffer 8287 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); 8288 } 8289 8290 // Count words ready 8291 var nWordsReady = nBlocksReady * blockSize; 8292 8293 // Count bytes ready 8294 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); 8295 8296 // Process blocks 8297 if (nWordsReady) { 8298 for (var offset = 0; offset < nWordsReady; offset += blockSize) { 8299 // Perform concrete-algorithm logic 8300 this._doProcessBlock(dataWords, offset); 8301 } 8302 8303 // Remove processed words 8304 var processedWords = dataWords.splice(0, nWordsReady); 8305 data.sigBytes -= nBytesReady; 8306 } 8307 8308 // Return processed words 8309 return new WordArray.init(processedWords, nBytesReady); 8310 }, 8311 8312 /** 8313 * Creates a copy of this object. 8314 * 8315 * @return {Object} The clone. 8316 * 8317 * @example 8318 * 8319 * var clone = bufferedBlockAlgorithm.clone(); 8320 */ 8321 clone: function () { 8322 var clone = Base.clone.call(this); 8323 clone._data = this._data.clone(); 8324 8325 return clone; 8326 }, 8327 8328 _minBufferSize: 0 8329 }); 8330 8331 /** 8332 * Abstract hasher template. 8333 * 8334 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) 8335 */ 8336 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ 8337 /** 8338 * Configuration options. 8339 */ 8340 cfg: Base.extend(), 8341 8342 /** 8343 * Initializes a newly created hasher. 8344 * 8345 * @param {Object} cfg (Optional) The configuration options to use for this hash computation. 8346 * 8347 * @example 8348 * 8349 * var hasher = CryptoJS.algo.SHA256.create(); 8350 */ 8351 init: function (cfg) { 8352 // Apply config defaults 8353 this.cfg = this.cfg.extend(cfg); 8354 8355 // Set initial values 8356 this.reset(); 8357 }, 8358 8359 /** 8360 * Resets this hasher to its initial state. 8361 * 8362 * @example 8363 * 8364 * hasher.reset(); 8365 */ 8366 reset: function () { 8367 // Reset data buffer 8368 BufferedBlockAlgorithm.reset.call(this); 8369 8370 // Perform concrete-hasher logic 8371 this._doReset(); 8372 }, 8373 8374 /** 8375 * Updates this hasher with a message. 8376 * 8377 * @param {WordArray|string} messageUpdate The message to append. 8378 * 8379 * @return {Hasher} This hasher. 8380 * 8381 * @example 8382 * 8383 * hasher.update('message'); 8384 * hasher.update(wordArray); 8385 */ 8386 update: function (messageUpdate) { 8387 // Append 8388 this._append(messageUpdate); 8389 8390 // Update the hash 8391 this._process(); 8392 8393 // Chainable 8394 return this; 8395 }, 8396 8397 /** 8398 * Finalizes the hash computation. 8399 * Note that the finalize operation is effectively a destructive, read-once operation. 8400 * 8401 * @param {WordArray|string} messageUpdate (Optional) A final message update. 8402 * 8403 * @return {WordArray} The hash. 8404 * 8405 * @example 8406 * 8407 * var hash = hasher.finalize(); 8408 * var hash = hasher.finalize('message'); 8409 * var hash = hasher.finalize(wordArray); 8410 */ 8411 finalize: function (messageUpdate) { 8412 // Final message update 8413 if (messageUpdate) { 8414 this._append(messageUpdate); 8415 } 8416 8417 // Perform concrete-hasher logic 8418 var hash = this._doFinalize(); 8419 8420 return hash; 8421 }, 8422 8423 blockSize: 512/32, 8424 8425 /** 8426 * Creates a shortcut function to a hasher's object interface. 8427 * 8428 * @param {Hasher} hasher The hasher to create a helper for. 8429 * 8430 * @return {Function} The shortcut function. 8431 * 8432 * @static 8433 * 8434 * @example 8435 * 8436 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); 8437 */ 8438 _createHelper: function (hasher) { 8439 return function (message, cfg) { 8440 return new hasher.init(cfg).finalize(message); 8441 }; 8442 }, 8443 8444 /** 8445 * Creates a shortcut function to the HMAC's object interface. 8446 * 8447 * @param {Hasher} hasher The hasher to use in this HMAC helper. 8448 * 8449 * @return {Function} The shortcut function. 8450 * 8451 * @static 8452 * 8453 * @example 8454 * 8455 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); 8456 */ 8457 _createHmacHelper: function (hasher) { 8458 return function (message, key) { 8459 return new C_algo.HMAC.init(hasher, key).finalize(message); 8460 }; 8461 } 8462 }); 8463 8464 /** 8465 * Algorithm namespace. 8466 */ 8467 var C_algo = C.algo = {}; 8468 8469 return C; 8470 }(Math)); 8471 8472 8473 return CryptoJS; 8474 8475 })); 8476 },{}],54:[function(require,module,exports){ 8477 ;(function (root, factory) { 8478 if (typeof exports === "object") { 8479 // CommonJS 8480 module.exports = exports = factory(require("./core")); 8481 } 8482 else if (typeof define === "function" && define.amd) { 8483 // AMD 8484 define(["./core"], factory); 8485 } 8486 else { 8487 // Global (browser) 8488 factory(root.CryptoJS); 8489 } 8490 }(this, function (CryptoJS) { 8491 8492 (function () { 8493 // Shortcuts 8494 var C = CryptoJS; 8495 var C_lib = C.lib; 8496 var WordArray = C_lib.WordArray; 8497 var C_enc = C.enc; 8498 8499 /** 8500 * Base64 encoding strategy. 8501 */ 8502 var Base64 = C_enc.Base64 = { 8503 /** 8504 * Converts a word array to a Base64 string. 8505 * 8506 * @param {WordArray} wordArray The word array. 8507 * 8508 * @return {string} The Base64 string. 8509 * 8510 * @static 8511 * 8512 * @example 8513 * 8514 * var base64String = CryptoJS.enc.Base64.stringify(wordArray); 8515 */ 8516 stringify: function (wordArray) { 8517 // Shortcuts 8518 var words = wordArray.words; 8519 var sigBytes = wordArray.sigBytes; 8520 var map = this._map; 8521 8522 // Clamp excess bits 8523 wordArray.clamp(); 8524 8525 // Convert 8526 var base64Chars = []; 8527 for (var i = 0; i < sigBytes; i += 3) { 8528 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 8529 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; 8530 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; 8531 8532 var triplet = (byte1 << 16) | (byte2 << 8) | byte3; 8533 8534 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { 8535 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); 8536 } 8537 } 8538 8539 // Add padding 8540 var paddingChar = map.charAt(64); 8541 if (paddingChar) { 8542 while (base64Chars.length % 4) { 8543 base64Chars.push(paddingChar); 8544 } 8545 } 8546 8547 return base64Chars.join(''); 8548 }, 8549 8550 /** 8551 * Converts a Base64 string to a word array. 8552 * 8553 * @param {string} base64Str The Base64 string. 8554 * 8555 * @return {WordArray} The word array. 8556 * 8557 * @static 8558 * 8559 * @example 8560 * 8561 * var wordArray = CryptoJS.enc.Base64.parse(base64String); 8562 */ 8563 parse: function (base64Str) { 8564 // Shortcuts 8565 var base64StrLength = base64Str.length; 8566 var map = this._map; 8567 var reverseMap = this._reverseMap; 8568 8569 if (!reverseMap) { 8570 reverseMap = this._reverseMap = []; 8571 for (var j = 0; j < map.length; j++) { 8572 reverseMap[map.charCodeAt(j)] = j; 8573 } 8574 } 8575 8576 // Ignore padding 8577 var paddingChar = map.charAt(64); 8578 if (paddingChar) { 8579 var paddingIndex = base64Str.indexOf(paddingChar); 8580 if (paddingIndex !== -1) { 8581 base64StrLength = paddingIndex; 8582 } 8583 } 8584 8585 // Convert 8586 return parseLoop(base64Str, base64StrLength, reverseMap); 8587 8588 }, 8589 8590 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' 8591 }; 8592 8593 function parseLoop(base64Str, base64StrLength, reverseMap) { 8594 var words = []; 8595 var nBytes = 0; 8596 for (var i = 0; i < base64StrLength; i++) { 8597 if (i % 4) { 8598 var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); 8599 var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); 8600 words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); 8601 nBytes++; 8602 } 8603 } 8604 return WordArray.create(words, nBytes); 8605 } 8606 }()); 8607 8608 8609 return CryptoJS.enc.Base64; 8610 8611 })); 8612 },{"./core":53}],55:[function(require,module,exports){ 8613 ;(function (root, factory) { 8614 if (typeof exports === "object") { 8615 // CommonJS 8616 module.exports = exports = factory(require("./core")); 8617 } 8618 else if (typeof define === "function" && define.amd) { 8619 // AMD 8620 define(["./core"], factory); 8621 } 8622 else { 8623 // Global (browser) 8624 factory(root.CryptoJS); 8625 } 8626 }(this, function (CryptoJS) { 8627 8628 (function () { 8629 // Shortcuts 8630 var C = CryptoJS; 8631 var C_lib = C.lib; 8632 var WordArray = C_lib.WordArray; 8633 var C_enc = C.enc; 8634 8635 /** 8636 * UTF-16 BE encoding strategy. 8637 */ 8638 var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { 8639 /** 8640 * Converts a word array to a UTF-16 BE string. 8641 * 8642 * @param {WordArray} wordArray The word array. 8643 * 8644 * @return {string} The UTF-16 BE string. 8645 * 8646 * @static 8647 * 8648 * @example 8649 * 8650 * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); 8651 */ 8652 stringify: function (wordArray) { 8653 // Shortcuts 8654 var words = wordArray.words; 8655 var sigBytes = wordArray.sigBytes; 8656 8657 // Convert 8658 var utf16Chars = []; 8659 for (var i = 0; i < sigBytes; i += 2) { 8660 var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; 8661 utf16Chars.push(String.fromCharCode(codePoint)); 8662 } 8663 8664 return utf16Chars.join(''); 8665 }, 8666 8667 /** 8668 * Converts a UTF-16 BE string to a word array. 8669 * 8670 * @param {string} utf16Str The UTF-16 BE string. 8671 * 8672 * @return {WordArray} The word array. 8673 * 8674 * @static 8675 * 8676 * @example 8677 * 8678 * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); 8679 */ 8680 parse: function (utf16Str) { 8681 // Shortcut 8682 var utf16StrLength = utf16Str.length; 8683 8684 // Convert 8685 var words = []; 8686 for (var i = 0; i < utf16StrLength; i++) { 8687 words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); 8688 } 8689 8690 return WordArray.create(words, utf16StrLength * 2); 8691 } 8692 }; 8693 8694 /** 8695 * UTF-16 LE encoding strategy. 8696 */ 8697 C_enc.Utf16LE = { 8698 /** 8699 * Converts a word array to a UTF-16 LE string. 8700 * 8701 * @param {WordArray} wordArray The word array. 8702 * 8703 * @return {string} The UTF-16 LE string. 8704 * 8705 * @static 8706 * 8707 * @example 8708 * 8709 * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); 8710 */ 8711 stringify: function (wordArray) { 8712 // Shortcuts 8713 var words = wordArray.words; 8714 var sigBytes = wordArray.sigBytes; 8715 8716 // Convert 8717 var utf16Chars = []; 8718 for (var i = 0; i < sigBytes; i += 2) { 8719 var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); 8720 utf16Chars.push(String.fromCharCode(codePoint)); 8721 } 8722 8723 return utf16Chars.join(''); 8724 }, 8725 8726 /** 8727 * Converts a UTF-16 LE string to a word array. 8728 * 8729 * @param {string} utf16Str The UTF-16 LE string. 8730 * 8731 * @return {WordArray} The word array. 8732 * 8733 * @static 8734 * 8735 * @example 8736 * 8737 * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); 8738 */ 8739 parse: function (utf16Str) { 8740 // Shortcut 8741 var utf16StrLength = utf16Str.length; 8742 8743 // Convert 8744 var words = []; 8745 for (var i = 0; i < utf16StrLength; i++) { 8746 words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); 8747 } 8748 8749 return WordArray.create(words, utf16StrLength * 2); 8750 } 8751 }; 8752 8753 function swapEndian(word) { 8754 return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); 8755 } 8756 }()); 8757 8758 8759 return CryptoJS.enc.Utf16; 8760 8761 })); 8762 },{"./core":53}],56:[function(require,module,exports){ 8763 ;(function (root, factory, undef) { 8764 if (typeof exports === "object") { 8765 // CommonJS 8766 module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); 8767 } 8768 else if (typeof define === "function" && define.amd) { 8769 // AMD 8770 define(["./core", "./sha1", "./hmac"], factory); 8771 } 8772 else { 8773 // Global (browser) 8774 factory(root.CryptoJS); 8775 } 8776 }(this, function (CryptoJS) { 8777 8778 (function () { 8779 // Shortcuts 8780 var C = CryptoJS; 8781 var C_lib = C.lib; 8782 var Base = C_lib.Base; 8783 var WordArray = C_lib.WordArray; 8784 var C_algo = C.algo; 8785 var MD5 = C_algo.MD5; 8786 8787 /** 8788 * This key derivation function is meant to conform with EVP_BytesToKey. 8789 * www.openssl.org/docs/crypto/EVP_BytesToKey.html 8790 */ 8791 var EvpKDF = C_algo.EvpKDF = Base.extend({ 8792 /** 8793 * Configuration options. 8794 * 8795 * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) 8796 * @property {Hasher} hasher The hash algorithm to use. Default: MD5 8797 * @property {number} iterations The number of iterations to perform. Default: 1 8798 */ 8799 cfg: Base.extend({ 8800 keySize: 128/32, 8801 hasher: MD5, 8802 iterations: 1 8803 }), 8804 8805 /** 8806 * Initializes a newly created key derivation function. 8807 * 8808 * @param {Object} cfg (Optional) The configuration options to use for the derivation. 8809 * 8810 * @example 8811 * 8812 * var kdf = CryptoJS.algo.EvpKDF.create(); 8813 * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); 8814 * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); 8815 */ 8816 init: function (cfg) { 8817 this.cfg = this.cfg.extend(cfg); 8818 }, 8819 8820 /** 8821 * Derives a key from a password. 8822 * 8823 * @param {WordArray|string} password The password. 8824 * @param {WordArray|string} salt A salt. 8825 * 8826 * @return {WordArray} The derived key. 8827 * 8828 * @example 8829 * 8830 * var key = kdf.compute(password, salt); 8831 */ 8832 compute: function (password, salt) { 8833 // Shortcut 8834 var cfg = this.cfg; 8835 8836 // Init hasher 8837 var hasher = cfg.hasher.create(); 8838 8839 // Initial values 8840 var derivedKey = WordArray.create(); 8841 8842 // Shortcuts 8843 var derivedKeyWords = derivedKey.words; 8844 var keySize = cfg.keySize; 8845 var iterations = cfg.iterations; 8846 8847 // Generate key 8848 while (derivedKeyWords.length < keySize) { 8849 if (block) { 8850 hasher.update(block); 8851 } 8852 var block = hasher.update(password).finalize(salt); 8853 hasher.reset(); 8854 8855 // Iterations 8856 for (var i = 1; i < iterations; i++) { 8857 block = hasher.finalize(block); 8858 hasher.reset(); 8859 } 8860 8861 derivedKey.concat(block); 8862 } 8863 derivedKey.sigBytes = keySize * 4; 8864 8865 return derivedKey; 8866 } 8867 }); 8868 8869 /** 8870 * Derives a key from a password. 8871 * 8872 * @param {WordArray|string} password The password. 8873 * @param {WordArray|string} salt A salt. 8874 * @param {Object} cfg (Optional) The configuration options to use for this computation. 8875 * 8876 * @return {WordArray} The derived key. 8877 * 8878 * @static 8879 * 8880 * @example 8881 * 8882 * var key = CryptoJS.EvpKDF(password, salt); 8883 * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); 8884 * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); 8885 */ 8886 C.EvpKDF = function (password, salt, cfg) { 8887 return EvpKDF.create(cfg).compute(password, salt); 8888 }; 8889 }()); 8890 8891 8892 return CryptoJS.EvpKDF; 8893 8894 })); 8895 },{"./core":53,"./hmac":58,"./sha1":77}],57:[function(require,module,exports){ 8896 ;(function (root, factory, undef) { 8897 if (typeof exports === "object") { 8898 // CommonJS 8899 module.exports = exports = factory(require("./core"), require("./cipher-core")); 8900 } 8901 else if (typeof define === "function" && define.amd) { 8902 // AMD 8903 define(["./core", "./cipher-core"], factory); 8904 } 8905 else { 8906 // Global (browser) 8907 factory(root.CryptoJS); 8908 } 8909 }(this, function (CryptoJS) { 8910 8911 (function (undefined) { 8912 // Shortcuts 8913 var C = CryptoJS; 8914 var C_lib = C.lib; 8915 var CipherParams = C_lib.CipherParams; 8916 var C_enc = C.enc; 8917 var Hex = C_enc.Hex; 8918 var C_format = C.format; 8919 8920 var HexFormatter = C_format.Hex = { 8921 /** 8922 * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. 8923 * 8924 * @param {CipherParams} cipherParams The cipher params object. 8925 * 8926 * @return {string} The hexadecimally encoded string. 8927 * 8928 * @static 8929 * 8930 * @example 8931 * 8932 * var hexString = CryptoJS.format.Hex.stringify(cipherParams); 8933 */ 8934 stringify: function (cipherParams) { 8935 return cipherParams.ciphertext.toString(Hex); 8936 }, 8937 8938 /** 8939 * Converts a hexadecimally encoded ciphertext string to a cipher params object. 8940 * 8941 * @param {string} input The hexadecimally encoded string. 8942 * 8943 * @return {CipherParams} The cipher params object. 8944 * 8945 * @static 8946 * 8947 * @example 8948 * 8949 * var cipherParams = CryptoJS.format.Hex.parse(hexString); 8950 */ 8951 parse: function (input) { 8952 var ciphertext = Hex.parse(input); 8953 return CipherParams.create({ ciphertext: ciphertext }); 8954 } 8955 }; 8956 }()); 8957 8958 8959 return CryptoJS.format.Hex; 8960 8961 })); 8962 },{"./cipher-core":52,"./core":53}],58:[function(require,module,exports){ 8963 ;(function (root, factory) { 8964 if (typeof exports === "object") { 8965 // CommonJS 8966 module.exports = exports = factory(require("./core")); 8967 } 8968 else if (typeof define === "function" && define.amd) { 8969 // AMD 8970 define(["./core"], factory); 8971 } 8972 else { 8973 // Global (browser) 8974 factory(root.CryptoJS); 8975 } 8976 }(this, function (CryptoJS) { 8977 8978 (function () { 8979 // Shortcuts 8980 var C = CryptoJS; 8981 var C_lib = C.lib; 8982 var Base = C_lib.Base; 8983 var C_enc = C.enc; 8984 var Utf8 = C_enc.Utf8; 8985 var C_algo = C.algo; 8986 8987 /** 8988 * HMAC algorithm. 8989 */ 8990 var HMAC = C_algo.HMAC = Base.extend({ 8991 /** 8992 * Initializes a newly created HMAC. 8993 * 8994 * @param {Hasher} hasher The hash algorithm to use. 8995 * @param {WordArray|string} key The secret key. 8996 * 8997 * @example 8998 * 8999 * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); 9000 */ 9001 init: function (hasher, key) { 9002 // Init hasher 9003 hasher = this._hasher = new hasher.init(); 9004 9005 // Convert string to WordArray, else assume WordArray already 9006 if (typeof key == 'string') { 9007 key = Utf8.parse(key); 9008 } 9009 9010 // Shortcuts 9011 var hasherBlockSize = hasher.blockSize; 9012 var hasherBlockSizeBytes = hasherBlockSize * 4; 9013 9014 // Allow arbitrary length keys 9015 if (key.sigBytes > hasherBlockSizeBytes) { 9016 key = hasher.finalize(key); 9017 } 9018 9019 // Clamp excess bits 9020 key.clamp(); 9021 9022 // Clone key for inner and outer pads 9023 var oKey = this._oKey = key.clone(); 9024 var iKey = this._iKey = key.clone(); 9025 9026 // Shortcuts 9027 var oKeyWords = oKey.words; 9028 var iKeyWords = iKey.words; 9029 9030 // XOR keys with pad constants 9031 for (var i = 0; i < hasherBlockSize; i++) { 9032 oKeyWords[i] ^= 0x5c5c5c5c; 9033 iKeyWords[i] ^= 0x36363636; 9034 } 9035 oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; 9036 9037 // Set initial values 9038 this.reset(); 9039 }, 9040 9041 /** 9042 * Resets this HMAC to its initial state. 9043 * 9044 * @example 9045 * 9046 * hmacHasher.reset(); 9047 */ 9048 reset: function () { 9049 // Shortcut 9050 var hasher = this._hasher; 9051 9052 // Reset 9053 hasher.reset(); 9054 hasher.update(this._iKey); 9055 }, 9056 9057 /** 9058 * Updates this HMAC with a message. 9059 * 9060 * @param {WordArray|string} messageUpdate The message to append. 9061 * 9062 * @return {HMAC} This HMAC instance. 9063 * 9064 * @example 9065 * 9066 * hmacHasher.update('message'); 9067 * hmacHasher.update(wordArray); 9068 */ 9069 update: function (messageUpdate) { 9070 this._hasher.update(messageUpdate); 9071 9072 // Chainable 9073 return this; 9074 }, 9075 9076 /** 9077 * Finalizes the HMAC computation. 9078 * Note that the finalize operation is effectively a destructive, read-once operation. 9079 * 9080 * @param {WordArray|string} messageUpdate (Optional) A final message update. 9081 * 9082 * @return {WordArray} The HMAC. 9083 * 9084 * @example 9085 * 9086 * var hmac = hmacHasher.finalize(); 9087 * var hmac = hmacHasher.finalize('message'); 9088 * var hmac = hmacHasher.finalize(wordArray); 9089 */ 9090 finalize: function (messageUpdate) { 9091 // Shortcut 9092 var hasher = this._hasher; 9093 9094 // Compute HMAC 9095 var innerHash = hasher.finalize(messageUpdate); 9096 hasher.reset(); 9097 var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); 9098 9099 return hmac; 9100 } 9101 }); 9102 }()); 9103 9104 9105 })); 9106 },{"./core":53}],59:[function(require,module,exports){ 9107 ;(function (root, factory, undef) { 9108 if (typeof exports === "object") { 9109 // CommonJS 9110 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")); 9111 } 9112 else if (typeof define === "function" && define.amd) { 9113 // AMD 9114 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); 9115 } 9116 else { 9117 // Global (browser) 9118 root.CryptoJS = factory(root.CryptoJS); 9119 } 9120 }(this, function (CryptoJS) { 9121 9122 return CryptoJS; 9123 9124 })); 9125 },{"./aes":51,"./cipher-core":52,"./core":53,"./enc-base64":54,"./enc-utf16":55,"./evpkdf":56,"./format-hex":57,"./hmac":58,"./lib-typedarrays":60,"./md5":61,"./mode-cfb":62,"./mode-ctr":64,"./mode-ctr-gladman":63,"./mode-ecb":65,"./mode-ofb":66,"./pad-ansix923":67,"./pad-iso10126":68,"./pad-iso97971":69,"./pad-nopadding":70,"./pad-zeropadding":71,"./pbkdf2":72,"./rabbit":74,"./rabbit-legacy":73,"./rc4":75,"./ripemd160":76,"./sha1":77,"./sha224":78,"./sha256":79,"./sha3":80,"./sha384":81,"./sha512":82,"./tripledes":83,"./x64-core":84}],60:[function(require,module,exports){ 9126 ;(function (root, factory) { 9127 if (typeof exports === "object") { 9128 // CommonJS 9129 module.exports = exports = factory(require("./core")); 9130 } 9131 else if (typeof define === "function" && define.amd) { 9132 // AMD 9133 define(["./core"], factory); 9134 } 9135 else { 9136 // Global (browser) 9137 factory(root.CryptoJS); 9138 } 9139 }(this, function (CryptoJS) { 9140 9141 (function () { 9142 // Check if typed arrays are supported 9143 if (typeof ArrayBuffer != 'function') { 9144 return; 9145 } 9146 9147 // Shortcuts 9148 var C = CryptoJS; 9149 var C_lib = C.lib; 9150 var WordArray = C_lib.WordArray; 9151 9152 // Reference original init 9153 var superInit = WordArray.init; 9154 9155 // Augment WordArray.init to handle typed arrays 9156 var subInit = WordArray.init = function (typedArray) { 9157 // Convert buffers to uint8 9158 if (typedArray instanceof ArrayBuffer) { 9159 typedArray = new Uint8Array(typedArray); 9160 } 9161 9162 // Convert other array views to uint8 9163 if ( 9164 typedArray instanceof Int8Array || 9165 (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || 9166 typedArray instanceof Int16Array || 9167 typedArray instanceof Uint16Array || 9168 typedArray instanceof Int32Array || 9169 typedArray instanceof Uint32Array || 9170 typedArray instanceof Float32Array || 9171 typedArray instanceof Float64Array 9172 ) { 9173 typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); 9174 } 9175 9176 // Handle Uint8Array 9177 if (typedArray instanceof Uint8Array) { 9178 // Shortcut 9179 var typedArrayByteLength = typedArray.byteLength; 9180 9181 // Extract bytes 9182 var words = []; 9183 for (var i = 0; i < typedArrayByteLength; i++) { 9184 words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); 9185 } 9186 9187 // Initialize this word array 9188 superInit.call(this, words, typedArrayByteLength); 9189 } else { 9190 // Else call normal init 9191 superInit.apply(this, arguments); 9192 } 9193 }; 9194 9195 subInit.prototype = WordArray; 9196 }()); 9197 9198 9199 return CryptoJS.lib.WordArray; 9200 9201 })); 9202 },{"./core":53}],61:[function(require,module,exports){ 9203 ;(function (root, factory) { 9204 if (typeof exports === "object") { 9205 // CommonJS 9206 module.exports = exports = factory(require("./core")); 9207 } 9208 else if (typeof define === "function" && define.amd) { 9209 // AMD 9210 define(["./core"], factory); 9211 } 9212 else { 9213 // Global (browser) 9214 factory(root.CryptoJS); 9215 } 9216 }(this, function (CryptoJS) { 9217 9218 (function (Math) { 9219 // Shortcuts 9220 var C = CryptoJS; 9221 var C_lib = C.lib; 9222 var WordArray = C_lib.WordArray; 9223 var Hasher = C_lib.Hasher; 9224 var C_algo = C.algo; 9225 9226 // Constants table 9227 var T = []; 9228 9229 // Compute constants 9230 (function () { 9231 for (var i = 0; i < 64; i++) { 9232 T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; 9233 } 9234 }()); 9235 9236 /** 9237 * MD5 hash algorithm. 9238 */ 9239 var MD5 = C_algo.MD5 = Hasher.extend({ 9240 _doReset: function () { 9241 this._hash = new WordArray.init([ 9242 0x67452301, 0xefcdab89, 9243 0x98badcfe, 0x10325476 9244 ]); 9245 }, 9246 9247 _doProcessBlock: function (M, offset) { 9248 // Swap endian 9249 for (var i = 0; i < 16; i++) { 9250 // Shortcuts 9251 var offset_i = offset + i; 9252 var M_offset_i = M[offset_i]; 9253 9254 M[offset_i] = ( 9255 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | 9256 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) 9257 ); 9258 } 9259 9260 // Shortcuts 9261 var H = this._hash.words; 9262 9263 var M_offset_0 = M[offset + 0]; 9264 var M_offset_1 = M[offset + 1]; 9265 var M_offset_2 = M[offset + 2]; 9266 var M_offset_3 = M[offset + 3]; 9267 var M_offset_4 = M[offset + 4]; 9268 var M_offset_5 = M[offset + 5]; 9269 var M_offset_6 = M[offset + 6]; 9270 var M_offset_7 = M[offset + 7]; 9271 var M_offset_8 = M[offset + 8]; 9272 var M_offset_9 = M[offset + 9]; 9273 var M_offset_10 = M[offset + 10]; 9274 var M_offset_11 = M[offset + 11]; 9275 var M_offset_12 = M[offset + 12]; 9276 var M_offset_13 = M[offset + 13]; 9277 var M_offset_14 = M[offset + 14]; 9278 var M_offset_15 = M[offset + 15]; 9279 9280 // Working varialbes 9281 var a = H[0]; 9282 var b = H[1]; 9283 var c = H[2]; 9284 var d = H[3]; 9285 9286 // Computation 9287 a = FF(a, b, c, d, M_offset_0, 7, T[0]); 9288 d = FF(d, a, b, c, M_offset_1, 12, T[1]); 9289 c = FF(c, d, a, b, M_offset_2, 17, T[2]); 9290 b = FF(b, c, d, a, M_offset_3, 22, T[3]); 9291 a = FF(a, b, c, d, M_offset_4, 7, T[4]); 9292 d = FF(d, a, b, c, M_offset_5, 12, T[5]); 9293 c = FF(c, d, a, b, M_offset_6, 17, T[6]); 9294 b = FF(b, c, d, a, M_offset_7, 22, T[7]); 9295 a = FF(a, b, c, d, M_offset_8, 7, T[8]); 9296 d = FF(d, a, b, c, M_offset_9, 12, T[9]); 9297 c = FF(c, d, a, b, M_offset_10, 17, T[10]); 9298 b = FF(b, c, d, a, M_offset_11, 22, T[11]); 9299 a = FF(a, b, c, d, M_offset_12, 7, T[12]); 9300 d = FF(d, a, b, c, M_offset_13, 12, T[13]); 9301 c = FF(c, d, a, b, M_offset_14, 17, T[14]); 9302 b = FF(b, c, d, a, M_offset_15, 22, T[15]); 9303 9304 a = GG(a, b, c, d, M_offset_1, 5, T[16]); 9305 d = GG(d, a, b, c, M_offset_6, 9, T[17]); 9306 c = GG(c, d, a, b, M_offset_11, 14, T[18]); 9307 b = GG(b, c, d, a, M_offset_0, 20, T[19]); 9308 a = GG(a, b, c, d, M_offset_5, 5, T[20]); 9309 d = GG(d, a, b, c, M_offset_10, 9, T[21]); 9310 c = GG(c, d, a, b, M_offset_15, 14, T[22]); 9311 b = GG(b, c, d, a, M_offset_4, 20, T[23]); 9312 a = GG(a, b, c, d, M_offset_9, 5, T[24]); 9313 d = GG(d, a, b, c, M_offset_14, 9, T[25]); 9314 c = GG(c, d, a, b, M_offset_3, 14, T[26]); 9315 b = GG(b, c, d, a, M_offset_8, 20, T[27]); 9316 a = GG(a, b, c, d, M_offset_13, 5, T[28]); 9317 d = GG(d, a, b, c, M_offset_2, 9, T[29]); 9318 c = GG(c, d, a, b, M_offset_7, 14, T[30]); 9319 b = GG(b, c, d, a, M_offset_12, 20, T[31]); 9320 9321 a = HH(a, b, c, d, M_offset_5, 4, T[32]); 9322 d = HH(d, a, b, c, M_offset_8, 11, T[33]); 9323 c = HH(c, d, a, b, M_offset_11, 16, T[34]); 9324 b = HH(b, c, d, a, M_offset_14, 23, T[35]); 9325 a = HH(a, b, c, d, M_offset_1, 4, T[36]); 9326 d = HH(d, a, b, c, M_offset_4, 11, T[37]); 9327 c = HH(c, d, a, b, M_offset_7, 16, T[38]); 9328 b = HH(b, c, d, a, M_offset_10, 23, T[39]); 9329 a = HH(a, b, c, d, M_offset_13, 4, T[40]); 9330 d = HH(d, a, b, c, M_offset_0, 11, T[41]); 9331 c = HH(c, d, a, b, M_offset_3, 16, T[42]); 9332 b = HH(b, c, d, a, M_offset_6, 23, T[43]); 9333 a = HH(a, b, c, d, M_offset_9, 4, T[44]); 9334 d = HH(d, a, b, c, M_offset_12, 11, T[45]); 9335 c = HH(c, d, a, b, M_offset_15, 16, T[46]); 9336 b = HH(b, c, d, a, M_offset_2, 23, T[47]); 9337 9338 a = II(a, b, c, d, M_offset_0, 6, T[48]); 9339 d = II(d, a, b, c, M_offset_7, 10, T[49]); 9340 c = II(c, d, a, b, M_offset_14, 15, T[50]); 9341 b = II(b, c, d, a, M_offset_5, 21, T[51]); 9342 a = II(a, b, c, d, M_offset_12, 6, T[52]); 9343 d = II(d, a, b, c, M_offset_3, 10, T[53]); 9344 c = II(c, d, a, b, M_offset_10, 15, T[54]); 9345 b = II(b, c, d, a, M_offset_1, 21, T[55]); 9346 a = II(a, b, c, d, M_offset_8, 6, T[56]); 9347 d = II(d, a, b, c, M_offset_15, 10, T[57]); 9348 c = II(c, d, a, b, M_offset_6, 15, T[58]); 9349 b = II(b, c, d, a, M_offset_13, 21, T[59]); 9350 a = II(a, b, c, d, M_offset_4, 6, T[60]); 9351 d = II(d, a, b, c, M_offset_11, 10, T[61]); 9352 c = II(c, d, a, b, M_offset_2, 15, T[62]); 9353 b = II(b, c, d, a, M_offset_9, 21, T[63]); 9354 9355 // Intermediate hash value 9356 H[0] = (H[0] + a) | 0; 9357 H[1] = (H[1] + b) | 0; 9358 H[2] = (H[2] + c) | 0; 9359 H[3] = (H[3] + d) | 0; 9360 }, 9361 9362 _doFinalize: function () { 9363 // Shortcuts 9364 var data = this._data; 9365 var dataWords = data.words; 9366 9367 var nBitsTotal = this._nDataBytes * 8; 9368 var nBitsLeft = data.sigBytes * 8; 9369 9370 // Add padding 9371 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 9372 9373 var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); 9374 var nBitsTotalL = nBitsTotal; 9375 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( 9376 (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | 9377 (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) 9378 ); 9379 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( 9380 (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | 9381 (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) 9382 ); 9383 9384 data.sigBytes = (dataWords.length + 1) * 4; 9385 9386 // Hash final blocks 9387 this._process(); 9388 9389 // Shortcuts 9390 var hash = this._hash; 9391 var H = hash.words; 9392 9393 // Swap endian 9394 for (var i = 0; i < 4; i++) { 9395 // Shortcut 9396 var H_i = H[i]; 9397 9398 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | 9399 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); 9400 } 9401 9402 // Return final computed hash 9403 return hash; 9404 }, 9405 9406 clone: function () { 9407 var clone = Hasher.clone.call(this); 9408 clone._hash = this._hash.clone(); 9409 9410 return clone; 9411 } 9412 }); 9413 9414 function FF(a, b, c, d, x, s, t) { 9415 var n = a + ((b & c) | (~b & d)) + x + t; 9416 return ((n << s) | (n >>> (32 - s))) + b; 9417 } 9418 9419 function GG(a, b, c, d, x, s, t) { 9420 var n = a + ((b & d) | (c & ~d)) + x + t; 9421 return ((n << s) | (n >>> (32 - s))) + b; 9422 } 9423 9424 function HH(a, b, c, d, x, s, t) { 9425 var n = a + (b ^ c ^ d) + x + t; 9426 return ((n << s) | (n >>> (32 - s))) + b; 9427 } 9428 9429 function II(a, b, c, d, x, s, t) { 9430 var n = a + (c ^ (b | ~d)) + x + t; 9431 return ((n << s) | (n >>> (32 - s))) + b; 9432 } 9433 9434 /** 9435 * Shortcut function to the hasher's object interface. 9436 * 9437 * @param {WordArray|string} message The message to hash. 9438 * 9439 * @return {WordArray} The hash. 9440 * 9441 * @static 9442 * 9443 * @example 9444 * 9445 * var hash = CryptoJS.MD5('message'); 9446 * var hash = CryptoJS.MD5(wordArray); 9447 */ 9448 C.MD5 = Hasher._createHelper(MD5); 9449 9450 /** 9451 * Shortcut function to the HMAC's object interface. 9452 * 9453 * @param {WordArray|string} message The message to hash. 9454 * @param {WordArray|string} key The secret key. 9455 * 9456 * @return {WordArray} The HMAC. 9457 * 9458 * @static 9459 * 9460 * @example 9461 * 9462 * var hmac = CryptoJS.HmacMD5(message, key); 9463 */ 9464 C.HmacMD5 = Hasher._createHmacHelper(MD5); 9465 }(Math)); 9466 9467 9468 return CryptoJS.MD5; 9469 9470 })); 9471 },{"./core":53}],62:[function(require,module,exports){ 9472 ;(function (root, factory, undef) { 9473 if (typeof exports === "object") { 9474 // CommonJS 9475 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9476 } 9477 else if (typeof define === "function" && define.amd) { 9478 // AMD 9479 define(["./core", "./cipher-core"], factory); 9480 } 9481 else { 9482 // Global (browser) 9483 factory(root.CryptoJS); 9484 } 9485 }(this, function (CryptoJS) { 9486 9487 /** 9488 * Cipher Feedback block mode. 9489 */ 9490 CryptoJS.mode.CFB = (function () { 9491 var CFB = CryptoJS.lib.BlockCipherMode.extend(); 9492 9493 CFB.Encryptor = CFB.extend({ 9494 processBlock: function (words, offset) { 9495 // Shortcuts 9496 var cipher = this._cipher; 9497 var blockSize = cipher.blockSize; 9498 9499 generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); 9500 9501 // Remember this block to use with next block 9502 this._prevBlock = words.slice(offset, offset + blockSize); 9503 } 9504 }); 9505 9506 CFB.Decryptor = CFB.extend({ 9507 processBlock: function (words, offset) { 9508 // Shortcuts 9509 var cipher = this._cipher; 9510 var blockSize = cipher.blockSize; 9511 9512 // Remember this block to use with next block 9513 var thisBlock = words.slice(offset, offset + blockSize); 9514 9515 generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); 9516 9517 // This block becomes the previous block 9518 this._prevBlock = thisBlock; 9519 } 9520 }); 9521 9522 function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { 9523 // Shortcut 9524 var iv = this._iv; 9525 9526 // Generate keystream 9527 if (iv) { 9528 var keystream = iv.slice(0); 9529 9530 // Remove IV for subsequent blocks 9531 this._iv = undefined; 9532 } else { 9533 var keystream = this._prevBlock; 9534 } 9535 cipher.encryptBlock(keystream, 0); 9536 9537 // Encrypt 9538 for (var i = 0; i < blockSize; i++) { 9539 words[offset + i] ^= keystream[i]; 9540 } 9541 } 9542 9543 return CFB; 9544 }()); 9545 9546 9547 return CryptoJS.mode.CFB; 9548 9549 })); 9550 },{"./cipher-core":52,"./core":53}],63:[function(require,module,exports){ 9551 ;(function (root, factory, undef) { 9552 if (typeof exports === "object") { 9553 // CommonJS 9554 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9555 } 9556 else if (typeof define === "function" && define.amd) { 9557 // AMD 9558 define(["./core", "./cipher-core"], factory); 9559 } 9560 else { 9561 // Global (browser) 9562 factory(root.CryptoJS); 9563 } 9564 }(this, function (CryptoJS) { 9565 9566 /** @preserve 9567 * Counter block mode compatible with Dr Brian Gladman fileenc.c 9568 * derived from CryptoJS.mode.CTR 9569 * Jan Hruby jhruby.web@gmail.com 9570 */ 9571 CryptoJS.mode.CTRGladman = (function () { 9572 var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); 9573 9574 function incWord(word) 9575 { 9576 if (((word >> 24) & 0xff) === 0xff) { //overflow 9577 var b1 = (word >> 16)&0xff; 9578 var b2 = (word >> 8)&0xff; 9579 var b3 = word & 0xff; 9580 9581 if (b1 === 0xff) // overflow b1 9582 { 9583 b1 = 0; 9584 if (b2 === 0xff) 9585 { 9586 b2 = 0; 9587 if (b3 === 0xff) 9588 { 9589 b3 = 0; 9590 } 9591 else 9592 { 9593 ++b3; 9594 } 9595 } 9596 else 9597 { 9598 ++b2; 9599 } 9600 } 9601 else 9602 { 9603 ++b1; 9604 } 9605 9606 word = 0; 9607 word += (b1 << 16); 9608 word += (b2 << 8); 9609 word += b3; 9610 } 9611 else 9612 { 9613 word += (0x01 << 24); 9614 } 9615 return word; 9616 } 9617 9618 function incCounter(counter) 9619 { 9620 if ((counter[0] = incWord(counter[0])) === 0) 9621 { 9622 // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 9623 counter[1] = incWord(counter[1]); 9624 } 9625 return counter; 9626 } 9627 9628 var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ 9629 processBlock: function (words, offset) { 9630 // Shortcuts 9631 var cipher = this._cipher 9632 var blockSize = cipher.blockSize; 9633 var iv = this._iv; 9634 var counter = this._counter; 9635 9636 // Generate keystream 9637 if (iv) { 9638 counter = this._counter = iv.slice(0); 9639 9640 // Remove IV for subsequent blocks 9641 this._iv = undefined; 9642 } 9643 9644 incCounter(counter); 9645 9646 var keystream = counter.slice(0); 9647 cipher.encryptBlock(keystream, 0); 9648 9649 // Encrypt 9650 for (var i = 0; i < blockSize; i++) { 9651 words[offset + i] ^= keystream[i]; 9652 } 9653 } 9654 }); 9655 9656 CTRGladman.Decryptor = Encryptor; 9657 9658 return CTRGladman; 9659 }()); 9660 9661 9662 9663 9664 return CryptoJS.mode.CTRGladman; 9665 9666 })); 9667 },{"./cipher-core":52,"./core":53}],64:[function(require,module,exports){ 9668 ;(function (root, factory, undef) { 9669 if (typeof exports === "object") { 9670 // CommonJS 9671 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9672 } 9673 else if (typeof define === "function" && define.amd) { 9674 // AMD 9675 define(["./core", "./cipher-core"], factory); 9676 } 9677 else { 9678 // Global (browser) 9679 factory(root.CryptoJS); 9680 } 9681 }(this, function (CryptoJS) { 9682 9683 /** 9684 * Counter block mode. 9685 */ 9686 CryptoJS.mode.CTR = (function () { 9687 var CTR = CryptoJS.lib.BlockCipherMode.extend(); 9688 9689 var Encryptor = CTR.Encryptor = CTR.extend({ 9690 processBlock: function (words, offset) { 9691 // Shortcuts 9692 var cipher = this._cipher 9693 var blockSize = cipher.blockSize; 9694 var iv = this._iv; 9695 var counter = this._counter; 9696 9697 // Generate keystream 9698 if (iv) { 9699 counter = this._counter = iv.slice(0); 9700 9701 // Remove IV for subsequent blocks 9702 this._iv = undefined; 9703 } 9704 var keystream = counter.slice(0); 9705 cipher.encryptBlock(keystream, 0); 9706 9707 // Increment counter 9708 counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 9709 9710 // Encrypt 9711 for (var i = 0; i < blockSize; i++) { 9712 words[offset + i] ^= keystream[i]; 9713 } 9714 } 9715 }); 9716 9717 CTR.Decryptor = Encryptor; 9718 9719 return CTR; 9720 }()); 9721 9722 9723 return CryptoJS.mode.CTR; 9724 9725 })); 9726 },{"./cipher-core":52,"./core":53}],65:[function(require,module,exports){ 9727 ;(function (root, factory, undef) { 9728 if (typeof exports === "object") { 9729 // CommonJS 9730 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9731 } 9732 else if (typeof define === "function" && define.amd) { 9733 // AMD 9734 define(["./core", "./cipher-core"], factory); 9735 } 9736 else { 9737 // Global (browser) 9738 factory(root.CryptoJS); 9739 } 9740 }(this, function (CryptoJS) { 9741 9742 /** 9743 * Electronic Codebook block mode. 9744 */ 9745 CryptoJS.mode.ECB = (function () { 9746 var ECB = CryptoJS.lib.BlockCipherMode.extend(); 9747 9748 ECB.Encryptor = ECB.extend({ 9749 processBlock: function (words, offset) { 9750 this._cipher.encryptBlock(words, offset); 9751 } 9752 }); 9753 9754 ECB.Decryptor = ECB.extend({ 9755 processBlock: function (words, offset) { 9756 this._cipher.decryptBlock(words, offset); 9757 } 9758 }); 9759 9760 return ECB; 9761 }()); 9762 9763 9764 return CryptoJS.mode.ECB; 9765 9766 })); 9767 },{"./cipher-core":52,"./core":53}],66:[function(require,module,exports){ 9768 ;(function (root, factory, undef) { 9769 if (typeof exports === "object") { 9770 // CommonJS 9771 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9772 } 9773 else if (typeof define === "function" && define.amd) { 9774 // AMD 9775 define(["./core", "./cipher-core"], factory); 9776 } 9777 else { 9778 // Global (browser) 9779 factory(root.CryptoJS); 9780 } 9781 }(this, function (CryptoJS) { 9782 9783 /** 9784 * Output Feedback block mode. 9785 */ 9786 CryptoJS.mode.OFB = (function () { 9787 var OFB = CryptoJS.lib.BlockCipherMode.extend(); 9788 9789 var Encryptor = OFB.Encryptor = OFB.extend({ 9790 processBlock: function (words, offset) { 9791 // Shortcuts 9792 var cipher = this._cipher 9793 var blockSize = cipher.blockSize; 9794 var iv = this._iv; 9795 var keystream = this._keystream; 9796 9797 // Generate keystream 9798 if (iv) { 9799 keystream = this._keystream = iv.slice(0); 9800 9801 // Remove IV for subsequent blocks 9802 this._iv = undefined; 9803 } 9804 cipher.encryptBlock(keystream, 0); 9805 9806 // Encrypt 9807 for (var i = 0; i < blockSize; i++) { 9808 words[offset + i] ^= keystream[i]; 9809 } 9810 } 9811 }); 9812 9813 OFB.Decryptor = Encryptor; 9814 9815 return OFB; 9816 }()); 9817 9818 9819 return CryptoJS.mode.OFB; 9820 9821 })); 9822 },{"./cipher-core":52,"./core":53}],67:[function(require,module,exports){ 9823 ;(function (root, factory, undef) { 9824 if (typeof exports === "object") { 9825 // CommonJS 9826 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9827 } 9828 else if (typeof define === "function" && define.amd) { 9829 // AMD 9830 define(["./core", "./cipher-core"], factory); 9831 } 9832 else { 9833 // Global (browser) 9834 factory(root.CryptoJS); 9835 } 9836 }(this, function (CryptoJS) { 9837 9838 /** 9839 * ANSI X.923 padding strategy. 9840 */ 9841 CryptoJS.pad.AnsiX923 = { 9842 pad: function (data, blockSize) { 9843 // Shortcuts 9844 var dataSigBytes = data.sigBytes; 9845 var blockSizeBytes = blockSize * 4; 9846 9847 // Count padding bytes 9848 var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; 9849 9850 // Compute last byte position 9851 var lastBytePos = dataSigBytes + nPaddingBytes - 1; 9852 9853 // Pad 9854 data.clamp(); 9855 data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); 9856 data.sigBytes += nPaddingBytes; 9857 }, 9858 9859 unpad: function (data) { 9860 // Get number of padding bytes from last byte 9861 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 9862 9863 // Remove padding 9864 data.sigBytes -= nPaddingBytes; 9865 } 9866 }; 9867 9868 9869 return CryptoJS.pad.Ansix923; 9870 9871 })); 9872 },{"./cipher-core":52,"./core":53}],68:[function(require,module,exports){ 9873 ;(function (root, factory, undef) { 9874 if (typeof exports === "object") { 9875 // CommonJS 9876 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9877 } 9878 else if (typeof define === "function" && define.amd) { 9879 // AMD 9880 define(["./core", "./cipher-core"], factory); 9881 } 9882 else { 9883 // Global (browser) 9884 factory(root.CryptoJS); 9885 } 9886 }(this, function (CryptoJS) { 9887 9888 /** 9889 * ISO 10126 padding strategy. 9890 */ 9891 CryptoJS.pad.Iso10126 = { 9892 pad: function (data, blockSize) { 9893 // Shortcut 9894 var blockSizeBytes = blockSize * 4; 9895 9896 // Count padding bytes 9897 var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; 9898 9899 // Pad 9900 data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). 9901 concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); 9902 }, 9903 9904 unpad: function (data) { 9905 // Get number of padding bytes from last byte 9906 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 9907 9908 // Remove padding 9909 data.sigBytes -= nPaddingBytes; 9910 } 9911 }; 9912 9913 9914 return CryptoJS.pad.Iso10126; 9915 9916 })); 9917 },{"./cipher-core":52,"./core":53}],69:[function(require,module,exports){ 9918 ;(function (root, factory, undef) { 9919 if (typeof exports === "object") { 9920 // CommonJS 9921 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9922 } 9923 else if (typeof define === "function" && define.amd) { 9924 // AMD 9925 define(["./core", "./cipher-core"], factory); 9926 } 9927 else { 9928 // Global (browser) 9929 factory(root.CryptoJS); 9930 } 9931 }(this, function (CryptoJS) { 9932 9933 /** 9934 * ISO/IEC 9797-1 Padding Method 2. 9935 */ 9936 CryptoJS.pad.Iso97971 = { 9937 pad: function (data, blockSize) { 9938 // Add 0x80 byte 9939 data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); 9940 9941 // Zero pad the rest 9942 CryptoJS.pad.ZeroPadding.pad(data, blockSize); 9943 }, 9944 9945 unpad: function (data) { 9946 // Remove zero padding 9947 CryptoJS.pad.ZeroPadding.unpad(data); 9948 9949 // Remove one more byte -- the 0x80 byte 9950 data.sigBytes--; 9951 } 9952 }; 9953 9954 9955 return CryptoJS.pad.Iso97971; 9956 9957 })); 9958 },{"./cipher-core":52,"./core":53}],70:[function(require,module,exports){ 9959 ;(function (root, factory, undef) { 9960 if (typeof exports === "object") { 9961 // CommonJS 9962 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9963 } 9964 else if (typeof define === "function" && define.amd) { 9965 // AMD 9966 define(["./core", "./cipher-core"], factory); 9967 } 9968 else { 9969 // Global (browser) 9970 factory(root.CryptoJS); 9971 } 9972 }(this, function (CryptoJS) { 9973 9974 /** 9975 * A noop padding strategy. 9976 */ 9977 CryptoJS.pad.NoPadding = { 9978 pad: function () { 9979 }, 9980 9981 unpad: function () { 9982 } 9983 }; 9984 9985 9986 return CryptoJS.pad.NoPadding; 9987 9988 })); 9989 },{"./cipher-core":52,"./core":53}],71:[function(require,module,exports){ 9990 ;(function (root, factory, undef) { 9991 if (typeof exports === "object") { 9992 // CommonJS 9993 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9994 } 9995 else if (typeof define === "function" && define.amd) { 9996 // AMD 9997 define(["./core", "./cipher-core"], factory); 9998 } 9999 else { 10000 // Global (browser) 10001 factory(root.CryptoJS); 10002 } 10003 }(this, function (CryptoJS) { 10004 10005 /** 10006 * Zero padding strategy. 10007 */ 10008 CryptoJS.pad.ZeroPadding = { 10009 pad: function (data, blockSize) { 10010 // Shortcut 10011 var blockSizeBytes = blockSize * 4; 10012 10013 // Pad 10014 data.clamp(); 10015 data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); 10016 }, 10017 10018 unpad: function (data) { 10019 // Shortcut 10020 var dataWords = data.words; 10021 10022 // Unpad 10023 var i = data.sigBytes - 1; 10024 while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { 10025 i--; 10026 } 10027 data.sigBytes = i + 1; 10028 } 10029 }; 10030 10031 10032 return CryptoJS.pad.ZeroPadding; 10033 10034 })); 10035 },{"./cipher-core":52,"./core":53}],72:[function(require,module,exports){ 10036 ;(function (root, factory, undef) { 10037 if (typeof exports === "object") { 10038 // CommonJS 10039 module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); 10040 } 10041 else if (typeof define === "function" && define.amd) { 10042 // AMD 10043 define(["./core", "./sha1", "./hmac"], factory); 10044 } 10045 else { 10046 // Global (browser) 10047 factory(root.CryptoJS); 10048 } 10049 }(this, function (CryptoJS) { 10050 10051 (function () { 10052 // Shortcuts 10053 var C = CryptoJS; 10054 var C_lib = C.lib; 10055 var Base = C_lib.Base; 10056 var WordArray = C_lib.WordArray; 10057 var C_algo = C.algo; 10058 var SHA1 = C_algo.SHA1; 10059 var HMAC = C_algo.HMAC; 10060 10061 /** 10062 * Password-Based Key Derivation Function 2 algorithm. 10063 */ 10064 var PBKDF2 = C_algo.PBKDF2 = Base.extend({ 10065 /** 10066 * Configuration options. 10067 * 10068 * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) 10069 * @property {Hasher} hasher The hasher to use. Default: SHA1 10070 * @property {number} iterations The number of iterations to perform. Default: 1 10071 */ 10072 cfg: Base.extend({ 10073 keySize: 128/32, 10074 hasher: SHA1, 10075 iterations: 1 10076 }), 10077 10078 /** 10079 * Initializes a newly created key derivation function. 10080 * 10081 * @param {Object} cfg (Optional) The configuration options to use for the derivation. 10082 * 10083 * @example 10084 * 10085 * var kdf = CryptoJS.algo.PBKDF2.create(); 10086 * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); 10087 * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); 10088 */ 10089 init: function (cfg) { 10090 this.cfg = this.cfg.extend(cfg); 10091 }, 10092 10093 /** 10094 * Computes the Password-Based Key Derivation Function 2. 10095 * 10096 * @param {WordArray|string} password The password. 10097 * @param {WordArray|string} salt A salt. 10098 * 10099 * @return {WordArray} The derived key. 10100 * 10101 * @example 10102 * 10103 * var key = kdf.compute(password, salt); 10104 */ 10105 compute: function (password, salt) { 10106 // Shortcut 10107 var cfg = this.cfg; 10108 10109 // Init HMAC 10110 var hmac = HMAC.create(cfg.hasher, password); 10111 10112 // Initial values 10113 var derivedKey = WordArray.create(); 10114 var blockIndex = WordArray.create([0x00000001]); 10115 10116 // Shortcuts 10117 var derivedKeyWords = derivedKey.words; 10118 var blockIndexWords = blockIndex.words; 10119 var keySize = cfg.keySize; 10120 var iterations = cfg.iterations; 10121 10122 // Generate key 10123 while (derivedKeyWords.length < keySize) { 10124 var block = hmac.update(salt).finalize(blockIndex); 10125 hmac.reset(); 10126 10127 // Shortcuts 10128 var blockWords = block.words; 10129 var blockWordsLength = blockWords.length; 10130 10131 // Iterations 10132 var intermediate = block; 10133 for (var i = 1; i < iterations; i++) { 10134 intermediate = hmac.finalize(intermediate); 10135 hmac.reset(); 10136 10137 // Shortcut 10138 var intermediateWords = intermediate.words; 10139 10140 // XOR intermediate with block 10141 for (var j = 0; j < blockWordsLength; j++) { 10142 blockWords[j] ^= intermediateWords[j]; 10143 } 10144 } 10145 10146 derivedKey.concat(block); 10147 blockIndexWords[0]++; 10148 } 10149 derivedKey.sigBytes = keySize * 4; 10150 10151 return derivedKey; 10152 } 10153 }); 10154 10155 /** 10156 * Computes the Password-Based Key Derivation Function 2. 10157 * 10158 * @param {WordArray|string} password The password. 10159 * @param {WordArray|string} salt A salt. 10160 * @param {Object} cfg (Optional) The configuration options to use for this computation. 10161 * 10162 * @return {WordArray} The derived key. 10163 * 10164 * @static 10165 * 10166 * @example 10167 * 10168 * var key = CryptoJS.PBKDF2(password, salt); 10169 * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); 10170 * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); 10171 */ 10172 C.PBKDF2 = function (password, salt, cfg) { 10173 return PBKDF2.create(cfg).compute(password, salt); 10174 }; 10175 }()); 10176 10177 10178 return CryptoJS.PBKDF2; 10179 10180 })); 10181 },{"./core":53,"./hmac":58,"./sha1":77}],73:[function(require,module,exports){ 10182 ;(function (root, factory, undef) { 10183 if (typeof exports === "object") { 10184 // CommonJS 10185 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10186 } 10187 else if (typeof define === "function" && define.amd) { 10188 // AMD 10189 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10190 } 10191 else { 10192 // Global (browser) 10193 factory(root.CryptoJS); 10194 } 10195 }(this, function (CryptoJS) { 10196 10197 (function () { 10198 // Shortcuts 10199 var C = CryptoJS; 10200 var C_lib = C.lib; 10201 var StreamCipher = C_lib.StreamCipher; 10202 var C_algo = C.algo; 10203 10204 // Reusable objects 10205 var S = []; 10206 var C_ = []; 10207 var G = []; 10208 10209 /** 10210 * Rabbit stream cipher algorithm. 10211 * 10212 * This is a legacy version that neglected to convert the key to little-endian. 10213 * This error doesn't affect the cipher's security, 10214 * but it does affect its compatibility with other implementations. 10215 */ 10216 var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ 10217 _doReset: function () { 10218 // Shortcuts 10219 var K = this._key.words; 10220 var iv = this.cfg.iv; 10221 10222 // Generate initial state values 10223 var X = this._X = [ 10224 K[0], (K[3] << 16) | (K[2] >>> 16), 10225 K[1], (K[0] << 16) | (K[3] >>> 16), 10226 K[2], (K[1] << 16) | (K[0] >>> 16), 10227 K[3], (K[2] << 16) | (K[1] >>> 16) 10228 ]; 10229 10230 // Generate initial counter values 10231 var C = this._C = [ 10232 (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), 10233 (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), 10234 (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), 10235 (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) 10236 ]; 10237 10238 // Carry bit 10239 this._b = 0; 10240 10241 // Iterate the system four times 10242 for (var i = 0; i < 4; i++) { 10243 nextState.call(this); 10244 } 10245 10246 // Modify the counters 10247 for (var i = 0; i < 8; i++) { 10248 C[i] ^= X[(i + 4) & 7]; 10249 } 10250 10251 // IV setup 10252 if (iv) { 10253 // Shortcuts 10254 var IV = iv.words; 10255 var IV_0 = IV[0]; 10256 var IV_1 = IV[1]; 10257 10258 // Generate four subvectors 10259 var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); 10260 var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); 10261 var i1 = (i0 >>> 16) | (i2 & 0xffff0000); 10262 var i3 = (i2 << 16) | (i0 & 0x0000ffff); 10263 10264 // Modify counter values 10265 C[0] ^= i0; 10266 C[1] ^= i1; 10267 C[2] ^= i2; 10268 C[3] ^= i3; 10269 C[4] ^= i0; 10270 C[5] ^= i1; 10271 C[6] ^= i2; 10272 C[7] ^= i3; 10273 10274 // Iterate the system four times 10275 for (var i = 0; i < 4; i++) { 10276 nextState.call(this); 10277 } 10278 } 10279 }, 10280 10281 _doProcessBlock: function (M, offset) { 10282 // Shortcut 10283 var X = this._X; 10284 10285 // Iterate the system 10286 nextState.call(this); 10287 10288 // Generate four keystream words 10289 S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); 10290 S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); 10291 S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); 10292 S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); 10293 10294 for (var i = 0; i < 4; i++) { 10295 // Swap endian 10296 S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | 10297 (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); 10298 10299 // Encrypt 10300 M[offset + i] ^= S[i]; 10301 } 10302 }, 10303 10304 blockSize: 128/32, 10305 10306 ivSize: 64/32 10307 }); 10308 10309 function nextState() { 10310 // Shortcuts 10311 var X = this._X; 10312 var C = this._C; 10313 10314 // Save old counter values 10315 for (var i = 0; i < 8; i++) { 10316 C_[i] = C[i]; 10317 } 10318 10319 // Calculate new counter values 10320 C[0] = (C[0] + 0x4d34d34d + this._b) | 0; 10321 C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; 10322 C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; 10323 C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; 10324 C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; 10325 C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; 10326 C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; 10327 C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; 10328 this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; 10329 10330 // Calculate the g-values 10331 for (var i = 0; i < 8; i++) { 10332 var gx = X[i] + C[i]; 10333 10334 // Construct high and low argument for squaring 10335 var ga = gx & 0xffff; 10336 var gb = gx >>> 16; 10337 10338 // Calculate high and low result of squaring 10339 var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; 10340 var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); 10341 10342 // High XOR low 10343 G[i] = gh ^ gl; 10344 } 10345 10346 // Calculate new state values 10347 X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; 10348 X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; 10349 X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; 10350 X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; 10351 X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; 10352 X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; 10353 X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; 10354 X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; 10355 } 10356 10357 /** 10358 * Shortcut functions to the cipher's object interface. 10359 * 10360 * @example 10361 * 10362 * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); 10363 * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); 10364 */ 10365 C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); 10366 }()); 10367 10368 10369 return CryptoJS.RabbitLegacy; 10370 10371 })); 10372 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],74:[function(require,module,exports){ 10373 ;(function (root, factory, undef) { 10374 if (typeof exports === "object") { 10375 // CommonJS 10376 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10377 } 10378 else if (typeof define === "function" && define.amd) { 10379 // AMD 10380 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10381 } 10382 else { 10383 // Global (browser) 10384 factory(root.CryptoJS); 10385 } 10386 }(this, function (CryptoJS) { 10387 10388 (function () { 10389 // Shortcuts 10390 var C = CryptoJS; 10391 var C_lib = C.lib; 10392 var StreamCipher = C_lib.StreamCipher; 10393 var C_algo = C.algo; 10394 10395 // Reusable objects 10396 var S = []; 10397 var C_ = []; 10398 var G = []; 10399 10400 /** 10401 * Rabbit stream cipher algorithm 10402 */ 10403 var Rabbit = C_algo.Rabbit = StreamCipher.extend({ 10404 _doReset: function () { 10405 // Shortcuts 10406 var K = this._key.words; 10407 var iv = this.cfg.iv; 10408 10409 // Swap endian 10410 for (var i = 0; i < 4; i++) { 10411 K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | 10412 (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); 10413 } 10414 10415 // Generate initial state values 10416 var X = this._X = [ 10417 K[0], (K[3] << 16) | (K[2] >>> 16), 10418 K[1], (K[0] << 16) | (K[3] >>> 16), 10419 K[2], (K[1] << 16) | (K[0] >>> 16), 10420 K[3], (K[2] << 16) | (K[1] >>> 16) 10421 ]; 10422 10423 // Generate initial counter values 10424 var C = this._C = [ 10425 (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), 10426 (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), 10427 (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), 10428 (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) 10429 ]; 10430 10431 // Carry bit 10432 this._b = 0; 10433 10434 // Iterate the system four times 10435 for (var i = 0; i < 4; i++) { 10436 nextState.call(this); 10437 } 10438 10439 // Modify the counters 10440 for (var i = 0; i < 8; i++) { 10441 C[i] ^= X[(i + 4) & 7]; 10442 } 10443 10444 // IV setup 10445 if (iv) { 10446 // Shortcuts 10447 var IV = iv.words; 10448 var IV_0 = IV[0]; 10449 var IV_1 = IV[1]; 10450 10451 // Generate four subvectors 10452 var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); 10453 var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); 10454 var i1 = (i0 >>> 16) | (i2 & 0xffff0000); 10455 var i3 = (i2 << 16) | (i0 & 0x0000ffff); 10456 10457 // Modify counter values 10458 C[0] ^= i0; 10459 C[1] ^= i1; 10460 C[2] ^= i2; 10461 C[3] ^= i3; 10462 C[4] ^= i0; 10463 C[5] ^= i1; 10464 C[6] ^= i2; 10465 C[7] ^= i3; 10466 10467 // Iterate the system four times 10468 for (var i = 0; i < 4; i++) { 10469 nextState.call(this); 10470 } 10471 } 10472 }, 10473 10474 _doProcessBlock: function (M, offset) { 10475 // Shortcut 10476 var X = this._X; 10477 10478 // Iterate the system 10479 nextState.call(this); 10480 10481 // Generate four keystream words 10482 S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); 10483 S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); 10484 S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); 10485 S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); 10486 10487 for (var i = 0; i < 4; i++) { 10488 // Swap endian 10489 S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | 10490 (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); 10491 10492 // Encrypt 10493 M[offset + i] ^= S[i]; 10494 } 10495 }, 10496 10497 blockSize: 128/32, 10498 10499 ivSize: 64/32 10500 }); 10501 10502 function nextState() { 10503 // Shortcuts 10504 var X = this._X; 10505 var C = this._C; 10506 10507 // Save old counter values 10508 for (var i = 0; i < 8; i++) { 10509 C_[i] = C[i]; 10510 } 10511 10512 // Calculate new counter values 10513 C[0] = (C[0] + 0x4d34d34d + this._b) | 0; 10514 C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; 10515 C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; 10516 C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; 10517 C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; 10518 C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; 10519 C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; 10520 C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; 10521 this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; 10522 10523 // Calculate the g-values 10524 for (var i = 0; i < 8; i++) { 10525 var gx = X[i] + C[i]; 10526 10527 // Construct high and low argument for squaring 10528 var ga = gx & 0xffff; 10529 var gb = gx >>> 16; 10530 10531 // Calculate high and low result of squaring 10532 var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; 10533 var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); 10534 10535 // High XOR low 10536 G[i] = gh ^ gl; 10537 } 10538 10539 // Calculate new state values 10540 X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; 10541 X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; 10542 X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; 10543 X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; 10544 X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; 10545 X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; 10546 X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; 10547 X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; 10548 } 10549 10550 /** 10551 * Shortcut functions to the cipher's object interface. 10552 * 10553 * @example 10554 * 10555 * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); 10556 * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); 10557 */ 10558 C.Rabbit = StreamCipher._createHelper(Rabbit); 10559 }()); 10560 10561 10562 return CryptoJS.Rabbit; 10563 10564 })); 10565 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],75:[function(require,module,exports){ 10566 ;(function (root, factory, undef) { 10567 if (typeof exports === "object") { 10568 // CommonJS 10569 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10570 } 10571 else if (typeof define === "function" && define.amd) { 10572 // AMD 10573 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10574 } 10575 else { 10576 // Global (browser) 10577 factory(root.CryptoJS); 10578 } 10579 }(this, function (CryptoJS) { 10580 10581 (function () { 10582 // Shortcuts 10583 var C = CryptoJS; 10584 var C_lib = C.lib; 10585 var StreamCipher = C_lib.StreamCipher; 10586 var C_algo = C.algo; 10587 10588 /** 10589 * RC4 stream cipher algorithm. 10590 */ 10591 var RC4 = C_algo.RC4 = StreamCipher.extend({ 10592 _doReset: function () { 10593 // Shortcuts 10594 var key = this._key; 10595 var keyWords = key.words; 10596 var keySigBytes = key.sigBytes; 10597 10598 // Init sbox 10599 var S = this._S = []; 10600 for (var i = 0; i < 256; i++) { 10601 S[i] = i; 10602 } 10603 10604 // Key setup 10605 for (var i = 0, j = 0; i < 256; i++) { 10606 var keyByteIndex = i % keySigBytes; 10607 var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; 10608 10609 j = (j + S[i] + keyByte) % 256; 10610 10611 // Swap 10612 var t = S[i]; 10613 S[i] = S[j]; 10614 S[j] = t; 10615 } 10616 10617 // Counters 10618 this._i = this._j = 0; 10619 }, 10620 10621 _doProcessBlock: function (M, offset) { 10622 M[offset] ^= generateKeystreamWord.call(this); 10623 }, 10624 10625 keySize: 256/32, 10626 10627 ivSize: 0 10628 }); 10629 10630 function generateKeystreamWord() { 10631 // Shortcuts 10632 var S = this._S; 10633 var i = this._i; 10634 var j = this._j; 10635 10636 // Generate keystream word 10637 var keystreamWord = 0; 10638 for (var n = 0; n < 4; n++) { 10639 i = (i + 1) % 256; 10640 j = (j + S[i]) % 256; 10641 10642 // Swap 10643 var t = S[i]; 10644 S[i] = S[j]; 10645 S[j] = t; 10646 10647 keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); 10648 } 10649 10650 // Update counters 10651 this._i = i; 10652 this._j = j; 10653 10654 return keystreamWord; 10655 } 10656 10657 /** 10658 * Shortcut functions to the cipher's object interface. 10659 * 10660 * @example 10661 * 10662 * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); 10663 * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); 10664 */ 10665 C.RC4 = StreamCipher._createHelper(RC4); 10666 10667 /** 10668 * Modified RC4 stream cipher algorithm. 10669 */ 10670 var RC4Drop = C_algo.RC4Drop = RC4.extend({ 10671 /** 10672 * Configuration options. 10673 * 10674 * @property {number} drop The number of keystream words to drop. Default 192 10675 */ 10676 cfg: RC4.cfg.extend({ 10677 drop: 192 10678 }), 10679 10680 _doReset: function () { 10681 RC4._doReset.call(this); 10682 10683 // Drop 10684 for (var i = this.cfg.drop; i > 0; i--) { 10685 generateKeystreamWord.call(this); 10686 } 10687 } 10688 }); 10689 10690 /** 10691 * Shortcut functions to the cipher's object interface. 10692 * 10693 * @example 10694 * 10695 * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); 10696 * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); 10697 */ 10698 C.RC4Drop = StreamCipher._createHelper(RC4Drop); 10699 }()); 10700 10701 10702 return CryptoJS.RC4; 10703 10704 })); 10705 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],76:[function(require,module,exports){ 10706 ;(function (root, factory) { 10707 if (typeof exports === "object") { 10708 // CommonJS 10709 module.exports = exports = factory(require("./core")); 10710 } 10711 else if (typeof define === "function" && define.amd) { 10712 // AMD 10713 define(["./core"], factory); 10714 } 10715 else { 10716 // Global (browser) 10717 factory(root.CryptoJS); 10718 } 10719 }(this, function (CryptoJS) { 10720 10721 /** @preserve 10722 (c) 2012 by Cédric Mesnil. All rights reserved. 10723 10724 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 10725 10726 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 10727 - 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. 10728 10729 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. 10730 */ 10731 10732 (function (Math) { 10733 // Shortcuts 10734 var C = CryptoJS; 10735 var C_lib = C.lib; 10736 var WordArray = C_lib.WordArray; 10737 var Hasher = C_lib.Hasher; 10738 var C_algo = C.algo; 10739 10740 // Constants table 10741 var _zl = WordArray.create([ 10742 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 10743 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 10744 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 10745 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 10746 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); 10747 var _zr = WordArray.create([ 10748 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 10749 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 10750 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 10751 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 10752 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); 10753 var _sl = WordArray.create([ 10754 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 10755 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 10756 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 10757 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 10758 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); 10759 var _sr = WordArray.create([ 10760 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 10761 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 10762 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 10763 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 10764 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); 10765 10766 var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); 10767 var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); 10768 10769 /** 10770 * RIPEMD160 hash algorithm. 10771 */ 10772 var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ 10773 _doReset: function () { 10774 this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); 10775 }, 10776 10777 _doProcessBlock: function (M, offset) { 10778 10779 // Swap endian 10780 for (var i = 0; i < 16; i++) { 10781 // Shortcuts 10782 var offset_i = offset + i; 10783 var M_offset_i = M[offset_i]; 10784 10785 // Swap 10786 M[offset_i] = ( 10787 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | 10788 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) 10789 ); 10790 } 10791 // Shortcut 10792 var H = this._hash.words; 10793 var hl = _hl.words; 10794 var hr = _hr.words; 10795 var zl = _zl.words; 10796 var zr = _zr.words; 10797 var sl = _sl.words; 10798 var sr = _sr.words; 10799 10800 // Working variables 10801 var al, bl, cl, dl, el; 10802 var ar, br, cr, dr, er; 10803 10804 ar = al = H[0]; 10805 br = bl = H[1]; 10806 cr = cl = H[2]; 10807 dr = dl = H[3]; 10808 er = el = H[4]; 10809 // Computation 10810 var t; 10811 for (var i = 0; i < 80; i += 1) { 10812 t = (al + M[offset+zl[i]])|0; 10813 if (i<16){ 10814 t += f1(bl,cl,dl) + hl[0]; 10815 } else if (i<32) { 10816 t += f2(bl,cl,dl) + hl[1]; 10817 } else if (i<48) { 10818 t += f3(bl,cl,dl) + hl[2]; 10819 } else if (i<64) { 10820 t += f4(bl,cl,dl) + hl[3]; 10821 } else {// if (i<80) { 10822 t += f5(bl,cl,dl) + hl[4]; 10823 } 10824 t = t|0; 10825 t = rotl(t,sl[i]); 10826 t = (t+el)|0; 10827 al = el; 10828 el = dl; 10829 dl = rotl(cl, 10); 10830 cl = bl; 10831 bl = t; 10832 10833 t = (ar + M[offset+zr[i]])|0; 10834 if (i<16){ 10835 t += f5(br,cr,dr) + hr[0]; 10836 } else if (i<32) { 10837 t += f4(br,cr,dr) + hr[1]; 10838 } else if (i<48) { 10839 t += f3(br,cr,dr) + hr[2]; 10840 } else if (i<64) { 10841 t += f2(br,cr,dr) + hr[3]; 10842 } else {// if (i<80) { 10843 t += f1(br,cr,dr) + hr[4]; 10844 } 10845 t = t|0; 10846 t = rotl(t,sr[i]) ; 10847 t = (t+er)|0; 10848 ar = er; 10849 er = dr; 10850 dr = rotl(cr, 10); 10851 cr = br; 10852 br = t; 10853 } 10854 // Intermediate hash value 10855 t = (H[1] + cl + dr)|0; 10856 H[1] = (H[2] + dl + er)|0; 10857 H[2] = (H[3] + el + ar)|0; 10858 H[3] = (H[4] + al + br)|0; 10859 H[4] = (H[0] + bl + cr)|0; 10860 H[0] = t; 10861 }, 10862 10863 _doFinalize: function () { 10864 // Shortcuts 10865 var data = this._data; 10866 var dataWords = data.words; 10867 10868 var nBitsTotal = this._nDataBytes * 8; 10869 var nBitsLeft = data.sigBytes * 8; 10870 10871 // Add padding 10872 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 10873 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( 10874 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | 10875 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) 10876 ); 10877 data.sigBytes = (dataWords.length + 1) * 4; 10878 10879 // Hash final blocks 10880 this._process(); 10881 10882 // Shortcuts 10883 var hash = this._hash; 10884 var H = hash.words; 10885 10886 // Swap endian 10887 for (var i = 0; i < 5; i++) { 10888 // Shortcut 10889 var H_i = H[i]; 10890 10891 // Swap 10892 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | 10893 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); 10894 } 10895 10896 // Return final computed hash 10897 return hash; 10898 }, 10899 10900 clone: function () { 10901 var clone = Hasher.clone.call(this); 10902 clone._hash = this._hash.clone(); 10903 10904 return clone; 10905 } 10906 }); 10907 10908 10909 function f1(x, y, z) { 10910 return ((x) ^ (y) ^ (z)); 10911 10912 } 10913 10914 function f2(x, y, z) { 10915 return (((x)&(y)) | ((~x)&(z))); 10916 } 10917 10918 function f3(x, y, z) { 10919 return (((x) | (~(y))) ^ (z)); 10920 } 10921 10922 function f4(x, y, z) { 10923 return (((x) & (z)) | ((y)&(~(z)))); 10924 } 10925 10926 function f5(x, y, z) { 10927 return ((x) ^ ((y) |(~(z)))); 10928 10929 } 10930 10931 function rotl(x,n) { 10932 return (x<<n) | (x>>>(32-n)); 10933 } 10934 10935 10936 /** 10937 * Shortcut function to the hasher's object interface. 10938 * 10939 * @param {WordArray|string} message The message to hash. 10940 * 10941 * @return {WordArray} The hash. 10942 * 10943 * @static 10944 * 10945 * @example 10946 * 10947 * var hash = CryptoJS.RIPEMD160('message'); 10948 * var hash = CryptoJS.RIPEMD160(wordArray); 10949 */ 10950 C.RIPEMD160 = Hasher._createHelper(RIPEMD160); 10951 10952 /** 10953 * Shortcut function to the HMAC's object interface. 10954 * 10955 * @param {WordArray|string} message The message to hash. 10956 * @param {WordArray|string} key The secret key. 10957 * 10958 * @return {WordArray} The HMAC. 10959 * 10960 * @static 10961 * 10962 * @example 10963 * 10964 * var hmac = CryptoJS.HmacRIPEMD160(message, key); 10965 */ 10966 C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); 10967 }(Math)); 10968 10969 10970 return CryptoJS.RIPEMD160; 10971 10972 })); 10973 },{"./core":53}],77:[function(require,module,exports){ 10974 ;(function (root, factory) { 10975 if (typeof exports === "object") { 10976 // CommonJS 10977 module.exports = exports = factory(require("./core")); 10978 } 10979 else if (typeof define === "function" && define.amd) { 10980 // AMD 10981 define(["./core"], factory); 10982 } 10983 else { 10984 // Global (browser) 10985 factory(root.CryptoJS); 10986 } 10987 }(this, function (CryptoJS) { 10988 10989 (function () { 10990 // Shortcuts 10991 var C = CryptoJS; 10992 var C_lib = C.lib; 10993 var WordArray = C_lib.WordArray; 10994 var Hasher = C_lib.Hasher; 10995 var C_algo = C.algo; 10996 10997 // Reusable object 10998 var W = []; 10999 11000 /** 11001 * SHA-1 hash algorithm. 11002 */ 11003 var SHA1 = C_algo.SHA1 = Hasher.extend({ 11004 _doReset: function () { 11005 this._hash = new WordArray.init([ 11006 0x67452301, 0xefcdab89, 11007 0x98badcfe, 0x10325476, 11008 0xc3d2e1f0 11009 ]); 11010 }, 11011 11012 _doProcessBlock: function (M, offset) { 11013 // Shortcut 11014 var H = this._hash.words; 11015 11016 // Working variables 11017 var a = H[0]; 11018 var b = H[1]; 11019 var c = H[2]; 11020 var d = H[3]; 11021 var e = H[4]; 11022 11023 // Computation 11024 for (var i = 0; i < 80; i++) { 11025 if (i < 16) { 11026 W[i] = M[offset + i] | 0; 11027 } else { 11028 var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; 11029 W[i] = (n << 1) | (n >>> 31); 11030 } 11031 11032 var t = ((a << 5) | (a >>> 27)) + e + W[i]; 11033 if (i < 20) { 11034 t += ((b & c) | (~b & d)) + 0x5a827999; 11035 } else if (i < 40) { 11036 t += (b ^ c ^ d) + 0x6ed9eba1; 11037 } else if (i < 60) { 11038 t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; 11039 } else /* if (i < 80) */ { 11040 t += (b ^ c ^ d) - 0x359d3e2a; 11041 } 11042 11043 e = d; 11044 d = c; 11045 c = (b << 30) | (b >>> 2); 11046 b = a; 11047 a = t; 11048 } 11049 11050 // Intermediate hash value 11051 H[0] = (H[0] + a) | 0; 11052 H[1] = (H[1] + b) | 0; 11053 H[2] = (H[2] + c) | 0; 11054 H[3] = (H[3] + d) | 0; 11055 H[4] = (H[4] + e) | 0; 11056 }, 11057 11058 _doFinalize: function () { 11059 // Shortcuts 11060 var data = this._data; 11061 var dataWords = data.words; 11062 11063 var nBitsTotal = this._nDataBytes * 8; 11064 var nBitsLeft = data.sigBytes * 8; 11065 11066 // Add padding 11067 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 11068 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); 11069 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; 11070 data.sigBytes = dataWords.length * 4; 11071 11072 // Hash final blocks 11073 this._process(); 11074 11075 // Return final computed hash 11076 return this._hash; 11077 }, 11078 11079 clone: function () { 11080 var clone = Hasher.clone.call(this); 11081 clone._hash = this._hash.clone(); 11082 11083 return clone; 11084 } 11085 }); 11086 11087 /** 11088 * Shortcut function to the hasher's object interface. 11089 * 11090 * @param {WordArray|string} message The message to hash. 11091 * 11092 * @return {WordArray} The hash. 11093 * 11094 * @static 11095 * 11096 * @example 11097 * 11098 * var hash = CryptoJS.SHA1('message'); 11099 * var hash = CryptoJS.SHA1(wordArray); 11100 */ 11101 C.SHA1 = Hasher._createHelper(SHA1); 11102 11103 /** 11104 * Shortcut function to the HMAC's object interface. 11105 * 11106 * @param {WordArray|string} message The message to hash. 11107 * @param {WordArray|string} key The secret key. 11108 * 11109 * @return {WordArray} The HMAC. 11110 * 11111 * @static 11112 * 11113 * @example 11114 * 11115 * var hmac = CryptoJS.HmacSHA1(message, key); 11116 */ 11117 C.HmacSHA1 = Hasher._createHmacHelper(SHA1); 11118 }()); 11119 11120 11121 return CryptoJS.SHA1; 11122 11123 })); 11124 },{"./core":53}],78:[function(require,module,exports){ 11125 ;(function (root, factory, undef) { 11126 if (typeof exports === "object") { 11127 // CommonJS 11128 module.exports = exports = factory(require("./core"), require("./sha256")); 11129 } 11130 else if (typeof define === "function" && define.amd) { 11131 // AMD 11132 define(["./core", "./sha256"], factory); 11133 } 11134 else { 11135 // Global (browser) 11136 factory(root.CryptoJS); 11137 } 11138 }(this, function (CryptoJS) { 11139 11140 (function () { 11141 // Shortcuts 11142 var C = CryptoJS; 11143 var C_lib = C.lib; 11144 var WordArray = C_lib.WordArray; 11145 var C_algo = C.algo; 11146 var SHA256 = C_algo.SHA256; 11147 11148 /** 11149 * SHA-224 hash algorithm. 11150 */ 11151 var SHA224 = C_algo.SHA224 = SHA256.extend({ 11152 _doReset: function () { 11153 this._hash = new WordArray.init([ 11154 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 11155 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 11156 ]); 11157 }, 11158 11159 _doFinalize: function () { 11160 var hash = SHA256._doFinalize.call(this); 11161 11162 hash.sigBytes -= 4; 11163 11164 return hash; 11165 } 11166 }); 11167 11168 /** 11169 * Shortcut function to the hasher's object interface. 11170 * 11171 * @param {WordArray|string} message The message to hash. 11172 * 11173 * @return {WordArray} The hash. 11174 * 11175 * @static 11176 * 11177 * @example 11178 * 11179 * var hash = CryptoJS.SHA224('message'); 11180 * var hash = CryptoJS.SHA224(wordArray); 11181 */ 11182 C.SHA224 = SHA256._createHelper(SHA224); 11183 11184 /** 11185 * Shortcut function to the HMAC's object interface. 11186 * 11187 * @param {WordArray|string} message The message to hash. 11188 * @param {WordArray|string} key The secret key. 11189 * 11190 * @return {WordArray} The HMAC. 11191 * 11192 * @static 11193 * 11194 * @example 11195 * 11196 * var hmac = CryptoJS.HmacSHA224(message, key); 11197 */ 11198 C.HmacSHA224 = SHA256._createHmacHelper(SHA224); 11199 }()); 11200 11201 11202 return CryptoJS.SHA224; 11203 11204 })); 11205 },{"./core":53,"./sha256":79}],79:[function(require,module,exports){ 11206 ;(function (root, factory) { 11207 if (typeof exports === "object") { 11208 // CommonJS 11209 module.exports = exports = factory(require("./core")); 11210 } 11211 else if (typeof define === "function" && define.amd) { 11212 // AMD 11213 define(["./core"], factory); 11214 } 11215 else { 11216 // Global (browser) 11217 factory(root.CryptoJS); 11218 } 11219 }(this, function (CryptoJS) { 11220 11221 (function (Math) { 11222 // Shortcuts 11223 var C = CryptoJS; 11224 var C_lib = C.lib; 11225 var WordArray = C_lib.WordArray; 11226 var Hasher = C_lib.Hasher; 11227 var C_algo = C.algo; 11228 11229 // Initialization and round constants tables 11230 var H = []; 11231 var K = []; 11232 11233 // Compute constants 11234 (function () { 11235 function isPrime(n) { 11236 var sqrtN = Math.sqrt(n); 11237 for (var factor = 2; factor <= sqrtN; factor++) { 11238 if (!(n % factor)) { 11239 return false; 11240 } 11241 } 11242 11243 return true; 11244 } 11245 11246 function getFractionalBits(n) { 11247 return ((n - (n | 0)) * 0x100000000) | 0; 11248 } 11249 11250 var n = 2; 11251 var nPrime = 0; 11252 while (nPrime < 64) { 11253 if (isPrime(n)) { 11254 if (nPrime < 8) { 11255 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); 11256 } 11257 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); 11258 11259 nPrime++; 11260 } 11261 11262 n++; 11263 } 11264 }()); 11265 11266 // Reusable object 11267 var W = []; 11268 11269 /** 11270 * SHA-256 hash algorithm. 11271 */ 11272 var SHA256 = C_algo.SHA256 = Hasher.extend({ 11273 _doReset: function () { 11274 this._hash = new WordArray.init(H.slice(0)); 11275 }, 11276 11277 _doProcessBlock: function (M, offset) { 11278 // Shortcut 11279 var H = this._hash.words; 11280 11281 // Working variables 11282 var a = H[0]; 11283 var b = H[1]; 11284 var c = H[2]; 11285 var d = H[3]; 11286 var e = H[4]; 11287 var f = H[5]; 11288 var g = H[6]; 11289 var h = H[7]; 11290 11291 // Computation 11292 for (var i = 0; i < 64; i++) { 11293 if (i < 16) { 11294 W[i] = M[offset + i] | 0; 11295 } else { 11296 var gamma0x = W[i - 15]; 11297 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ 11298 ((gamma0x << 14) | (gamma0x >>> 18)) ^ 11299 (gamma0x >>> 3); 11300 11301 var gamma1x = W[i - 2]; 11302 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ 11303 ((gamma1x << 13) | (gamma1x >>> 19)) ^ 11304 (gamma1x >>> 10); 11305 11306 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; 11307 } 11308 11309 var ch = (e & f) ^ (~e & g); 11310 var maj = (a & b) ^ (a & c) ^ (b & c); 11311 11312 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); 11313 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); 11314 11315 var t1 = h + sigma1 + ch + K[i] + W[i]; 11316 var t2 = sigma0 + maj; 11317 11318 h = g; 11319 g = f; 11320 f = e; 11321 e = (d + t1) | 0; 11322 d = c; 11323 c = b; 11324 b = a; 11325 a = (t1 + t2) | 0; 11326 } 11327 11328 // Intermediate hash value 11329 H[0] = (H[0] + a) | 0; 11330 H[1] = (H[1] + b) | 0; 11331 H[2] = (H[2] + c) | 0; 11332 H[3] = (H[3] + d) | 0; 11333 H[4] = (H[4] + e) | 0; 11334 H[5] = (H[5] + f) | 0; 11335 H[6] = (H[6] + g) | 0; 11336 H[7] = (H[7] + h) | 0; 11337 }, 11338 11339 _doFinalize: function () { 11340 // Shortcuts 11341 var data = this._data; 11342 var dataWords = data.words; 11343 11344 var nBitsTotal = this._nDataBytes * 8; 11345 var nBitsLeft = data.sigBytes * 8; 11346 11347 // Add padding 11348 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 11349 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); 11350 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; 11351 data.sigBytes = dataWords.length * 4; 11352 11353 // Hash final blocks 11354 this._process(); 11355 11356 // Return final computed hash 11357 return this._hash; 11358 }, 11359 11360 clone: function () { 11361 var clone = Hasher.clone.call(this); 11362 clone._hash = this._hash.clone(); 11363 11364 return clone; 11365 } 11366 }); 11367 11368 /** 11369 * Shortcut function to the hasher's object interface. 11370 * 11371 * @param {WordArray|string} message The message to hash. 11372 * 11373 * @return {WordArray} The hash. 11374 * 11375 * @static 11376 * 11377 * @example 11378 * 11379 * var hash = CryptoJS.SHA256('message'); 11380 * var hash = CryptoJS.SHA256(wordArray); 11381 */ 11382 C.SHA256 = Hasher._createHelper(SHA256); 11383 11384 /** 11385 * Shortcut function to the HMAC's object interface. 11386 * 11387 * @param {WordArray|string} message The message to hash. 11388 * @param {WordArray|string} key The secret key. 11389 * 11390 * @return {WordArray} The HMAC. 11391 * 11392 * @static 11393 * 11394 * @example 11395 * 11396 * var hmac = CryptoJS.HmacSHA256(message, key); 11397 */ 11398 C.HmacSHA256 = Hasher._createHmacHelper(SHA256); 11399 }(Math)); 11400 11401 11402 return CryptoJS.SHA256; 11403 11404 })); 11405 },{"./core":53}],80:[function(require,module,exports){ 11406 ;(function (root, factory, undef) { 11407 if (typeof exports === "object") { 11408 // CommonJS 11409 module.exports = exports = factory(require("./core"), require("./x64-core")); 11410 } 11411 else if (typeof define === "function" && define.amd) { 11412 // AMD 11413 define(["./core", "./x64-core"], factory); 11414 } 11415 else { 11416 // Global (browser) 11417 factory(root.CryptoJS); 11418 } 11419 }(this, function (CryptoJS) { 11420 11421 (function (Math) { 11422 // Shortcuts 11423 var C = CryptoJS; 11424 var C_lib = C.lib; 11425 var WordArray = C_lib.WordArray; 11426 var Hasher = C_lib.Hasher; 11427 var C_x64 = C.x64; 11428 var X64Word = C_x64.Word; 11429 var C_algo = C.algo; 11430 11431 // Constants tables 11432 var RHO_OFFSETS = []; 11433 var PI_INDEXES = []; 11434 var ROUND_CONSTANTS = []; 11435 11436 // Compute Constants 11437 (function () { 11438 // Compute rho offset constants 11439 var x = 1, y = 0; 11440 for (var t = 0; t < 24; t++) { 11441 RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; 11442 11443 var newX = y % 5; 11444 var newY = (2 * x + 3 * y) % 5; 11445 x = newX; 11446 y = newY; 11447 } 11448 11449 // Compute pi index constants 11450 for (var x = 0; x < 5; x++) { 11451 for (var y = 0; y < 5; y++) { 11452 PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; 11453 } 11454 } 11455 11456 // Compute round constants 11457 var LFSR = 0x01; 11458 for (var i = 0; i < 24; i++) { 11459 var roundConstantMsw = 0; 11460 var roundConstantLsw = 0; 11461 11462 for (var j = 0; j < 7; j++) { 11463 if (LFSR & 0x01) { 11464 var bitPosition = (1 << j) - 1; 11465 if (bitPosition < 32) { 11466 roundConstantLsw ^= 1 << bitPosition; 11467 } else /* if (bitPosition >= 32) */ { 11468 roundConstantMsw ^= 1 << (bitPosition - 32); 11469 } 11470 } 11471 11472 // Compute next LFSR 11473 if (LFSR & 0x80) { 11474 // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 11475 LFSR = (LFSR << 1) ^ 0x71; 11476 } else { 11477 LFSR <<= 1; 11478 } 11479 } 11480 11481 ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); 11482 } 11483 }()); 11484 11485 // Reusable objects for temporary values 11486 var T = []; 11487 (function () { 11488 for (var i = 0; i < 25; i++) { 11489 T[i] = X64Word.create(); 11490 } 11491 }()); 11492 11493 /** 11494 * SHA-3 hash algorithm. 11495 */ 11496 var SHA3 = C_algo.SHA3 = Hasher.extend({ 11497 /** 11498 * Configuration options. 11499 * 11500 * @property {number} outputLength 11501 * The desired number of bits in the output hash. 11502 * Only values permitted are: 224, 256, 384, 512. 11503 * Default: 512 11504 */ 11505 cfg: Hasher.cfg.extend({ 11506 outputLength: 512 11507 }), 11508 11509 _doReset: function () { 11510 var state = this._state = [] 11511 for (var i = 0; i < 25; i++) { 11512 state[i] = new X64Word.init(); 11513 } 11514 11515 this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; 11516 }, 11517 11518 _doProcessBlock: function (M, offset) { 11519 // Shortcuts 11520 var state = this._state; 11521 var nBlockSizeLanes = this.blockSize / 2; 11522 11523 // Absorb 11524 for (var i = 0; i < nBlockSizeLanes; i++) { 11525 // Shortcuts 11526 var M2i = M[offset + 2 * i]; 11527 var M2i1 = M[offset + 2 * i + 1]; 11528 11529 // Swap endian 11530 M2i = ( 11531 (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | 11532 (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) 11533 ); 11534 M2i1 = ( 11535 (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | 11536 (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) 11537 ); 11538 11539 // Absorb message into state 11540 var lane = state[i]; 11541 lane.high ^= M2i1; 11542 lane.low ^= M2i; 11543 } 11544 11545 // Rounds 11546 for (var round = 0; round < 24; round++) { 11547 // Theta 11548 for (var x = 0; x < 5; x++) { 11549 // Mix column lanes 11550 var tMsw = 0, tLsw = 0; 11551 for (var y = 0; y < 5; y++) { 11552 var lane = state[x + 5 * y]; 11553 tMsw ^= lane.high; 11554 tLsw ^= lane.low; 11555 } 11556 11557 // Temporary values 11558 var Tx = T[x]; 11559 Tx.high = tMsw; 11560 Tx.low = tLsw; 11561 } 11562 for (var x = 0; x < 5; x++) { 11563 // Shortcuts 11564 var Tx4 = T[(x + 4) % 5]; 11565 var Tx1 = T[(x + 1) % 5]; 11566 var Tx1Msw = Tx1.high; 11567 var Tx1Lsw = Tx1.low; 11568 11569 // Mix surrounding columns 11570 var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); 11571 var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); 11572 for (var y = 0; y < 5; y++) { 11573 var lane = state[x + 5 * y]; 11574 lane.high ^= tMsw; 11575 lane.low ^= tLsw; 11576 } 11577 } 11578 11579 // Rho Pi 11580 for (var laneIndex = 1; laneIndex < 25; laneIndex++) { 11581 // Shortcuts 11582 var lane = state[laneIndex]; 11583 var laneMsw = lane.high; 11584 var laneLsw = lane.low; 11585 var rhoOffset = RHO_OFFSETS[laneIndex]; 11586 11587 // Rotate lanes 11588 if (rhoOffset < 32) { 11589 var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); 11590 var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); 11591 } else /* if (rhoOffset >= 32) */ { 11592 var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); 11593 var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); 11594 } 11595 11596 // Transpose lanes 11597 var TPiLane = T[PI_INDEXES[laneIndex]]; 11598 TPiLane.high = tMsw; 11599 TPiLane.low = tLsw; 11600 } 11601 11602 // Rho pi at x = y = 0 11603 var T0 = T[0]; 11604 var state0 = state[0]; 11605 T0.high = state0.high; 11606 T0.low = state0.low; 11607 11608 // Chi 11609 for (var x = 0; x < 5; x++) { 11610 for (var y = 0; y < 5; y++) { 11611 // Shortcuts 11612 var laneIndex = x + 5 * y; 11613 var lane = state[laneIndex]; 11614 var TLane = T[laneIndex]; 11615 var Tx1Lane = T[((x + 1) % 5) + 5 * y]; 11616 var Tx2Lane = T[((x + 2) % 5) + 5 * y]; 11617 11618 // Mix rows 11619 lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); 11620 lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); 11621 } 11622 } 11623 11624 // Iota 11625 var lane = state[0]; 11626 var roundConstant = ROUND_CONSTANTS[round]; 11627 lane.high ^= roundConstant.high; 11628 lane.low ^= roundConstant.low;; 11629 } 11630 }, 11631 11632 _doFinalize: function () { 11633 // Shortcuts 11634 var data = this._data; 11635 var dataWords = data.words; 11636 var nBitsTotal = this._nDataBytes * 8; 11637 var nBitsLeft = data.sigBytes * 8; 11638 var blockSizeBits = this.blockSize * 32; 11639 11640 // Add padding 11641 dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); 11642 dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; 11643 data.sigBytes = dataWords.length * 4; 11644 11645 // Hash final blocks 11646 this._process(); 11647 11648 // Shortcuts 11649 var state = this._state; 11650 var outputLengthBytes = this.cfg.outputLength / 8; 11651 var outputLengthLanes = outputLengthBytes / 8; 11652 11653 // Squeeze 11654 var hashWords = []; 11655 for (var i = 0; i < outputLengthLanes; i++) { 11656 // Shortcuts 11657 var lane = state[i]; 11658 var laneMsw = lane.high; 11659 var laneLsw = lane.low; 11660 11661 // Swap endian 11662 laneMsw = ( 11663 (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | 11664 (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) 11665 ); 11666 laneLsw = ( 11667 (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | 11668 (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) 11669 ); 11670 11671 // Squeeze state to retrieve hash 11672 hashWords.push(laneLsw); 11673 hashWords.push(laneMsw); 11674 } 11675 11676 // Return final computed hash 11677 return new WordArray.init(hashWords, outputLengthBytes); 11678 }, 11679 11680 clone: function () { 11681 var clone = Hasher.clone.call(this); 11682 11683 var state = clone._state = this._state.slice(0); 11684 for (var i = 0; i < 25; i++) { 11685 state[i] = state[i].clone(); 11686 } 11687 11688 return clone; 11689 } 11690 }); 11691 11692 /** 11693 * Shortcut function to the hasher's object interface. 11694 * 11695 * @param {WordArray|string} message The message to hash. 11696 * 11697 * @return {WordArray} The hash. 11698 * 11699 * @static 11700 * 11701 * @example 11702 * 11703 * var hash = CryptoJS.SHA3('message'); 11704 * var hash = CryptoJS.SHA3(wordArray); 11705 */ 11706 C.SHA3 = Hasher._createHelper(SHA3); 11707 11708 /** 11709 * Shortcut function to the HMAC's object interface. 11710 * 11711 * @param {WordArray|string} message The message to hash. 11712 * @param {WordArray|string} key The secret key. 11713 * 11714 * @return {WordArray} The HMAC. 11715 * 11716 * @static 11717 * 11718 * @example 11719 * 11720 * var hmac = CryptoJS.HmacSHA3(message, key); 11721 */ 11722 C.HmacSHA3 = Hasher._createHmacHelper(SHA3); 11723 }(Math)); 11724 11725 11726 return CryptoJS.SHA3; 11727 11728 })); 11729 },{"./core":53,"./x64-core":84}],81:[function(require,module,exports){ 11730 ;(function (root, factory, undef) { 11731 if (typeof exports === "object") { 11732 // CommonJS 11733 module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512")); 11734 } 11735 else if (typeof define === "function" && define.amd) { 11736 // AMD 11737 define(["./core", "./x64-core", "./sha512"], factory); 11738 } 11739 else { 11740 // Global (browser) 11741 factory(root.CryptoJS); 11742 } 11743 }(this, function (CryptoJS) { 11744 11745 (function () { 11746 // Shortcuts 11747 var C = CryptoJS; 11748 var C_x64 = C.x64; 11749 var X64Word = C_x64.Word; 11750 var X64WordArray = C_x64.WordArray; 11751 var C_algo = C.algo; 11752 var SHA512 = C_algo.SHA512; 11753 11754 /** 11755 * SHA-384 hash algorithm. 11756 */ 11757 var SHA384 = C_algo.SHA384 = SHA512.extend({ 11758 _doReset: function () { 11759 this._hash = new X64WordArray.init([ 11760 new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), 11761 new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), 11762 new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), 11763 new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) 11764 ]); 11765 }, 11766 11767 _doFinalize: function () { 11768 var hash = SHA512._doFinalize.call(this); 11769 11770 hash.sigBytes -= 16; 11771 11772 return hash; 11773 } 11774 }); 11775 11776 /** 11777 * Shortcut function to the hasher's object interface. 11778 * 11779 * @param {WordArray|string} message The message to hash. 11780 * 11781 * @return {WordArray} The hash. 11782 * 11783 * @static 11784 * 11785 * @example 11786 * 11787 * var hash = CryptoJS.SHA384('message'); 11788 * var hash = CryptoJS.SHA384(wordArray); 11789 */ 11790 C.SHA384 = SHA512._createHelper(SHA384); 11791 11792 /** 11793 * Shortcut function to the HMAC's object interface. 11794 * 11795 * @param {WordArray|string} message The message to hash. 11796 * @param {WordArray|string} key The secret key. 11797 * 11798 * @return {WordArray} The HMAC. 11799 * 11800 * @static 11801 * 11802 * @example 11803 * 11804 * var hmac = CryptoJS.HmacSHA384(message, key); 11805 */ 11806 C.HmacSHA384 = SHA512._createHmacHelper(SHA384); 11807 }()); 11808 11809 11810 return CryptoJS.SHA384; 11811 11812 })); 11813 },{"./core":53,"./sha512":82,"./x64-core":84}],82:[function(require,module,exports){ 11814 ;(function (root, factory, undef) { 11815 if (typeof exports === "object") { 11816 // CommonJS 11817 module.exports = exports = factory(require("./core"), require("./x64-core")); 11818 } 11819 else if (typeof define === "function" && define.amd) { 11820 // AMD 11821 define(["./core", "./x64-core"], factory); 11822 } 11823 else { 11824 // Global (browser) 11825 factory(root.CryptoJS); 11826 } 11827 }(this, function (CryptoJS) { 11828 11829 (function () { 11830 // Shortcuts 11831 var C = CryptoJS; 11832 var C_lib = C.lib; 11833 var Hasher = C_lib.Hasher; 11834 var C_x64 = C.x64; 11835 var X64Word = C_x64.Word; 11836 var X64WordArray = C_x64.WordArray; 11837 var C_algo = C.algo; 11838 11839 function X64Word_create() { 11840 return X64Word.create.apply(X64Word, arguments); 11841 } 11842 11843 // Constants 11844 var K = [ 11845 X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), 11846 X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), 11847 X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), 11848 X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), 11849 X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), 11850 X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), 11851 X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), 11852 X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), 11853 X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), 11854 X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), 11855 X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), 11856 X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), 11857 X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), 11858 X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), 11859 X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), 11860 X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), 11861 X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), 11862 X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), 11863 X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), 11864 X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), 11865 X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), 11866 X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), 11867 X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), 11868 X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), 11869 X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), 11870 X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), 11871 X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), 11872 X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), 11873 X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), 11874 X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), 11875 X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), 11876 X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), 11877 X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), 11878 X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), 11879 X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), 11880 X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), 11881 X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), 11882 X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), 11883 X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), 11884 X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) 11885 ]; 11886 11887 // Reusable objects 11888 var W = []; 11889 (function () { 11890 for (var i = 0; i < 80; i++) { 11891 W[i] = X64Word_create(); 11892 } 11893 }()); 11894 11895 /** 11896 * SHA-512 hash algorithm. 11897 */ 11898 var SHA512 = C_algo.SHA512 = Hasher.extend({ 11899 _doReset: function () { 11900 this._hash = new X64WordArray.init([ 11901 new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), 11902 new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), 11903 new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), 11904 new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) 11905 ]); 11906 }, 11907 11908 _doProcessBlock: function (M, offset) { 11909 // Shortcuts 11910 var H = this._hash.words; 11911 11912 var H0 = H[0]; 11913 var H1 = H[1]; 11914 var H2 = H[2]; 11915 var H3 = H[3]; 11916 var H4 = H[4]; 11917 var H5 = H[5]; 11918 var H6 = H[6]; 11919 var H7 = H[7]; 11920 11921 var H0h = H0.high; 11922 var H0l = H0.low; 11923 var H1h = H1.high; 11924 var H1l = H1.low; 11925 var H2h = H2.high; 11926 var H2l = H2.low; 11927 var H3h = H3.high; 11928 var H3l = H3.low; 11929 var H4h = H4.high; 11930 var H4l = H4.low; 11931 var H5h = H5.high; 11932 var H5l = H5.low; 11933 var H6h = H6.high; 11934 var H6l = H6.low; 11935 var H7h = H7.high; 11936 var H7l = H7.low; 11937 11938 // Working variables 11939 var ah = H0h; 11940 var al = H0l; 11941 var bh = H1h; 11942 var bl = H1l; 11943 var ch = H2h; 11944 var cl = H2l; 11945 var dh = H3h; 11946 var dl = H3l; 11947 var eh = H4h; 11948 var el = H4l; 11949 var fh = H5h; 11950 var fl = H5l; 11951 var gh = H6h; 11952 var gl = H6l; 11953 var hh = H7h; 11954 var hl = H7l; 11955 11956 // Rounds 11957 for (var i = 0; i < 80; i++) { 11958 // Shortcut 11959 var Wi = W[i]; 11960 11961 // Extend message 11962 if (i < 16) { 11963 var Wih = Wi.high = M[offset + i * 2] | 0; 11964 var Wil = Wi.low = M[offset + i * 2 + 1] | 0; 11965 } else { 11966 // Gamma0 11967 var gamma0x = W[i - 15]; 11968 var gamma0xh = gamma0x.high; 11969 var gamma0xl = gamma0x.low; 11970 var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); 11971 var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); 11972 11973 // Gamma1 11974 var gamma1x = W[i - 2]; 11975 var gamma1xh = gamma1x.high; 11976 var gamma1xl = gamma1x.low; 11977 var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); 11978 var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); 11979 11980 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] 11981 var Wi7 = W[i - 7]; 11982 var Wi7h = Wi7.high; 11983 var Wi7l = Wi7.low; 11984 11985 var Wi16 = W[i - 16]; 11986 var Wi16h = Wi16.high; 11987 var Wi16l = Wi16.low; 11988 11989 var Wil = gamma0l + Wi7l; 11990 var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); 11991 var Wil = Wil + gamma1l; 11992 var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); 11993 var Wil = Wil + Wi16l; 11994 var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); 11995 11996 Wi.high = Wih; 11997 Wi.low = Wil; 11998 } 11999 12000 var chh = (eh & fh) ^ (~eh & gh); 12001 var chl = (el & fl) ^ (~el & gl); 12002 var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); 12003 var majl = (al & bl) ^ (al & cl) ^ (bl & cl); 12004 12005 var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); 12006 var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); 12007 var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); 12008 var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); 12009 12010 // t1 = h + sigma1 + ch + K[i] + W[i] 12011 var Ki = K[i]; 12012 var Kih = Ki.high; 12013 var Kil = Ki.low; 12014 12015 var t1l = hl + sigma1l; 12016 var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); 12017 var t1l = t1l + chl; 12018 var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); 12019 var t1l = t1l + Kil; 12020 var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); 12021 var t1l = t1l + Wil; 12022 var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); 12023 12024 // t2 = sigma0 + maj 12025 var t2l = sigma0l + majl; 12026 var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); 12027 12028 // Update working variables 12029 hh = gh; 12030 hl = gl; 12031 gh = fh; 12032 gl = fl; 12033 fh = eh; 12034 fl = el; 12035 el = (dl + t1l) | 0; 12036 eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; 12037 dh = ch; 12038 dl = cl; 12039 ch = bh; 12040 cl = bl; 12041 bh = ah; 12042 bl = al; 12043 al = (t1l + t2l) | 0; 12044 ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; 12045 } 12046 12047 // Intermediate hash value 12048 H0l = H0.low = (H0l + al); 12049 H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); 12050 H1l = H1.low = (H1l + bl); 12051 H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); 12052 H2l = H2.low = (H2l + cl); 12053 H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); 12054 H3l = H3.low = (H3l + dl); 12055 H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); 12056 H4l = H4.low = (H4l + el); 12057 H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); 12058 H5l = H5.low = (H5l + fl); 12059 H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); 12060 H6l = H6.low = (H6l + gl); 12061 H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); 12062 H7l = H7.low = (H7l + hl); 12063 H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); 12064 }, 12065 12066 _doFinalize: function () { 12067 // Shortcuts 12068 var data = this._data; 12069 var dataWords = data.words; 12070 12071 var nBitsTotal = this._nDataBytes * 8; 12072 var nBitsLeft = data.sigBytes * 8; 12073 12074 // Add padding 12075 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 12076 dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); 12077 dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; 12078 data.sigBytes = dataWords.length * 4; 12079 12080 // Hash final blocks 12081 this._process(); 12082 12083 // Convert hash to 32-bit word array before returning 12084 var hash = this._hash.toX32(); 12085 12086 // Return final computed hash 12087 return hash; 12088 }, 12089 12090 clone: function () { 12091 var clone = Hasher.clone.call(this); 12092 clone._hash = this._hash.clone(); 12093 12094 return clone; 12095 }, 12096 12097 blockSize: 1024/32 12098 }); 12099 12100 /** 12101 * Shortcut function to the hasher's object interface. 12102 * 12103 * @param {WordArray|string} message The message to hash. 12104 * 12105 * @return {WordArray} The hash. 12106 * 12107 * @static 12108 * 12109 * @example 12110 * 12111 * var hash = CryptoJS.SHA512('message'); 12112 * var hash = CryptoJS.SHA512(wordArray); 12113 */ 12114 C.SHA512 = Hasher._createHelper(SHA512); 12115 12116 /** 12117 * Shortcut function to the HMAC's object interface. 12118 * 12119 * @param {WordArray|string} message The message to hash. 12120 * @param {WordArray|string} key The secret key. 12121 * 12122 * @return {WordArray} The HMAC. 12123 * 12124 * @static 12125 * 12126 * @example 12127 * 12128 * var hmac = CryptoJS.HmacSHA512(message, key); 12129 */ 12130 C.HmacSHA512 = Hasher._createHmacHelper(SHA512); 12131 }()); 12132 12133 12134 return CryptoJS.SHA512; 12135 12136 })); 12137 },{"./core":53,"./x64-core":84}],83:[function(require,module,exports){ 12138 ;(function (root, factory, undef) { 12139 if (typeof exports === "object") { 12140 // CommonJS 12141 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 12142 } 12143 else if (typeof define === "function" && define.amd) { 12144 // AMD 12145 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 12146 } 12147 else { 12148 // Global (browser) 12149 factory(root.CryptoJS); 12150 } 12151 }(this, function (CryptoJS) { 12152 12153 (function () { 12154 // Shortcuts 12155 var C = CryptoJS; 12156 var C_lib = C.lib; 12157 var WordArray = C_lib.WordArray; 12158 var BlockCipher = C_lib.BlockCipher; 12159 var C_algo = C.algo; 12160 12161 // Permuted Choice 1 constants 12162 var PC1 = [ 12163 57, 49, 41, 33, 25, 17, 9, 1, 12164 58, 50, 42, 34, 26, 18, 10, 2, 12165 59, 51, 43, 35, 27, 19, 11, 3, 12166 60, 52, 44, 36, 63, 55, 47, 39, 12167 31, 23, 15, 7, 62, 54, 46, 38, 12168 30, 22, 14, 6, 61, 53, 45, 37, 12169 29, 21, 13, 5, 28, 20, 12, 4 12170 ]; 12171 12172 // Permuted Choice 2 constants 12173 var PC2 = [ 12174 14, 17, 11, 24, 1, 5, 12175 3, 28, 15, 6, 21, 10, 12176 23, 19, 12, 4, 26, 8, 12177 16, 7, 27, 20, 13, 2, 12178 41, 52, 31, 37, 47, 55, 12179 30, 40, 51, 45, 33, 48, 12180 44, 49, 39, 56, 34, 53, 12181 46, 42, 50, 36, 29, 32 12182 ]; 12183 12184 // Cumulative bit shift constants 12185 var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; 12186 12187 // SBOXes and round permutation constants 12188 var SBOX_P = [ 12189 { 12190 0x0: 0x808200, 12191 0x10000000: 0x8000, 12192 0x20000000: 0x808002, 12193 0x30000000: 0x2, 12194 0x40000000: 0x200, 12195 0x50000000: 0x808202, 12196 0x60000000: 0x800202, 12197 0x70000000: 0x800000, 12198 0x80000000: 0x202, 12199 0x90000000: 0x800200, 12200 0xa0000000: 0x8200, 12201 0xb0000000: 0x808000, 12202 0xc0000000: 0x8002, 12203 0xd0000000: 0x800002, 12204 0xe0000000: 0x0, 12205 0xf0000000: 0x8202, 12206 0x8000000: 0x0, 12207 0x18000000: 0x808202, 12208 0x28000000: 0x8202, 12209 0x38000000: 0x8000, 12210 0x48000000: 0x808200, 12211 0x58000000: 0x200, 12212 0x68000000: 0x808002, 12213 0x78000000: 0x2, 12214 0x88000000: 0x800200, 12215 0x98000000: 0x8200, 12216 0xa8000000: 0x808000, 12217 0xb8000000: 0x800202, 12218 0xc8000000: 0x800002, 12219 0xd8000000: 0x8002, 12220 0xe8000000: 0x202, 12221 0xf8000000: 0x800000, 12222 0x1: 0x8000, 12223 0x10000001: 0x2, 12224 0x20000001: 0x808200, 12225 0x30000001: 0x800000, 12226 0x40000001: 0x808002, 12227 0x50000001: 0x8200, 12228 0x60000001: 0x200, 12229 0x70000001: 0x800202, 12230 0x80000001: 0x808202, 12231 0x90000001: 0x808000, 12232 0xa0000001: 0x800002, 12233 0xb0000001: 0x8202, 12234 0xc0000001: 0x202, 12235 0xd0000001: 0x800200, 12236 0xe0000001: 0x8002, 12237 0xf0000001: 0x0, 12238 0x8000001: 0x808202, 12239 0x18000001: 0x808000, 12240 0x28000001: 0x800000, 12241 0x38000001: 0x200, 12242 0x48000001: 0x8000, 12243 0x58000001: 0x800002, 12244 0x68000001: 0x2, 12245 0x78000001: 0x8202, 12246 0x88000001: 0x8002, 12247 0x98000001: 0x800202, 12248 0xa8000001: 0x202, 12249 0xb8000001: 0x808200, 12250 0xc8000001: 0x800200, 12251 0xd8000001: 0x0, 12252 0xe8000001: 0x8200, 12253 0xf8000001: 0x808002 12254 }, 12255 { 12256 0x0: 0x40084010, 12257 0x1000000: 0x4000, 12258 0x2000000: 0x80000, 12259 0x3000000: 0x40080010, 12260 0x4000000: 0x40000010, 12261 0x5000000: 0x40084000, 12262 0x6000000: 0x40004000, 12263 0x7000000: 0x10, 12264 0x8000000: 0x84000, 12265 0x9000000: 0x40004010, 12266 0xa000000: 0x40000000, 12267 0xb000000: 0x84010, 12268 0xc000000: 0x80010, 12269 0xd000000: 0x0, 12270 0xe000000: 0x4010, 12271 0xf000000: 0x40080000, 12272 0x800000: 0x40004000, 12273 0x1800000: 0x84010, 12274 0x2800000: 0x10, 12275 0x3800000: 0x40004010, 12276 0x4800000: 0x40084010, 12277 0x5800000: 0x40000000, 12278 0x6800000: 0x80000, 12279 0x7800000: 0x40080010, 12280 0x8800000: 0x80010, 12281 0x9800000: 0x0, 12282 0xa800000: 0x4000, 12283 0xb800000: 0x40080000, 12284 0xc800000: 0x40000010, 12285 0xd800000: 0x84000, 12286 0xe800000: 0x40084000, 12287 0xf800000: 0x4010, 12288 0x10000000: 0x0, 12289 0x11000000: 0x40080010, 12290 0x12000000: 0x40004010, 12291 0x13000000: 0x40084000, 12292 0x14000000: 0x40080000, 12293 0x15000000: 0x10, 12294 0x16000000: 0x84010, 12295 0x17000000: 0x4000, 12296 0x18000000: 0x4010, 12297 0x19000000: 0x80000, 12298 0x1a000000: 0x80010, 12299 0x1b000000: 0x40000010, 12300 0x1c000000: 0x84000, 12301 0x1d000000: 0x40004000, 12302 0x1e000000: 0x40000000, 12303 0x1f000000: 0x40084010, 12304 0x10800000: 0x84010, 12305 0x11800000: 0x80000, 12306 0x12800000: 0x40080000, 12307 0x13800000: 0x4000, 12308 0x14800000: 0x40004000, 12309 0x15800000: 0x40084010, 12310 0x16800000: 0x10, 12311 0x17800000: 0x40000000, 12312 0x18800000: 0x40084000, 12313 0x19800000: 0x40000010, 12314 0x1a800000: 0x40004010, 12315 0x1b800000: 0x80010, 12316 0x1c800000: 0x0, 12317 0x1d800000: 0x4010, 12318 0x1e800000: 0x40080010, 12319 0x1f800000: 0x84000 12320 }, 12321 { 12322 0x0: 0x104, 12323 0x100000: 0x0, 12324 0x200000: 0x4000100, 12325 0x300000: 0x10104, 12326 0x400000: 0x10004, 12327 0x500000: 0x4000004, 12328 0x600000: 0x4010104, 12329 0x700000: 0x4010000, 12330 0x800000: 0x4000000, 12331 0x900000: 0x4010100, 12332 0xa00000: 0x10100, 12333 0xb00000: 0x4010004, 12334 0xc00000: 0x4000104, 12335 0xd00000: 0x10000, 12336 0xe00000: 0x4, 12337 0xf00000: 0x100, 12338 0x80000: 0x4010100, 12339 0x180000: 0x4010004, 12340 0x280000: 0x0, 12341 0x380000: 0x4000100, 12342 0x480000: 0x4000004, 12343 0x580000: 0x10000, 12344 0x680000: 0x10004, 12345 0x780000: 0x104, 12346 0x880000: 0x4, 12347 0x980000: 0x100, 12348 0xa80000: 0x4010000, 12349 0xb80000: 0x10104, 12350 0xc80000: 0x10100, 12351 0xd80000: 0x4000104, 12352 0xe80000: 0x4010104, 12353 0xf80000: 0x4000000, 12354 0x1000000: 0x4010100, 12355 0x1100000: 0x10004, 12356 0x1200000: 0x10000, 12357 0x1300000: 0x4000100, 12358 0x1400000: 0x100, 12359 0x1500000: 0x4010104, 12360 0x1600000: 0x4000004, 12361 0x1700000: 0x0, 12362 0x1800000: 0x4000104, 12363 0x1900000: 0x4000000, 12364 0x1a00000: 0x4, 12365 0x1b00000: 0x10100, 12366 0x1c00000: 0x4010000, 12367 0x1d00000: 0x104, 12368 0x1e00000: 0x10104, 12369 0x1f00000: 0x4010004, 12370 0x1080000: 0x4000000, 12371 0x1180000: 0x104, 12372 0x1280000: 0x4010100, 12373 0x1380000: 0x0, 12374 0x1480000: 0x10004, 12375 0x1580000: 0x4000100, 12376 0x1680000: 0x100, 12377 0x1780000: 0x4010004, 12378 0x1880000: 0x10000, 12379 0x1980000: 0x4010104, 12380 0x1a80000: 0x10104, 12381 0x1b80000: 0x4000004, 12382 0x1c80000: 0x4000104, 12383 0x1d80000: 0x4010000, 12384 0x1e80000: 0x4, 12385 0x1f80000: 0x10100 12386 }, 12387 { 12388 0x0: 0x80401000, 12389 0x10000: 0x80001040, 12390 0x20000: 0x401040, 12391 0x30000: 0x80400000, 12392 0x40000: 0x0, 12393 0x50000: 0x401000, 12394 0x60000: 0x80000040, 12395 0x70000: 0x400040, 12396 0x80000: 0x80000000, 12397 0x90000: 0x400000, 12398 0xa0000: 0x40, 12399 0xb0000: 0x80001000, 12400 0xc0000: 0x80400040, 12401 0xd0000: 0x1040, 12402 0xe0000: 0x1000, 12403 0xf0000: 0x80401040, 12404 0x8000: 0x80001040, 12405 0x18000: 0x40, 12406 0x28000: 0x80400040, 12407 0x38000: 0x80001000, 12408 0x48000: 0x401000, 12409 0x58000: 0x80401040, 12410 0x68000: 0x0, 12411 0x78000: 0x80400000, 12412 0x88000: 0x1000, 12413 0x98000: 0x80401000, 12414 0xa8000: 0x400000, 12415 0xb8000: 0x1040, 12416 0xc8000: 0x80000000, 12417 0xd8000: 0x400040, 12418 0xe8000: 0x401040, 12419 0xf8000: 0x80000040, 12420 0x100000: 0x400040, 12421 0x110000: 0x401000, 12422 0x120000: 0x80000040, 12423 0x130000: 0x0, 12424 0x140000: 0x1040, 12425 0x150000: 0x80400040, 12426 0x160000: 0x80401000, 12427 0x170000: 0x80001040, 12428 0x180000: 0x80401040, 12429 0x190000: 0x80000000, 12430 0x1a0000: 0x80400000, 12431 0x1b0000: 0x401040, 12432 0x1c0000: 0x80001000, 12433 0x1d0000: 0x400000, 12434 0x1e0000: 0x40, 12435 0x1f0000: 0x1000, 12436 0x108000: 0x80400000, 12437 0x118000: 0x80401040, 12438 0x128000: 0x0, 12439 0x138000: 0x401000, 12440 0x148000: 0x400040, 12441 0x158000: 0x80000000, 12442 0x168000: 0x80001040, 12443 0x178000: 0x40, 12444 0x188000: 0x80000040, 12445 0x198000: 0x1000, 12446 0x1a8000: 0x80001000, 12447 0x1b8000: 0x80400040, 12448 0x1c8000: 0x1040, 12449 0x1d8000: 0x80401000, 12450 0x1e8000: 0x400000, 12451 0x1f8000: 0x401040 12452 }, 12453 { 12454 0x0: 0x80, 12455 0x1000: 0x1040000, 12456 0x2000: 0x40000, 12457 0x3000: 0x20000000, 12458 0x4000: 0x20040080, 12459 0x5000: 0x1000080, 12460 0x6000: 0x21000080, 12461 0x7000: 0x40080, 12462 0x8000: 0x1000000, 12463 0x9000: 0x20040000, 12464 0xa000: 0x20000080, 12465 0xb000: 0x21040080, 12466 0xc000: 0x21040000, 12467 0xd000: 0x0, 12468 0xe000: 0x1040080, 12469 0xf000: 0x21000000, 12470 0x800: 0x1040080, 12471 0x1800: 0x21000080, 12472 0x2800: 0x80, 12473 0x3800: 0x1040000, 12474 0x4800: 0x40000, 12475 0x5800: 0x20040080, 12476 0x6800: 0x21040000, 12477 0x7800: 0x20000000, 12478 0x8800: 0x20040000, 12479 0x9800: 0x0, 12480 0xa800: 0x21040080, 12481 0xb800: 0x1000080, 12482 0xc800: 0x20000080, 12483 0xd800: 0x21000000, 12484 0xe800: 0x1000000, 12485 0xf800: 0x40080, 12486 0x10000: 0x40000, 12487 0x11000: 0x80, 12488 0x12000: 0x20000000, 12489 0x13000: 0x21000080, 12490 0x14000: 0x1000080, 12491 0x15000: 0x21040000, 12492 0x16000: 0x20040080, 12493 0x17000: 0x1000000, 12494 0x18000: 0x21040080, 12495 0x19000: 0x21000000, 12496 0x1a000: 0x1040000, 12497 0x1b000: 0x20040000, 12498 0x1c000: 0x40080, 12499 0x1d000: 0x20000080, 12500 0x1e000: 0x0, 12501 0x1f000: 0x1040080, 12502 0x10800: 0x21000080, 12503 0x11800: 0x1000000, 12504 0x12800: 0x1040000, 12505 0x13800: 0x20040080, 12506 0x14800: 0x20000000, 12507 0x15800: 0x1040080, 12508 0x16800: 0x80, 12509 0x17800: 0x21040000, 12510 0x18800: 0x40080, 12511 0x19800: 0x21040080, 12512 0x1a800: 0x0, 12513 0x1b800: 0x21000000, 12514 0x1c800: 0x1000080, 12515 0x1d800: 0x40000, 12516 0x1e800: 0x20040000, 12517 0x1f800: 0x20000080 12518 }, 12519 { 12520 0x0: 0x10000008, 12521 0x100: 0x2000, 12522 0x200: 0x10200000, 12523 0x300: 0x10202008, 12524 0x400: 0x10002000, 12525 0x500: 0x200000, 12526 0x600: 0x200008, 12527 0x700: 0x10000000, 12528 0x800: 0x0, 12529 0x900: 0x10002008, 12530 0xa00: 0x202000, 12531 0xb00: 0x8, 12532 0xc00: 0x10200008, 12533 0xd00: 0x202008, 12534 0xe00: 0x2008, 12535 0xf00: 0x10202000, 12536 0x80: 0x10200000, 12537 0x180: 0x10202008, 12538 0x280: 0x8, 12539 0x380: 0x200000, 12540 0x480: 0x202008, 12541 0x580: 0x10000008, 12542 0x680: 0x10002000, 12543 0x780: 0x2008, 12544 0x880: 0x200008, 12545 0x980: 0x2000, 12546 0xa80: 0x10002008, 12547 0xb80: 0x10200008, 12548 0xc80: 0x0, 12549 0xd80: 0x10202000, 12550 0xe80: 0x202000, 12551 0xf80: 0x10000000, 12552 0x1000: 0x10002000, 12553 0x1100: 0x10200008, 12554 0x1200: 0x10202008, 12555 0x1300: 0x2008, 12556 0x1400: 0x200000, 12557 0x1500: 0x10000000, 12558 0x1600: 0x10000008, 12559 0x1700: 0x202000, 12560 0x1800: 0x202008, 12561 0x1900: 0x0, 12562 0x1a00: 0x8, 12563 0x1b00: 0x10200000, 12564 0x1c00: 0x2000, 12565 0x1d00: 0x10002008, 12566 0x1e00: 0x10202000, 12567 0x1f00: 0x200008, 12568 0x1080: 0x8, 12569 0x1180: 0x202000, 12570 0x1280: 0x200000, 12571 0x1380: 0x10000008, 12572 0x1480: 0x10002000, 12573 0x1580: 0x2008, 12574 0x1680: 0x10202008, 12575 0x1780: 0x10200000, 12576 0x1880: 0x10202000, 12577 0x1980: 0x10200008, 12578 0x1a80: 0x2000, 12579 0x1b80: 0x202008, 12580 0x1c80: 0x200008, 12581 0x1d80: 0x0, 12582 0x1e80: 0x10000000, 12583 0x1f80: 0x10002008 12584 }, 12585 { 12586 0x0: 0x100000, 12587 0x10: 0x2000401, 12588 0x20: 0x400, 12589 0x30: 0x100401, 12590 0x40: 0x2100401, 12591 0x50: 0x0, 12592 0x60: 0x1, 12593 0x70: 0x2100001, 12594 0x80: 0x2000400, 12595 0x90: 0x100001, 12596 0xa0: 0x2000001, 12597 0xb0: 0x2100400, 12598 0xc0: 0x2100000, 12599 0xd0: 0x401, 12600 0xe0: 0x100400, 12601 0xf0: 0x2000000, 12602 0x8: 0x2100001, 12603 0x18: 0x0, 12604 0x28: 0x2000401, 12605 0x38: 0x2100400, 12606 0x48: 0x100000, 12607 0x58: 0x2000001, 12608 0x68: 0x2000000, 12609 0x78: 0x401, 12610 0x88: 0x100401, 12611 0x98: 0x2000400, 12612 0xa8: 0x2100000, 12613 0xb8: 0x100001, 12614 0xc8: 0x400, 12615 0xd8: 0x2100401, 12616 0xe8: 0x1, 12617 0xf8: 0x100400, 12618 0x100: 0x2000000, 12619 0x110: 0x100000, 12620 0x120: 0x2000401, 12621 0x130: 0x2100001, 12622 0x140: 0x100001, 12623 0x150: 0x2000400, 12624 0x160: 0x2100400, 12625 0x170: 0x100401, 12626 0x180: 0x401, 12627 0x190: 0x2100401, 12628 0x1a0: 0x100400, 12629 0x1b0: 0x1, 12630 0x1c0: 0x0, 12631 0x1d0: 0x2100000, 12632 0x1e0: 0x2000001, 12633 0x1f0: 0x400, 12634 0x108: 0x100400, 12635 0x118: 0x2000401, 12636 0x128: 0x2100001, 12637 0x138: 0x1, 12638 0x148: 0x2000000, 12639 0x158: 0x100000, 12640 0x168: 0x401, 12641 0x178: 0x2100400, 12642 0x188: 0x2000001, 12643 0x198: 0x2100000, 12644 0x1a8: 0x0, 12645 0x1b8: 0x2100401, 12646 0x1c8: 0x100401, 12647 0x1d8: 0x400, 12648 0x1e8: 0x2000400, 12649 0x1f8: 0x100001 12650 }, 12651 { 12652 0x0: 0x8000820, 12653 0x1: 0x20000, 12654 0x2: 0x8000000, 12655 0x3: 0x20, 12656 0x4: 0x20020, 12657 0x5: 0x8020820, 12658 0x6: 0x8020800, 12659 0x7: 0x800, 12660 0x8: 0x8020000, 12661 0x9: 0x8000800, 12662 0xa: 0x20800, 12663 0xb: 0x8020020, 12664 0xc: 0x820, 12665 0xd: 0x0, 12666 0xe: 0x8000020, 12667 0xf: 0x20820, 12668 0x80000000: 0x800, 12669 0x80000001: 0x8020820, 12670 0x80000002: 0x8000820, 12671 0x80000003: 0x8000000, 12672 0x80000004: 0x8020000, 12673 0x80000005: 0x20800, 12674 0x80000006: 0x20820, 12675 0x80000007: 0x20, 12676 0x80000008: 0x8000020, 12677 0x80000009: 0x820, 12678 0x8000000a: 0x20020, 12679 0x8000000b: 0x8020800, 12680 0x8000000c: 0x0, 12681 0x8000000d: 0x8020020, 12682 0x8000000e: 0x8000800, 12683 0x8000000f: 0x20000, 12684 0x10: 0x20820, 12685 0x11: 0x8020800, 12686 0x12: 0x20, 12687 0x13: 0x800, 12688 0x14: 0x8000800, 12689 0x15: 0x8000020, 12690 0x16: 0x8020020, 12691 0x17: 0x20000, 12692 0x18: 0x0, 12693 0x19: 0x20020, 12694 0x1a: 0x8020000, 12695 0x1b: 0x8000820, 12696 0x1c: 0x8020820, 12697 0x1d: 0x20800, 12698 0x1e: 0x820, 12699 0x1f: 0x8000000, 12700 0x80000010: 0x20000, 12701 0x80000011: 0x800, 12702 0x80000012: 0x8020020, 12703 0x80000013: 0x20820, 12704 0x80000014: 0x20, 12705 0x80000015: 0x8020000, 12706 0x80000016: 0x8000000, 12707 0x80000017: 0x8000820, 12708 0x80000018: 0x8020820, 12709 0x80000019: 0x8000020, 12710 0x8000001a: 0x8000800, 12711 0x8000001b: 0x0, 12712 0x8000001c: 0x20800, 12713 0x8000001d: 0x820, 12714 0x8000001e: 0x20020, 12715 0x8000001f: 0x8020800 12716 } 12717 ]; 12718 12719 // Masks that select the SBOX input 12720 var SBOX_MASK = [ 12721 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 12722 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f 12723 ]; 12724 12725 /** 12726 * DES block cipher algorithm. 12727 */ 12728 var DES = C_algo.DES = BlockCipher.extend({ 12729 _doReset: function () { 12730 // Shortcuts 12731 var key = this._key; 12732 var keyWords = key.words; 12733 12734 // Select 56 bits according to PC1 12735 var keyBits = []; 12736 for (var i = 0; i < 56; i++) { 12737 var keyBitPos = PC1[i] - 1; 12738 keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; 12739 } 12740 12741 // Assemble 16 subkeys 12742 var subKeys = this._subKeys = []; 12743 for (var nSubKey = 0; nSubKey < 16; nSubKey++) { 12744 // Create subkey 12745 var subKey = subKeys[nSubKey] = []; 12746 12747 // Shortcut 12748 var bitShift = BIT_SHIFTS[nSubKey]; 12749 12750 // Select 48 bits according to PC2 12751 for (var i = 0; i < 24; i++) { 12752 // Select from the left 28 key bits 12753 subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); 12754 12755 // Select from the right 28 key bits 12756 subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); 12757 } 12758 12759 // Since each subkey is applied to an expanded 32-bit input, 12760 // the subkey can be broken into 8 values scaled to 32-bits, 12761 // which allows the key to be used without expansion 12762 subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); 12763 for (var i = 1; i < 7; i++) { 12764 subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); 12765 } 12766 subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); 12767 } 12768 12769 // Compute inverse subkeys 12770 var invSubKeys = this._invSubKeys = []; 12771 for (var i = 0; i < 16; i++) { 12772 invSubKeys[i] = subKeys[15 - i]; 12773 } 12774 }, 12775 12776 encryptBlock: function (M, offset) { 12777 this._doCryptBlock(M, offset, this._subKeys); 12778 }, 12779 12780 decryptBlock: function (M, offset) { 12781 this._doCryptBlock(M, offset, this._invSubKeys); 12782 }, 12783 12784 _doCryptBlock: function (M, offset, subKeys) { 12785 // Get input 12786 this._lBlock = M[offset]; 12787 this._rBlock = M[offset + 1]; 12788 12789 // Initial permutation 12790 exchangeLR.call(this, 4, 0x0f0f0f0f); 12791 exchangeLR.call(this, 16, 0x0000ffff); 12792 exchangeRL.call(this, 2, 0x33333333); 12793 exchangeRL.call(this, 8, 0x00ff00ff); 12794 exchangeLR.call(this, 1, 0x55555555); 12795 12796 // Rounds 12797 for (var round = 0; round < 16; round++) { 12798 // Shortcuts 12799 var subKey = subKeys[round]; 12800 var lBlock = this._lBlock; 12801 var rBlock = this._rBlock; 12802 12803 // Feistel function 12804 var f = 0; 12805 for (var i = 0; i < 8; i++) { 12806 f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; 12807 } 12808 this._lBlock = rBlock; 12809 this._rBlock = lBlock ^ f; 12810 } 12811 12812 // Undo swap from last round 12813 var t = this._lBlock; 12814 this._lBlock = this._rBlock; 12815 this._rBlock = t; 12816 12817 // Final permutation 12818 exchangeLR.call(this, 1, 0x55555555); 12819 exchangeRL.call(this, 8, 0x00ff00ff); 12820 exchangeRL.call(this, 2, 0x33333333); 12821 exchangeLR.call(this, 16, 0x0000ffff); 12822 exchangeLR.call(this, 4, 0x0f0f0f0f); 12823 12824 // Set output 12825 M[offset] = this._lBlock; 12826 M[offset + 1] = this._rBlock; 12827 }, 12828 12829 keySize: 64/32, 12830 12831 ivSize: 64/32, 12832 12833 blockSize: 64/32 12834 }); 12835 12836 // Swap bits across the left and right words 12837 function exchangeLR(offset, mask) { 12838 var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; 12839 this._rBlock ^= t; 12840 this._lBlock ^= t << offset; 12841 } 12842 12843 function exchangeRL(offset, mask) { 12844 var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; 12845 this._lBlock ^= t; 12846 this._rBlock ^= t << offset; 12847 } 12848 12849 /** 12850 * Shortcut functions to the cipher's object interface. 12851 * 12852 * @example 12853 * 12854 * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); 12855 * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); 12856 */ 12857 C.DES = BlockCipher._createHelper(DES); 12858 12859 /** 12860 * Triple-DES block cipher algorithm. 12861 */ 12862 var TripleDES = C_algo.TripleDES = BlockCipher.extend({ 12863 _doReset: function () { 12864 // Shortcuts 12865 var key = this._key; 12866 var keyWords = key.words; 12867 12868 // Create DES instances 12869 this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); 12870 this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); 12871 this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); 12872 }, 12873 12874 encryptBlock: function (M, offset) { 12875 this._des1.encryptBlock(M, offset); 12876 this._des2.decryptBlock(M, offset); 12877 this._des3.encryptBlock(M, offset); 12878 }, 12879 12880 decryptBlock: function (M, offset) { 12881 this._des3.decryptBlock(M, offset); 12882 this._des2.encryptBlock(M, offset); 12883 this._des1.decryptBlock(M, offset); 12884 }, 12885 12886 keySize: 192/32, 12887 12888 ivSize: 64/32, 12889 12890 blockSize: 64/32 12891 }); 12892 12893 /** 12894 * Shortcut functions to the cipher's object interface. 12895 * 12896 * @example 12897 * 12898 * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); 12899 * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); 12900 */ 12901 C.TripleDES = BlockCipher._createHelper(TripleDES); 12902 }()); 12903 12904 12905 return CryptoJS.TripleDES; 12906 12907 })); 12908 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],84:[function(require,module,exports){ 12909 ;(function (root, factory) { 12910 if (typeof exports === "object") { 12911 // CommonJS 12912 module.exports = exports = factory(require("./core")); 12913 } 12914 else if (typeof define === "function" && define.amd) { 12915 // AMD 12916 define(["./core"], factory); 12917 } 12918 else { 12919 // Global (browser) 12920 factory(root.CryptoJS); 12921 } 12922 }(this, function (CryptoJS) { 12923 12924 (function (undefined) { 12925 // Shortcuts 12926 var C = CryptoJS; 12927 var C_lib = C.lib; 12928 var Base = C_lib.Base; 12929 var X32WordArray = C_lib.WordArray; 12930 12931 /** 12932 * x64 namespace. 12933 */ 12934 var C_x64 = C.x64 = {}; 12935 12936 /** 12937 * A 64-bit word. 12938 */ 12939 var X64Word = C_x64.Word = Base.extend({ 12940 /** 12941 * Initializes a newly created 64-bit word. 12942 * 12943 * @param {number} high The high 32 bits. 12944 * @param {number} low The low 32 bits. 12945 * 12946 * @example 12947 * 12948 * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); 12949 */ 12950 init: function (high, low) { 12951 this.high = high; 12952 this.low = low; 12953 } 12954 12955 /** 12956 * Bitwise NOTs this word. 12957 * 12958 * @return {X64Word} A new x64-Word object after negating. 12959 * 12960 * @example 12961 * 12962 * var negated = x64Word.not(); 12963 */ 12964 // not: function () { 12965 // var high = ~this.high; 12966 // var low = ~this.low; 12967 12968 // return X64Word.create(high, low); 12969 // }, 12970 12971 /** 12972 * Bitwise ANDs this word with the passed word. 12973 * 12974 * @param {X64Word} word The x64-Word to AND with this word. 12975 * 12976 * @return {X64Word} A new x64-Word object after ANDing. 12977 * 12978 * @example 12979 * 12980 * var anded = x64Word.and(anotherX64Word); 12981 */ 12982 // and: function (word) { 12983 // var high = this.high & word.high; 12984 // var low = this.low & word.low; 12985 12986 // return X64Word.create(high, low); 12987 // }, 12988 12989 /** 12990 * Bitwise ORs this word with the passed word. 12991 * 12992 * @param {X64Word} word The x64-Word to OR with this word. 12993 * 12994 * @return {X64Word} A new x64-Word object after ORing. 12995 * 12996 * @example 12997 * 12998 * var ored = x64Word.or(anotherX64Word); 12999 */ 13000 // or: function (word) { 13001 // var high = this.high | word.high; 13002 // var low = this.low | word.low; 13003 13004 // return X64Word.create(high, low); 13005 // }, 13006 13007 /** 13008 * Bitwise XORs this word with the passed word. 13009 * 13010 * @param {X64Word} word The x64-Word to XOR with this word. 13011 * 13012 * @return {X64Word} A new x64-Word object after XORing. 13013 * 13014 * @example 13015 * 13016 * var xored = x64Word.xor(anotherX64Word); 13017 */ 13018 // xor: function (word) { 13019 // var high = this.high ^ word.high; 13020 // var low = this.low ^ word.low; 13021 13022 // return X64Word.create(high, low); 13023 // }, 13024 13025 /** 13026 * Shifts this word n bits to the left. 13027 * 13028 * @param {number} n The number of bits to shift. 13029 * 13030 * @return {X64Word} A new x64-Word object after shifting. 13031 * 13032 * @example 13033 * 13034 * var shifted = x64Word.shiftL(25); 13035 */ 13036 // shiftL: function (n) { 13037 // if (n < 32) { 13038 // var high = (this.high << n) | (this.low >>> (32 - n)); 13039 // var low = this.low << n; 13040 // } else { 13041 // var high = this.low << (n - 32); 13042 // var low = 0; 13043 // } 13044 13045 // return X64Word.create(high, low); 13046 // }, 13047 13048 /** 13049 * Shifts this word n bits to the right. 13050 * 13051 * @param {number} n The number of bits to shift. 13052 * 13053 * @return {X64Word} A new x64-Word object after shifting. 13054 * 13055 * @example 13056 * 13057 * var shifted = x64Word.shiftR(7); 13058 */ 13059 // shiftR: function (n) { 13060 // if (n < 32) { 13061 // var low = (this.low >>> n) | (this.high << (32 - n)); 13062 // var high = this.high >>> n; 13063 // } else { 13064 // var low = this.high >>> (n - 32); 13065 // var high = 0; 13066 // } 13067 13068 // return X64Word.create(high, low); 13069 // }, 13070 13071 /** 13072 * Rotates this word n bits to the left. 13073 * 13074 * @param {number} n The number of bits to rotate. 13075 * 13076 * @return {X64Word} A new x64-Word object after rotating. 13077 * 13078 * @example 13079 * 13080 * var rotated = x64Word.rotL(25); 13081 */ 13082 // rotL: function (n) { 13083 // return this.shiftL(n).or(this.shiftR(64 - n)); 13084 // }, 13085 13086 /** 13087 * Rotates this word n bits to the right. 13088 * 13089 * @param {number} n The number of bits to rotate. 13090 * 13091 * @return {X64Word} A new x64-Word object after rotating. 13092 * 13093 * @example 13094 * 13095 * var rotated = x64Word.rotR(7); 13096 */ 13097 // rotR: function (n) { 13098 // return this.shiftR(n).or(this.shiftL(64 - n)); 13099 // }, 13100 13101 /** 13102 * Adds this word with the passed word. 13103 * 13104 * @param {X64Word} word The x64-Word to add with this word. 13105 * 13106 * @return {X64Word} A new x64-Word object after adding. 13107 * 13108 * @example 13109 * 13110 * var added = x64Word.add(anotherX64Word); 13111 */ 13112 // add: function (word) { 13113 // var low = (this.low + word.low) | 0; 13114 // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; 13115 // var high = (this.high + word.high + carry) | 0; 13116 13117 // return X64Word.create(high, low); 13118 // } 13119 }); 13120 13121 /** 13122 * An array of 64-bit words. 13123 * 13124 * @property {Array} words The array of CryptoJS.x64.Word objects. 13125 * @property {number} sigBytes The number of significant bytes in this word array. 13126 */ 13127 var X64WordArray = C_x64.WordArray = Base.extend({ 13128 /** 13129 * Initializes a newly created word array. 13130 * 13131 * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. 13132 * @param {number} sigBytes (Optional) The number of significant bytes in the words. 13133 * 13134 * @example 13135 * 13136 * var wordArray = CryptoJS.x64.WordArray.create(); 13137 * 13138 * var wordArray = CryptoJS.x64.WordArray.create([ 13139 * CryptoJS.x64.Word.create(0x00010203, 0x04050607), 13140 * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) 13141 * ]); 13142 * 13143 * var wordArray = CryptoJS.x64.WordArray.create([ 13144 * CryptoJS.x64.Word.create(0x00010203, 0x04050607), 13145 * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) 13146 * ], 10); 13147 */ 13148 init: function (words, sigBytes) { 13149 words = this.words = words || []; 13150 13151 if (sigBytes != undefined) { 13152 this.sigBytes = sigBytes; 13153 } else { 13154 this.sigBytes = words.length * 8; 13155 } 13156 }, 13157 13158 /** 13159 * Converts this 64-bit word array to a 32-bit word array. 13160 * 13161 * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. 13162 * 13163 * @example 13164 * 13165 * var x32WordArray = x64WordArray.toX32(); 13166 */ 13167 toX32: function () { 13168 // Shortcuts 13169 var x64Words = this.words; 13170 var x64WordsLength = x64Words.length; 13171 13172 // Convert 13173 var x32Words = []; 13174 for (var i = 0; i < x64WordsLength; i++) { 13175 var x64Word = x64Words[i]; 13176 x32Words.push(x64Word.high); 13177 x32Words.push(x64Word.low); 13178 } 13179 13180 return X32WordArray.create(x32Words, this.sigBytes); 13181 }, 13182 13183 /** 13184 * Creates a copy of this word array. 13185 * 13186 * @return {X64WordArray} The clone. 13187 * 13188 * @example 13189 * 13190 * var clone = x64WordArray.clone(); 13191 */ 13192 clone: function () { 13193 var clone = Base.clone.call(this); 13194 13195 // Clone "words" array 13196 var words = clone.words = this.words.slice(0); 13197 13198 // Clone each X64Word object 13199 var wordsLength = words.length; 13200 for (var i = 0; i < wordsLength; i++) { 13201 words[i] = words[i].clone(); 13202 } 13203 13204 return clone; 13205 } 13206 }); 13207 }()); 13208 13209 13210 return CryptoJS; 13211 13212 })); 13213 },{"./core":53}],85:[function(require,module,exports){ 13214 /*! https://mths.be/utf8js v2.1.2 by @mathias */ 13215 ;(function(root) { 13216 13217 // Detect free variables `exports` 13218 var freeExports = typeof exports == 'object' && exports; 13219 13220 // Detect free variable `module` 13221 var freeModule = typeof module == 'object' && module && 13222 module.exports == freeExports && module; 13223 13224 // Detect free variable `global`, from Node.js or Browserified code, 13225 // and use it as `root` 13226 var freeGlobal = typeof global == 'object' && global; 13227 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { 13228 root = freeGlobal; 13229 } 13230 13231 /*--------------------------------------------------------------------------*/ 13232 13233 var stringFromCharCode = String.fromCharCode; 13234 13235 // Taken from https://mths.be/punycode 13236 function ucs2decode(string) { 13237 var output = []; 13238 var counter = 0; 13239 var length = string.length; 13240 var value; 13241 var extra; 13242 while (counter < length) { 13243 value = string.charCodeAt(counter++); 13244 if (value >= 0xD800 && value <= 0xDBFF && counter < length) { 13245 // high surrogate, and there is a next character 13246 extra = string.charCodeAt(counter++); 13247 if ((extra & 0xFC00) == 0xDC00) { // low surrogate 13248 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); 13249 } else { 13250 // unmatched surrogate; only append this code unit, in case the next 13251 // code unit is the high surrogate of a surrogate pair 13252 output.push(value); 13253 counter--; 13254 } 13255 } else { 13256 output.push(value); 13257 } 13258 } 13259 return output; 13260 } 13261 13262 // Taken from https://mths.be/punycode 13263 function ucs2encode(array) { 13264 var length = array.length; 13265 var index = -1; 13266 var value; 13267 var output = ''; 13268 while (++index < length) { 13269 value = array[index]; 13270 if (value > 0xFFFF) { 13271 value -= 0x10000; 13272 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); 13273 value = 0xDC00 | value & 0x3FF; 13274 } 13275 output += stringFromCharCode(value); 13276 } 13277 return output; 13278 } 13279 13280 function checkScalarValue(codePoint) { 13281 if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { 13282 throw Error( 13283 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + 13284 ' is not a scalar value' 13285 ); 13286 } 13287 } 13288 /*--------------------------------------------------------------------------*/ 13289 13290 function createByte(codePoint, shift) { 13291 return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); 13292 } 13293 13294 function encodeCodePoint(codePoint) { 13295 if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence 13296 return stringFromCharCode(codePoint); 13297 } 13298 var symbol = ''; 13299 if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence 13300 symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); 13301 } 13302 else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence 13303 checkScalarValue(codePoint); 13304 symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); 13305 symbol += createByte(codePoint, 6); 13306 } 13307 else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence 13308 symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); 13309 symbol += createByte(codePoint, 12); 13310 symbol += createByte(codePoint, 6); 13311 } 13312 symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); 13313 return symbol; 13314 } 13315 13316 function utf8encode(string) { 13317 var codePoints = ucs2decode(string); 13318 var length = codePoints.length; 13319 var index = -1; 13320 var codePoint; 13321 var byteString = ''; 13322 while (++index < length) { 13323 codePoint = codePoints[index]; 13324 byteString += encodeCodePoint(codePoint); 13325 } 13326 return byteString; 13327 } 13328 13329 /*--------------------------------------------------------------------------*/ 13330 13331 function readContinuationByte() { 13332 if (byteIndex >= byteCount) { 13333 throw Error('Invalid byte index'); 13334 } 13335 13336 var continuationByte = byteArray[byteIndex] & 0xFF; 13337 byteIndex++; 13338 13339 if ((continuationByte & 0xC0) == 0x80) { 13340 return continuationByte & 0x3F; 13341 } 13342 13343 // If we end up here, it’s not a continuation byte 13344 throw Error('Invalid continuation byte'); 13345 } 13346 13347 function decodeSymbol() { 13348 var byte1; 13349 var byte2; 13350 var byte3; 13351 var byte4; 13352 var codePoint; 13353 13354 if (byteIndex > byteCount) { 13355 throw Error('Invalid byte index'); 13356 } 13357 13358 if (byteIndex == byteCount) { 13359 return false; 13360 } 13361 13362 // Read first byte 13363 byte1 = byteArray[byteIndex] & 0xFF; 13364 byteIndex++; 13365 13366 // 1-byte sequence (no continuation bytes) 13367 if ((byte1 & 0x80) == 0) { 13368 return byte1; 13369 } 13370 13371 // 2-byte sequence 13372 if ((byte1 & 0xE0) == 0xC0) { 13373 byte2 = readContinuationByte(); 13374 codePoint = ((byte1 & 0x1F) << 6) | byte2; 13375 if (codePoint >= 0x80) { 13376 return codePoint; 13377 } else { 13378 throw Error('Invalid continuation byte'); 13379 } 13380 } 13381 13382 // 3-byte sequence (may include unpaired surrogates) 13383 if ((byte1 & 0xF0) == 0xE0) { 13384 byte2 = readContinuationByte(); 13385 byte3 = readContinuationByte(); 13386 codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; 13387 if (codePoint >= 0x0800) { 13388 checkScalarValue(codePoint); 13389 return codePoint; 13390 } else { 13391 throw Error('Invalid continuation byte'); 13392 } 13393 } 13394 13395 // 4-byte sequence 13396 if ((byte1 & 0xF8) == 0xF0) { 13397 byte2 = readContinuationByte(); 13398 byte3 = readContinuationByte(); 13399 byte4 = readContinuationByte(); 13400 codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | 13401 (byte3 << 0x06) | byte4; 13402 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { 13403 return codePoint; 13404 } 13405 } 13406 13407 throw Error('Invalid UTF-8 detected'); 13408 } 13409 13410 var byteArray; 13411 var byteCount; 13412 var byteIndex; 13413 function utf8decode(byteString) { 13414 byteArray = ucs2decode(byteString); 13415 byteCount = byteArray.length; 13416 byteIndex = 0; 13417 var codePoints = []; 13418 var tmp; 13419 while ((tmp = decodeSymbol()) !== false) { 13420 codePoints.push(tmp); 13421 } 13422 return ucs2encode(codePoints); 13423 } 13424 13425 /*--------------------------------------------------------------------------*/ 13426 13427 var utf8 = { 13428 'version': '2.1.2', 13429 'encode': utf8encode, 13430 'decode': utf8decode 13431 }; 13432 13433 // Some AMD build optimizers, like r.js, check for specific condition patterns 13434 // like the following: 13435 if ( 13436 typeof define == 'function' && 13437 typeof define.amd == 'object' && 13438 define.amd 13439 ) { 13440 define(function() { 13441 return utf8; 13442 }); 13443 } else if (freeExports && !freeExports.nodeType) { 13444 if (freeModule) { // in Node.js or RingoJS v0.8.0+ 13445 freeModule.exports = utf8; 13446 } else { // in Narwhal or RingoJS v0.7.0- 13447 var object = {}; 13448 var hasOwnProperty = object.hasOwnProperty; 13449 for (var key in utf8) { 13450 hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); 13451 } 13452 } 13453 } else { // in Rhino or a web browser 13454 root.utf8 = utf8; 13455 } 13456 13457 }(this)); 13458 13459 },{}],86:[function(require,module,exports){ 13460 module.exports = XMLHttpRequest; 13461 13462 },{}],"bignumber.js":[function(require,module,exports){ 13463 /*! bignumber.js v2.0.7 https://github.com/MikeMcl/bignumber.js/LICENCE */ 13464 13465 ;(function (global) { 13466 'use strict'; 13467 13468 /* 13469 bignumber.js v2.0.7 13470 A JavaScript library for arbitrary-precision arithmetic. 13471 https://github.com/MikeMcl/bignumber.js 13472 Copyright (c) 2015 Michael Mclaughlin <M8ch88l@gmail.com> 13473 MIT Expat Licence 13474 */ 13475 13476 13477 var BigNumber, crypto, parseNumeric, 13478 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, 13479 mathceil = Math.ceil, 13480 mathfloor = Math.floor, 13481 notBool = ' not a boolean or binary digit', 13482 roundingMode = 'rounding mode', 13483 tooManyDigits = 'number type has more than 15 significant digits', 13484 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_', 13485 BASE = 1e14, 13486 LOG_BASE = 14, 13487 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 13488 // MAX_INT32 = 0x7fffffff, // 2^31 - 1 13489 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], 13490 SQRT_BASE = 1e7, 13491 13492 /* 13493 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and 13494 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an 13495 * exception is thrown (if ERRORS is true). 13496 */ 13497 MAX = 1E9; // 0 to MAX_INT32 13498 13499 13500 /* 13501 * Create and return a BigNumber constructor. 13502 */ 13503 function another(configObj) { 13504 var div, 13505 13506 // id tracks the caller function, so its name can be included in error messages. 13507 id = 0, 13508 P = BigNumber.prototype, 13509 ONE = new BigNumber(1), 13510 13511 13512 /********************************* EDITABLE DEFAULTS **********************************/ 13513 13514 13515 /* 13516 * The default values below must be integers within the inclusive ranges stated. 13517 * The values can also be changed at run-time using BigNumber.config. 13518 */ 13519 13520 // The maximum number of decimal places for operations involving division. 13521 DECIMAL_PLACES = 20, // 0 to MAX 13522 13523 /* 13524 * The rounding mode used when rounding to the above decimal places, and when using 13525 * toExponential, toFixed, toFormat and toPrecision, and round (default value). 13526 * UP 0 Away from zero. 13527 * DOWN 1 Towards zero. 13528 * CEIL 2 Towards +Infinity. 13529 * FLOOR 3 Towards -Infinity. 13530 * HALF_UP 4 Towards nearest neighbour. If equidistant, up. 13531 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. 13532 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. 13533 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. 13534 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. 13535 */ 13536 ROUNDING_MODE = 4, // 0 to 8 13537 13538 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] 13539 13540 // The exponent value at and beneath which toString returns exponential notation. 13541 // Number type: -7 13542 TO_EXP_NEG = -7, // 0 to -MAX 13543 13544 // The exponent value at and above which toString returns exponential notation. 13545 // Number type: 21 13546 TO_EXP_POS = 21, // 0 to MAX 13547 13548 // RANGE : [MIN_EXP, MAX_EXP] 13549 13550 // The minimum exponent value, beneath which underflow to zero occurs. 13551 // Number type: -324 (5e-324) 13552 MIN_EXP = -1e7, // -1 to -MAX 13553 13554 // The maximum exponent value, above which overflow to Infinity occurs. 13555 // Number type: 308 (1.7976931348623157e+308) 13556 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. 13557 MAX_EXP = 1e7, // 1 to MAX 13558 13559 // Whether BigNumber Errors are ever thrown. 13560 ERRORS = true, // true or false 13561 13562 // Change to intValidatorNoErrors if ERRORS is false. 13563 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors 13564 13565 // Whether to use cryptographically-secure random number generation, if available. 13566 CRYPTO = false, // true or false 13567 13568 /* 13569 * The modulo mode used when calculating the modulus: a mod n. 13570 * The quotient (q = a / n) is calculated according to the corresponding rounding mode. 13571 * The remainder (r) is calculated as: r = a - n * q. 13572 * 13573 * UP 0 The remainder is positive if the dividend is negative, else is negative. 13574 * DOWN 1 The remainder has the same sign as the dividend. 13575 * This modulo mode is commonly known as 'truncated division' and is 13576 * equivalent to (a % n) in JavaScript. 13577 * FLOOR 3 The remainder has the same sign as the divisor (Python %). 13578 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. 13579 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). 13580 * The remainder is always positive. 13581 * 13582 * The truncated division, floored division, Euclidian division and IEEE 754 remainder 13583 * modes are commonly used for the modulus operation. 13584 * Although the other rounding modes can also be used, they may not give useful results. 13585 */ 13586 MODULO_MODE = 1, // 0 to 9 13587 13588 // The maximum number of significant digits of the result of the toPower operation. 13589 // If POW_PRECISION is 0, there will be unlimited significant digits. 13590 POW_PRECISION = 100, // 0 to MAX 13591 13592 // The format specification used by the BigNumber.prototype.toFormat method. 13593 FORMAT = { 13594 decimalSeparator: '.', 13595 groupSeparator: ',', 13596 groupSize: 3, 13597 secondaryGroupSize: 0, 13598 fractionGroupSeparator: '\xA0', // non-breaking space 13599 fractionGroupSize: 0 13600 }; 13601 13602 13603 /******************************************************************************************/ 13604 13605 13606 // CONSTRUCTOR 13607 13608 13609 /* 13610 * The BigNumber constructor and exported function. 13611 * Create and return a new instance of a BigNumber object. 13612 * 13613 * n {number|string|BigNumber} A numeric value. 13614 * [b] {number} The base of n. Integer, 2 to 64 inclusive. 13615 */ 13616 function BigNumber( n, b ) { 13617 var c, e, i, num, len, str, 13618 x = this; 13619 13620 // Enable constructor usage without new. 13621 if ( !( x instanceof BigNumber ) ) { 13622 13623 // 'BigNumber() constructor call without new: {n}' 13624 if (ERRORS) raise( 26, 'constructor call without new', n ); 13625 return new BigNumber( n, b ); 13626 } 13627 13628 // 'new BigNumber() base not an integer: {b}' 13629 // 'new BigNumber() base out of range: {b}' 13630 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { 13631 13632 // Duplicate. 13633 if ( n instanceof BigNumber ) { 13634 x.s = n.s; 13635 x.e = n.e; 13636 x.c = ( n = n.c ) ? n.slice() : n; 13637 id = 0; 13638 return; 13639 } 13640 13641 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { 13642 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; 13643 13644 // Fast path for integers. 13645 if ( n === ~~n ) { 13646 for ( e = 0, i = n; i >= 10; i /= 10, e++ ); 13647 x.e = e; 13648 x.c = [n]; 13649 id = 0; 13650 return; 13651 } 13652 13653 str = n + ''; 13654 } else { 13655 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); 13656 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; 13657 } 13658 } else { 13659 b = b | 0; 13660 str = n + ''; 13661 13662 // Ensure return value is rounded to DECIMAL_PLACES as with other bases. 13663 // Allow exponential notation to be used with base 10 argument. 13664 if ( b == 10 ) { 13665 x = new BigNumber( n instanceof BigNumber ? n : str ); 13666 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); 13667 } 13668 13669 // Avoid potential interpretation of Infinity and NaN as base 44+ values. 13670 // Any number in exponential form will fail due to the [Ee][+-]. 13671 if ( ( num = typeof n == 'number' ) && n * 0 != 0 || 13672 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + 13673 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { 13674 return parseNumeric( x, str, num, b ); 13675 } 13676 13677 if (num) { 13678 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; 13679 13680 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { 13681 13682 // 'new BigNumber() number type has more than 15 significant digits: {n}' 13683 raise( id, tooManyDigits, n ); 13684 } 13685 13686 // Prevent later check for length on converted number. 13687 num = false; 13688 } else { 13689 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; 13690 } 13691 13692 str = convertBase( str, 10, b, x.s ); 13693 } 13694 13695 // Decimal point? 13696 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); 13697 13698 // Exponential form? 13699 if ( ( i = str.search( /e/i ) ) > 0 ) { 13700 13701 // Determine exponent. 13702 if ( e < 0 ) e = i; 13703 e += +str.slice( i + 1 ); 13704 str = str.substring( 0, i ); 13705 } else if ( e < 0 ) { 13706 13707 // Integer. 13708 e = str.length; 13709 } 13710 13711 // Determine leading zeros. 13712 for ( i = 0; str.charCodeAt(i) === 48; i++ ); 13713 13714 // Determine trailing zeros. 13715 for ( len = str.length; str.charCodeAt(--len) === 48; ); 13716 str = str.slice( i, len + 1 ); 13717 13718 if (str) { 13719 len = str.length; 13720 13721 // Disallow numbers with over 15 significant digits if number type. 13722 // 'new BigNumber() number type has more than 15 significant digits: {n}' 13723 if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n ); 13724 13725 e = e - i - 1; 13726 13727 // Overflow? 13728 if ( e > MAX_EXP ) { 13729 13730 // Infinity. 13731 x.c = x.e = null; 13732 13733 // Underflow? 13734 } else if ( e < MIN_EXP ) { 13735 13736 // Zero. 13737 x.c = [ x.e = 0 ]; 13738 } else { 13739 x.e = e; 13740 x.c = []; 13741 13742 // Transform base 13743 13744 // e is the base 10 exponent. 13745 // i is where to slice str to get the first element of the coefficient array. 13746 i = ( e + 1 ) % LOG_BASE; 13747 if ( e < 0 ) i += LOG_BASE; 13748 13749 if ( i < len ) { 13750 if (i) x.c.push( +str.slice( 0, i ) ); 13751 13752 for ( len -= LOG_BASE; i < len; ) { 13753 x.c.push( +str.slice( i, i += LOG_BASE ) ); 13754 } 13755 13756 str = str.slice(i); 13757 i = LOG_BASE - str.length; 13758 } else { 13759 i -= len; 13760 } 13761 13762 for ( ; i--; str += '0' ); 13763 x.c.push( +str ); 13764 } 13765 } else { 13766 13767 // Zero. 13768 x.c = [ x.e = 0 ]; 13769 } 13770 13771 id = 0; 13772 } 13773 13774 13775 // CONSTRUCTOR PROPERTIES 13776 13777 13778 BigNumber.another = another; 13779 13780 BigNumber.ROUND_UP = 0; 13781 BigNumber.ROUND_DOWN = 1; 13782 BigNumber.ROUND_CEIL = 2; 13783 BigNumber.ROUND_FLOOR = 3; 13784 BigNumber.ROUND_HALF_UP = 4; 13785 BigNumber.ROUND_HALF_DOWN = 5; 13786 BigNumber.ROUND_HALF_EVEN = 6; 13787 BigNumber.ROUND_HALF_CEIL = 7; 13788 BigNumber.ROUND_HALF_FLOOR = 8; 13789 BigNumber.EUCLID = 9; 13790 13791 13792 /* 13793 * Configure infrequently-changing library-wide settings. 13794 * 13795 * Accept an object or an argument list, with one or many of the following properties or 13796 * parameters respectively: 13797 * 13798 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive 13799 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive 13800 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or 13801 * [integer -MAX to 0 incl., 0 to MAX incl.] 13802 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or 13803 * [integer -MAX to -1 incl., integer 1 to MAX incl.] 13804 * ERRORS {boolean|number} true, false, 1 or 0 13805 * CRYPTO {boolean|number} true, false, 1 or 0 13806 * MODULO_MODE {number} 0 to 9 inclusive 13807 * POW_PRECISION {number} 0 to MAX inclusive 13808 * FORMAT {object} See BigNumber.prototype.toFormat 13809 * decimalSeparator {string} 13810 * groupSeparator {string} 13811 * groupSize {number} 13812 * secondaryGroupSize {number} 13813 * fractionGroupSeparator {string} 13814 * fractionGroupSize {number} 13815 * 13816 * (The values assigned to the above FORMAT object properties are not checked for validity.) 13817 * 13818 * E.g. 13819 * BigNumber.config(20, 4) is equivalent to 13820 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) 13821 * 13822 * Ignore properties/parameters set to null or undefined. 13823 * Return an object with the properties current values. 13824 */ 13825 BigNumber.config = function () { 13826 var v, p, 13827 i = 0, 13828 r = {}, 13829 a = arguments, 13830 o = a[0], 13831 has = o && typeof o == 'object' 13832 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; } 13833 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; }; 13834 13835 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. 13836 // 'config() DECIMAL_PLACES not an integer: {v}' 13837 // 'config() DECIMAL_PLACES out of range: {v}' 13838 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) { 13839 DECIMAL_PLACES = v | 0; 13840 } 13841 r[p] = DECIMAL_PLACES; 13842 13843 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. 13844 // 'config() ROUNDING_MODE not an integer: {v}' 13845 // 'config() ROUNDING_MODE out of range: {v}' 13846 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) { 13847 ROUNDING_MODE = v | 0; 13848 } 13849 r[p] = ROUNDING_MODE; 13850 13851 // EXPONENTIAL_AT {number|number[]} 13852 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive]. 13853 // 'config() EXPONENTIAL_AT not an integer: {v}' 13854 // 'config() EXPONENTIAL_AT out of range: {v}' 13855 if ( has( p = 'EXPONENTIAL_AT' ) ) { 13856 13857 if ( isArray(v) ) { 13858 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) { 13859 TO_EXP_NEG = v[0] | 0; 13860 TO_EXP_POS = v[1] | 0; 13861 } 13862 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { 13863 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); 13864 } 13865 } 13866 r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; 13867 13868 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or 13869 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. 13870 // 'config() RANGE not an integer: {v}' 13871 // 'config() RANGE cannot be zero: {v}' 13872 // 'config() RANGE out of range: {v}' 13873 if ( has( p = 'RANGE' ) ) { 13874 13875 if ( isArray(v) ) { 13876 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { 13877 MIN_EXP = v[0] | 0; 13878 MAX_EXP = v[1] | 0; 13879 } 13880 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { 13881 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 ); 13882 else if (ERRORS) raise( 2, p + ' cannot be zero', v ); 13883 } 13884 } 13885 r[p] = [ MIN_EXP, MAX_EXP ]; 13886 13887 // ERRORS {boolean|number} true, false, 1 or 0. 13888 // 'config() ERRORS not a boolean or binary digit: {v}' 13889 if ( has( p = 'ERRORS' ) ) { 13890 13891 if ( v === !!v || v === 1 || v === 0 ) { 13892 id = 0; 13893 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; 13894 } else if (ERRORS) { 13895 raise( 2, p + notBool, v ); 13896 } 13897 } 13898 r[p] = ERRORS; 13899 13900 // CRYPTO {boolean|number} true, false, 1 or 0. 13901 // 'config() CRYPTO not a boolean or binary digit: {v}' 13902 // 'config() crypto unavailable: {crypto}' 13903 if ( has( p = 'CRYPTO' ) ) { 13904 13905 if ( v === !!v || v === 1 || v === 0 ) { 13906 CRYPTO = !!( v && crypto && typeof crypto == 'object' ); 13907 if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', crypto ); 13908 } else if (ERRORS) { 13909 raise( 2, p + notBool, v ); 13910 } 13911 } 13912 r[p] = CRYPTO; 13913 13914 // MODULO_MODE {number} Integer, 0 to 9 inclusive. 13915 // 'config() MODULO_MODE not an integer: {v}' 13916 // 'config() MODULO_MODE out of range: {v}' 13917 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) { 13918 MODULO_MODE = v | 0; 13919 } 13920 r[p] = MODULO_MODE; 13921 13922 // POW_PRECISION {number} Integer, 0 to MAX inclusive. 13923 // 'config() POW_PRECISION not an integer: {v}' 13924 // 'config() POW_PRECISION out of range: {v}' 13925 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) { 13926 POW_PRECISION = v | 0; 13927 } 13928 r[p] = POW_PRECISION; 13929 13930 // FORMAT {object} 13931 // 'config() FORMAT not an object: {v}' 13932 if ( has( p = 'FORMAT' ) ) { 13933 13934 if ( typeof v == 'object' ) { 13935 FORMAT = v; 13936 } else if (ERRORS) { 13937 raise( 2, p + ' not an object', v ); 13938 } 13939 } 13940 r[p] = FORMAT; 13941 13942 return r; 13943 }; 13944 13945 13946 /* 13947 * Return a new BigNumber whose value is the maximum of the arguments. 13948 * 13949 * arguments {number|string|BigNumber} 13950 */ 13951 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); }; 13952 13953 13954 /* 13955 * Return a new BigNumber whose value is the minimum of the arguments. 13956 * 13957 * arguments {number|string|BigNumber} 13958 */ 13959 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); }; 13960 13961 13962 /* 13963 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, 13964 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing 13965 * zeros are produced). 13966 * 13967 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 13968 * 13969 * 'random() decimal places not an integer: {dp}' 13970 * 'random() decimal places out of range: {dp}' 13971 * 'random() crypto unavailable: {crypto}' 13972 */ 13973 BigNumber.random = (function () { 13974 var pow2_53 = 0x20000000000000; 13975 13976 // Return a 53 bit integer n, where 0 <= n < 9007199254740992. 13977 // Check if Math.random() produces more than 32 bits of randomness. 13978 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. 13979 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. 13980 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff 13981 ? function () { return mathfloor( Math.random() * pow2_53 ); } 13982 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + 13983 (Math.random() * 0x800000 | 0); }; 13984 13985 return function (dp) { 13986 var a, b, e, k, v, 13987 i = 0, 13988 c = [], 13989 rand = new BigNumber(ONE); 13990 13991 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; 13992 k = mathceil( dp / LOG_BASE ); 13993 13994 if (CRYPTO) { 13995 13996 // Browsers supporting crypto.getRandomValues. 13997 if ( crypto && crypto.getRandomValues ) { 13998 13999 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); 14000 14001 for ( ; i < k; ) { 14002 14003 // 53 bits: 14004 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) 14005 // 11111 11111111 11111111 11111111 11100000 00000000 00000000 14006 // ((Math.pow(2, 32) - 1) >>> 11).toString(2) 14007 // 11111 11111111 11111111 14008 // 0x20000 is 2^21. 14009 v = a[i] * 0x20000 + (a[i + 1] >>> 11); 14010 14011 // Rejection sampling: 14012 // 0 <= v < 9007199254740992 14013 // Probability that v >= 9e15, is 14014 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 14015 if ( v >= 9e15 ) { 14016 b = crypto.getRandomValues( new Uint32Array(2) ); 14017 a[i] = b[0]; 14018 a[i + 1] = b[1]; 14019 } else { 14020 14021 // 0 <= v <= 8999999999999999 14022 // 0 <= (v % 1e14) <= 99999999999999 14023 c.push( v % 1e14 ); 14024 i += 2; 14025 } 14026 } 14027 i = k / 2; 14028 14029 // Node.js supporting crypto.randomBytes. 14030 } else if ( crypto && crypto.randomBytes ) { 14031 14032 // buffer 14033 a = crypto.randomBytes( k *= 7 ); 14034 14035 for ( ; i < k; ) { 14036 14037 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 14038 // 0x100000000 is 2^32, 0x1000000 is 2^24 14039 // 11111 11111111 11111111 11111111 11111111 11111111 11111111 14040 // 0 <= v < 9007199254740992 14041 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + 14042 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + 14043 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; 14044 14045 if ( v >= 9e15 ) { 14046 crypto.randomBytes(7).copy( a, i ); 14047 } else { 14048 14049 // 0 <= (v % 1e14) <= 99999999999999 14050 c.push( v % 1e14 ); 14051 i += 7; 14052 } 14053 } 14054 i = k / 7; 14055 } else if (ERRORS) { 14056 raise( 14, 'crypto unavailable', crypto ); 14057 } 14058 } 14059 14060 // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false. 14061 if (!i) { 14062 14063 for ( ; i < k; ) { 14064 v = random53bitInt(); 14065 if ( v < 9e15 ) c[i++] = v % 1e14; 14066 } 14067 } 14068 14069 k = c[--i]; 14070 dp %= LOG_BASE; 14071 14072 // Convert trailing digits to zeros according to dp. 14073 if ( k && dp ) { 14074 v = POWS_TEN[LOG_BASE - dp]; 14075 c[i] = mathfloor( k / v ) * v; 14076 } 14077 14078 // Remove trailing elements which are zero. 14079 for ( ; c[i] === 0; c.pop(), i-- ); 14080 14081 // Zero? 14082 if ( i < 0 ) { 14083 c = [ e = 0 ]; 14084 } else { 14085 14086 // Remove leading elements which are zero and adjust exponent accordingly. 14087 for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE); 14088 14089 // Count the digits of the first element of c to determine leading zeros, and... 14090 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); 14091 14092 // adjust the exponent accordingly. 14093 if ( i < LOG_BASE ) e -= LOG_BASE - i; 14094 } 14095 14096 rand.e = e; 14097 rand.c = c; 14098 return rand; 14099 }; 14100 })(); 14101 14102 14103 // PRIVATE FUNCTIONS 14104 14105 14106 // Convert a numeric string of baseIn to a numeric string of baseOut. 14107 function convertBase( str, baseOut, baseIn, sign ) { 14108 var d, e, k, r, x, xc, y, 14109 i = str.indexOf( '.' ), 14110 dp = DECIMAL_PLACES, 14111 rm = ROUNDING_MODE; 14112 14113 if ( baseIn < 37 ) str = str.toLowerCase(); 14114 14115 // Non-integer. 14116 if ( i >= 0 ) { 14117 k = POW_PRECISION; 14118 14119 // Unlimited precision. 14120 POW_PRECISION = 0; 14121 str = str.replace( '.', '' ); 14122 y = new BigNumber(baseIn); 14123 x = y.pow( str.length - i ); 14124 POW_PRECISION = k; 14125 14126 // Convert str as if an integer, then restore the fraction part by dividing the 14127 // result by its base raised to a power. 14128 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut ); 14129 y.e = y.c.length; 14130 } 14131 14132 // Convert the number as integer. 14133 xc = toBaseOut( str, baseIn, baseOut ); 14134 e = k = xc.length; 14135 14136 // Remove trailing zeros. 14137 for ( ; xc[--k] == 0; xc.pop() ); 14138 if ( !xc[0] ) return '0'; 14139 14140 if ( i < 0 ) { 14141 --e; 14142 } else { 14143 x.c = xc; 14144 x.e = e; 14145 14146 // sign is needed for correct rounding. 14147 x.s = sign; 14148 x = div( x, y, dp, rm, baseOut ); 14149 xc = x.c; 14150 r = x.r; 14151 e = x.e; 14152 } 14153 14154 d = e + dp + 1; 14155 14156 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up. 14157 i = xc[d]; 14158 k = baseOut / 2; 14159 r = r || d < 0 || xc[d + 1] != null; 14160 14161 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) 14162 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || 14163 rm == ( x.s < 0 ? 8 : 7 ) ); 14164 14165 if ( d < 1 || !xc[0] ) { 14166 14167 // 1^-dp or 0. 14168 str = r ? toFixedPoint( '1', -dp ) : '0'; 14169 } else { 14170 xc.length = d; 14171 14172 if (r) { 14173 14174 // Rounding up may mean the previous digit has to be rounded up and so on. 14175 for ( --baseOut; ++xc[--d] > baseOut; ) { 14176 xc[d] = 0; 14177 14178 if ( !d ) { 14179 ++e; 14180 xc.unshift(1); 14181 } 14182 } 14183 } 14184 14185 // Determine trailing zeros. 14186 for ( k = xc.length; !xc[--k]; ); 14187 14188 // E.g. [4, 11, 15] becomes 4bf. 14189 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) ); 14190 str = toFixedPoint( str, e ); 14191 } 14192 14193 // The caller will add the sign. 14194 return str; 14195 } 14196 14197 14198 // Perform division in the specified base. Called by div and convertBase. 14199 div = (function () { 14200 14201 // Assume non-zero x and k. 14202 function multiply( x, k, base ) { 14203 var m, temp, xlo, xhi, 14204 carry = 0, 14205 i = x.length, 14206 klo = k % SQRT_BASE, 14207 khi = k / SQRT_BASE | 0; 14208 14209 for ( x = x.slice(); i--; ) { 14210 xlo = x[i] % SQRT_BASE; 14211 xhi = x[i] / SQRT_BASE | 0; 14212 m = khi * xlo + xhi * klo; 14213 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry; 14214 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi; 14215 x[i] = temp % base; 14216 } 14217 14218 if (carry) x.unshift(carry); 14219 14220 return x; 14221 } 14222 14223 function compare( a, b, aL, bL ) { 14224 var i, cmp; 14225 14226 if ( aL != bL ) { 14227 cmp = aL > bL ? 1 : -1; 14228 } else { 14229 14230 for ( i = cmp = 0; i < aL; i++ ) { 14231 14232 if ( a[i] != b[i] ) { 14233 cmp = a[i] > b[i] ? 1 : -1; 14234 break; 14235 } 14236 } 14237 } 14238 return cmp; 14239 } 14240 14241 function subtract( a, b, aL, base ) { 14242 var i = 0; 14243 14244 // Subtract b from a. 14245 for ( ; aL--; ) { 14246 a[aL] -= i; 14247 i = a[aL] < b[aL] ? 1 : 0; 14248 a[aL] = i * base + a[aL] - b[aL]; 14249 } 14250 14251 // Remove leading zeros. 14252 for ( ; !a[0] && a.length > 1; a.shift() ); 14253 } 14254 14255 // x: dividend, y: divisor. 14256 return function ( x, y, dp, rm, base ) { 14257 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, 14258 yL, yz, 14259 s = x.s == y.s ? 1 : -1, 14260 xc = x.c, 14261 yc = y.c; 14262 14263 // Either NaN, Infinity or 0? 14264 if ( !xc || !xc[0] || !yc || !yc[0] ) { 14265 14266 return new BigNumber( 14267 14268 // Return NaN if either NaN, or both Infinity or 0. 14269 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : 14270 14271 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. 14272 xc && xc[0] == 0 || !yc ? s * 0 : s / 0 14273 ); 14274 } 14275 14276 q = new BigNumber(s); 14277 qc = q.c = []; 14278 e = x.e - y.e; 14279 s = dp + e + 1; 14280 14281 if ( !base ) { 14282 base = BASE; 14283 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); 14284 s = s / LOG_BASE | 0; 14285 } 14286 14287 // Result exponent may be one less then the current value of e. 14288 // The coefficients of the BigNumbers from convertBase may have trailing zeros. 14289 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ ); 14290 if ( yc[i] > ( xc[i] || 0 ) ) e--; 14291 14292 if ( s < 0 ) { 14293 qc.push(1); 14294 more = true; 14295 } else { 14296 xL = xc.length; 14297 yL = yc.length; 14298 i = 0; 14299 s += 2; 14300 14301 // Normalise xc and yc so highest order digit of yc is >= base / 2. 14302 14303 n = mathfloor( base / ( yc[0] + 1 ) ); 14304 14305 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. 14306 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { 14307 if ( n > 1 ) { 14308 yc = multiply( yc, n, base ); 14309 xc = multiply( xc, n, base ); 14310 yL = yc.length; 14311 xL = xc.length; 14312 } 14313 14314 xi = yL; 14315 rem = xc.slice( 0, yL ); 14316 remL = rem.length; 14317 14318 // Add zeros to make remainder as long as divisor. 14319 for ( ; remL < yL; rem[remL++] = 0 ); 14320 yz = yc.slice(); 14321 yz.unshift(0); 14322 yc0 = yc[0]; 14323 if ( yc[1] >= base / 2 ) yc0++; 14324 // Not necessary, but to prevent trial digit n > base, when using base 3. 14325 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15; 14326 14327 do { 14328 n = 0; 14329 14330 // Compare divisor and remainder. 14331 cmp = compare( yc, rem, yL, remL ); 14332 14333 // If divisor < remainder. 14334 if ( cmp < 0 ) { 14335 14336 // Calculate trial digit, n. 14337 14338 rem0 = rem[0]; 14339 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); 14340 14341 // n is how many times the divisor goes into the current remainder. 14342 n = mathfloor( rem0 / yc0 ); 14343 14344 // Algorithm: 14345 // 1. product = divisor * trial digit (n) 14346 // 2. if product > remainder: product -= divisor, n-- 14347 // 3. remainder -= product 14348 // 4. if product was < remainder at 2: 14349 // 5. compare new remainder and divisor 14350 // 6. If remainder > divisor: remainder -= divisor, n++ 14351 14352 if ( n > 1 ) { 14353 14354 // n may be > base only when base is 3. 14355 if (n >= base) n = base - 1; 14356 14357 // product = divisor * trial digit. 14358 prod = multiply( yc, n, base ); 14359 prodL = prod.length; 14360 remL = rem.length; 14361 14362 // Compare product and remainder. 14363 // If product > remainder. 14364 // Trial digit n too high. 14365 // n is 1 too high about 5% of the time, and is not known to have 14366 // ever been more than 1 too high. 14367 while ( compare( prod, rem, prodL, remL ) == 1 ) { 14368 n--; 14369 14370 // Subtract divisor from product. 14371 subtract( prod, yL < prodL ? yz : yc, prodL, base ); 14372 prodL = prod.length; 14373 cmp = 1; 14374 } 14375 } else { 14376 14377 // n is 0 or 1, cmp is -1. 14378 // If n is 0, there is no need to compare yc and rem again below, 14379 // so change cmp to 1 to avoid it. 14380 // If n is 1, leave cmp as -1, so yc and rem are compared again. 14381 if ( n == 0 ) { 14382 14383 // divisor < remainder, so n must be at least 1. 14384 cmp = n = 1; 14385 } 14386 14387 // product = divisor 14388 prod = yc.slice(); 14389 prodL = prod.length; 14390 } 14391 14392 if ( prodL < remL ) prod.unshift(0); 14393 14394 // Subtract product from remainder. 14395 subtract( rem, prod, remL, base ); 14396 remL = rem.length; 14397 14398 // If product was < remainder. 14399 if ( cmp == -1 ) { 14400 14401 // Compare divisor and new remainder. 14402 // If divisor < new remainder, subtract divisor from remainder. 14403 // Trial digit n too low. 14404 // n is 1 too low about 5% of the time, and very rarely 2 too low. 14405 while ( compare( yc, rem, yL, remL ) < 1 ) { 14406 n++; 14407 14408 // Subtract divisor from remainder. 14409 subtract( rem, yL < remL ? yz : yc, remL, base ); 14410 remL = rem.length; 14411 } 14412 } 14413 } else if ( cmp === 0 ) { 14414 n++; 14415 rem = [0]; 14416 } // else cmp === 1 and n will be 0 14417 14418 // Add the next digit, n, to the result array. 14419 qc[i++] = n; 14420 14421 // Update the remainder. 14422 if ( rem[0] ) { 14423 rem[remL++] = xc[xi] || 0; 14424 } else { 14425 rem = [ xc[xi] ]; 14426 remL = 1; 14427 } 14428 } while ( ( xi++ < xL || rem[0] != null ) && s-- ); 14429 14430 more = rem[0] != null; 14431 14432 // Leading zero? 14433 if ( !qc[0] ) qc.shift(); 14434 } 14435 14436 if ( base == BASE ) { 14437 14438 // To calculate q.e, first get the number of digits of qc[0]. 14439 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ ); 14440 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more ); 14441 14442 // Caller is convertBase. 14443 } else { 14444 q.e = e; 14445 q.r = +more; 14446 } 14447 14448 return q; 14449 }; 14450 })(); 14451 14452 14453 /* 14454 * Return a string representing the value of BigNumber n in fixed-point or exponential 14455 * notation rounded to the specified decimal places or significant digits. 14456 * 14457 * n is a BigNumber. 14458 * i is the index of the last digit required (i.e. the digit that may be rounded up). 14459 * rm is the rounding mode. 14460 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24. 14461 */ 14462 function format( n, i, rm, caller ) { 14463 var c0, e, ne, len, str; 14464 14465 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode ) 14466 ? rm | 0 : ROUNDING_MODE; 14467 14468 if ( !n.c ) return n.toString(); 14469 c0 = n.c[0]; 14470 ne = n.e; 14471 14472 if ( i == null ) { 14473 str = coeffToString( n.c ); 14474 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG 14475 ? toExponential( str, ne ) 14476 : toFixedPoint( str, ne ); 14477 } else { 14478 n = round( new BigNumber(n), i, rm ); 14479 14480 // n.e may have changed if the value was rounded up. 14481 e = n.e; 14482 14483 str = coeffToString( n.c ); 14484 len = str.length; 14485 14486 // toPrecision returns exponential notation if the number of significant digits 14487 // specified is less than the number of digits necessary to represent the integer 14488 // part of the value in fixed-point notation. 14489 14490 // Exponential notation. 14491 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) { 14492 14493 // Append zeros? 14494 for ( ; len < i; str += '0', len++ ); 14495 str = toExponential( str, e ); 14496 14497 // Fixed-point notation. 14498 } else { 14499 i -= ne; 14500 str = toFixedPoint( str, e ); 14501 14502 // Append zeros? 14503 if ( e + 1 > len ) { 14504 if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); 14505 } else { 14506 i += e - len; 14507 if ( i > 0 ) { 14508 if ( e + 1 == len ) str += '.'; 14509 for ( ; i--; str += '0' ); 14510 } 14511 } 14512 } 14513 } 14514 14515 return n.s < 0 && c0 ? '-' + str : str; 14516 } 14517 14518 14519 // Handle BigNumber.max and BigNumber.min. 14520 function maxOrMin( args, method ) { 14521 var m, n, 14522 i = 0; 14523 14524 if ( isArray( args[0] ) ) args = args[0]; 14525 m = new BigNumber( args[0] ); 14526 14527 for ( ; ++i < args.length; ) { 14528 n = new BigNumber( args[i] ); 14529 14530 // If any number is NaN, return NaN. 14531 if ( !n.s ) { 14532 m = n; 14533 break; 14534 } else if ( method.call( m, n ) ) { 14535 m = n; 14536 } 14537 } 14538 14539 return m; 14540 } 14541 14542 14543 /* 14544 * Return true if n is an integer in range, otherwise throw. 14545 * Use for argument validation when ERRORS is true. 14546 */ 14547 function intValidatorWithErrors( n, min, max, caller, name ) { 14548 if ( n < min || n > max || n != truncate(n) ) { 14549 raise( caller, ( name || 'decimal places' ) + 14550 ( n < min || n > max ? ' out of range' : ' not an integer' ), n ); 14551 } 14552 14553 return true; 14554 } 14555 14556 14557 /* 14558 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. 14559 * Called by minus, plus and times. 14560 */ 14561 function normalise( n, c, e ) { 14562 var i = 1, 14563 j = c.length; 14564 14565 // Remove trailing zeros. 14566 for ( ; !c[--j]; c.pop() ); 14567 14568 // Calculate the base 10 exponent. First get the number of digits of c[0]. 14569 for ( j = c[0]; j >= 10; j /= 10, i++ ); 14570 14571 // Overflow? 14572 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { 14573 14574 // Infinity. 14575 n.c = n.e = null; 14576 14577 // Underflow? 14578 } else if ( e < MIN_EXP ) { 14579 14580 // Zero. 14581 n.c = [ n.e = 0 ]; 14582 } else { 14583 n.e = e; 14584 n.c = c; 14585 } 14586 14587 return n; 14588 } 14589 14590 14591 // Handle values that fail the validity test in BigNumber. 14592 parseNumeric = (function () { 14593 var basePrefix = /^(-?)0([xbo])/i, 14594 dotAfter = /^([^.]+)\.$/, 14595 dotBefore = /^\.([^.]+)$/, 14596 isInfinityOrNaN = /^-?(Infinity|NaN)$/, 14597 whitespaceOrPlus = /^\s*\+|^\s+|\s+$/g; 14598 14599 return function ( x, str, num, b ) { 14600 var base, 14601 s = num ? str : str.replace( whitespaceOrPlus, '' ); 14602 14603 // No exception on ±Infinity or NaN. 14604 if ( isInfinityOrNaN.test(s) ) { 14605 x.s = isNaN(s) ? null : s < 0 ? -1 : 1; 14606 } else { 14607 if ( !num ) { 14608 14609 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i 14610 s = s.replace( basePrefix, function ( m, p1, p2 ) { 14611 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8; 14612 return !b || b == base ? p1 : m; 14613 }); 14614 14615 if (b) { 14616 base = b; 14617 14618 // E.g. '1.' to '1', '.1' to '0.1' 14619 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); 14620 } 14621 14622 if ( str != s ) return new BigNumber( s, base ); 14623 } 14624 14625 // 'new BigNumber() not a number: {n}' 14626 // 'new BigNumber() not a base {b} number: {n}' 14627 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str ); 14628 x.s = null; 14629 } 14630 14631 x.c = x.e = null; 14632 id = 0; 14633 } 14634 })(); 14635 14636 14637 // Throw a BigNumber Error. 14638 function raise( caller, msg, val ) { 14639 var error = new Error( [ 14640 'new BigNumber', // 0 14641 'cmp', // 1 14642 'config', // 2 14643 'div', // 3 14644 'divToInt', // 4 14645 'eq', // 5 14646 'gt', // 6 14647 'gte', // 7 14648 'lt', // 8 14649 'lte', // 9 14650 'minus', // 10 14651 'mod', // 11 14652 'plus', // 12 14653 'precision', // 13 14654 'random', // 14 14655 'round', // 15 14656 'shift', // 16 14657 'times', // 17 14658 'toDigits', // 18 14659 'toExponential', // 19 14660 'toFixed', // 20 14661 'toFormat', // 21 14662 'toFraction', // 22 14663 'pow', // 23 14664 'toPrecision', // 24 14665 'toString', // 25 14666 'BigNumber' // 26 14667 ][caller] + '() ' + msg + ': ' + val ); 14668 14669 error.name = 'BigNumber Error'; 14670 id = 0; 14671 throw error; 14672 } 14673 14674 14675 /* 14676 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. 14677 * If r is truthy, it is known that there are more digits after the rounding digit. 14678 */ 14679 function round( x, sd, rm, r ) { 14680 var d, i, j, k, n, ni, rd, 14681 xc = x.c, 14682 pows10 = POWS_TEN; 14683 14684 // if x is not Infinity or NaN... 14685 if (xc) { 14686 14687 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. 14688 // n is a base 1e14 number, the value of the element of array x.c containing rd. 14689 // ni is the index of n within x.c. 14690 // d is the number of digits of n. 14691 // i is the index of rd within n including leading zeros. 14692 // j is the actual index of rd within n (if < 0, rd is a leading zero). 14693 out: { 14694 14695 // Get the number of digits of the first element of xc. 14696 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); 14697 i = sd - d; 14698 14699 // If the rounding digit is in the first element of xc... 14700 if ( i < 0 ) { 14701 i += LOG_BASE; 14702 j = sd; 14703 n = xc[ ni = 0 ]; 14704 14705 // Get the rounding digit at index j of n. 14706 rd = n / pows10[ d - j - 1 ] % 10 | 0; 14707 } else { 14708 ni = mathceil( ( i + 1 ) / LOG_BASE ); 14709 14710 if ( ni >= xc.length ) { 14711 14712 if (r) { 14713 14714 // Needed by sqrt. 14715 for ( ; xc.length <= ni; xc.push(0) ); 14716 n = rd = 0; 14717 d = 1; 14718 i %= LOG_BASE; 14719 j = i - LOG_BASE + 1; 14720 } else { 14721 break out; 14722 } 14723 } else { 14724 n = k = xc[ni]; 14725 14726 // Get the number of digits of n. 14727 for ( d = 1; k >= 10; k /= 10, d++ ); 14728 14729 // Get the index of rd within n. 14730 i %= LOG_BASE; 14731 14732 // Get the index of rd within n, adjusted for leading zeros. 14733 // The number of leading zeros of n is given by LOG_BASE - d. 14734 j = i - LOG_BASE + d; 14735 14736 // Get the rounding digit at index j of n. 14737 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; 14738 } 14739 } 14740 14741 r = r || sd < 0 || 14742 14743 // Are there any non-zero digits after the rounding digit? 14744 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right 14745 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. 14746 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] ); 14747 14748 r = rm < 4 14749 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) 14750 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && 14751 14752 // Check whether the digit to the left of the rounding digit is odd. 14753 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 || 14754 rm == ( x.s < 0 ? 8 : 7 ) ); 14755 14756 if ( sd < 1 || !xc[0] ) { 14757 xc.length = 0; 14758 14759 if (r) { 14760 14761 // Convert sd to decimal places. 14762 sd -= x.e + 1; 14763 14764 // 1, 0.1, 0.01, 0.001, 0.0001 etc. 14765 xc[0] = pows10[ sd % LOG_BASE ]; 14766 x.e = -sd || 0; 14767 } else { 14768 14769 // Zero. 14770 xc[0] = x.e = 0; 14771 } 14772 14773 return x; 14774 } 14775 14776 // Remove excess digits. 14777 if ( i == 0 ) { 14778 xc.length = ni; 14779 k = 1; 14780 ni--; 14781 } else { 14782 xc.length = ni + 1; 14783 k = pows10[ LOG_BASE - i ]; 14784 14785 // E.g. 56700 becomes 56000 if 7 is the rounding digit. 14786 // j > 0 means i > number of leading zeros of n. 14787 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0; 14788 } 14789 14790 // Round up? 14791 if (r) { 14792 14793 for ( ; ; ) { 14794 14795 // If the digit to be rounded up is in the first element of xc... 14796 if ( ni == 0 ) { 14797 14798 // i will be the length of xc[0] before k is added. 14799 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ ); 14800 j = xc[0] += k; 14801 for ( k = 1; j >= 10; j /= 10, k++ ); 14802 14803 // if i != k the length has increased. 14804 if ( i != k ) { 14805 x.e++; 14806 if ( xc[0] == BASE ) xc[0] = 1; 14807 } 14808 14809 break; 14810 } else { 14811 xc[ni] += k; 14812 if ( xc[ni] != BASE ) break; 14813 xc[ni--] = 0; 14814 k = 1; 14815 } 14816 } 14817 } 14818 14819 // Remove trailing zeros. 14820 for ( i = xc.length; xc[--i] === 0; xc.pop() ); 14821 } 14822 14823 // Overflow? Infinity. 14824 if ( x.e > MAX_EXP ) { 14825 x.c = x.e = null; 14826 14827 // Underflow? Zero. 14828 } else if ( x.e < MIN_EXP ) { 14829 x.c = [ x.e = 0 ]; 14830 } 14831 } 14832 14833 return x; 14834 } 14835 14836 14837 // PROTOTYPE/INSTANCE METHODS 14838 14839 14840 /* 14841 * Return a new BigNumber whose value is the absolute value of this BigNumber. 14842 */ 14843 P.absoluteValue = P.abs = function () { 14844 var x = new BigNumber(this); 14845 if ( x.s < 0 ) x.s = 1; 14846 return x; 14847 }; 14848 14849 14850 /* 14851 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole 14852 * number in the direction of Infinity. 14853 */ 14854 P.ceil = function () { 14855 return round( new BigNumber(this), this.e + 1, 2 ); 14856 }; 14857 14858 14859 /* 14860 * Return 14861 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), 14862 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), 14863 * 0 if they have the same value, 14864 * or null if the value of either is NaN. 14865 */ 14866 P.comparedTo = P.cmp = function ( y, b ) { 14867 id = 1; 14868 return compare( this, new BigNumber( y, b ) ); 14869 }; 14870 14871 14872 /* 14873 * Return the number of decimal places of the value of this BigNumber, or null if the value 14874 * of this BigNumber is ±Infinity or NaN. 14875 */ 14876 P.decimalPlaces = P.dp = function () { 14877 var n, v, 14878 c = this.c; 14879 14880 if ( !c ) return null; 14881 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; 14882 14883 // Subtract the number of trailing zeros of the last number. 14884 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); 14885 if ( n < 0 ) n = 0; 14886 14887 return n; 14888 }; 14889 14890 14891 /* 14892 * n / 0 = I 14893 * n / N = N 14894 * n / I = 0 14895 * 0 / n = 0 14896 * 0 / 0 = N 14897 * 0 / N = N 14898 * 0 / I = 0 14899 * N / n = N 14900 * N / 0 = N 14901 * N / N = N 14902 * N / I = N 14903 * I / n = I 14904 * I / 0 = I 14905 * I / N = N 14906 * I / I = N 14907 * 14908 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of 14909 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. 14910 */ 14911 P.dividedBy = P.div = function ( y, b ) { 14912 id = 3; 14913 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); 14914 }; 14915 14916 14917 /* 14918 * Return a new BigNumber whose value is the integer part of dividing the value of this 14919 * BigNumber by the value of BigNumber(y, b). 14920 */ 14921 P.dividedToIntegerBy = P.divToInt = function ( y, b ) { 14922 id = 4; 14923 return div( this, new BigNumber( y, b ), 0, 1 ); 14924 }; 14925 14926 14927 /* 14928 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), 14929 * otherwise returns false. 14930 */ 14931 P.equals = P.eq = function ( y, b ) { 14932 id = 5; 14933 return compare( this, new BigNumber( y, b ) ) === 0; 14934 }; 14935 14936 14937 /* 14938 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole 14939 * number in the direction of -Infinity. 14940 */ 14941 P.floor = function () { 14942 return round( new BigNumber(this), this.e + 1, 3 ); 14943 }; 14944 14945 14946 /* 14947 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), 14948 * otherwise returns false. 14949 */ 14950 P.greaterThan = P.gt = function ( y, b ) { 14951 id = 6; 14952 return compare( this, new BigNumber( y, b ) ) > 0; 14953 }; 14954 14955 14956 /* 14957 * Return true if the value of this BigNumber is greater than or equal to the value of 14958 * BigNumber(y, b), otherwise returns false. 14959 */ 14960 P.greaterThanOrEqualTo = P.gte = function ( y, b ) { 14961 id = 7; 14962 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; 14963 14964 }; 14965 14966 14967 /* 14968 * Return true if the value of this BigNumber is a finite number, otherwise returns false. 14969 */ 14970 P.isFinite = function () { 14971 return !!this.c; 14972 }; 14973 14974 14975 /* 14976 * Return true if the value of this BigNumber is an integer, otherwise return false. 14977 */ 14978 P.isInteger = P.isInt = function () { 14979 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; 14980 }; 14981 14982 14983 /* 14984 * Return true if the value of this BigNumber is NaN, otherwise returns false. 14985 */ 14986 P.isNaN = function () { 14987 return !this.s; 14988 }; 14989 14990 14991 /* 14992 * Return true if the value of this BigNumber is negative, otherwise returns false. 14993 */ 14994 P.isNegative = P.isNeg = function () { 14995 return this.s < 0; 14996 }; 14997 14998 14999 /* 15000 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false. 15001 */ 15002 P.isZero = function () { 15003 return !!this.c && this.c[0] == 0; 15004 }; 15005 15006 15007 /* 15008 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), 15009 * otherwise returns false. 15010 */ 15011 P.lessThan = P.lt = function ( y, b ) { 15012 id = 8; 15013 return compare( this, new BigNumber( y, b ) ) < 0; 15014 }; 15015 15016 15017 /* 15018 * Return true if the value of this BigNumber is less than or equal to the value of 15019 * BigNumber(y, b), otherwise returns false. 15020 */ 15021 P.lessThanOrEqualTo = P.lte = function ( y, b ) { 15022 id = 9; 15023 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; 15024 }; 15025 15026 15027 /* 15028 * n - 0 = n 15029 * n - N = N 15030 * n - I = -I 15031 * 0 - n = -n 15032 * 0 - 0 = 0 15033 * 0 - N = N 15034 * 0 - I = -I 15035 * N - n = N 15036 * N - 0 = N 15037 * N - N = N 15038 * N - I = N 15039 * I - n = I 15040 * I - 0 = I 15041 * I - N = N 15042 * I - I = N 15043 * 15044 * Return a new BigNumber whose value is the value of this BigNumber minus the value of 15045 * BigNumber(y, b). 15046 */ 15047 P.minus = P.sub = function ( y, b ) { 15048 var i, j, t, xLTy, 15049 x = this, 15050 a = x.s; 15051 15052 id = 10; 15053 y = new BigNumber( y, b ); 15054 b = y.s; 15055 15056 // Either NaN? 15057 if ( !a || !b ) return new BigNumber(NaN); 15058 15059 // Signs differ? 15060 if ( a != b ) { 15061 y.s = -b; 15062 return x.plus(y); 15063 } 15064 15065 var xe = x.e / LOG_BASE, 15066 ye = y.e / LOG_BASE, 15067 xc = x.c, 15068 yc = y.c; 15069 15070 if ( !xe || !ye ) { 15071 15072 // Either Infinity? 15073 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); 15074 15075 // Either zero? 15076 if ( !xc[0] || !yc[0] ) { 15077 15078 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. 15079 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : 15080 15081 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity 15082 ROUNDING_MODE == 3 ? -0 : 0 ); 15083 } 15084 } 15085 15086 xe = bitFloor(xe); 15087 ye = bitFloor(ye); 15088 xc = xc.slice(); 15089 15090 // Determine which is the bigger number. 15091 if ( a = xe - ye ) { 15092 15093 if ( xLTy = a < 0 ) { 15094 a = -a; 15095 t = xc; 15096 } else { 15097 ye = xe; 15098 t = yc; 15099 } 15100 15101 t.reverse(); 15102 15103 // Prepend zeros to equalise exponents. 15104 for ( b = a; b--; t.push(0) ); 15105 t.reverse(); 15106 } else { 15107 15108 // Exponents equal. Check digit by digit. 15109 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; 15110 15111 for ( a = b = 0; b < j; b++ ) { 15112 15113 if ( xc[b] != yc[b] ) { 15114 xLTy = xc[b] < yc[b]; 15115 break; 15116 } 15117 } 15118 } 15119 15120 // x < y? Point xc to the array of the bigger number. 15121 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; 15122 15123 b = ( j = yc.length ) - ( i = xc.length ); 15124 15125 // Append zeros to xc if shorter. 15126 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. 15127 if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); 15128 b = BASE - 1; 15129 15130 // Subtract yc from xc. 15131 for ( ; j > a; ) { 15132 15133 if ( xc[--j] < yc[j] ) { 15134 for ( i = j; i && !xc[--i]; xc[i] = b ); 15135 --xc[i]; 15136 xc[j] += BASE; 15137 } 15138 15139 xc[j] -= yc[j]; 15140 } 15141 15142 // Remove leading zeros and adjust exponent accordingly. 15143 for ( ; xc[0] == 0; xc.shift(), --ye ); 15144 15145 // Zero? 15146 if ( !xc[0] ) { 15147 15148 // Following IEEE 754 (2008) 6.3, 15149 // n - n = +0 but n - n = -0 when rounding towards -Infinity. 15150 y.s = ROUNDING_MODE == 3 ? -1 : 1; 15151 y.c = [ y.e = 0 ]; 15152 return y; 15153 } 15154 15155 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity 15156 // for finite x and y. 15157 return normalise( y, xc, ye ); 15158 }; 15159 15160 15161 /* 15162 * n % 0 = N 15163 * n % N = N 15164 * n % I = n 15165 * 0 % n = 0 15166 * -0 % n = -0 15167 * 0 % 0 = N 15168 * 0 % N = N 15169 * 0 % I = 0 15170 * N % n = N 15171 * N % 0 = N 15172 * N % N = N 15173 * N % I = N 15174 * I % n = N 15175 * I % 0 = N 15176 * I % N = N 15177 * I % I = N 15178 * 15179 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of 15180 * BigNumber(y, b). The result depends on the value of MODULO_MODE. 15181 */ 15182 P.modulo = P.mod = function ( y, b ) { 15183 var q, s, 15184 x = this; 15185 15186 id = 11; 15187 y = new BigNumber( y, b ); 15188 15189 // Return NaN if x is Infinity or NaN, or y is NaN or zero. 15190 if ( !x.c || !y.s || y.c && !y.c[0] ) { 15191 return new BigNumber(NaN); 15192 15193 // Return x if y is Infinity or x is zero. 15194 } else if ( !y.c || x.c && !x.c[0] ) { 15195 return new BigNumber(x); 15196 } 15197 15198 if ( MODULO_MODE == 9 ) { 15199 15200 // Euclidian division: q = sign(y) * floor(x / abs(y)) 15201 // r = x - qy where 0 <= r < abs(y) 15202 s = y.s; 15203 y.s = 1; 15204 q = div( x, y, 0, 3 ); 15205 y.s = s; 15206 q.s *= s; 15207 } else { 15208 q = div( x, y, 0, MODULO_MODE ); 15209 } 15210 15211 return x.minus( q.times(y) ); 15212 }; 15213 15214 15215 /* 15216 * Return a new BigNumber whose value is the value of this BigNumber negated, 15217 * i.e. multiplied by -1. 15218 */ 15219 P.negated = P.neg = function () { 15220 var x = new BigNumber(this); 15221 x.s = -x.s || null; 15222 return x; 15223 }; 15224 15225 15226 /* 15227 * n + 0 = n 15228 * n + N = N 15229 * n + I = I 15230 * 0 + n = n 15231 * 0 + 0 = 0 15232 * 0 + N = N 15233 * 0 + I = I 15234 * N + n = N 15235 * N + 0 = N 15236 * N + N = N 15237 * N + I = N 15238 * I + n = I 15239 * I + 0 = I 15240 * I + N = N 15241 * I + I = I 15242 * 15243 * Return a new BigNumber whose value is the value of this BigNumber plus the value of 15244 * BigNumber(y, b). 15245 */ 15246 P.plus = P.add = function ( y, b ) { 15247 var t, 15248 x = this, 15249 a = x.s; 15250 15251 id = 12; 15252 y = new BigNumber( y, b ); 15253 b = y.s; 15254 15255 // Either NaN? 15256 if ( !a || !b ) return new BigNumber(NaN); 15257 15258 // Signs differ? 15259 if ( a != b ) { 15260 y.s = -b; 15261 return x.minus(y); 15262 } 15263 15264 var xe = x.e / LOG_BASE, 15265 ye = y.e / LOG_BASE, 15266 xc = x.c, 15267 yc = y.c; 15268 15269 if ( !xe || !ye ) { 15270 15271 // Return ±Infinity if either ±Infinity. 15272 if ( !xc || !yc ) return new BigNumber( a / 0 ); 15273 15274 // Either zero? 15275 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. 15276 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); 15277 } 15278 15279 xe = bitFloor(xe); 15280 ye = bitFloor(ye); 15281 xc = xc.slice(); 15282 15283 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. 15284 if ( a = xe - ye ) { 15285 if ( a > 0 ) { 15286 ye = xe; 15287 t = yc; 15288 } else { 15289 a = -a; 15290 t = xc; 15291 } 15292 15293 t.reverse(); 15294 for ( ; a--; t.push(0) ); 15295 t.reverse(); 15296 } 15297 15298 a = xc.length; 15299 b = yc.length; 15300 15301 // Point xc to the longer array, and b to the shorter length. 15302 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; 15303 15304 // Only start adding at yc.length - 1 as the further digits of xc can be ignored. 15305 for ( a = 0; b; ) { 15306 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; 15307 xc[b] %= BASE; 15308 } 15309 15310 if (a) { 15311 xc.unshift(a); 15312 ++ye; 15313 } 15314 15315 // No need to check for zero, as +x + +y != 0 && -x + -y != 0 15316 // ye = MAX_EXP + 1 possible 15317 return normalise( y, xc, ye ); 15318 }; 15319 15320 15321 /* 15322 * Return the number of significant digits of the value of this BigNumber. 15323 * 15324 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. 15325 */ 15326 P.precision = P.sd = function (z) { 15327 var n, v, 15328 x = this, 15329 c = x.c; 15330 15331 // 'precision() argument not a boolean or binary digit: {z}' 15332 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { 15333 if (ERRORS) raise( 13, 'argument' + notBool, z ); 15334 if ( z != !!z ) z = null; 15335 } 15336 15337 if ( !c ) return null; 15338 v = c.length - 1; 15339 n = v * LOG_BASE + 1; 15340 15341 if ( v = c[v] ) { 15342 15343 // Subtract the number of trailing zeros of the last element. 15344 for ( ; v % 10 == 0; v /= 10, n-- ); 15345 15346 // Add the number of digits of the first element. 15347 for ( v = c[0]; v >= 10; v /= 10, n++ ); 15348 } 15349 15350 if ( z && x.e + 1 > n ) n = x.e + 1; 15351 15352 return n; 15353 }; 15354 15355 15356 /* 15357 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of 15358 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if 15359 * omitted. 15360 * 15361 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15362 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15363 * 15364 * 'round() decimal places out of range: {dp}' 15365 * 'round() decimal places not an integer: {dp}' 15366 * 'round() rounding mode not an integer: {rm}' 15367 * 'round() rounding mode out of range: {rm}' 15368 */ 15369 P.round = function ( dp, rm ) { 15370 var n = new BigNumber(this); 15371 15372 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) { 15373 round( n, ~~dp + this.e + 1, rm == null || 15374 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 ); 15375 } 15376 15377 return n; 15378 }; 15379 15380 15381 /* 15382 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places 15383 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. 15384 * 15385 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. 15386 * 15387 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity 15388 * otherwise. 15389 * 15390 * 'shift() argument not an integer: {k}' 15391 * 'shift() argument out of range: {k}' 15392 */ 15393 P.shift = function (k) { 15394 var n = this; 15395 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) 15396 15397 // k < 1e+21, or truncate(k) will produce exponential notation. 15398 ? n.times( '1e' + truncate(k) ) 15399 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER ) 15400 ? n.s * ( k < 0 ? 0 : 1 / 0 ) 15401 : n ); 15402 }; 15403 15404 15405 /* 15406 * sqrt(-n) = N 15407 * sqrt( N) = N 15408 * sqrt(-I) = N 15409 * sqrt( I) = I 15410 * sqrt( 0) = 0 15411 * sqrt(-0) = -0 15412 * 15413 * Return a new BigNumber whose value is the square root of the value of this BigNumber, 15414 * rounded according to DECIMAL_PLACES and ROUNDING_MODE. 15415 */ 15416 P.squareRoot = P.sqrt = function () { 15417 var m, n, r, rep, t, 15418 x = this, 15419 c = x.c, 15420 s = x.s, 15421 e = x.e, 15422 dp = DECIMAL_PLACES + 4, 15423 half = new BigNumber('0.5'); 15424 15425 // Negative/NaN/Infinity/zero? 15426 if ( s !== 1 || !c || !c[0] ) { 15427 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); 15428 } 15429 15430 // Initial estimate. 15431 s = Math.sqrt( +x ); 15432 15433 // Math.sqrt underflow/overflow? 15434 // Pass x to Math.sqrt as integer, then adjust the exponent of the result. 15435 if ( s == 0 || s == 1 / 0 ) { 15436 n = coeffToString(c); 15437 if ( ( n.length + e ) % 2 == 0 ) n += '0'; 15438 s = Math.sqrt(n); 15439 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); 15440 15441 if ( s == 1 / 0 ) { 15442 n = '1e' + e; 15443 } else { 15444 n = s.toExponential(); 15445 n = n.slice( 0, n.indexOf('e') + 1 ) + e; 15446 } 15447 15448 r = new BigNumber(n); 15449 } else { 15450 r = new BigNumber( s + '' ); 15451 } 15452 15453 // Check for zero. 15454 // r could be zero if MIN_EXP is changed after the this value was created. 15455 // This would cause a division by zero (x/t) and hence Infinity below, which would cause 15456 // coeffToString to throw. 15457 if ( r.c[0] ) { 15458 e = r.e; 15459 s = e + dp; 15460 if ( s < 3 ) s = 0; 15461 15462 // Newton-Raphson iteration. 15463 for ( ; ; ) { 15464 t = r; 15465 r = half.times( t.plus( div( x, t, dp, 1 ) ) ); 15466 15467 if ( coeffToString( t.c ).slice( 0, s ) === ( n = 15468 coeffToString( r.c ) ).slice( 0, s ) ) { 15469 15470 // The exponent of r may here be one less than the final result exponent, 15471 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits 15472 // are indexed correctly. 15473 if ( r.e < e ) --s; 15474 n = n.slice( s - 3, s + 1 ); 15475 15476 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits 15477 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the 15478 // iteration. 15479 if ( n == '9999' || !rep && n == '4999' ) { 15480 15481 // On the first iteration only, check to see if rounding up gives the 15482 // exact result as the nines may infinitely repeat. 15483 if ( !rep ) { 15484 round( t, t.e + DECIMAL_PLACES + 2, 0 ); 15485 15486 if ( t.times(t).eq(x) ) { 15487 r = t; 15488 break; 15489 } 15490 } 15491 15492 dp += 4; 15493 s += 4; 15494 rep = 1; 15495 } else { 15496 15497 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact 15498 // result. If not, then there are further digits and m will be truthy. 15499 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { 15500 15501 // Truncate to the first rounding digit. 15502 round( r, r.e + DECIMAL_PLACES + 2, 1 ); 15503 m = !r.times(r).eq(x); 15504 } 15505 15506 break; 15507 } 15508 } 15509 } 15510 } 15511 15512 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); 15513 }; 15514 15515 15516 /* 15517 * n * 0 = 0 15518 * n * N = N 15519 * n * I = I 15520 * 0 * n = 0 15521 * 0 * 0 = 0 15522 * 0 * N = N 15523 * 0 * I = N 15524 * N * n = N 15525 * N * 0 = N 15526 * N * N = N 15527 * N * I = N 15528 * I * n = I 15529 * I * 0 = N 15530 * I * N = N 15531 * I * I = I 15532 * 15533 * Return a new BigNumber whose value is the value of this BigNumber times the value of 15534 * BigNumber(y, b). 15535 */ 15536 P.times = P.mul = function ( y, b ) { 15537 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, 15538 base, sqrtBase, 15539 x = this, 15540 xc = x.c, 15541 yc = ( id = 17, y = new BigNumber( y, b ) ).c; 15542 15543 // Either NaN, ±Infinity or ±0? 15544 if ( !xc || !yc || !xc[0] || !yc[0] ) { 15545 15546 // Return NaN if either is NaN, or one is 0 and the other is Infinity. 15547 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { 15548 y.c = y.e = y.s = null; 15549 } else { 15550 y.s *= x.s; 15551 15552 // Return ±Infinity if either is ±Infinity. 15553 if ( !xc || !yc ) { 15554 y.c = y.e = null; 15555 15556 // Return ±0 if either is ±0. 15557 } else { 15558 y.c = [0]; 15559 y.e = 0; 15560 } 15561 } 15562 15563 return y; 15564 } 15565 15566 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); 15567 y.s *= x.s; 15568 xcL = xc.length; 15569 ycL = yc.length; 15570 15571 // Ensure xc points to longer array and xcL to its length. 15572 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; 15573 15574 // Initialise the result array with zeros. 15575 for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); 15576 15577 base = BASE; 15578 sqrtBase = SQRT_BASE; 15579 15580 for ( i = ycL; --i >= 0; ) { 15581 c = 0; 15582 ylo = yc[i] % sqrtBase; 15583 yhi = yc[i] / sqrtBase | 0; 15584 15585 for ( k = xcL, j = i + k; j > i; ) { 15586 xlo = xc[--k] % sqrtBase; 15587 xhi = xc[k] / sqrtBase | 0; 15588 m = yhi * xlo + xhi * ylo; 15589 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; 15590 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; 15591 zc[j--] = xlo % base; 15592 } 15593 15594 zc[j] = c; 15595 } 15596 15597 if (c) { 15598 ++e; 15599 } else { 15600 zc.shift(); 15601 } 15602 15603 return normalise( y, zc, e ); 15604 }; 15605 15606 15607 /* 15608 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of 15609 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted. 15610 * 15611 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. 15612 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15613 * 15614 * 'toDigits() precision out of range: {sd}' 15615 * 'toDigits() precision not an integer: {sd}' 15616 * 'toDigits() rounding mode not an integer: {rm}' 15617 * 'toDigits() rounding mode out of range: {rm}' 15618 */ 15619 P.toDigits = function ( sd, rm ) { 15620 var n = new BigNumber(this); 15621 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0; 15622 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0; 15623 return sd ? round( n, sd, rm ) : n; 15624 }; 15625 15626 15627 /* 15628 * Return a string representing the value of this BigNumber in exponential notation and 15629 * rounded using ROUNDING_MODE to dp fixed decimal places. 15630 * 15631 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15632 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15633 * 15634 * 'toExponential() decimal places not an integer: {dp}' 15635 * 'toExponential() decimal places out of range: {dp}' 15636 * 'toExponential() rounding mode not an integer: {rm}' 15637 * 'toExponential() rounding mode out of range: {rm}' 15638 */ 15639 P.toExponential = function ( dp, rm ) { 15640 return format( this, 15641 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); 15642 }; 15643 15644 15645 /* 15646 * Return a string representing the value of this BigNumber in fixed-point notation rounding 15647 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. 15648 * 15649 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', 15650 * but e.g. (-0.00001).toFixed(0) is '-0'. 15651 * 15652 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15653 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15654 * 15655 * 'toFixed() decimal places not an integer: {dp}' 15656 * 'toFixed() decimal places out of range: {dp}' 15657 * 'toFixed() rounding mode not an integer: {rm}' 15658 * 'toFixed() rounding mode out of range: {rm}' 15659 */ 15660 P.toFixed = function ( dp, rm ) { 15661 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 ) 15662 ? ~~dp + this.e + 1 : null, rm, 20 ); 15663 }; 15664 15665 15666 /* 15667 * Return a string representing the value of this BigNumber in fixed-point notation rounded 15668 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties 15669 * of the FORMAT object (see BigNumber.config). 15670 * 15671 * FORMAT = { 15672 * decimalSeparator : '.', 15673 * groupSeparator : ',', 15674 * groupSize : 3, 15675 * secondaryGroupSize : 0, 15676 * fractionGroupSeparator : '\xA0', // non-breaking space 15677 * fractionGroupSize : 0 15678 * }; 15679 * 15680 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15681 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15682 * 15683 * 'toFormat() decimal places not an integer: {dp}' 15684 * 'toFormat() decimal places out of range: {dp}' 15685 * 'toFormat() rounding mode not an integer: {rm}' 15686 * 'toFormat() rounding mode out of range: {rm}' 15687 */ 15688 P.toFormat = function ( dp, rm ) { 15689 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 ) 15690 ? ~~dp + this.e + 1 : null, rm, 21 ); 15691 15692 if ( this.c ) { 15693 var i, 15694 arr = str.split('.'), 15695 g1 = +FORMAT.groupSize, 15696 g2 = +FORMAT.secondaryGroupSize, 15697 groupSeparator = FORMAT.groupSeparator, 15698 intPart = arr[0], 15699 fractionPart = arr[1], 15700 isNeg = this.s < 0, 15701 intDigits = isNeg ? intPart.slice(1) : intPart, 15702 len = intDigits.length; 15703 15704 if (g2) i = g1, g1 = g2, g2 = i, len -= i; 15705 15706 if ( g1 > 0 && len > 0 ) { 15707 i = len % g1 || g1; 15708 intPart = intDigits.substr( 0, i ); 15709 15710 for ( ; i < len; i += g1 ) { 15711 intPart += groupSeparator + intDigits.substr( i, g1 ); 15712 } 15713 15714 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); 15715 if (isNeg) intPart = '-' + intPart; 15716 } 15717 15718 str = fractionPart 15719 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) 15720 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), 15721 '$&' + FORMAT.fractionGroupSeparator ) 15722 : fractionPart ) 15723 : intPart; 15724 } 15725 15726 return str; 15727 }; 15728 15729 15730 /* 15731 * Return a string array representing the value of this BigNumber as a simple fraction with 15732 * an integer numerator and an integer denominator. The denominator will be a positive 15733 * non-zero value less than or equal to the specified maximum denominator. If a maximum 15734 * denominator is not specified, the denominator will be the lowest value necessary to 15735 * represent the number exactly. 15736 * 15737 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. 15738 * 15739 * 'toFraction() max denominator not an integer: {md}' 15740 * 'toFraction() max denominator out of range: {md}' 15741 */ 15742 P.toFraction = function (md) { 15743 var arr, d0, d2, e, exp, n, n0, q, s, 15744 k = ERRORS, 15745 x = this, 15746 xc = x.c, 15747 d = new BigNumber(ONE), 15748 n1 = d0 = new BigNumber(ONE), 15749 d1 = n0 = new BigNumber(ONE); 15750 15751 if ( md != null ) { 15752 ERRORS = false; 15753 n = new BigNumber(md); 15754 ERRORS = k; 15755 15756 if ( !( k = n.isInt() ) || n.lt(ONE) ) { 15757 15758 if (ERRORS) { 15759 raise( 22, 15760 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); 15761 } 15762 15763 // ERRORS is false: 15764 // If md is a finite non-integer >= 1, round it to an integer and use it. 15765 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null; 15766 } 15767 } 15768 15769 if ( !xc ) return x.toString(); 15770 s = coeffToString(xc); 15771 15772 // Determine initial denominator. 15773 // d is a power of 10 and the minimum max denominator that specifies the value exactly. 15774 e = d.e = s.length - x.e - 1; 15775 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; 15776 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n; 15777 15778 exp = MAX_EXP; 15779 MAX_EXP = 1 / 0; 15780 n = new BigNumber(s); 15781 15782 // n0 = d1 = 0 15783 n0.c[0] = 0; 15784 15785 for ( ; ; ) { 15786 q = div( n, d, 0, 1 ); 15787 d2 = d0.plus( q.times(d1) ); 15788 if ( d2.cmp(md) == 1 ) break; 15789 d0 = d1; 15790 d1 = d2; 15791 n1 = n0.plus( q.times( d2 = n1 ) ); 15792 n0 = d2; 15793 d = n.minus( q.times( d2 = d ) ); 15794 n = d2; 15795 } 15796 15797 d2 = div( md.minus(d0), d1, 0, 1 ); 15798 n0 = n0.plus( d2.times(n1) ); 15799 d0 = d0.plus( d2.times(d1) ); 15800 n0.s = n1.s = x.s; 15801 e *= 2; 15802 15803 // Determine which fraction is closer to x, n0/d0 or n1/d1 15804 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp( 15805 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 15806 ? [ n1.toString(), d1.toString() ] 15807 : [ n0.toString(), d0.toString() ]; 15808 15809 MAX_EXP = exp; 15810 return arr; 15811 }; 15812 15813 15814 /* 15815 * Return the value of this BigNumber converted to a number primitive. 15816 */ 15817 P.toNumber = function () { 15818 var x = this; 15819 15820 // Ensure zero has correct sign. 15821 return +x || ( x.s ? x.s * 0 : NaN ); 15822 }; 15823 15824 15825 /* 15826 * Return a BigNumber whose value is the value of this BigNumber raised to the power n. 15827 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. 15828 * If POW_PRECISION is not 0, round to POW_PRECISION using ROUNDING_MODE. 15829 * 15830 * n {number} Integer, -9007199254740992 to 9007199254740992 inclusive. 15831 * (Performs 54 loop iterations for n of 9007199254740992.) 15832 * 15833 * 'pow() exponent not an integer: {n}' 15834 * 'pow() exponent out of range: {n}' 15835 */ 15836 P.toPower = P.pow = function (n) { 15837 var k, y, 15838 i = mathfloor( n < 0 ? -n : +n ), 15839 x = this; 15840 15841 // Pass ±Infinity to Math.pow if exponent is out of range. 15842 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && 15843 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || 15844 parseFloat(n) != n && !( n = NaN ) ) ) { 15845 return new BigNumber( Math.pow( +x, n ) ); 15846 } 15847 15848 // Truncating each coefficient array to a length of k after each multiplication equates 15849 // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a 15850 // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.) 15851 k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0; 15852 y = new BigNumber(ONE); 15853 15854 for ( ; ; ) { 15855 15856 if ( i % 2 ) { 15857 y = y.times(x); 15858 if ( !y.c ) break; 15859 if ( k && y.c.length > k ) y.c.length = k; 15860 } 15861 15862 i = mathfloor( i / 2 ); 15863 if ( !i ) break; 15864 15865 x = x.times(x); 15866 if ( k && x.c && x.c.length > k ) x.c.length = k; 15867 } 15868 15869 if ( n < 0 ) y = ONE.div(y); 15870 return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; 15871 }; 15872 15873 15874 /* 15875 * Return a string representing the value of this BigNumber rounded to sd significant digits 15876 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits 15877 * necessary to represent the integer part of the value in fixed-point notation, then use 15878 * exponential notation. 15879 * 15880 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. 15881 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15882 * 15883 * 'toPrecision() precision not an integer: {sd}' 15884 * 'toPrecision() precision out of range: {sd}' 15885 * 'toPrecision() rounding mode not an integer: {rm}' 15886 * 'toPrecision() rounding mode out of range: {rm}' 15887 */ 15888 P.toPrecision = function ( sd, rm ) { 15889 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) 15890 ? sd | 0 : null, rm, 24 ); 15891 }; 15892 15893 15894 /* 15895 * Return a string representing the value of this BigNumber in base b, or base 10 if b is 15896 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and 15897 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent 15898 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than 15899 * TO_EXP_NEG, return exponential notation. 15900 * 15901 * [b] {number} Integer, 2 to 64 inclusive. 15902 * 15903 * 'toString() base not an integer: {b}' 15904 * 'toString() base out of range: {b}' 15905 */ 15906 P.toString = function (b) { 15907 var str, 15908 n = this, 15909 s = n.s, 15910 e = n.e; 15911 15912 // Infinity or NaN? 15913 if ( e === null ) { 15914 15915 if (s) { 15916 str = 'Infinity'; 15917 if ( s < 0 ) str = '-' + str; 15918 } else { 15919 str = 'NaN'; 15920 } 15921 } else { 15922 str = coeffToString( n.c ); 15923 15924 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) { 15925 str = e <= TO_EXP_NEG || e >= TO_EXP_POS 15926 ? toExponential( str, e ) 15927 : toFixedPoint( str, e ); 15928 } else { 15929 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); 15930 } 15931 15932 if ( s < 0 && n.c[0] ) str = '-' + str; 15933 } 15934 15935 return str; 15936 }; 15937 15938 15939 /* 15940 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole 15941 * number. 15942 */ 15943 P.truncated = P.trunc = function () { 15944 return round( new BigNumber(this), this.e + 1, 1 ); 15945 }; 15946 15947 15948 15949 /* 15950 * Return as toString, but do not accept a base argument. 15951 */ 15952 P.valueOf = P.toJSON = function () { 15953 return this.toString(); 15954 }; 15955 15956 15957 // Aliases for BigDecimal methods. 15958 //P.add = P.plus; // P.add included above 15959 //P.subtract = P.minus; // P.sub included above 15960 //P.multiply = P.times; // P.mul included above 15961 //P.divide = P.div; 15962 //P.remainder = P.mod; 15963 //P.compareTo = P.cmp; 15964 //P.negate = P.neg; 15965 15966 15967 if ( configObj != null ) BigNumber.config(configObj); 15968 15969 return BigNumber; 15970 } 15971 15972 15973 // PRIVATE HELPER FUNCTIONS 15974 15975 15976 function bitFloor(n) { 15977 var i = n | 0; 15978 return n > 0 || n === i ? i : i - 1; 15979 } 15980 15981 15982 // Return a coefficient array as a string of base 10 digits. 15983 function coeffToString(a) { 15984 var s, z, 15985 i = 1, 15986 j = a.length, 15987 r = a[0] + ''; 15988 15989 for ( ; i < j; ) { 15990 s = a[i++] + ''; 15991 z = LOG_BASE - s.length; 15992 for ( ; z--; s = '0' + s ); 15993 r += s; 15994 } 15995 15996 // Determine trailing zeros. 15997 for ( j = r.length; r.charCodeAt(--j) === 48; ); 15998 return r.slice( 0, j + 1 || 1 ); 15999 } 16000 16001 16002 // Compare the value of BigNumbers x and y. 16003 function compare( x, y ) { 16004 var a, b, 16005 xc = x.c, 16006 yc = y.c, 16007 i = x.s, 16008 j = y.s, 16009 k = x.e, 16010 l = y.e; 16011 16012 // Either NaN? 16013 if ( !i || !j ) return null; 16014 16015 a = xc && !xc[0]; 16016 b = yc && !yc[0]; 16017 16018 // Either zero? 16019 if ( a || b ) return a ? b ? 0 : -j : i; 16020 16021 // Signs differ? 16022 if ( i != j ) return i; 16023 16024 a = i < 0; 16025 b = k == l; 16026 16027 // Either Infinity? 16028 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; 16029 16030 // Compare exponents. 16031 if ( !b ) return k > l ^ a ? 1 : -1; 16032 16033 j = ( k = xc.length ) < ( l = yc.length ) ? k : l; 16034 16035 // Compare digit by digit. 16036 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1; 16037 16038 // Compare lengths. 16039 return k == l ? 0 : k > l ^ a ? 1 : -1; 16040 } 16041 16042 16043 /* 16044 * Return true if n is a valid number in range, otherwise false. 16045 * Use for argument validation when ERRORS is false. 16046 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10. 16047 */ 16048 function intValidatorNoErrors( n, min, max ) { 16049 return ( n = truncate(n) ) >= min && n <= max; 16050 } 16051 16052 16053 function isArray(obj) { 16054 return Object.prototype.toString.call(obj) == '[object Array]'; 16055 } 16056 16057 16058 /* 16059 * Convert string of baseIn to an array of numbers of baseOut. 16060 * Eg. convertBase('255', 10, 16) returns [15, 15]. 16061 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. 16062 */ 16063 function toBaseOut( str, baseIn, baseOut ) { 16064 var j, 16065 arr = [0], 16066 arrL, 16067 i = 0, 16068 len = str.length; 16069 16070 for ( ; i < len; ) { 16071 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); 16072 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) ); 16073 16074 for ( ; j < arr.length; j++ ) { 16075 16076 if ( arr[j] > baseOut - 1 ) { 16077 if ( arr[j + 1] == null ) arr[j + 1] = 0; 16078 arr[j + 1] += arr[j] / baseOut | 0; 16079 arr[j] %= baseOut; 16080 } 16081 } 16082 } 16083 16084 return arr.reverse(); 16085 } 16086 16087 16088 function toExponential( str, e ) { 16089 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + 16090 ( e < 0 ? 'e' : 'e+' ) + e; 16091 } 16092 16093 16094 function toFixedPoint( str, e ) { 16095 var len, z; 16096 16097 // Negative exponent? 16098 if ( e < 0 ) { 16099 16100 // Prepend zeros. 16101 for ( z = '0.'; ++e; z += '0' ); 16102 str = z + str; 16103 16104 // Positive exponent 16105 } else { 16106 len = str.length; 16107 16108 // Append zeros. 16109 if ( ++e > len ) { 16110 for ( z = '0', e -= len; --e; z += '0' ); 16111 str += z; 16112 } else if ( e < len ) { 16113 str = str.slice( 0, e ) + '.' + str.slice(e); 16114 } 16115 } 16116 16117 return str; 16118 } 16119 16120 16121 function truncate(n) { 16122 n = parseFloat(n); 16123 return n < 0 ? mathceil(n) : mathfloor(n); 16124 } 16125 16126 16127 // EXPORT 16128 16129 16130 BigNumber = another(); 16131 16132 // AMD. 16133 if ( typeof define == 'function' && define.amd ) { 16134 define( function () { return BigNumber; } ); 16135 16136 // Node and other environments that support module.exports. 16137 } else if ( typeof module != 'undefined' && module.exports ) { 16138 module.exports = BigNumber; 16139 if ( !crypto ) try { crypto = require('crypto'); } catch (e) {} 16140 16141 // Browser. 16142 } else { 16143 global.BigNumber = BigNumber; 16144 } 16145 })(this); 16146 16147 },{"crypto":50}],"web3":[function(require,module,exports){ 16148 var Web3 = require('./lib/web3'); 16149 16150 // dont override global variable 16151 if (typeof window !== 'undefined' && typeof window.Web3 === 'undefined') { 16152 window.Web3 = Web3; 16153 } 16154 16155 module.exports = Web3; 16156 16157 },{"./lib/web3":22}]},{},["web3"]) 16158 //# sourceMappingURL=web3.js.map