github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/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 /// ether -> reap by leejaeseong 1765 var ETH_UNITS = [ 1766 'wei', 1767 'kwei', 1768 'Mwei', 1769 'Gwei', 1770 'szabo', 1771 'finney', 1772 'femtoreap', 1773 'picoreap', 1774 'nanoreap', 1775 'microreap', 1776 'millireap', 1777 'nano', 1778 'micro', 1779 'milli', 1780 'reap', 1781 'grand', 1782 'Mreap', 1783 'Greap', 1784 'Treap', 1785 'Preap', 1786 'Ereap', 1787 'Zreap', 1788 'Yreap', 1789 'Nreap', 1790 'Dreap', 1791 'Vreap', 1792 'Ureap' 1793 ]; 1794 1795 module.exports = { 1796 ETH_PADDING: 32, 1797 ETH_SIGNATURE_LENGTH: 4, 1798 ETH_UNITS: ETH_UNITS, 1799 ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN }, 1800 ETH_POLLING_TIMEOUT: 1000/2, 1801 defaultBlock: 'latest', 1802 defaultAccount: undefined 1803 }; 1804 1805 1806 },{"bignumber.js":"bignumber.js"}],19:[function(require,module,exports){ 1807 /* 1808 This file is part of web3.js. 1809 1810 web3.js is free software: you can redistribute it and/or modify 1811 it under the terms of the GNU Lesser General Public License as published by 1812 the Free Software Foundation, either version 3 of the License, or 1813 (at your option) any later version. 1814 1815 web3.js is distributed in the hope that it will be useful, 1816 but WITHOUT ANY WARRANTY; without even the implied warranty of 1817 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1818 GNU Lesser General Public License for more details. 1819 1820 You should have received a copy of the GNU Lesser General Public License 1821 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1822 */ 1823 /** 1824 * @file sha3.js 1825 * @author Marek Kotewicz <marek@ethdev.com> 1826 * @date 2015 1827 */ 1828 1829 var CryptoJS = require('crypto-js'); 1830 var sha3 = require('crypto-js/sha3'); 1831 1832 module.exports = function (value, options) { 1833 if (options && options.encoding === 'hex') { 1834 if (value.length > 2 && value.substr(0, 2) === '0x') { 1835 value = value.substr(2); 1836 } 1837 value = CryptoJS.enc.Hex.parse(value); 1838 } 1839 1840 return sha3(value, { 1841 outputLength: 256 1842 }).toString(); 1843 }; 1844 1845 1846 },{"crypto-js":59,"crypto-js/sha3":80}],20:[function(require,module,exports){ 1847 /* 1848 This file is part of web3.js. 1849 1850 web3.js is free software: you can redistribute it and/or modify 1851 it under the terms of the GNU Lesser General Public License as published by 1852 the Free Software Foundation, either version 3 of the License, or 1853 (at your option) any later version. 1854 1855 web3.js is distributed in the hope that it will be useful, 1856 but WITHOUT ANY WARRANTY; without even the implied warranty of 1857 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1858 GNU Lesser General Public License for more details. 1859 1860 You should have received a copy of the GNU Lesser General Public License 1861 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 1862 */ 1863 /** 1864 * @file utils.js 1865 * @author Marek Kotewicz <marek@ethdev.com> 1866 * @date 2015 1867 */ 1868 1869 /** 1870 * Utils 1871 * 1872 * @module utils 1873 */ 1874 1875 /** 1876 * Utility functions 1877 * 1878 * @class [utils] utils 1879 * @constructor 1880 */ 1881 1882 1883 var BigNumber = require('bignumber.js'); 1884 var sha3 = require('./sha3.js'); 1885 var utf8 = require('utf8'); 1886 1887 /// ether -> reap by leejaeseong 1888 var unitMap = { 1889 'noreap': '0', 1890 'wei': '1', 1891 'kwei': '1000', 1892 'Kwei': '1000', 1893 'babbage': '1000', 1894 'femtoreap': '1000', 1895 'mwei': '1000000', 1896 'Mwei': '1000000', 1897 'lovelace': '1000000', 1898 'picoreap': '1000000', 1899 'gwei': '1000000000', 1900 'Gwei': '1000000000', 1901 'shannon': '1000000000', 1902 'nanoreap': '1000000000', 1903 'nano': '1000000000', 1904 'szabo': '1000000000000', 1905 'microreap': '1000000000000', 1906 'micro': '1000000000000', 1907 'finney': '1000000000000000', 1908 'millireap': '1000000000000000', 1909 'milli': '1000000000000000', 1910 'reap': '1000000000000000000', 1911 'kreap': '1000000000000000000000', 1912 'grand': '1000000000000000000000', 1913 'mreap': '1000000000000000000000000', 1914 'greap': '1000000000000000000000000000', 1915 'treap': '1000000000000000000000000000000' 1916 }; 1917 1918 /** 1919 * Should be called to pad string to expected length 1920 * 1921 * @method padLeft 1922 * @param {String} string to be padded 1923 * @param {Number} characters that result string should have 1924 * @param {String} sign, by default 0 1925 * @returns {String} right aligned string 1926 */ 1927 var padLeft = function (string, chars, sign) { 1928 return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; 1929 }; 1930 1931 /** 1932 * Should be called to pad string to expected length 1933 * 1934 * @method padRight 1935 * @param {String} string to be padded 1936 * @param {Number} characters that result string should have 1937 * @param {String} sign, by default 0 1938 * @returns {String} right aligned string 1939 */ 1940 var padRight = function (string, chars, sign) { 1941 return string + (new Array(chars - string.length + 1).join(sign ? sign : "0")); 1942 }; 1943 1944 /** 1945 * Should be called to get utf8 from it's hex representation 1946 * 1947 * @method toUtf8 1948 * @param {String} string in hex 1949 * @returns {String} ascii string representation of hex value 1950 */ 1951 var toUtf8 = function(hex) { 1952 // Find termination 1953 var str = ""; 1954 var i = 0, l = hex.length; 1955 if (hex.substring(0, 2) === '0x') { 1956 i = 2; 1957 } 1958 for (; i < l; i+=2) { 1959 var code = parseInt(hex.substr(i, 2), 16); 1960 if (code === 0) 1961 break; 1962 str += String.fromCharCode(code); 1963 } 1964 1965 return utf8.decode(str); 1966 }; 1967 1968 /** 1969 * Should be called to get ascii from it's hex representation 1970 * 1971 * @method toAscii 1972 * @param {String} string in hex 1973 * @returns {String} ascii string representation of hex value 1974 */ 1975 var toAscii = function(hex) { 1976 // Find termination 1977 var str = ""; 1978 var i = 0, l = hex.length; 1979 if (hex.substring(0, 2) === '0x') { 1980 i = 2; 1981 } 1982 for (; i < l; i+=2) { 1983 var code = parseInt(hex.substr(i, 2), 16); 1984 str += String.fromCharCode(code); 1985 } 1986 1987 return str; 1988 }; 1989 1990 /** 1991 * Should be called to get hex representation (prefixed by 0x) of utf8 string 1992 * 1993 * @method fromUtf8 1994 * @param {String} string 1995 * @param {Number} optional padding 1996 * @returns {String} hex representation of input string 1997 */ 1998 var fromUtf8 = function(str) { 1999 str = utf8.encode(str); 2000 var hex = ""; 2001 for(var i = 0; i < str.length; i++) { 2002 var code = str.charCodeAt(i); 2003 if (code === 0) 2004 break; 2005 var n = code.toString(16); 2006 hex += n.length < 2 ? '0' + n : n; 2007 } 2008 2009 return "0x" + hex; 2010 }; 2011 2012 /** 2013 * Should be called to get hex representation (prefixed by 0x) of ascii string 2014 * 2015 * @method fromAscii 2016 * @param {String} string 2017 * @param {Number} optional padding 2018 * @returns {String} hex representation of input string 2019 */ 2020 var fromAscii = function(str) { 2021 var hex = ""; 2022 for(var i = 0; i < str.length; i++) { 2023 var code = str.charCodeAt(i); 2024 var n = code.toString(16); 2025 hex += n.length < 2 ? '0' + n : n; 2026 } 2027 2028 return "0x" + hex; 2029 }; 2030 2031 /** 2032 * Should be used to create full function/event name from json abi 2033 * 2034 * @method transformToFullName 2035 * @param {Object} json-abi 2036 * @return {String} full fnction/event name 2037 */ 2038 var transformToFullName = function (json) { 2039 if (json.name.indexOf('(') !== -1) { 2040 return json.name; 2041 } 2042 2043 var typeName = json.inputs.map(function(i){return i.type; }).join(); 2044 return json.name + '(' + typeName + ')'; 2045 }; 2046 2047 /** 2048 * Should be called to get display name of contract function 2049 * 2050 * @method extractDisplayName 2051 * @param {String} name of function/event 2052 * @returns {String} display name for function/event eg. multiply(uint256) -> multiply 2053 */ 2054 var extractDisplayName = function (name) { 2055 var length = name.indexOf('('); 2056 return length !== -1 ? name.substr(0, length) : name; 2057 }; 2058 2059 /// @returns overloaded part of function/event name 2060 var extractTypeName = function (name) { 2061 /// TODO: make it invulnerable 2062 var length = name.indexOf('('); 2063 return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : ""; 2064 }; 2065 2066 /** 2067 * Converts value to it's decimal representation in string 2068 * 2069 * @method toDecimal 2070 * @param {String|Number|BigNumber} 2071 * @return {String} 2072 */ 2073 var toDecimal = function (value) { 2074 return toBigNumber(value).toNumber(); 2075 }; 2076 2077 /** 2078 * Converts value to it's hex representation 2079 * 2080 * @method fromDecimal 2081 * @param {String|Number|BigNumber} 2082 * @return {String} 2083 */ 2084 var fromDecimal = function (value) { 2085 var number = toBigNumber(value); 2086 var result = number.toString(16); 2087 2088 return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result; 2089 }; 2090 2091 /** 2092 * Auto converts any given value into it's hex representation. 2093 * 2094 * And even stringifys objects before. 2095 * 2096 * @method toHex 2097 * @param {String|Number|BigNumber|Object} 2098 * @return {String} 2099 */ 2100 var toHex = function (val) { 2101 /*jshint maxcomplexity: 8 */ 2102 2103 if (isBoolean(val)) 2104 return fromDecimal(+val); 2105 2106 if (isBigNumber(val)) 2107 return fromDecimal(val); 2108 2109 if (isObject(val)) 2110 return fromUtf8(JSON.stringify(val)); 2111 2112 // if its a negative number, pass it through fromDecimal 2113 if (isString(val)) { 2114 if (val.indexOf('-0x') === 0) 2115 return fromDecimal(val); 2116 else if(val.indexOf('0x') === 0) 2117 return val; 2118 else if (!isFinite(val)) 2119 return fromAscii(val); 2120 } 2121 2122 return fromDecimal(val); 2123 }; 2124 2125 /** 2126 * Returns value of unit in Wei 2127 * 2128 * @method getValueOfUnit 2129 * @param {String} unit the unit to convert to, default ether 2130 * @returns {BigNumber} value of the unit (in Wei) 2131 * @throws error if the unit is not correct:w 2132 */ 2133 var getValueOfUnit = function (unit) { 2134 unit = unit ? unit.toLowerCase() : 'reap'; 2135 var unitValue = unitMap[unit]; 2136 if (unitValue === undefined) { 2137 throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2)); 2138 } 2139 return new BigNumber(unitValue, 10); 2140 }; 2141 2142 /** 2143 * Takes a number of wei and converts it to any other ether unit. 2144 * 2145 * Possible units are: 2146 * SI Short SI Full Effigy Other 2147 * - kwei femtoether babbage 2148 * - mwei picoether lovelace 2149 * - gwei nanoether shannon nano 2150 * - -- microether szabo micro 2151 * - -- milliether finney milli 2152 * - ether -- -- 2153 * - kether -- grand 2154 * - mether 2155 * - gether 2156 * - tether 2157 * 2158 * @method fromWei 2159 * @param {Number|String} number can be a number, number string or a HEX of a decimal 2160 * @param {String} unit the unit to convert to, default ether 2161 * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number 2162 */ 2163 var fromWei = function(number, unit) { 2164 var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); 2165 2166 return isBigNumber(number) ? returnValue : returnValue.toString(10); 2167 }; 2168 2169 /** 2170 * Takes a number of a unit and converts it to wei. 2171 * 2172 * Possible units are: 2173 * SI Short SI Full Effigy Other 2174 * - kwei femtoether babbage 2175 * - mwei picoether lovelace 2176 * - gwei nanoether shannon nano 2177 * - -- microether szabo micro 2178 * - -- microether szabo micro 2179 * - -- milliether finney milli 2180 * - ether -- -- 2181 * - kether -- grand 2182 * - mether 2183 * - gether 2184 * - tether 2185 * 2186 * @method toWei 2187 * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal 2188 * @param {String} unit the unit to convert from, default ether 2189 * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number 2190 */ 2191 var toWei = function(number, unit) { 2192 var returnValue = toBigNumber(number).times(getValueOfUnit(unit)); 2193 2194 return isBigNumber(number) ? returnValue : returnValue.toString(10); 2195 }; 2196 2197 /** 2198 * Takes an input and transforms it into an bignumber 2199 * 2200 * @method toBigNumber 2201 * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber 2202 * @return {BigNumber} BigNumber 2203 */ 2204 var toBigNumber = function(number) { 2205 /*jshint maxcomplexity:5 */ 2206 number = number || 0; 2207 if (isBigNumber(number)) 2208 return number; 2209 2210 if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) { 2211 return new BigNumber(number.replace('0x',''), 16); 2212 } 2213 2214 return new BigNumber(number.toString(10), 10); 2215 }; 2216 2217 /** 2218 * Takes and input transforms it into bignumber and if it is negative value, into two's complement 2219 * 2220 * @method toTwosComplement 2221 * @param {Number|String|BigNumber} 2222 * @return {BigNumber} 2223 */ 2224 var toTwosComplement = function (number) { 2225 var bigNumber = toBigNumber(number).round(); 2226 if (bigNumber.lessThan(0)) { 2227 return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1); 2228 } 2229 return bigNumber; 2230 }; 2231 2232 /** 2233 * Checks if the given string is strictly an address 2234 * 2235 * @method isStrictAddress 2236 * @param {String} address the given HEX adress 2237 * @return {Boolean} 2238 */ 2239 var isStrictAddress = function (address) { 2240 return /^0x[0-9a-f]{40}$/i.test(address); 2241 }; 2242 2243 /** 2244 * Checks if the given string is an address 2245 * 2246 * @method isAddress 2247 * @param {String} address the given HEX adress 2248 * @return {Boolean} 2249 */ 2250 var isAddress = function (address) { 2251 if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { 2252 // check if it has the basic requirements of an address 2253 return false; 2254 } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { 2255 // If it's all small caps or all all caps, return true 2256 return true; 2257 } else { 2258 // Otherwise check each case 2259 return isChecksumAddress(address); 2260 } 2261 }; 2262 2263 2264 2265 /** 2266 * Checks if the given string is a checksummed address 2267 * 2268 * @method isChecksumAddress 2269 * @param {String} address the given HEX adress 2270 * @return {Boolean} 2271 */ 2272 var isChecksumAddress = function (address) { 2273 // Check each case 2274 address = address.replace('0x',''); 2275 var addressHash = sha3(address.toLowerCase()); 2276 2277 for (var i = 0; i < 40; i++ ) { 2278 // the nth letter should be uppercase if the nth digit of casemap is 1 2279 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { 2280 return false; 2281 } 2282 } 2283 return true; 2284 }; 2285 2286 2287 2288 /** 2289 * Makes a checksum address 2290 * 2291 * @method toChecksumAddress 2292 * @param {String} address the given HEX adress 2293 * @return {String} 2294 */ 2295 var toChecksumAddress = function (address) { 2296 if (typeof address === 'undefined') return ''; 2297 2298 address = address.toLowerCase().replace('0x',''); 2299 var addressHash = sha3(address); 2300 var checksumAddress = '0x'; 2301 2302 for (var i = 0; i < address.length; i++ ) { 2303 // If ith character is 9 to f then make it uppercase 2304 if (parseInt(addressHash[i], 16) > 7) { 2305 checksumAddress += address[i].toUpperCase(); 2306 } else { 2307 checksumAddress += address[i]; 2308 } 2309 } 2310 return checksumAddress; 2311 }; 2312 2313 /** 2314 * Transforms given string to valid 20 bytes-length addres with 0x prefix 2315 * 2316 * @method toAddress 2317 * @param {String} address 2318 * @return {String} formatted address 2319 */ 2320 var toAddress = function (address) { 2321 if (isStrictAddress(address)) { 2322 return address; 2323 } 2324 2325 if (/^[0-9a-f]{40}$/.test(address)) { 2326 return '0x' + address; 2327 } 2328 2329 return '0x' + padLeft(toHex(address).substr(2), 40); 2330 }; 2331 2332 /** 2333 * Returns true if object is BigNumber, otherwise false 2334 * 2335 * @method isBigNumber 2336 * @param {Object} 2337 * @return {Boolean} 2338 */ 2339 var isBigNumber = function (object) { 2340 return object instanceof BigNumber || 2341 (object && object.constructor && object.constructor.name === 'BigNumber'); 2342 }; 2343 2344 /** 2345 * Returns true if object is string, otherwise false 2346 * 2347 * @method isString 2348 * @param {Object} 2349 * @return {Boolean} 2350 */ 2351 var isString = function (object) { 2352 return typeof object === 'string' || 2353 (object && object.constructor && object.constructor.name === 'String'); 2354 }; 2355 2356 /** 2357 * Returns true if object is function, otherwise false 2358 * 2359 * @method isFunction 2360 * @param {Object} 2361 * @return {Boolean} 2362 */ 2363 var isFunction = function (object) { 2364 return typeof object === 'function'; 2365 }; 2366 2367 /** 2368 * Returns true if object is Objet, otherwise false 2369 * 2370 * @method isObject 2371 * @param {Object} 2372 * @return {Boolean} 2373 */ 2374 var isObject = function (object) { 2375 return typeof object === 'object'; 2376 }; 2377 2378 /** 2379 * Returns true if object is boolean, otherwise false 2380 * 2381 * @method isBoolean 2382 * @param {Object} 2383 * @return {Boolean} 2384 */ 2385 var isBoolean = function (object) { 2386 return typeof object === 'boolean'; 2387 }; 2388 2389 /** 2390 * Returns true if object is array, otherwise false 2391 * 2392 * @method isArray 2393 * @param {Object} 2394 * @return {Boolean} 2395 */ 2396 var isArray = function (object) { 2397 return object instanceof Array; 2398 }; 2399 2400 /** 2401 * Returns true if given string is valid json object 2402 * 2403 * @method isJson 2404 * @param {String} 2405 * @return {Boolean} 2406 */ 2407 var isJson = function (str) { 2408 try { 2409 return !!JSON.parse(str); 2410 } catch (e) { 2411 return false; 2412 } 2413 }; 2414 2415 module.exports = { 2416 padLeft: padLeft, 2417 padRight: padRight, 2418 toHex: toHex, 2419 toDecimal: toDecimal, 2420 fromDecimal: fromDecimal, 2421 toUtf8: toUtf8, 2422 toAscii: toAscii, 2423 fromUtf8: fromUtf8, 2424 fromAscii: fromAscii, 2425 transformToFullName: transformToFullName, 2426 extractDisplayName: extractDisplayName, 2427 extractTypeName: extractTypeName, 2428 toWei: toWei, 2429 fromWei: fromWei, 2430 toBigNumber: toBigNumber, 2431 toTwosComplement: toTwosComplement, 2432 toAddress: toAddress, 2433 isBigNumber: isBigNumber, 2434 isStrictAddress: isStrictAddress, 2435 isAddress: isAddress, 2436 isChecksumAddress: isChecksumAddress, 2437 toChecksumAddress: toChecksumAddress, 2438 isFunction: isFunction, 2439 isString: isString, 2440 isObject: isObject, 2441 isBoolean: isBoolean, 2442 isArray: isArray, 2443 isJson: isJson 2444 }; 2445 2446 },{"./sha3.js":19,"bignumber.js":"bignumber.js","utf8":85}],21:[function(require,module,exports){ 2447 module.exports={ 2448 "version": "0.18.1" 2449 } 2450 2451 },{}],22:[function(require,module,exports){ 2452 /* 2453 This file is part of web3.js. 2454 2455 web3.js is free software: you can redistribute it and/or modify 2456 it under the terms of the GNU Lesser General Public License as published by 2457 the Free Software Foundation, either version 3 of the License, or 2458 (at your option) any later version. 2459 2460 web3.js is distributed in the hope that it will be useful, 2461 but WITHOUT ANY WARRANTY; without even the implied warranty of 2462 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2463 GNU Lesser General Public License for more details. 2464 2465 You should have received a copy of the GNU Lesser General Public License 2466 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2467 */ 2468 /** 2469 * @file web3.js 2470 * @authors: 2471 * Jeffrey Wilcke <jeff@ethdev.com> 2472 * Marek Kotewicz <marek@ethdev.com> 2473 * Marian Oancea <marian@ethdev.com> 2474 * Fabian Vogelsteller <fabian@ethdev.com> 2475 * Gav Wood <g@ethdev.com> 2476 * @date 2014 2477 */ 2478 2479 var RequestManager = require('./web3/requestmanager'); 2480 var Iban = require('./web3/iban'); 2481 var Eth = require('./web3/methods/eth'); 2482 var DB = require('./web3/methods/db'); 2483 var Shh = require('./web3/methods/shh'); 2484 var Net = require('./web3/methods/net'); 2485 var Personal = require('./web3/methods/personal'); 2486 var Swarm = require('./web3/methods/swarm'); 2487 var Settings = require('./web3/settings'); 2488 var version = require('./version.json'); 2489 var utils = require('./utils/utils'); 2490 var sha3 = require('./utils/sha3'); 2491 var extend = require('./web3/extend'); 2492 var Batch = require('./web3/batch'); 2493 var Property = require('./web3/property'); 2494 var HttpProvider = require('./web3/httpprovider'); 2495 var IpcProvider = require('./web3/ipcprovider'); 2496 var BigNumber = require('bignumber.js'); 2497 2498 2499 2500 function Web3 (provider) { 2501 this._requestManager = new RequestManager(provider); 2502 this.currentProvider = provider; 2503 this.eth = new Eth(this); 2504 this.db = new DB(this); 2505 this.shh = new Shh(this); 2506 this.net = new Net(this); 2507 this.personal = new Personal(this); 2508 this.bzz = new Swarm(this); 2509 this.settings = new Settings(); 2510 this.version = { 2511 api: version.version 2512 }; 2513 this.providers = { 2514 HttpProvider: HttpProvider, 2515 IpcProvider: IpcProvider 2516 }; 2517 this._extend = extend(this); 2518 this._extend({ 2519 properties: properties() 2520 }); 2521 } 2522 2523 // expose providers on the class 2524 Web3.providers = { 2525 HttpProvider: HttpProvider, 2526 IpcProvider: IpcProvider 2527 }; 2528 2529 Web3.prototype.setProvider = function (provider) { 2530 this._requestManager.setProvider(provider); 2531 this.currentProvider = provider; 2532 }; 2533 2534 Web3.prototype.reset = function (keepIsSyncing) { 2535 this._requestManager.reset(keepIsSyncing); 2536 this.settings = new Settings(); 2537 }; 2538 2539 Web3.prototype.BigNumber = BigNumber; 2540 Web3.prototype.toHex = utils.toHex; 2541 Web3.prototype.toAscii = utils.toAscii; 2542 Web3.prototype.toUtf8 = utils.toUtf8; 2543 Web3.prototype.fromAscii = utils.fromAscii; 2544 Web3.prototype.fromUtf8 = utils.fromUtf8; 2545 Web3.prototype.toDecimal = utils.toDecimal; 2546 Web3.prototype.fromDecimal = utils.fromDecimal; 2547 Web3.prototype.toBigNumber = utils.toBigNumber; 2548 Web3.prototype.toWei = utils.toWei; 2549 Web3.prototype.fromWei = utils.fromWei; 2550 Web3.prototype.isAddress = utils.isAddress; 2551 Web3.prototype.isChecksumAddress = utils.isChecksumAddress; 2552 Web3.prototype.toChecksumAddress = utils.toChecksumAddress; 2553 Web3.prototype.isIBAN = utils.isIBAN; 2554 2555 2556 Web3.prototype.sha3 = function(string, options) { 2557 return '0x' + sha3(string, options); 2558 }; 2559 2560 /** 2561 * Transforms direct icap to address 2562 */ 2563 Web3.prototype.fromICAP = function (icap) { 2564 var iban = new Iban(icap); 2565 return iban.address(); 2566 }; 2567 2568 var properties = function () { 2569 return [ 2570 new Property({ 2571 name: 'version.node', 2572 getter: 'web3_clientVersion' 2573 }), 2574 new Property({ 2575 name: 'version.network', 2576 getter: 'net_version', 2577 inputFormatter: utils.toDecimal 2578 }), 2579 new Property({ 2580 name: 'version.ethereum', 2581 getter: 'eth_protocolVersion', 2582 inputFormatter: utils.toDecimal 2583 }), 2584 new Property({ 2585 name: 'version.whisper', 2586 getter: 'shh_version', 2587 inputFormatter: utils.toDecimal 2588 }) 2589 ]; 2590 }; 2591 2592 Web3.prototype.isConnected = function(){ 2593 return (this.currentProvider && this.currentProvider.isConnected()); 2594 }; 2595 2596 Web3.prototype.createBatch = function () { 2597 return new Batch(this); 2598 }; 2599 2600 module.exports = Web3; 2601 2602 2603 },{"./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){ 2604 /* 2605 This file is part of web3.js. 2606 2607 web3.js is free software: you can redistribute it and/or modify 2608 it under the terms of the GNU Lesser General Public License as published by 2609 the Free Software Foundation, either version 3 of the License, or 2610 (at your option) any later version. 2611 2612 web3.js is distributed in the hope that it will be useful, 2613 but WITHOUT ANY WARRANTY; without even the implied warranty of 2614 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2615 GNU Lesser General Public License for more details. 2616 2617 You should have received a copy of the GNU Lesser General Public License 2618 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2619 */ 2620 /** 2621 * @file allevents.js 2622 * @author Marek Kotewicz <marek@ethdev.com> 2623 * @date 2014 2624 */ 2625 2626 var sha3 = require('../utils/sha3'); 2627 var SolidityEvent = require('./event'); 2628 var formatters = require('./formatters'); 2629 var utils = require('../utils/utils'); 2630 var Filter = require('./filter'); 2631 var watches = require('./methods/watches'); 2632 2633 var AllSolidityEvents = function (requestManager, json, address) { 2634 this._requestManager = requestManager; 2635 this._json = json; 2636 this._address = address; 2637 }; 2638 2639 AllSolidityEvents.prototype.encode = function (options) { 2640 options = options || {}; 2641 var result = {}; 2642 2643 ['fromBlock', 'toBlock'].filter(function (f) { 2644 return options[f] !== undefined; 2645 }).forEach(function (f) { 2646 result[f] = formatters.inputBlockNumberFormatter(options[f]); 2647 }); 2648 2649 result.address = this._address; 2650 2651 return result; 2652 }; 2653 2654 AllSolidityEvents.prototype.decode = function (data) { 2655 data.data = data.data || ''; 2656 data.topics = data.topics || []; 2657 2658 var eventTopic = data.topics[0].slice(2); 2659 var match = this._json.filter(function (j) { 2660 return eventTopic === sha3(utils.transformToFullName(j)); 2661 })[0]; 2662 2663 if (!match) { // cannot find matching event? 2664 console.warn('cannot find event for log'); 2665 return data; 2666 } 2667 2668 var event = new SolidityEvent(this._requestManager, match, this._address); 2669 return event.decode(data); 2670 }; 2671 2672 AllSolidityEvents.prototype.execute = function (options, callback) { 2673 2674 if (utils.isFunction(arguments[arguments.length - 1])) { 2675 callback = arguments[arguments.length - 1]; 2676 if(arguments.length === 1) 2677 options = null; 2678 } 2679 2680 var o = this.encode(options); 2681 var formatter = this.decode.bind(this); 2682 return new Filter(this._requestManager, o, watches.eth(), formatter, callback); 2683 }; 2684 2685 AllSolidityEvents.prototype.attachToContract = function (contract) { 2686 var execute = this.execute.bind(this); 2687 contract.allEvents = execute; 2688 }; 2689 2690 module.exports = AllSolidityEvents; 2691 2692 2693 },{"../utils/sha3":19,"../utils/utils":20,"./event":27,"./filter":29,"./formatters":30,"./methods/watches":43}],24:[function(require,module,exports){ 2694 /* 2695 This file is part of web3.js. 2696 2697 web3.js is free software: you can redistribute it and/or modify 2698 it under the terms of the GNU Lesser General Public License as published by 2699 the Free Software Foundation, either version 3 of the License, or 2700 (at your option) any later version. 2701 2702 web3.js is distributed in the hope that it will be useful, 2703 but WITHOUT ANY WARRANTY; without even the implied warranty of 2704 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2705 GNU Lesser General Public License for more details. 2706 2707 You should have received a copy of the GNU Lesser General Public License 2708 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2709 */ 2710 /** 2711 * @file batch.js 2712 * @author Marek Kotewicz <marek@ethdev.com> 2713 * @date 2015 2714 */ 2715 2716 var Jsonrpc = require('./jsonrpc'); 2717 var errors = require('./errors'); 2718 2719 var Batch = function (web3) { 2720 this.requestManager = web3._requestManager; 2721 this.requests = []; 2722 }; 2723 2724 /** 2725 * Should be called to add create new request to batch request 2726 * 2727 * @method add 2728 * @param {Object} jsonrpc requet object 2729 */ 2730 Batch.prototype.add = function (request) { 2731 this.requests.push(request); 2732 }; 2733 2734 /** 2735 * Should be called to execute batch request 2736 * 2737 * @method execute 2738 */ 2739 Batch.prototype.execute = function () { 2740 var requests = this.requests; 2741 this.requestManager.sendBatch(requests, function (err, results) { 2742 results = results || []; 2743 requests.map(function (request, index) { 2744 return results[index] || {}; 2745 }).forEach(function (result, index) { 2746 if (requests[index].callback) { 2747 2748 if (!Jsonrpc.isValidResponse(result)) { 2749 return requests[index].callback(errors.InvalidResponse(result)); 2750 } 2751 2752 requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result)); 2753 } 2754 }); 2755 }); 2756 }; 2757 2758 module.exports = Batch; 2759 2760 2761 },{"./errors":26,"./jsonrpc":35}],25:[function(require,module,exports){ 2762 /* 2763 This file is part of web3.js. 2764 2765 web3.js is free software: you can redistribute it and/or modify 2766 it under the terms of the GNU Lesser General Public License as published by 2767 the Free Software Foundation, either version 3 of the License, or 2768 (at your option) any later version. 2769 2770 web3.js is distributed in the hope that it will be useful, 2771 but WITHOUT ANY WARRANTY; without even the implied warranty of 2772 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 2773 GNU Lesser General Public License for more details. 2774 2775 You should have received a copy of the GNU Lesser General Public License 2776 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 2777 */ 2778 /** 2779 * @file contract.js 2780 * @author Marek Kotewicz <marek@ethdev.com> 2781 * @date 2014 2782 */ 2783 2784 var utils = require('../utils/utils'); 2785 var coder = require('../solidity/coder'); 2786 var SolidityEvent = require('./event'); 2787 var SolidityFunction = require('./function'); 2788 var AllEvents = require('./allevents'); 2789 2790 /** 2791 * Should be called to encode constructor params 2792 * 2793 * @method encodeConstructorParams 2794 * @param {Array} abi 2795 * @param {Array} constructor params 2796 */ 2797 var encodeConstructorParams = function (abi, params) { 2798 return abi.filter(function (json) { 2799 return json.type === 'constructor' && json.inputs.length === params.length; 2800 }).map(function (json) { 2801 return json.inputs.map(function (input) { 2802 return input.type; 2803 }); 2804 }).map(function (types) { 2805 return coder.encodeParams(types, params); 2806 })[0] || ''; 2807 }; 2808 2809 /** 2810 * Should be called to add functions to contract object 2811 * 2812 * @method addFunctionsToContract 2813 * @param {Contract} contract 2814 * @param {Array} abi 2815 */ 2816 var addFunctionsToContract = function (contract) { 2817 contract.abi.filter(function (json) { 2818 return json.type === 'function'; 2819 }).map(function (json) { 2820 return new SolidityFunction(contract._eth, json, contract.address); 2821 }).forEach(function (f) { 2822 f.attachToContract(contract); 2823 }); 2824 }; 2825 2826 /** 2827 * Should be called to add events to contract object 2828 * 2829 * @method addEventsToContract 2830 * @param {Contract} contract 2831 * @param {Array} abi 2832 */ 2833 var addEventsToContract = function (contract) { 2834 var events = contract.abi.filter(function (json) { 2835 return json.type === 'event'; 2836 }); 2837 2838 var All = new AllEvents(contract._eth._requestManager, events, contract.address); 2839 All.attachToContract(contract); 2840 2841 events.map(function (json) { 2842 return new SolidityEvent(contract._eth._requestManager, json, contract.address); 2843 }).forEach(function (e) { 2844 e.attachToContract(contract); 2845 }); 2846 }; 2847 2848 2849 /** 2850 * Should be called to check if the contract gets properly deployed on the blockchain. 2851 * 2852 * @method checkForContractAddress 2853 * @param {Object} contract 2854 * @param {Function} callback 2855 * @returns {Undefined} 2856 */ 2857 var checkForContractAddress = function(contract, callback){ 2858 var count = 0, 2859 callbackFired = false; 2860 2861 // wait for receipt 2862 var filter = contract._eth.filter('latest', function(e){ 2863 if (!e && !callbackFired) { 2864 count++; 2865 2866 // stop watching after 50 blocks (timeout) 2867 if (count > 50) { 2868 2869 filter.stopWatching(function() {}); 2870 callbackFired = true; 2871 2872 if (callback) 2873 callback(new Error('Contract transaction couldn\'t be found after 50 blocks')); 2874 else 2875 throw new Error('Contract transaction couldn\'t be found after 50 blocks'); 2876 2877 2878 } else { 2879 2880 contract._eth.getTransactionReceipt(contract.transactionHash, function(e, receipt){ 2881 if(receipt && !callbackFired) { 2882 2883 contract._eth.getCode(receipt.contractAddress, function(e, code){ 2884 /*jshint maxcomplexity: 6 */ 2885 2886 if(callbackFired || !code) 2887 return; 2888 2889 filter.stopWatching(function() {}); 2890 callbackFired = true; 2891 2892 if(code.length > 3) { 2893 2894 // console.log('Contract code deployed!'); 2895 2896 contract.address = receipt.contractAddress; 2897 2898 // attach events and methods again after we have 2899 addFunctionsToContract(contract); 2900 addEventsToContract(contract); 2901 2902 // call callback for the second time 2903 if(callback) 2904 callback(null, contract); 2905 2906 } else { 2907 if(callback) 2908 callback(new Error('The contract code couldn\'t be stored, please check your gas amount.')); 2909 else 2910 throw new Error('The contract code couldn\'t be stored, please check your gas amount.'); 2911 } 2912 }); 2913 } 2914 }); 2915 } 2916 } 2917 }); 2918 }; 2919 2920 /** 2921 * Should be called to create new ContractFactory instance 2922 * 2923 * @method ContractFactory 2924 * @param {Array} abi 2925 */ 2926 var ContractFactory = function (eth, abi) { 2927 this.eth = eth; 2928 this.abi = abi; 2929 2930 /** 2931 * Should be called to create new contract on a blockchain 2932 * 2933 * @method new 2934 * @param {Any} contract constructor param1 (optional) 2935 * @param {Any} contract constructor param2 (optional) 2936 * @param {Object} contract transaction object (required) 2937 * @param {Function} callback 2938 * @returns {Contract} returns contract instance 2939 */ 2940 this.new = function () { 2941 var contract = new Contract(this.eth, this.abi); 2942 2943 // parse arguments 2944 var options = {}; // required! 2945 var callback; 2946 2947 var args = Array.prototype.slice.call(arguments); 2948 if (utils.isFunction(args[args.length - 1])) { 2949 callback = args.pop(); 2950 } 2951 2952 var last = args[args.length - 1]; 2953 if (utils.isObject(last) && !utils.isArray(last)) { 2954 options = args.pop(); 2955 } 2956 2957 if (options.value > 0) { 2958 var constructorAbi = abi.filter(function (json) { 2959 return json.type === 'constructor' && json.inputs.length === args.length; 2960 })[0] || {}; 2961 2962 if (!constructorAbi.payable) { 2963 throw new Error('Cannot send value to non-payable constructor'); 2964 } 2965 } 2966 2967 var bytes = encodeConstructorParams(this.abi, args); 2968 options.data += bytes; 2969 2970 if (callback) { 2971 2972 // wait for the contract address adn check if the code was deployed 2973 this.eth.sendTransaction(options, function (err, hash) { 2974 if (err) { 2975 callback(err); 2976 } else { 2977 // add the transaction hash 2978 contract.transactionHash = hash; 2979 2980 // call callback for the first time 2981 callback(null, contract); 2982 2983 checkForContractAddress(contract, callback); 2984 } 2985 }); 2986 } else { 2987 var hash = this.eth.sendTransaction(options); 2988 // add the transaction hash 2989 contract.transactionHash = hash; 2990 checkForContractAddress(contract); 2991 } 2992 2993 return contract; 2994 }; 2995 2996 this.new.getData = this.getData.bind(this); 2997 }; 2998 2999 /** 3000 * Should be called to create new ContractFactory 3001 * 3002 * @method contract 3003 * @param {Array} abi 3004 * @returns {ContractFactory} new contract factory 3005 */ 3006 //var contract = function (abi) { 3007 //return new ContractFactory(abi); 3008 //}; 3009 3010 3011 3012 /** 3013 * Should be called to get access to existing contract on a blockchain 3014 * 3015 * @method at 3016 * @param {Address} contract address (required) 3017 * @param {Function} callback {optional) 3018 * @returns {Contract} returns contract if no callback was passed, 3019 * otherwise calls callback function (err, contract) 3020 */ 3021 ContractFactory.prototype.at = function (address, callback) { 3022 var contract = new Contract(this.eth, this.abi, address); 3023 3024 // this functions are not part of prototype, 3025 // because we dont want to spoil the interface 3026 addFunctionsToContract(contract); 3027 addEventsToContract(contract); 3028 3029 if (callback) { 3030 callback(null, contract); 3031 } 3032 return contract; 3033 }; 3034 3035 /** 3036 * Gets the data, which is data to deploy plus constructor params 3037 * 3038 * @method getData 3039 */ 3040 ContractFactory.prototype.getData = function () { 3041 var options = {}; // required! 3042 var args = Array.prototype.slice.call(arguments); 3043 3044 var last = args[args.length - 1]; 3045 if (utils.isObject(last) && !utils.isArray(last)) { 3046 options = args.pop(); 3047 } 3048 3049 var bytes = encodeConstructorParams(this.abi, args); 3050 options.data += bytes; 3051 3052 return options.data; 3053 }; 3054 3055 /** 3056 * Should be called to create new contract instance 3057 * 3058 * @method Contract 3059 * @param {Array} abi 3060 * @param {Address} contract address 3061 */ 3062 var Contract = function (eth, abi, address) { 3063 this._eth = eth; 3064 this.transactionHash = null; 3065 this.address = address; 3066 this.abi = abi; 3067 }; 3068 3069 module.exports = ContractFactory; 3070 3071 },{"../solidity/coder":7,"../utils/utils":20,"./allevents":23,"./event":27,"./function":31}],26:[function(require,module,exports){ 3072 /* 3073 This file is part of web3.js. 3074 3075 web3.js is free software: you can redistribute it and/or modify 3076 it under the terms of the GNU Lesser General Public License as published by 3077 the Free Software Foundation, either version 3 of the License, or 3078 (at your option) any later version. 3079 3080 web3.js is distributed in the hope that it will be useful, 3081 but WITHOUT ANY WARRANTY; without even the implied warranty of 3082 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3083 GNU Lesser General Public License for more details. 3084 3085 You should have received a copy of the GNU Lesser General Public License 3086 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3087 */ 3088 /** 3089 * @file errors.js 3090 * @author Marek Kotewicz <marek@ethdev.com> 3091 * @date 2015 3092 */ 3093 3094 module.exports = { 3095 InvalidNumberOfParams: function () { 3096 return new Error('Invalid number of input parameters'); 3097 }, 3098 InvalidConnection: function (host){ 3099 return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.'); 3100 }, 3101 InvalidProvider: function () { 3102 return new Error('Provider not set or invalid'); 3103 }, 3104 InvalidResponse: function (result){ 3105 var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); 3106 return new Error(message); 3107 }, 3108 ConnectionTimeout: function (ms){ 3109 return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived'); 3110 } 3111 }; 3112 3113 },{}],27:[function(require,module,exports){ 3114 /* 3115 This file is part of web3.js. 3116 3117 web3.js is free software: you can redistribute it and/or modify 3118 it under the terms of the GNU Lesser General Public License as published by 3119 the Free Software Foundation, either version 3 of the License, or 3120 (at your option) any later version. 3121 3122 web3.js is distributed in the hope that it will be useful, 3123 but WITHOUT ANY WARRANTY; without even the implied warranty of 3124 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3125 GNU Lesser General Public License for more details. 3126 3127 You should have received a copy of the GNU Lesser General Public License 3128 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3129 */ 3130 /** 3131 * @file event.js 3132 * @author Marek Kotewicz <marek@ethdev.com> 3133 * @date 2014 3134 */ 3135 3136 var utils = require('../utils/utils'); 3137 var coder = require('../solidity/coder'); 3138 var formatters = require('./formatters'); 3139 var sha3 = require('../utils/sha3'); 3140 var Filter = require('./filter'); 3141 var watches = require('./methods/watches'); 3142 3143 /** 3144 * This prototype should be used to create event filters 3145 */ 3146 var SolidityEvent = function (requestManager, json, address) { 3147 this._requestManager = requestManager; 3148 this._params = json.inputs; 3149 this._name = utils.transformToFullName(json); 3150 this._address = address; 3151 this._anonymous = json.anonymous; 3152 }; 3153 3154 /** 3155 * Should be used to get filtered param types 3156 * 3157 * @method types 3158 * @param {Bool} decide if returned typed should be indexed 3159 * @return {Array} array of types 3160 */ 3161 SolidityEvent.prototype.types = function (indexed) { 3162 return this._params.filter(function (i) { 3163 return i.indexed === indexed; 3164 }).map(function (i) { 3165 return i.type; 3166 }); 3167 }; 3168 3169 /** 3170 * Should be used to get event display name 3171 * 3172 * @method displayName 3173 * @return {String} event display name 3174 */ 3175 SolidityEvent.prototype.displayName = function () { 3176 return utils.extractDisplayName(this._name); 3177 }; 3178 3179 /** 3180 * Should be used to get event type name 3181 * 3182 * @method typeName 3183 * @return {String} event type name 3184 */ 3185 SolidityEvent.prototype.typeName = function () { 3186 return utils.extractTypeName(this._name); 3187 }; 3188 3189 /** 3190 * Should be used to get event signature 3191 * 3192 * @method signature 3193 * @return {String} event signature 3194 */ 3195 SolidityEvent.prototype.signature = function () { 3196 return sha3(this._name); 3197 }; 3198 3199 /** 3200 * Should be used to encode indexed params and options to one final object 3201 * 3202 * @method encode 3203 * @param {Object} indexed 3204 * @param {Object} options 3205 * @return {Object} everything combined together and encoded 3206 */ 3207 SolidityEvent.prototype.encode = function (indexed, options) { 3208 indexed = indexed || {}; 3209 options = options || {}; 3210 var result = {}; 3211 3212 ['fromBlock', 'toBlock'].filter(function (f) { 3213 return options[f] !== undefined; 3214 }).forEach(function (f) { 3215 result[f] = formatters.inputBlockNumberFormatter(options[f]); 3216 }); 3217 3218 result.topics = []; 3219 3220 result.address = this._address; 3221 if (!this._anonymous) { 3222 result.topics.push('0x' + this.signature()); 3223 } 3224 3225 var indexedTopics = this._params.filter(function (i) { 3226 return i.indexed === true; 3227 }).map(function (i) { 3228 var value = indexed[i.name]; 3229 if (value === undefined || value === null) { 3230 return null; 3231 } 3232 3233 if (utils.isArray(value)) { 3234 return value.map(function (v) { 3235 return '0x' + coder.encodeParam(i.type, v); 3236 }); 3237 } 3238 return '0x' + coder.encodeParam(i.type, value); 3239 }); 3240 3241 result.topics = result.topics.concat(indexedTopics); 3242 3243 return result; 3244 }; 3245 3246 /** 3247 * Should be used to decode indexed params and options 3248 * 3249 * @method decode 3250 * @param {Object} data 3251 * @return {Object} result object with decoded indexed && not indexed params 3252 */ 3253 SolidityEvent.prototype.decode = function (data) { 3254 3255 data.data = data.data || ''; 3256 data.topics = data.topics || []; 3257 3258 var argTopics = this._anonymous ? data.topics : data.topics.slice(1); 3259 var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join(""); 3260 var indexedParams = coder.decodeParams(this.types(true), indexedData); 3261 3262 var notIndexedData = data.data.slice(2); 3263 var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData); 3264 3265 var result = formatters.outputLogFormatter(data); 3266 result.event = this.displayName(); 3267 result.address = data.address; 3268 3269 result.args = this._params.reduce(function (acc, current) { 3270 acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift(); 3271 return acc; 3272 }, {}); 3273 3274 delete result.data; 3275 delete result.topics; 3276 3277 return result; 3278 }; 3279 3280 /** 3281 * Should be used to create new filter object from event 3282 * 3283 * @method execute 3284 * @param {Object} indexed 3285 * @param {Object} options 3286 * @return {Object} filter object 3287 */ 3288 SolidityEvent.prototype.execute = function (indexed, options, callback) { 3289 3290 if (utils.isFunction(arguments[arguments.length - 1])) { 3291 callback = arguments[arguments.length - 1]; 3292 if(arguments.length === 2) 3293 options = null; 3294 if(arguments.length === 1) { 3295 options = null; 3296 indexed = {}; 3297 } 3298 } 3299 3300 var o = this.encode(indexed, options); 3301 var formatter = this.decode.bind(this); 3302 return new Filter(this._requestManager, o, watches.eth(), formatter, callback); 3303 }; 3304 3305 /** 3306 * Should be used to attach event to contract object 3307 * 3308 * @method attachToContract 3309 * @param {Contract} 3310 */ 3311 SolidityEvent.prototype.attachToContract = function (contract) { 3312 var execute = this.execute.bind(this); 3313 var displayName = this.displayName(); 3314 if (!contract[displayName]) { 3315 contract[displayName] = execute; 3316 } 3317 contract[displayName][this.typeName()] = this.execute.bind(this, contract); 3318 }; 3319 3320 module.exports = SolidityEvent; 3321 3322 3323 },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters":30,"./methods/watches":43}],28:[function(require,module,exports){ 3324 var formatters = require('./formatters'); 3325 var utils = require('./../utils/utils'); 3326 var Method = require('./method'); 3327 var Property = require('./property'); 3328 3329 // TODO: refactor, so the input params are not altered. 3330 // it's necessary to make same 'extension' work with multiple providers 3331 var extend = function (web3) { 3332 /* jshint maxcomplexity:5 */ 3333 var ex = function (extension) { 3334 3335 var extendedObject; 3336 if (extension.property) { 3337 if (!web3[extension.property]) { 3338 web3[extension.property] = {}; 3339 } 3340 extendedObject = web3[extension.property]; 3341 } else { 3342 extendedObject = web3; 3343 } 3344 3345 if (extension.methods) { 3346 extension.methods.forEach(function (method) { 3347 method.attachToObject(extendedObject); 3348 method.setRequestManager(web3._requestManager); 3349 }); 3350 } 3351 3352 if (extension.properties) { 3353 extension.properties.forEach(function (property) { 3354 property.attachToObject(extendedObject); 3355 property.setRequestManager(web3._requestManager); 3356 }); 3357 } 3358 }; 3359 3360 ex.formatters = formatters; 3361 ex.utils = utils; 3362 ex.Method = Method; 3363 ex.Property = Property; 3364 3365 return ex; 3366 }; 3367 3368 3369 3370 module.exports = extend; 3371 3372 3373 },{"./../utils/utils":20,"./formatters":30,"./method":36,"./property":45}],29:[function(require,module,exports){ 3374 /* 3375 This file is part of web3.js. 3376 3377 web3.js is free software: you can redistribute it and/or modify 3378 it under the terms of the GNU Lesser General Public License as published by 3379 the Free Software Foundation, either version 3 of the License, or 3380 (at your option) any later version. 3381 3382 web3.js is distributed in the hope that it will be useful, 3383 but WITHOUT ANY WARRANTY; without even the implied warranty of 3384 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3385 GNU Lesser General Public License for more details. 3386 3387 You should have received a copy of the GNU Lesser General Public License 3388 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3389 */ 3390 /** @file filter.js 3391 * @authors: 3392 * Jeffrey Wilcke <jeff@ethdev.com> 3393 * Marek Kotewicz <marek@ethdev.com> 3394 * Marian Oancea <marian@ethdev.com> 3395 * Fabian Vogelsteller <fabian@ethdev.com> 3396 * Gav Wood <g@ethdev.com> 3397 * @date 2014 3398 */ 3399 3400 var formatters = require('./formatters'); 3401 var utils = require('../utils/utils'); 3402 3403 /** 3404 * Converts a given topic to a hex string, but also allows null values. 3405 * 3406 * @param {Mixed} value 3407 * @return {String} 3408 */ 3409 var toTopic = function(value){ 3410 3411 if(value === null || typeof value === 'undefined') 3412 return null; 3413 3414 value = String(value); 3415 3416 if(value.indexOf('0x') === 0) 3417 return value; 3418 else 3419 return utils.fromUtf8(value); 3420 }; 3421 3422 /// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones 3423 /// @param should be string or object 3424 /// @returns options string or object 3425 var getOptions = function (options) { 3426 3427 if (utils.isString(options)) { 3428 return options; 3429 } 3430 3431 options = options || {}; 3432 3433 // make sure topics, get converted to hex 3434 options.topics = options.topics || []; 3435 options.topics = options.topics.map(function(topic){ 3436 return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic); 3437 }); 3438 3439 return { 3440 topics: options.topics, 3441 from: options.from, 3442 to: options.to, 3443 address: options.address, 3444 fromBlock: formatters.inputBlockNumberFormatter(options.fromBlock), 3445 toBlock: formatters.inputBlockNumberFormatter(options.toBlock) 3446 }; 3447 }; 3448 3449 /** 3450 Adds the callback and sets up the methods, to iterate over the results. 3451 3452 @method getLogsAtStart 3453 @param {Object} self 3454 @param {funciton} 3455 */ 3456 var getLogsAtStart = function(self, callback){ 3457 // call getFilterLogs for the first watch callback start 3458 if (!utils.isString(self.options)) { 3459 self.get(function (err, messages) { 3460 // don't send all the responses to all the watches again... just to self one 3461 if (err) { 3462 callback(err); 3463 } 3464 3465 if(utils.isArray(messages)) { 3466 messages.forEach(function (message) { 3467 callback(null, message); 3468 }); 3469 } 3470 }); 3471 } 3472 }; 3473 3474 /** 3475 Adds the callback and sets up the methods, to iterate over the results. 3476 3477 @method pollFilter 3478 @param {Object} self 3479 */ 3480 var pollFilter = function(self) { 3481 3482 var onMessage = function (error, messages) { 3483 if (error) { 3484 return self.callbacks.forEach(function (callback) { 3485 callback(error); 3486 }); 3487 } 3488 3489 if(utils.isArray(messages)) { 3490 messages.forEach(function (message) { 3491 message = self.formatter ? self.formatter(message) : message; 3492 self.callbacks.forEach(function (callback) { 3493 callback(null, message); 3494 }); 3495 }); 3496 } 3497 }; 3498 3499 self.requestManager.startPolling({ 3500 method: self.implementation.poll.call, 3501 params: [self.filterId], 3502 }, self.filterId, onMessage, self.stopWatching.bind(self)); 3503 3504 }; 3505 3506 var Filter = function (requestManager, options, methods, formatter, callback, filterCreationErrorCallback) { 3507 var self = this; 3508 var implementation = {}; 3509 methods.forEach(function (method) { 3510 method.setRequestManager(requestManager); 3511 method.attachToObject(implementation); 3512 }); 3513 this.requestManager = requestManager; 3514 this.options = getOptions(options); 3515 this.implementation = implementation; 3516 this.filterId = null; 3517 this.callbacks = []; 3518 this.getLogsCallbacks = []; 3519 this.pollFilters = []; 3520 this.formatter = formatter; 3521 this.implementation.newFilter(this.options, function(error, id){ 3522 if(error) { 3523 self.callbacks.forEach(function(cb){ 3524 cb(error); 3525 }); 3526 filterCreationErrorCallback(error); 3527 } else { 3528 self.filterId = id; 3529 3530 // check if there are get pending callbacks as a consequence 3531 // of calling get() with filterId unassigned. 3532 self.getLogsCallbacks.forEach(function (cb){ 3533 self.get(cb); 3534 }); 3535 self.getLogsCallbacks = []; 3536 3537 // get filter logs for the already existing watch calls 3538 self.callbacks.forEach(function(cb){ 3539 getLogsAtStart(self, cb); 3540 }); 3541 if(self.callbacks.length > 0) 3542 pollFilter(self); 3543 3544 // start to watch immediately 3545 if(typeof callback === 'function') { 3546 return self.watch(callback); 3547 } 3548 } 3549 }); 3550 3551 return this; 3552 }; 3553 3554 Filter.prototype.watch = function (callback) { 3555 this.callbacks.push(callback); 3556 3557 if(this.filterId) { 3558 getLogsAtStart(this, callback); 3559 pollFilter(this); 3560 } 3561 3562 return this; 3563 }; 3564 3565 Filter.prototype.stopWatching = function (callback) { 3566 this.requestManager.stopPolling(this.filterId); 3567 this.callbacks = []; 3568 // remove filter async 3569 if (callback) { 3570 this.implementation.uninstallFilter(this.filterId, callback); 3571 } else { 3572 return this.implementation.uninstallFilter(this.filterId); 3573 } 3574 }; 3575 3576 Filter.prototype.get = function (callback) { 3577 var self = this; 3578 if (utils.isFunction(callback)) { 3579 if (this.filterId === null) { 3580 // If filterId is not set yet, call it back 3581 // when newFilter() assigns it. 3582 this.getLogsCallbacks.push(callback); 3583 } else { 3584 this.implementation.getLogs(this.filterId, function(err, res){ 3585 if (err) { 3586 callback(err); 3587 } else { 3588 callback(null, res.map(function (log) { 3589 return self.formatter ? self.formatter(log) : log; 3590 })); 3591 } 3592 }); 3593 } 3594 } else { 3595 if (this.filterId === null) { 3596 throw new Error('Filter ID Error: filter().get() can\'t be chained synchronous, please provide a callback for the get() method.'); 3597 } 3598 var logs = this.implementation.getLogs(this.filterId); 3599 return logs.map(function (log) { 3600 return self.formatter ? self.formatter(log) : log; 3601 }); 3602 } 3603 3604 return this; 3605 }; 3606 3607 module.exports = Filter; 3608 3609 3610 },{"../utils/utils":20,"./formatters":30}],30:[function(require,module,exports){ 3611 /* 3612 This file is part of web3.js. 3613 3614 web3.js is free software: you can redistribute it and/or modify 3615 it under the terms of the GNU Lesser General Public License as published by 3616 the Free Software Foundation, either version 3 of the License, or 3617 (at your option) any later version. 3618 3619 web3.js is distributed in the hope that it will be useful, 3620 but WITHOUT ANY WARRANTY; without even the implied warranty of 3621 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3622 GNU Lesser General Public License for more details. 3623 3624 You should have received a copy of the GNU Lesser General Public License 3625 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3626 */ 3627 /** 3628 * @file formatters.js 3629 * @author Marek Kotewicz <marek@ethdev.com> 3630 * @author Fabian Vogelsteller <fabian@ethdev.com> 3631 * @date 2015 3632 */ 3633 3634 var utils = require('../utils/utils'); 3635 var config = require('../utils/config'); 3636 var Iban = require('./iban'); 3637 3638 /** 3639 * Should the format output to a big number 3640 * 3641 * @method outputBigNumberFormatter 3642 * @param {String|Number|BigNumber} 3643 * @returns {BigNumber} object 3644 */ 3645 var outputBigNumberFormatter = function (number) { 3646 return utils.toBigNumber(number); 3647 }; 3648 3649 var isPredefinedBlockNumber = function (blockNumber) { 3650 return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest'; 3651 }; 3652 3653 var inputDefaultBlockNumberFormatter = function (blockNumber) { 3654 if (blockNumber === undefined) { 3655 return config.defaultBlock; 3656 } 3657 return inputBlockNumberFormatter(blockNumber); 3658 }; 3659 3660 var inputBlockNumberFormatter = function (blockNumber) { 3661 if (blockNumber === undefined) { 3662 return undefined; 3663 } else if (isPredefinedBlockNumber(blockNumber)) { 3664 return blockNumber; 3665 } 3666 return utils.toHex(blockNumber); 3667 }; 3668 3669 /** 3670 * Formats the input of a transaction and converts all values to HEX 3671 * 3672 * @method inputCallFormatter 3673 * @param {Object} transaction options 3674 * @returns object 3675 */ 3676 var inputCallFormatter = function (options){ 3677 3678 options.from = options.from || config.defaultAccount; 3679 3680 if (options.from) { 3681 options.from = inputAddressFormatter(options.from); 3682 } 3683 3684 if (options.to) { // it might be contract creation 3685 options.to = inputAddressFormatter(options.to); 3686 } 3687 3688 ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { 3689 return options[key] !== undefined; 3690 }).forEach(function(key){ 3691 options[key] = utils.fromDecimal(options[key]); 3692 }); 3693 3694 return options; 3695 }; 3696 3697 /** 3698 * Formats the input of a transaction and converts all values to HEX 3699 * 3700 * @method inputTransactionFormatter 3701 * @param {Object} transaction options 3702 * @returns object 3703 */ 3704 var inputTransactionFormatter = function (options){ 3705 3706 options.from = options.from || config.defaultAccount; 3707 options.from = inputAddressFormatter(options.from); 3708 3709 if (options.to) { // it might be contract creation 3710 options.to = inputAddressFormatter(options.to); 3711 } 3712 3713 ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { 3714 return options[key] !== undefined; 3715 }).forEach(function(key){ 3716 options[key] = utils.fromDecimal(options[key]); 3717 }); 3718 3719 return options; 3720 }; 3721 3722 /** 3723 * Formats the output of a transaction to its proper values 3724 * 3725 * @method outputTransactionFormatter 3726 * @param {Object} tx 3727 * @returns {Object} 3728 */ 3729 var outputTransactionFormatter = function (tx){ 3730 if(tx.blockNumber !== null) 3731 tx.blockNumber = utils.toDecimal(tx.blockNumber); 3732 if(tx.transactionIndex !== null) 3733 tx.transactionIndex = utils.toDecimal(tx.transactionIndex); 3734 tx.nonce = utils.toDecimal(tx.nonce); 3735 tx.gas = utils.toDecimal(tx.gas); 3736 tx.gasPrice = utils.toBigNumber(tx.gasPrice); 3737 tx.value = utils.toBigNumber(tx.value); 3738 return tx; 3739 }; 3740 3741 /** 3742 * Formats the output of a transaction receipt to its proper values 3743 * 3744 * @method outputTransactionReceiptFormatter 3745 * @param {Object} receipt 3746 * @returns {Object} 3747 */ 3748 var outputTransactionReceiptFormatter = function (receipt){ 3749 if(receipt.blockNumber !== null) 3750 receipt.blockNumber = utils.toDecimal(receipt.blockNumber); 3751 if(receipt.transactionIndex !== null) 3752 receipt.transactionIndex = utils.toDecimal(receipt.transactionIndex); 3753 receipt.cumulativeGasUsed = utils.toDecimal(receipt.cumulativeGasUsed); 3754 receipt.gasUsed = utils.toDecimal(receipt.gasUsed); 3755 3756 if(utils.isArray(receipt.logs)) { 3757 receipt.logs = receipt.logs.map(function(log){ 3758 return outputLogFormatter(log); 3759 }); 3760 } 3761 3762 return receipt; 3763 }; 3764 3765 /** 3766 * Formats the output of a block to its proper values 3767 * 3768 * @method outputBlockFormatter 3769 * @param {Object} block 3770 * @returns {Object} 3771 */ 3772 var outputBlockFormatter = function(block) { 3773 3774 // transform to number 3775 block.gasLimit = utils.toDecimal(block.gasLimit); 3776 block.gasUsed = utils.toDecimal(block.gasUsed); 3777 block.size = utils.toDecimal(block.size); 3778 block.timestamp = utils.toDecimal(block.timestamp); 3779 if(block.number !== null) 3780 block.number = utils.toDecimal(block.number); 3781 3782 block.difficulty = utils.toBigNumber(block.difficulty); 3783 block.totalDifficulty = utils.toBigNumber(block.totalDifficulty); 3784 3785 if (utils.isArray(block.transactions)) { 3786 block.transactions.forEach(function(item){ 3787 if(!utils.isString(item)) 3788 return outputTransactionFormatter(item); 3789 }); 3790 } 3791 3792 return block; 3793 }; 3794 3795 /** 3796 * Formats the output of a log 3797 * 3798 * @method outputLogFormatter 3799 * @param {Object} log object 3800 * @returns {Object} log 3801 */ 3802 var outputLogFormatter = function(log) { 3803 if(log.blockNumber !== null) 3804 log.blockNumber = utils.toDecimal(log.blockNumber); 3805 if(log.transactionIndex !== null) 3806 log.transactionIndex = utils.toDecimal(log.transactionIndex); 3807 if(log.logIndex !== null) 3808 log.logIndex = utils.toDecimal(log.logIndex); 3809 3810 return log; 3811 }; 3812 3813 /** 3814 * Formats the input of a whisper post and converts all values to HEX 3815 * 3816 * @method inputPostFormatter 3817 * @param {Object} transaction object 3818 * @returns {Object} 3819 */ 3820 var inputPostFormatter = function(post) { 3821 3822 // post.payload = utils.toHex(post.payload); 3823 post.ttl = utils.fromDecimal(post.ttl); 3824 post.workToProve = utils.fromDecimal(post.workToProve); 3825 post.priority = utils.fromDecimal(post.priority); 3826 3827 // fallback 3828 if (!utils.isArray(post.topics)) { 3829 post.topics = post.topics ? [post.topics] : []; 3830 } 3831 3832 // format the following options 3833 post.topics = post.topics.map(function(topic){ 3834 // convert only if not hex 3835 return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); 3836 }); 3837 3838 return post; 3839 }; 3840 3841 /** 3842 * Formats the output of a received post message 3843 * 3844 * @method outputPostFormatter 3845 * @param {Object} 3846 * @returns {Object} 3847 */ 3848 var outputPostFormatter = function(post){ 3849 3850 post.expiry = utils.toDecimal(post.expiry); 3851 post.sent = utils.toDecimal(post.sent); 3852 post.ttl = utils.toDecimal(post.ttl); 3853 post.workProved = utils.toDecimal(post.workProved); 3854 // post.payloadRaw = post.payload; 3855 // post.payload = utils.toAscii(post.payload); 3856 3857 // if (utils.isJson(post.payload)) { 3858 // post.payload = JSON.parse(post.payload); 3859 // } 3860 3861 // format the following options 3862 if (!post.topics) { 3863 post.topics = []; 3864 } 3865 post.topics = post.topics.map(function(topic){ 3866 return utils.toAscii(topic); 3867 }); 3868 3869 return post; 3870 }; 3871 3872 var inputAddressFormatter = function (address) { 3873 var iban = new Iban(address); 3874 if (iban.isValid() && iban.isDirect()) { 3875 return '0x' + iban.address(); 3876 } else if (utils.isStrictAddress(address)) { 3877 return address; 3878 } else if (utils.isAddress(address)) { 3879 return '0x' + address; 3880 } 3881 throw new Error('invalid address'); 3882 }; 3883 3884 3885 var outputSyncingFormatter = function(result) { 3886 3887 result.startingBlock = utils.toDecimal(result.startingBlock); 3888 result.currentBlock = utils.toDecimal(result.currentBlock); 3889 result.highestBlock = utils.toDecimal(result.highestBlock); 3890 if (result.knownStates) { 3891 result.knownStates = utils.toDecimal(result.knownStates); 3892 result.pulledStates = utils.toDecimal(result.pulledStates); 3893 } 3894 3895 return result; 3896 }; 3897 3898 module.exports = { 3899 inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, 3900 inputBlockNumberFormatter: inputBlockNumberFormatter, 3901 inputCallFormatter: inputCallFormatter, 3902 inputTransactionFormatter: inputTransactionFormatter, 3903 inputAddressFormatter: inputAddressFormatter, 3904 inputPostFormatter: inputPostFormatter, 3905 outputBigNumberFormatter: outputBigNumberFormatter, 3906 outputTransactionFormatter: outputTransactionFormatter, 3907 outputTransactionReceiptFormatter: outputTransactionReceiptFormatter, 3908 outputBlockFormatter: outputBlockFormatter, 3909 outputLogFormatter: outputLogFormatter, 3910 outputPostFormatter: outputPostFormatter, 3911 outputSyncingFormatter: outputSyncingFormatter 3912 }; 3913 3914 3915 },{"../utils/config":18,"../utils/utils":20,"./iban":33}],31:[function(require,module,exports){ 3916 /* 3917 This file is part of web3.js. 3918 3919 web3.js is free software: you can redistribute it and/or modify 3920 it under the terms of the GNU Lesser General Public License as published by 3921 the Free Software Foundation, either version 3 of the License, or 3922 (at your option) any later version. 3923 3924 web3.js is distributed in the hope that it will be useful, 3925 but WITHOUT ANY WARRANTY; without even the implied warranty of 3926 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3927 GNU Lesser General Public License for more details. 3928 3929 You should have received a copy of the GNU Lesser General Public License 3930 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 3931 */ 3932 /** 3933 * @file function.js 3934 * @author Marek Kotewicz <marek@ethdev.com> 3935 * @date 2015 3936 */ 3937 3938 var coder = require('../solidity/coder'); 3939 var utils = require('../utils/utils'); 3940 var formatters = require('./formatters'); 3941 var sha3 = require('../utils/sha3'); 3942 3943 /** 3944 * This prototype should be used to call/sendTransaction to solidity functions 3945 */ 3946 var SolidityFunction = function (eth, json, address) { 3947 this._eth = eth; 3948 this._inputTypes = json.inputs.map(function (i) { 3949 return i.type; 3950 }); 3951 this._outputTypes = json.outputs.map(function (i) { 3952 return i.type; 3953 }); 3954 this._constant = json.constant; 3955 this._payable = json.payable; 3956 this._name = utils.transformToFullName(json); 3957 this._address = address; 3958 }; 3959 3960 SolidityFunction.prototype.extractCallback = function (args) { 3961 if (utils.isFunction(args[args.length - 1])) { 3962 return args.pop(); // modify the args array! 3963 } 3964 }; 3965 3966 SolidityFunction.prototype.extractDefaultBlock = function (args) { 3967 if (args.length > this._inputTypes.length && !utils.isObject(args[args.length -1])) { 3968 return formatters.inputDefaultBlockNumberFormatter(args.pop()); // modify the args array! 3969 } 3970 }; 3971 3972 /** 3973 * Should be used to create payload from arguments 3974 * 3975 * @method toPayload 3976 * @param {Array} solidity function params 3977 * @param {Object} optional payload options 3978 */ 3979 SolidityFunction.prototype.toPayload = function (args) { 3980 var options = {}; 3981 if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) { 3982 options = args[args.length - 1]; 3983 } 3984 options.to = this._address; 3985 options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args); 3986 return options; 3987 }; 3988 3989 /** 3990 * Should be used to get function signature 3991 * 3992 * @method signature 3993 * @return {String} function signature 3994 */ 3995 SolidityFunction.prototype.signature = function () { 3996 return sha3(this._name).slice(0, 8); 3997 }; 3998 3999 4000 SolidityFunction.prototype.unpackOutput = function (output) { 4001 if (!output) { 4002 return; 4003 } 4004 4005 output = output.length >= 2 ? output.slice(2) : output; 4006 var result = coder.decodeParams(this._outputTypes, output); 4007 return result.length === 1 ? result[0] : result; 4008 }; 4009 4010 /** 4011 * Calls a contract function. 4012 * 4013 * @method call 4014 * @param {...Object} Contract function arguments 4015 * @param {function} If the last argument is a function, the contract function 4016 * call will be asynchronous, and the callback will be passed the 4017 * error and result. 4018 * @return {String} output bytes 4019 */ 4020 SolidityFunction.prototype.call = function () { 4021 var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); 4022 var callback = this.extractCallback(args); 4023 var defaultBlock = this.extractDefaultBlock(args); 4024 var payload = this.toPayload(args); 4025 4026 4027 if (!callback) { 4028 var output = this._eth.call(payload, defaultBlock); 4029 return this.unpackOutput(output); 4030 } 4031 4032 var self = this; 4033 this._eth.call(payload, defaultBlock, function (error, output) { 4034 if (error) return callback(error, null); 4035 4036 var unpacked = null; 4037 try { 4038 unpacked = self.unpackOutput(output); 4039 } 4040 catch (e) { 4041 error = e; 4042 } 4043 4044 callback(error, unpacked); 4045 }); 4046 }; 4047 4048 /** 4049 * Should be used to sendTransaction to solidity function 4050 * 4051 * @method sendTransaction 4052 */ 4053 SolidityFunction.prototype.sendTransaction = function () { 4054 var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); 4055 var callback = this.extractCallback(args); 4056 var payload = this.toPayload(args); 4057 4058 if (payload.value > 0 && !this._payable) { 4059 throw new Error('Cannot send value to non-payable function'); 4060 } 4061 4062 if (!callback) { 4063 return this._eth.sendTransaction(payload); 4064 } 4065 4066 this._eth.sendTransaction(payload, callback); 4067 }; 4068 4069 /** 4070 * Should be used to estimateGas of solidity function 4071 * 4072 * @method estimateGas 4073 */ 4074 SolidityFunction.prototype.estimateGas = function () { 4075 var args = Array.prototype.slice.call(arguments); 4076 var callback = this.extractCallback(args); 4077 var payload = this.toPayload(args); 4078 4079 if (!callback) { 4080 return this._eth.estimateGas(payload); 4081 } 4082 4083 this._eth.estimateGas(payload, callback); 4084 }; 4085 4086 /** 4087 * Return the encoded data of the call 4088 * 4089 * @method getData 4090 * @return {String} the encoded data 4091 */ 4092 SolidityFunction.prototype.getData = function () { 4093 var args = Array.prototype.slice.call(arguments); 4094 var payload = this.toPayload(args); 4095 4096 return payload.data; 4097 }; 4098 4099 /** 4100 * Should be used to get function display name 4101 * 4102 * @method displayName 4103 * @return {String} display name of the function 4104 */ 4105 SolidityFunction.prototype.displayName = function () { 4106 return utils.extractDisplayName(this._name); 4107 }; 4108 4109 /** 4110 * Should be used to get function type name 4111 * 4112 * @method typeName 4113 * @return {String} type name of the function 4114 */ 4115 SolidityFunction.prototype.typeName = function () { 4116 return utils.extractTypeName(this._name); 4117 }; 4118 4119 /** 4120 * Should be called to get rpc requests from solidity function 4121 * 4122 * @method request 4123 * @returns {Object} 4124 */ 4125 SolidityFunction.prototype.request = function () { 4126 var args = Array.prototype.slice.call(arguments); 4127 var callback = this.extractCallback(args); 4128 var payload = this.toPayload(args); 4129 var format = this.unpackOutput.bind(this); 4130 4131 return { 4132 method: this._constant ? 'eth_call' : 'eth_sendTransaction', 4133 callback: callback, 4134 params: [payload], 4135 format: format 4136 }; 4137 }; 4138 4139 /** 4140 * Should be called to execute function 4141 * 4142 * @method execute 4143 */ 4144 SolidityFunction.prototype.execute = function () { 4145 var transaction = !this._constant; 4146 4147 // send transaction 4148 if (transaction) { 4149 return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments)); 4150 } 4151 4152 // call 4153 return this.call.apply(this, Array.prototype.slice.call(arguments)); 4154 }; 4155 4156 /** 4157 * Should be called to attach function to contract 4158 * 4159 * @method attachToContract 4160 * @param {Contract} 4161 */ 4162 SolidityFunction.prototype.attachToContract = function (contract) { 4163 var execute = this.execute.bind(this); 4164 execute.request = this.request.bind(this); 4165 execute.call = this.call.bind(this); 4166 execute.sendTransaction = this.sendTransaction.bind(this); 4167 execute.estimateGas = this.estimateGas.bind(this); 4168 execute.getData = this.getData.bind(this); 4169 var displayName = this.displayName(); 4170 if (!contract[displayName]) { 4171 contract[displayName] = execute; 4172 } 4173 contract[displayName][this.typeName()] = execute; // circular!!!! 4174 }; 4175 4176 module.exports = SolidityFunction; 4177 4178 4179 },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./formatters":30}],32:[function(require,module,exports){ 4180 /* 4181 This file is part of web3.js. 4182 4183 web3.js is free software: you can redistribute it and/or modify 4184 it under the terms of the GNU Lesser General Public License as published by 4185 the Free Software Foundation, either version 3 of the License, or 4186 (at your option) any later version. 4187 4188 web3.js is distributed in the hope that it will be useful, 4189 but WITHOUT ANY WARRANTY; without even the implied warranty of 4190 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4191 GNU Lesser General Public License for more details. 4192 4193 You should have received a copy of the GNU Lesser General Public License 4194 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4195 */ 4196 /** @file httpprovider.js 4197 * @authors: 4198 * Marek Kotewicz <marek@ethdev.com> 4199 * Marian Oancea <marian@ethdev.com> 4200 * Fabian Vogelsteller <fabian@ethdev.com> 4201 * @date 2015 4202 */ 4203 4204 "use strict"; 4205 4206 var errors = require('./errors'); 4207 4208 // workaround to use httpprovider in different envs 4209 // var XMLHttpRequest; // jshint ignore: line 4210 4211 // browser 4212 if (typeof window !== 'undefined' && window.XMLHttpRequest) { 4213 XMLHttpRequest = window.XMLHttpRequest; // jshint ignore: line 4214 // node 4215 } else { 4216 XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line 4217 } 4218 4219 var XHR2 = require('xhr2'); // jshint ignore: line 4220 4221 /** 4222 * HttpProvider should be used to send rpc calls over http 4223 */ 4224 var HttpProvider = function (host, timeout) { 4225 this.host = host || 'http://localhost:8545'; 4226 this.timeout = timeout || 0; 4227 }; 4228 4229 /** 4230 * Should be called to prepare new XMLHttpRequest 4231 * 4232 * @method prepareRequest 4233 * @param {Boolean} true if request should be async 4234 * @return {XMLHttpRequest} object 4235 */ 4236 HttpProvider.prototype.prepareRequest = function (async) { 4237 var request; 4238 4239 if (async) { 4240 request = new XHR2(); 4241 request.timeout = this.timeout; 4242 }else { 4243 request = new XMLHttpRequest(); 4244 } 4245 4246 request.open('POST', this.host, async); 4247 request.setRequestHeader('Content-Type','application/json'); 4248 return request; 4249 }; 4250 4251 /** 4252 * Should be called to make sync request 4253 * 4254 * @method send 4255 * @param {Object} payload 4256 * @return {Object} result 4257 */ 4258 HttpProvider.prototype.send = function (payload) { 4259 var request = this.prepareRequest(false); 4260 4261 try { 4262 request.send(JSON.stringify(payload)); 4263 } catch(error) { 4264 throw errors.InvalidConnection(this.host); 4265 } 4266 4267 var result = request.responseText; 4268 4269 try { 4270 result = JSON.parse(result); 4271 } catch(e) { 4272 throw errors.InvalidResponse(request.responseText); 4273 } 4274 4275 return result; 4276 }; 4277 4278 /** 4279 * Should be used to make async request 4280 * 4281 * @method sendAsync 4282 * @param {Object} payload 4283 * @param {Function} callback triggered on end with (err, result) 4284 */ 4285 HttpProvider.prototype.sendAsync = function (payload, callback) { 4286 var request = this.prepareRequest(true); 4287 4288 request.onreadystatechange = function() { 4289 if (request.readyState === 4 && request.timeout !== 1) { 4290 var result = request.responseText; 4291 var error = null; 4292 4293 try { 4294 result = JSON.parse(result); 4295 } catch(e) { 4296 error = errors.InvalidResponse(request.responseText); 4297 } 4298 4299 callback(error, result); 4300 } 4301 }; 4302 4303 request.ontimeout = function() { 4304 callback(errors.ConnectionTimeout(this.timeout)); 4305 }; 4306 4307 try { 4308 request.send(JSON.stringify(payload)); 4309 } catch(error) { 4310 callback(errors.InvalidConnection(this.host)); 4311 } 4312 }; 4313 4314 /** 4315 * Synchronously tries to make Http request 4316 * 4317 * @method isConnected 4318 * @return {Boolean} returns true if request haven't failed. Otherwise false 4319 */ 4320 HttpProvider.prototype.isConnected = function() { 4321 try { 4322 this.send({ 4323 id: 9999999999, 4324 jsonrpc: '2.0', 4325 method: 'net_listening', 4326 params: [] 4327 }); 4328 return true; 4329 } catch(e) { 4330 return false; 4331 } 4332 }; 4333 4334 module.exports = HttpProvider; 4335 4336 },{"./errors":26,"xhr2":86,"xmlhttprequest":17}],33:[function(require,module,exports){ 4337 /* 4338 This file is part of web3.js. 4339 4340 web3.js is free software: you can redistribute it and/or modify 4341 it under the terms of the GNU Lesser General Public License as published by 4342 the Free Software Foundation, either version 3 of the License, or 4343 (at your option) any later version. 4344 4345 web3.js is distributed in the hope that it will be useful, 4346 but WITHOUT ANY WARRANTY; without even the implied warranty of 4347 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4348 GNU Lesser General Public License for more details. 4349 4350 You should have received a copy of the GNU Lesser General Public License 4351 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4352 */ 4353 /** 4354 * @file iban.js 4355 * @author Marek Kotewicz <marek@ethdev.com> 4356 * @date 2015 4357 */ 4358 4359 var BigNumber = require('bignumber.js'); 4360 4361 var padLeft = function (string, bytes) { 4362 var result = string; 4363 while (result.length < bytes * 2) { 4364 result = '0' + result; 4365 } 4366 return result; 4367 }; 4368 4369 /** 4370 * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to 4371 * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. 4372 * 4373 * @method iso13616Prepare 4374 * @param {String} iban the IBAN 4375 * @returns {String} the prepared IBAN 4376 */ 4377 var iso13616Prepare = function (iban) { 4378 var A = 'A'.charCodeAt(0); 4379 var Z = 'Z'.charCodeAt(0); 4380 4381 iban = iban.toUpperCase(); 4382 iban = iban.substr(4) + iban.substr(0,4); 4383 4384 return iban.split('').map(function(n){ 4385 var code = n.charCodeAt(0); 4386 if (code >= A && code <= Z){ 4387 // A = 10, B = 11, ... Z = 35 4388 return code - A + 10; 4389 } else { 4390 return n; 4391 } 4392 }).join(''); 4393 }; 4394 4395 /** 4396 * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. 4397 * 4398 * @method mod9710 4399 * @param {String} iban 4400 * @returns {Number} 4401 */ 4402 var mod9710 = function (iban) { 4403 var remainder = iban, 4404 block; 4405 4406 while (remainder.length > 2){ 4407 block = remainder.slice(0, 9); 4408 remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); 4409 } 4410 4411 return parseInt(remainder, 10) % 97; 4412 }; 4413 4414 /** 4415 * This prototype should be used to create iban object from iban correct string 4416 * 4417 * @param {String} iban 4418 */ 4419 var Iban = function (iban) { 4420 this._iban = iban; 4421 }; 4422 4423 /** 4424 * This method should be used to create iban object from ethereum address 4425 * 4426 * @method fromAddress 4427 * @param {String} address 4428 * @return {Iban} the IBAN object 4429 */ 4430 Iban.fromAddress = function (address) { 4431 var asBn = new BigNumber(address, 16); 4432 var base36 = asBn.toString(36); 4433 var padded = padLeft(base36, 15); 4434 return Iban.fromBban(padded.toUpperCase()); 4435 }; 4436 4437 /** 4438 * Convert the passed BBAN to an IBAN for this country specification. 4439 * Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. 4440 * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits 4441 * 4442 * @method fromBban 4443 * @param {String} bban the BBAN to convert to IBAN 4444 * @returns {Iban} the IBAN object 4445 */ 4446 Iban.fromBban = function (bban) { 4447 var countryCode = 'XE'; 4448 4449 var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); 4450 var checkDigit = ('0' + (98 - remainder)).slice(-2); 4451 4452 return new Iban(countryCode + checkDigit + bban); 4453 }; 4454 4455 /** 4456 * Should be used to create IBAN object for given institution and identifier 4457 * 4458 * @method createIndirect 4459 * @param {Object} options, required options are "institution" and "identifier" 4460 * @return {Iban} the IBAN object 4461 */ 4462 Iban.createIndirect = function (options) { 4463 return Iban.fromBban('ETH' + options.institution + options.identifier); 4464 }; 4465 4466 /** 4467 * Thos method should be used to check if given string is valid iban object 4468 * 4469 * @method isValid 4470 * @param {String} iban string 4471 * @return {Boolean} true if it is valid IBAN 4472 */ 4473 Iban.isValid = function (iban) { 4474 var i = new Iban(iban); 4475 return i.isValid(); 4476 }; 4477 4478 /** 4479 * Should be called to check if iban is correct 4480 * 4481 * @method isValid 4482 * @returns {Boolean} true if it is, otherwise false 4483 */ 4484 Iban.prototype.isValid = function () { 4485 return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && 4486 mod9710(iso13616Prepare(this._iban)) === 1; 4487 }; 4488 4489 /** 4490 * Should be called to check if iban number is direct 4491 * 4492 * @method isDirect 4493 * @returns {Boolean} true if it is, otherwise false 4494 */ 4495 Iban.prototype.isDirect = function () { 4496 return this._iban.length === 34 || this._iban.length === 35; 4497 }; 4498 4499 /** 4500 * Should be called to check if iban number if indirect 4501 * 4502 * @method isIndirect 4503 * @returns {Boolean} true if it is, otherwise false 4504 */ 4505 Iban.prototype.isIndirect = function () { 4506 return this._iban.length === 20; 4507 }; 4508 4509 /** 4510 * Should be called to get iban checksum 4511 * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) 4512 * 4513 * @method checksum 4514 * @returns {String} checksum 4515 */ 4516 Iban.prototype.checksum = function () { 4517 return this._iban.substr(2, 2); 4518 }; 4519 4520 /** 4521 * Should be called to get institution identifier 4522 * eg. XREG 4523 * 4524 * @method institution 4525 * @returns {String} institution identifier 4526 */ 4527 Iban.prototype.institution = function () { 4528 return this.isIndirect() ? this._iban.substr(7, 4) : ''; 4529 }; 4530 4531 /** 4532 * Should be called to get client identifier within institution 4533 * eg. GAVOFYORK 4534 * 4535 * @method client 4536 * @returns {String} client identifier 4537 */ 4538 Iban.prototype.client = function () { 4539 return this.isIndirect() ? this._iban.substr(11) : ''; 4540 }; 4541 4542 /** 4543 * Should be called to get client direct address 4544 * 4545 * @method address 4546 * @returns {String} client direct address 4547 */ 4548 Iban.prototype.address = function () { 4549 if (this.isDirect()) { 4550 var base36 = this._iban.substr(4); 4551 var asBn = new BigNumber(base36, 36); 4552 return padLeft(asBn.toString(16), 20); 4553 } 4554 4555 return ''; 4556 }; 4557 4558 Iban.prototype.toString = function () { 4559 return this._iban; 4560 }; 4561 4562 module.exports = Iban; 4563 4564 4565 },{"bignumber.js":"bignumber.js"}],34:[function(require,module,exports){ 4566 /* 4567 This file is part of web3.js. 4568 4569 web3.js is free software: you can redistribute it and/or modify 4570 it under the terms of the GNU Lesser General Public License as published by 4571 the Free Software Foundation, either version 3 of the License, or 4572 (at your option) any later version. 4573 4574 web3.js is distributed in the hope that it will be useful, 4575 but WITHOUT ANY WARRANTY; without even the implied warranty of 4576 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4577 GNU Lesser General Public License for more details. 4578 4579 You should have received a copy of the GNU Lesser General Public License 4580 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4581 */ 4582 /** @file ipcprovider.js 4583 * @authors: 4584 * Fabian Vogelsteller <fabian@ethdev.com> 4585 * @date 2015 4586 */ 4587 4588 "use strict"; 4589 4590 var utils = require('../utils/utils'); 4591 var errors = require('./errors'); 4592 4593 4594 var IpcProvider = function (path, net) { 4595 var _this = this; 4596 this.responseCallbacks = {}; 4597 this.path = path; 4598 4599 this.connection = net.connect({path: this.path}); 4600 4601 this.connection.on('error', function(e){ 4602 console.error('IPC Connection Error', e); 4603 _this._timeout(); 4604 }); 4605 4606 this.connection.on('end', function(){ 4607 _this._timeout(); 4608 }); 4609 4610 4611 // LISTEN FOR CONNECTION RESPONSES 4612 this.connection.on('data', function(data) { 4613 /*jshint maxcomplexity: 6 */ 4614 4615 _this._parseResponse(data.toString()).forEach(function(result){ 4616 4617 var id = null; 4618 4619 // get the id which matches the returned id 4620 if(utils.isArray(result)) { 4621 result.forEach(function(load){ 4622 if(_this.responseCallbacks[load.id]) 4623 id = load.id; 4624 }); 4625 } else { 4626 id = result.id; 4627 } 4628 4629 // fire the callback 4630 if(_this.responseCallbacks[id]) { 4631 _this.responseCallbacks[id](null, result); 4632 delete _this.responseCallbacks[id]; 4633 } 4634 }); 4635 }); 4636 }; 4637 4638 /** 4639 Will parse the response and make an array out of it. 4640 4641 @method _parseResponse 4642 @param {String} data 4643 */ 4644 IpcProvider.prototype._parseResponse = function(data) { 4645 var _this = this, 4646 returnValues = []; 4647 4648 // DE-CHUNKER 4649 var dechunkedData = data 4650 .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ 4651 .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ 4652 .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ 4653 .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ 4654 .split('|--|'); 4655 4656 dechunkedData.forEach(function(data){ 4657 4658 // prepend the last chunk 4659 if(_this.lastChunk) 4660 data = _this.lastChunk + data; 4661 4662 var result = null; 4663 4664 try { 4665 result = JSON.parse(data); 4666 4667 } catch(e) { 4668 4669 _this.lastChunk = data; 4670 4671 // start timeout to cancel all requests 4672 clearTimeout(_this.lastChunkTimeout); 4673 _this.lastChunkTimeout = setTimeout(function(){ 4674 _this._timeout(); 4675 throw errors.InvalidResponse(data); 4676 }, 1000 * 15); 4677 4678 return; 4679 } 4680 4681 // cancel timeout and set chunk to null 4682 clearTimeout(_this.lastChunkTimeout); 4683 _this.lastChunk = null; 4684 4685 if(result) 4686 returnValues.push(result); 4687 }); 4688 4689 return returnValues; 4690 }; 4691 4692 4693 /** 4694 Get the adds a callback to the responseCallbacks object, 4695 which will be called if a response matching the response Id will arrive. 4696 4697 @method _addResponseCallback 4698 */ 4699 IpcProvider.prototype._addResponseCallback = function(payload, callback) { 4700 var id = payload.id || payload[0].id; 4701 var method = payload.method || payload[0].method; 4702 4703 this.responseCallbacks[id] = callback; 4704 this.responseCallbacks[id].method = method; 4705 }; 4706 4707 /** 4708 Timeout all requests when the end/error event is fired 4709 4710 @method _timeout 4711 */ 4712 IpcProvider.prototype._timeout = function() { 4713 for(var key in this.responseCallbacks) { 4714 if(this.responseCallbacks.hasOwnProperty(key)){ 4715 this.responseCallbacks[key](errors.InvalidConnection('on IPC')); 4716 delete this.responseCallbacks[key]; 4717 } 4718 } 4719 }; 4720 4721 4722 /** 4723 Check if the current connection is still valid. 4724 4725 @method isConnected 4726 */ 4727 IpcProvider.prototype.isConnected = function() { 4728 var _this = this; 4729 4730 // try reconnect, when connection is gone 4731 if(!_this.connection.writable) 4732 _this.connection.connect({path: _this.path}); 4733 4734 return !!this.connection.writable; 4735 }; 4736 4737 IpcProvider.prototype.send = function (payload) { 4738 4739 if(this.connection.writeSync) { 4740 var result; 4741 4742 // try reconnect, when connection is gone 4743 if(!this.connection.writable) 4744 this.connection.connect({path: this.path}); 4745 4746 var data = this.connection.writeSync(JSON.stringify(payload)); 4747 4748 try { 4749 result = JSON.parse(data); 4750 } catch(e) { 4751 throw errors.InvalidResponse(data); 4752 } 4753 4754 return result; 4755 4756 } else { 4757 throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported by the IPC provider.'); 4758 } 4759 }; 4760 4761 IpcProvider.prototype.sendAsync = function (payload, callback) { 4762 // try reconnect, when connection is gone 4763 if(!this.connection.writable) 4764 this.connection.connect({path: this.path}); 4765 4766 4767 this.connection.write(JSON.stringify(payload)); 4768 this._addResponseCallback(payload, callback); 4769 }; 4770 4771 module.exports = IpcProvider; 4772 4773 4774 },{"../utils/utils":20,"./errors":26}],35:[function(require,module,exports){ 4775 /* 4776 This file is part of web3.js. 4777 4778 web3.js is free software: you can redistribute it and/or modify 4779 it under the terms of the GNU Lesser General Public License as published by 4780 the Free Software Foundation, either version 3 of the License, or 4781 (at your option) any later version. 4782 4783 web3.js is distributed in the hope that it will be useful, 4784 but WITHOUT ANY WARRANTY; without even the implied warranty of 4785 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4786 GNU Lesser General Public License for more details. 4787 4788 You should have received a copy of the GNU Lesser General Public License 4789 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4790 */ 4791 /** @file jsonrpc.js 4792 * @authors: 4793 * Marek Kotewicz <marek@ethdev.com> 4794 * Aaron Kumavis <aaron@kumavis.me> 4795 * @date 2015 4796 */ 4797 4798 // Initialize Jsonrpc as a simple object with utility functions. 4799 var Jsonrpc = { 4800 messageId: 0 4801 }; 4802 4803 /** 4804 * Should be called to valid json create payload object 4805 * 4806 * @method toPayload 4807 * @param {Function} method of jsonrpc call, required 4808 * @param {Array} params, an array of method params, optional 4809 * @returns {Object} valid jsonrpc payload object 4810 */ 4811 Jsonrpc.toPayload = function (method, params) { 4812 if (!method) 4813 console.error('jsonrpc method should be specified!'); 4814 4815 // advance message ID 4816 Jsonrpc.messageId++; 4817 4818 return { 4819 jsonrpc: '2.0', 4820 id: Jsonrpc.messageId, 4821 method: method, 4822 params: params || [] 4823 }; 4824 }; 4825 4826 /** 4827 * Should be called to check if jsonrpc response is valid 4828 * 4829 * @method isValidResponse 4830 * @param {Object} 4831 * @returns {Boolean} true if response is valid, otherwise false 4832 */ 4833 Jsonrpc.isValidResponse = function (response) { 4834 return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); 4835 4836 function validateSingleMessage(message){ 4837 return !!message && 4838 !message.error && 4839 message.jsonrpc === '2.0' && 4840 typeof message.id === 'number' && 4841 message.result !== undefined; // only undefined is not valid json object 4842 } 4843 }; 4844 4845 /** 4846 * Should be called to create batch payload object 4847 * 4848 * @method toBatchPayload 4849 * @param {Array} messages, an array of objects with method (required) and params (optional) fields 4850 * @returns {Array} batch payload 4851 */ 4852 Jsonrpc.toBatchPayload = function (messages) { 4853 return messages.map(function (message) { 4854 return Jsonrpc.toPayload(message.method, message.params); 4855 }); 4856 }; 4857 4858 module.exports = Jsonrpc; 4859 4860 4861 },{}],36:[function(require,module,exports){ 4862 /* 4863 This file is part of web3.js. 4864 4865 web3.js is free software: you can redistribute it and/or modify 4866 it under the terms of the GNU Lesser General Public License as published by 4867 the Free Software Foundation, either version 3 of the License, or 4868 (at your option) any later version. 4869 4870 web3.js is distributed in the hope that it will be useful, 4871 but WITHOUT ANY WARRANTY; without even the implied warranty of 4872 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 4873 GNU Lesser General Public License for more details. 4874 4875 You should have received a copy of the GNU Lesser General Public License 4876 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 4877 */ 4878 /** 4879 * @file method.js 4880 * @author Marek Kotewicz <marek@ethdev.com> 4881 * @date 2015 4882 */ 4883 4884 var utils = require('../utils/utils'); 4885 var errors = require('./errors'); 4886 4887 var Method = function (options) { 4888 this.name = options.name; 4889 this.call = options.call; 4890 this.params = options.params || 0; 4891 this.inputFormatter = options.inputFormatter; 4892 this.outputFormatter = options.outputFormatter; 4893 this.requestManager = null; 4894 }; 4895 4896 Method.prototype.setRequestManager = function (rm) { 4897 this.requestManager = rm; 4898 }; 4899 4900 /** 4901 * Should be used to determine name of the jsonrpc method based on arguments 4902 * 4903 * @method getCall 4904 * @param {Array} arguments 4905 * @return {String} name of jsonrpc method 4906 */ 4907 Method.prototype.getCall = function (args) { 4908 return utils.isFunction(this.call) ? this.call(args) : this.call; 4909 }; 4910 4911 /** 4912 * Should be used to extract callback from array of arguments. Modifies input param 4913 * 4914 * @method extractCallback 4915 * @param {Array} arguments 4916 * @return {Function|Null} callback, if exists 4917 */ 4918 Method.prototype.extractCallback = function (args) { 4919 if (utils.isFunction(args[args.length - 1])) { 4920 return args.pop(); // modify the args array! 4921 } 4922 }; 4923 4924 /** 4925 * Should be called to check if the number of arguments is correct 4926 * 4927 * @method validateArgs 4928 * @param {Array} arguments 4929 * @throws {Error} if it is not 4930 */ 4931 Method.prototype.validateArgs = function (args) { 4932 if (args.length !== this.params) { 4933 throw errors.InvalidNumberOfParams(); 4934 } 4935 }; 4936 4937 /** 4938 * Should be called to format input args of method 4939 * 4940 * @method formatInput 4941 * @param {Array} 4942 * @return {Array} 4943 */ 4944 Method.prototype.formatInput = function (args) { 4945 if (!this.inputFormatter) { 4946 return args; 4947 } 4948 4949 return this.inputFormatter.map(function (formatter, index) { 4950 return formatter ? formatter(args[index]) : args[index]; 4951 }); 4952 }; 4953 4954 /** 4955 * Should be called to format output(result) of method 4956 * 4957 * @method formatOutput 4958 * @param {Object} 4959 * @return {Object} 4960 */ 4961 Method.prototype.formatOutput = function (result) { 4962 return this.outputFormatter && result ? this.outputFormatter(result) : result; 4963 }; 4964 4965 /** 4966 * Should create payload from given input args 4967 * 4968 * @method toPayload 4969 * @param {Array} args 4970 * @return {Object} 4971 */ 4972 Method.prototype.toPayload = function (args) { 4973 var call = this.getCall(args); 4974 var callback = this.extractCallback(args); 4975 var params = this.formatInput(args); 4976 this.validateArgs(params); 4977 4978 return { 4979 method: call, 4980 params: params, 4981 callback: callback 4982 }; 4983 }; 4984 4985 Method.prototype.attachToObject = function (obj) { 4986 var func = this.buildCall(); 4987 func.call = this.call; // TODO!!! that's ugly. filter.js uses it 4988 var name = this.name.split('.'); 4989 if (name.length > 1) { 4990 obj[name[0]] = obj[name[0]] || {}; 4991 obj[name[0]][name[1]] = func; 4992 } else { 4993 obj[name[0]] = func; 4994 } 4995 }; 4996 4997 Method.prototype.buildCall = function() { 4998 var method = this; 4999 var send = function () { 5000 var payload = method.toPayload(Array.prototype.slice.call(arguments)); 5001 if (payload.callback) { 5002 return method.requestManager.sendAsync(payload, function (err, result) { 5003 payload.callback(err, method.formatOutput(result)); 5004 }); 5005 } 5006 return method.formatOutput(method.requestManager.send(payload)); 5007 }; 5008 send.request = this.request.bind(this); 5009 return send; 5010 }; 5011 5012 /** 5013 * Should be called to create pure JSONRPC request which can be used in batch request 5014 * 5015 * @method request 5016 * @param {...} params 5017 * @return {Object} jsonrpc request 5018 */ 5019 Method.prototype.request = function () { 5020 var payload = this.toPayload(Array.prototype.slice.call(arguments)); 5021 payload.format = this.formatOutput.bind(this); 5022 return payload; 5023 }; 5024 5025 module.exports = Method; 5026 5027 5028 },{"../utils/utils":20,"./errors":26}],37:[function(require,module,exports){ 5029 /* 5030 This file is part of web3.js. 5031 5032 web3.js is free software: you can redistribute it and/or modify 5033 it under the terms of the GNU Lesser General Public License as published by 5034 the Free Software Foundation, either version 3 of the License, or 5035 (at your option) any later version. 5036 5037 web3.js is distributed in the hope that it will be useful, 5038 but WITHOUT ANY WARRANTY; without even the implied warranty of 5039 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5040 GNU Lesser General Public License for more details. 5041 5042 You should have received a copy of the GNU Lesser General Public License 5043 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5044 */ 5045 /** @file db.js 5046 * @authors: 5047 * Marek Kotewicz <marek@ethdev.com> 5048 * @date 2015 5049 */ 5050 5051 var Method = require('../method'); 5052 5053 var DB = function (web3) { 5054 this._requestManager = web3._requestManager; 5055 5056 var self = this; 5057 5058 methods().forEach(function(method) { 5059 method.attachToObject(self); 5060 method.setRequestManager(web3._requestManager); 5061 }); 5062 }; 5063 5064 var methods = function () { 5065 var putString = new Method({ 5066 name: 'putString', 5067 call: 'db_putString', 5068 params: 3 5069 }); 5070 5071 var getString = new Method({ 5072 name: 'getString', 5073 call: 'db_getString', 5074 params: 2 5075 }); 5076 5077 var putHex = new Method({ 5078 name: 'putHex', 5079 call: 'db_putHex', 5080 params: 3 5081 }); 5082 5083 var getHex = new Method({ 5084 name: 'getHex', 5085 call: 'db_getHex', 5086 params: 2 5087 }); 5088 5089 return [ 5090 putString, getString, putHex, getHex 5091 ]; 5092 }; 5093 5094 module.exports = DB; 5095 5096 },{"../method":36}],38:[function(require,module,exports){ 5097 /* 5098 This file is part of web3.js. 5099 5100 web3.js is free software: you can redistribute it and/or modify 5101 it under the terms of the GNU Lesser General Public License as published by 5102 the Free Software Foundation, either version 3 of the License, or 5103 (at your option) any later version. 5104 5105 web3.js is distributed in the hope that it will be useful, 5106 but WITHOUT ANY WARRANTY; without even the implied warranty of 5107 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5108 GNU Lesser General Public License for more details. 5109 5110 You should have received a copy of the GNU Lesser General Public License 5111 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5112 */ 5113 /** 5114 * @file eth.js 5115 * @author Marek Kotewicz <marek@ethdev.com> 5116 * @author Fabian Vogelsteller <fabian@ethdev.com> 5117 * @date 2015 5118 */ 5119 5120 "use strict"; 5121 5122 var formatters = require('../formatters'); 5123 var utils = require('../../utils/utils'); 5124 var Method = require('../method'); 5125 var Property = require('../property'); 5126 var c = require('../../utils/config'); 5127 var Contract = require('../contract'); 5128 var watches = require('./watches'); 5129 var Filter = require('../filter'); 5130 var IsSyncing = require('../syncing'); 5131 var namereg = require('../namereg'); 5132 var Iban = require('../iban'); 5133 var transfer = require('../transfer'); 5134 5135 var blockCall = function (args) { 5136 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber"; 5137 }; 5138 5139 var transactionFromBlockCall = function (args) { 5140 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex'; 5141 }; 5142 5143 var uncleCall = function (args) { 5144 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex'; 5145 }; 5146 5147 var getBlockTransactionCountCall = function (args) { 5148 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber'; 5149 }; 5150 5151 var uncleCountCall = function (args) { 5152 return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber'; 5153 }; 5154 5155 function Eth(web3) { 5156 this._requestManager = web3._requestManager; 5157 5158 var self = this; 5159 5160 methods().forEach(function(method) { 5161 method.attachToObject(self); 5162 method.setRequestManager(self._requestManager); 5163 }); 5164 5165 properties().forEach(function(p) { 5166 p.attachToObject(self); 5167 p.setRequestManager(self._requestManager); 5168 }); 5169 5170 5171 this.iban = Iban; 5172 this.sendIBANTransaction = transfer.bind(null, this); 5173 } 5174 5175 Object.defineProperty(Eth.prototype, 'defaultBlock', { 5176 get: function () { 5177 return c.defaultBlock; 5178 }, 5179 set: function (val) { 5180 c.defaultBlock = val; 5181 return val; 5182 } 5183 }); 5184 5185 Object.defineProperty(Eth.prototype, 'defaultAccount', { 5186 get: function () { 5187 return c.defaultAccount; 5188 }, 5189 set: function (val) { 5190 c.defaultAccount = val; 5191 return val; 5192 } 5193 }); 5194 5195 var methods = function () { 5196 var getBalance = new Method({ 5197 name: 'getBalance', 5198 call: 'eth_getBalance', 5199 params: 2, 5200 inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter], 5201 outputFormatter: formatters.outputBigNumberFormatter 5202 }); 5203 5204 var getStorageAt = new Method({ 5205 name: 'getStorageAt', 5206 call: 'eth_getStorageAt', 5207 params: 3, 5208 inputFormatter: [null, utils.toHex, formatters.inputDefaultBlockNumberFormatter] 5209 }); 5210 5211 var getCode = new Method({ 5212 name: 'getCode', 5213 call: 'eth_getCode', 5214 params: 2, 5215 inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter] 5216 }); 5217 5218 var getBlock = new Method({ 5219 name: 'getBlock', 5220 call: blockCall, 5221 params: 2, 5222 inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }], 5223 outputFormatter: formatters.outputBlockFormatter 5224 }); 5225 5226 var getUncle = new Method({ 5227 name: 'getUncle', 5228 call: uncleCall, 5229 params: 2, 5230 inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex], 5231 outputFormatter: formatters.outputBlockFormatter, 5232 5233 }); 5234 5235 var getCompilers = new Method({ 5236 name: 'getCompilers', 5237 call: 'eth_getCompilers', 5238 params: 0 5239 }); 5240 5241 var getBlockTransactionCount = new Method({ 5242 name: 'getBlockTransactionCount', 5243 call: getBlockTransactionCountCall, 5244 params: 1, 5245 inputFormatter: [formatters.inputBlockNumberFormatter], 5246 outputFormatter: utils.toDecimal 5247 }); 5248 5249 var getBlockUncleCount = new Method({ 5250 name: 'getBlockUncleCount', 5251 call: uncleCountCall, 5252 params: 1, 5253 inputFormatter: [formatters.inputBlockNumberFormatter], 5254 outputFormatter: utils.toDecimal 5255 }); 5256 5257 var getTransaction = new Method({ 5258 name: 'getTransaction', 5259 call: 'eth_getTransactionByHash', 5260 params: 1, 5261 outputFormatter: formatters.outputTransactionFormatter 5262 }); 5263 5264 var getTransactionFromBlock = new Method({ 5265 name: 'getTransactionFromBlock', 5266 call: transactionFromBlockCall, 5267 params: 2, 5268 inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex], 5269 outputFormatter: formatters.outputTransactionFormatter 5270 }); 5271 5272 var getTransactionReceipt = new Method({ 5273 name: 'getTransactionReceipt', 5274 call: 'eth_getTransactionReceipt', 5275 params: 1, 5276 outputFormatter: formatters.outputTransactionReceiptFormatter 5277 }); 5278 5279 var getTransactionCount = new Method({ 5280 name: 'getTransactionCount', 5281 call: 'eth_getTransactionCount', 5282 params: 2, 5283 inputFormatter: [null, formatters.inputDefaultBlockNumberFormatter], 5284 outputFormatter: utils.toDecimal 5285 }); 5286 5287 var sendRawTransaction = new Method({ 5288 name: 'sendRawTransaction', 5289 call: 'eth_sendRawTransaction', 5290 params: 1, 5291 inputFormatter: [null] 5292 }); 5293 5294 var sendTransaction = new Method({ 5295 name: 'sendTransaction', 5296 call: 'eth_sendTransaction', 5297 params: 1, 5298 inputFormatter: [formatters.inputTransactionFormatter] 5299 }); 5300 5301 var signTransaction = new Method({ 5302 name: 'signTransaction', 5303 call: 'eth_signTransaction', 5304 params: 1, 5305 inputFormatter: [formatters.inputTransactionFormatter] 5306 }); 5307 5308 var sign = new Method({ 5309 name: 'sign', 5310 call: 'eth_sign', 5311 params: 2, 5312 inputFormatter: [formatters.inputAddressFormatter, null] 5313 }); 5314 5315 var call = new Method({ 5316 name: 'call', 5317 call: 'eth_call', 5318 params: 2, 5319 inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter] 5320 }); 5321 5322 var estimateGas = new Method({ 5323 name: 'estimateGas', 5324 call: 'eth_estimateGas', 5325 params: 1, 5326 inputFormatter: [formatters.inputCallFormatter], 5327 outputFormatter: utils.toDecimal 5328 }); 5329 5330 var compileSolidity = new Method({ 5331 name: 'compile.solidity', 5332 call: 'eth_compileSolidity', 5333 params: 1 5334 }); 5335 5336 var compileLLL = new Method({ 5337 name: 'compile.lll', 5338 call: 'eth_compileLLL', 5339 params: 1 5340 }); 5341 5342 var compileSerpent = new Method({ 5343 name: 'compile.serpent', 5344 call: 'eth_compileSerpent', 5345 params: 1 5346 }); 5347 5348 var submitWork = new Method({ 5349 name: 'submitWork', 5350 call: 'eth_submitWork', 5351 params: 3 5352 }); 5353 5354 var getWork = new Method({ 5355 name: 'getWork', 5356 call: 'eth_getWork', 5357 params: 0 5358 }); 5359 5360 return [ 5361 getBalance, 5362 getStorageAt, 5363 getCode, 5364 getBlock, 5365 getUncle, 5366 getCompilers, 5367 getBlockTransactionCount, 5368 getBlockUncleCount, 5369 getTransaction, 5370 getTransactionFromBlock, 5371 getTransactionReceipt, 5372 getTransactionCount, 5373 call, 5374 estimateGas, 5375 sendRawTransaction, 5376 sendTransaction, 5377 signTransaction, 5378 sign, 5379 compileSolidity, 5380 compileLLL, 5381 compileSerpent, 5382 submitWork, 5383 getWork 5384 ]; 5385 }; 5386 5387 5388 var properties = function () { 5389 return [ 5390 new Property({ 5391 name: 'coinbase', 5392 getter: 'eth_coinbase' 5393 }), 5394 new Property({ 5395 name: 'mining', 5396 getter: 'eth_mining' 5397 }), 5398 new Property({ 5399 name: 'hashrate', 5400 getter: 'eth_hashrate', 5401 outputFormatter: utils.toDecimal 5402 }), 5403 new Property({ 5404 name: 'syncing', 5405 getter: 'eth_syncing', 5406 outputFormatter: formatters.outputSyncingFormatter 5407 }), 5408 new Property({ 5409 name: 'gasPrice', 5410 getter: 'eth_gasPrice', 5411 outputFormatter: formatters.outputBigNumberFormatter 5412 }), 5413 new Property({ 5414 name: 'accounts', 5415 getter: 'eth_accounts' 5416 }), 5417 new Property({ 5418 name: 'blockNumber', 5419 getter: 'eth_blockNumber', 5420 outputFormatter: utils.toDecimal 5421 }), 5422 new Property({ 5423 name: 'protocolVersion', 5424 getter: 'eth_protocolVersion' 5425 }) 5426 ]; 5427 }; 5428 5429 Eth.prototype.contract = function (abi) { 5430 var factory = new Contract(this, abi); 5431 return factory; 5432 }; 5433 5434 Eth.prototype.filter = function (fil, callback) { 5435 return new Filter(this._requestManager, fil, watches.eth(), formatters.outputLogFormatter, callback); 5436 }; 5437 5438 Eth.prototype.namereg = function () { 5439 return this.contract(namereg.global.abi).at(namereg.global.address); 5440 }; 5441 5442 Eth.prototype.icapNamereg = function () { 5443 return this.contract(namereg.icap.abi).at(namereg.icap.address); 5444 }; 5445 5446 Eth.prototype.isSyncing = function (callback) { 5447 return new IsSyncing(this._requestManager, callback); 5448 }; 5449 5450 module.exports = Eth; 5451 5452 5453 },{"../../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){ 5454 /* 5455 This file is part of web3.js. 5456 5457 web3.js is free software: you can redistribute it and/or modify 5458 it under the terms of the GNU Lesser General Public License as published by 5459 the Free Software Foundation, either version 3 of the License, or 5460 (at your option) any later version. 5461 5462 web3.js is distributed in the hope that it will be useful, 5463 but WITHOUT ANY WARRANTY; without even the implied warranty of 5464 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5465 GNU Lesser General Public License for more details. 5466 5467 You should have received a copy of the GNU Lesser General Public License 5468 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5469 */ 5470 /** @file eth.js 5471 * @authors: 5472 * Marek Kotewicz <marek@ethdev.com> 5473 * @date 2015 5474 */ 5475 5476 var utils = require('../../utils/utils'); 5477 var Property = require('../property'); 5478 5479 var Net = function (web3) { 5480 this._requestManager = web3._requestManager; 5481 5482 var self = this; 5483 5484 properties().forEach(function(p) { 5485 p.attachToObject(self); 5486 p.setRequestManager(web3._requestManager); 5487 }); 5488 }; 5489 5490 /// @returns an array of objects describing web3.eth api properties 5491 var properties = function () { 5492 return [ 5493 new Property({ 5494 name: 'listening', 5495 getter: 'net_listening' 5496 }), 5497 new Property({ 5498 name: 'peerCount', 5499 getter: 'net_peerCount', 5500 outputFormatter: utils.toDecimal 5501 }) 5502 ]; 5503 }; 5504 5505 module.exports = Net; 5506 5507 },{"../../utils/utils":20,"../property":45}],40:[function(require,module,exports){ 5508 /* 5509 This file is part of web3.js. 5510 5511 web3.js is free software: you can redistribute it and/or modify 5512 it under the terms of the GNU Lesser General Public License as published by 5513 the Free Software Foundation, either version 3 of the License, or 5514 (at your option) any later version. 5515 5516 web3.js is distributed in the hope that it will be useful, 5517 but WITHOUT ANY WARRANTY; without even the implied warranty of 5518 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5519 GNU Lesser General Public License for more details. 5520 5521 You should have received a copy of the GNU Lesser General Public License 5522 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5523 */ 5524 /** 5525 * @file eth.js 5526 * @author Marek Kotewicz <marek@ethdev.com> 5527 * @author Fabian Vogelsteller <fabian@ethdev.com> 5528 * @date 2015 5529 */ 5530 5531 "use strict"; 5532 5533 var Method = require('../method'); 5534 var Property = require('../property'); 5535 var formatters = require('../formatters'); 5536 5537 function Personal(web3) { 5538 this._requestManager = web3._requestManager; 5539 5540 var self = this; 5541 5542 methods().forEach(function(method) { 5543 method.attachToObject(self); 5544 method.setRequestManager(self._requestManager); 5545 }); 5546 5547 properties().forEach(function(p) { 5548 p.attachToObject(self); 5549 p.setRequestManager(self._requestManager); 5550 }); 5551 } 5552 5553 var methods = function () { 5554 var newAccount = new Method({ 5555 name: 'newAccount', 5556 call: 'personal_newAccount', 5557 params: 1, 5558 inputFormatter: [null] 5559 }); 5560 5561 var unlockAccount = new Method({ 5562 name: 'unlockAccount', 5563 call: 'personal_unlockAccount', 5564 params: 3, 5565 inputFormatter: [formatters.inputAddressFormatter, null, null] 5566 }); 5567 5568 var sendTransaction = new Method({ 5569 name: 'sendTransaction', 5570 call: 'personal_sendTransaction', 5571 params: 2, 5572 inputFormatter: [formatters.inputTransactionFormatter, null] 5573 }); 5574 5575 var sign = new Method({ 5576 name: 'sign', 5577 call: 'personal_sign', 5578 params: 3, 5579 inputFormatter: [null, formatters.inputAddressFormatter, null] 5580 }); 5581 5582 var lockAccount = new Method({ 5583 name: 'lockAccount', 5584 call: 'personal_lockAccount', 5585 params: 1, 5586 inputFormatter: [formatters.inputAddressFormatter] 5587 }); 5588 5589 return [ 5590 newAccount, 5591 unlockAccount, 5592 sign, 5593 sendTransaction, 5594 lockAccount 5595 ]; 5596 }; 5597 5598 var properties = function () { 5599 return [ 5600 new Property({ 5601 name: 'listAccounts', 5602 getter: 'personal_listAccounts' 5603 }) 5604 ]; 5605 }; 5606 5607 5608 module.exports = Personal; 5609 5610 },{"../formatters":30,"../method":36,"../property":45}],41:[function(require,module,exports){ 5611 /* 5612 This file is part of web3.js. 5613 5614 web3.js is free software: you can redistribute it and/or modify 5615 it under the terms of the GNU Lesser General Public License as published by 5616 the Free Software Foundation, either version 3 of the License, or 5617 (at your option) any later version. 5618 5619 web3.js is distributed in the hope that it will be useful, 5620 but WITHOUT ANY WARRANTY; without even the implied warranty of 5621 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5622 GNU Lesser General Public License for more details. 5623 5624 You should have received a copy of the GNU Lesser General Public License 5625 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5626 */ 5627 /** @file shh.js 5628 * @authors: 5629 * Marek Kotewicz <marek@ethdev.com> 5630 * @date 2015 5631 */ 5632 5633 var Method = require('../method'); 5634 var formatters = require('../formatters'); 5635 var Filter = require('../filter'); 5636 var watches = require('./watches'); 5637 5638 var Shh = function (web3) { 5639 this._requestManager = web3._requestManager; 5640 5641 var self = this; 5642 5643 methods().forEach(function(method) { 5644 method.attachToObject(self); 5645 method.setRequestManager(self._requestManager); 5646 }); 5647 }; 5648 5649 Shh.prototype.filter = function (fil, callback) { 5650 return new Filter(this._requestManager, fil, watches.shh(), formatters.outputPostFormatter, callback); 5651 }; 5652 5653 var methods = function () { 5654 5655 var post = new Method({ 5656 name: 'post', 5657 call: 'shh_post', 5658 params: 1, 5659 inputFormatter: [formatters.inputPostFormatter] 5660 }); 5661 5662 var newIdentity = new Method({ 5663 name: 'newIdentity', 5664 call: 'shh_newIdentity', 5665 params: 0 5666 }); 5667 5668 var hasIdentity = new Method({ 5669 name: 'hasIdentity', 5670 call: 'shh_hasIdentity', 5671 params: 1 5672 }); 5673 5674 var newGroup = new Method({ 5675 name: 'newGroup', 5676 call: 'shh_newGroup', 5677 params: 0 5678 }); 5679 5680 var addToGroup = new Method({ 5681 name: 'addToGroup', 5682 call: 'shh_addToGroup', 5683 params: 0 5684 }); 5685 5686 return [ 5687 post, 5688 newIdentity, 5689 hasIdentity, 5690 newGroup, 5691 addToGroup 5692 ]; 5693 }; 5694 5695 module.exports = Shh; 5696 5697 5698 },{"../filter":29,"../formatters":30,"../method":36,"./watches":43}],42:[function(require,module,exports){ 5699 /* 5700 This file is part of web3.js. 5701 5702 web3.js is free software: you can redistribute it and/or modify 5703 it under the terms of the GNU Lesser General Public License as published by 5704 the Free Software Foundation, either version 3 of the License, or 5705 (at your option) any later version. 5706 5707 web3.js is distributed in the hope that it will be useful, 5708 but WITHOUT ANY WARRANTY; without even the implied warranty of 5709 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5710 GNU Lesser General Public License for more details. 5711 5712 You should have received a copy of the GNU Lesser General Public License 5713 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5714 */ 5715 /** 5716 * @file bzz.js 5717 * @author Alex Beregszaszi <alex@rtfs.hu> 5718 * @date 2016 5719 * 5720 * Reference: https://github.com/ethereum/go-ethereum/blob/swarm/internal/web3ext/web3ext.go#L33 5721 */ 5722 5723 "use strict"; 5724 5725 var Method = require('../method'); 5726 var Property = require('../property'); 5727 5728 function Swarm(web3) { 5729 this._requestManager = web3._requestManager; 5730 5731 var self = this; 5732 5733 methods().forEach(function(method) { 5734 method.attachToObject(self); 5735 method.setRequestManager(self._requestManager); 5736 }); 5737 5738 properties().forEach(function(p) { 5739 p.attachToObject(self); 5740 p.setRequestManager(self._requestManager); 5741 }); 5742 } 5743 5744 var methods = function () { 5745 var blockNetworkRead = new Method({ 5746 name: 'blockNetworkRead', 5747 call: 'bzz_blockNetworkRead', 5748 params: 1, 5749 inputFormatter: [null] 5750 }); 5751 5752 var syncEnabled = new Method({ 5753 name: 'syncEnabled', 5754 call: 'bzz_syncEnabled', 5755 params: 1, 5756 inputFormatter: [null] 5757 }); 5758 5759 var swapEnabled = new Method({ 5760 name: 'swapEnabled', 5761 call: 'bzz_swapEnabled', 5762 params: 1, 5763 inputFormatter: [null] 5764 }); 5765 5766 var download = new Method({ 5767 name: 'download', 5768 call: 'bzz_download', 5769 params: 2, 5770 inputFormatter: [null, null] 5771 }); 5772 5773 var upload = new Method({ 5774 name: 'upload', 5775 call: 'bzz_upload', 5776 params: 2, 5777 inputFormatter: [null, null] 5778 }); 5779 5780 var retrieve = new Method({ 5781 name: 'retrieve', 5782 call: 'bzz_retrieve', 5783 params: 1, 5784 inputFormatter: [null] 5785 }); 5786 5787 var store = new Method({ 5788 name: 'store', 5789 call: 'bzz_store', 5790 params: 2, 5791 inputFormatter: [null, null] 5792 }); 5793 5794 var get = new Method({ 5795 name: 'get', 5796 call: 'bzz_get', 5797 params: 1, 5798 inputFormatter: [null] 5799 }); 5800 5801 var put = new Method({ 5802 name: 'put', 5803 call: 'bzz_put', 5804 params: 2, 5805 inputFormatter: [null, null] 5806 }); 5807 5808 var modify = new Method({ 5809 name: 'modify', 5810 call: 'bzz_modify', 5811 params: 4, 5812 inputFormatter: [null, null, null, null] 5813 }); 5814 5815 return [ 5816 blockNetworkRead, 5817 syncEnabled, 5818 swapEnabled, 5819 download, 5820 upload, 5821 retrieve, 5822 store, 5823 get, 5824 put, 5825 modify 5826 ]; 5827 }; 5828 5829 var properties = function () { 5830 return [ 5831 new Property({ 5832 name: 'hive', 5833 getter: 'bzz_hive' 5834 }), 5835 new Property({ 5836 name: 'info', 5837 getter: 'bzz_info' 5838 }) 5839 ]; 5840 }; 5841 5842 5843 module.exports = Swarm; 5844 5845 },{"../method":36,"../property":45}],43:[function(require,module,exports){ 5846 /* 5847 This file is part of web3.js. 5848 5849 web3.js is free software: you can redistribute it and/or modify 5850 it under the terms of the GNU Lesser General Public License as published by 5851 the Free Software Foundation, either version 3 of the License, or 5852 (at your option) any later version. 5853 5854 web3.js is distributed in the hope that it will be useful, 5855 but WITHOUT ANY WARRANTY; without even the implied warranty of 5856 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5857 GNU Lesser General Public License for more details. 5858 5859 You should have received a copy of the GNU Lesser General Public License 5860 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5861 */ 5862 /** @file watches.js 5863 * @authors: 5864 * Marek Kotewicz <marek@ethdev.com> 5865 * @date 2015 5866 */ 5867 5868 var Method = require('../method'); 5869 5870 /// @returns an array of objects describing web3.eth.filter api methods 5871 var eth = function () { 5872 var newFilterCall = function (args) { 5873 var type = args[0]; 5874 5875 switch(type) { 5876 case 'latest': 5877 args.shift(); 5878 this.params = 0; 5879 return 'eth_newBlockFilter'; 5880 case 'pending': 5881 args.shift(); 5882 this.params = 0; 5883 return 'eth_newPendingTransactionFilter'; 5884 default: 5885 return 'eth_newFilter'; 5886 } 5887 }; 5888 5889 var newFilter = new Method({ 5890 name: 'newFilter', 5891 call: newFilterCall, 5892 params: 1 5893 }); 5894 5895 var uninstallFilter = new Method({ 5896 name: 'uninstallFilter', 5897 call: 'eth_uninstallFilter', 5898 params: 1 5899 }); 5900 5901 var getLogs = new Method({ 5902 name: 'getLogs', 5903 call: 'eth_getFilterLogs', 5904 params: 1 5905 }); 5906 5907 var poll = new Method({ 5908 name: 'poll', 5909 call: 'eth_getFilterChanges', 5910 params: 1 5911 }); 5912 5913 return [ 5914 newFilter, 5915 uninstallFilter, 5916 getLogs, 5917 poll 5918 ]; 5919 }; 5920 5921 /// @returns an array of objects describing web3.shh.watch api methods 5922 var shh = function () { 5923 var newFilter = new Method({ 5924 name: 'newFilter', 5925 call: 'shh_newFilter', 5926 params: 1 5927 }); 5928 5929 var uninstallFilter = new Method({ 5930 name: 'uninstallFilter', 5931 call: 'shh_uninstallFilter', 5932 params: 1 5933 }); 5934 5935 var getLogs = new Method({ 5936 name: 'getLogs', 5937 call: 'shh_getMessages', 5938 params: 1 5939 }); 5940 5941 var poll = new Method({ 5942 name: 'poll', 5943 call: 'shh_getFilterChanges', 5944 params: 1 5945 }); 5946 5947 return [ 5948 newFilter, 5949 uninstallFilter, 5950 getLogs, 5951 poll 5952 ]; 5953 }; 5954 5955 module.exports = { 5956 eth: eth, 5957 shh: shh 5958 }; 5959 5960 5961 },{"../method":36}],44:[function(require,module,exports){ 5962 /* 5963 This file is part of web3.js. 5964 5965 web3.js is free software: you can redistribute it and/or modify 5966 it under the terms of the GNU Lesser General Public License as published by 5967 the Free Software Foundation, either version 3 of the License, or 5968 (at your option) any later version. 5969 5970 web3.js is distributed in the hope that it will be useful, 5971 but WITHOUT ANY WARRANTY; without even the implied warranty of 5972 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 5973 GNU Lesser General Public License for more details. 5974 5975 You should have received a copy of the GNU Lesser General Public License 5976 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 5977 */ 5978 /** 5979 * @file namereg.js 5980 * @author Marek Kotewicz <marek@ethdev.com> 5981 * @date 2015 5982 */ 5983 5984 var globalRegistrarAbi = require('../contracts/GlobalRegistrar.json'); 5985 var icapRegistrarAbi= require('../contracts/ICAPRegistrar.json'); 5986 5987 var globalNameregAddress = '0xc6d9d2cd449a754c494264e1809c50e34d64562b'; 5988 var icapNameregAddress = '0xa1a111bc074c9cfa781f0c38e63bd51c91b8af00'; 5989 5990 module.exports = { 5991 global: { 5992 abi: globalRegistrarAbi, 5993 address: globalNameregAddress 5994 }, 5995 icap: { 5996 abi: icapRegistrarAbi, 5997 address: icapNameregAddress 5998 } 5999 }; 6000 6001 6002 },{"../contracts/GlobalRegistrar.json":1,"../contracts/ICAPRegistrar.json":2}],45:[function(require,module,exports){ 6003 /* 6004 This file is part of web3.js. 6005 6006 web3.js is free software: you can redistribute it and/or modify 6007 it under the terms of the GNU Lesser General Public License as published by 6008 the Free Software Foundation, either version 3 of the License, or 6009 (at your option) any later version. 6010 6011 web3.js is distributed in the hope that it will be useful, 6012 but WITHOUT ANY WARRANTY; without even the implied warranty of 6013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6014 GNU Lesser General Public License for more details. 6015 6016 You should have received a copy of the GNU Lesser General Public License 6017 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6018 */ 6019 /** 6020 * @file property.js 6021 * @author Fabian Vogelsteller <fabian@frozeman.de> 6022 * @author Marek Kotewicz <marek@ethdev.com> 6023 * @date 2015 6024 */ 6025 6026 var utils = require('../utils/utils'); 6027 6028 var Property = function (options) { 6029 this.name = options.name; 6030 this.getter = options.getter; 6031 this.setter = options.setter; 6032 this.outputFormatter = options.outputFormatter; 6033 this.inputFormatter = options.inputFormatter; 6034 this.requestManager = null; 6035 }; 6036 6037 Property.prototype.setRequestManager = function (rm) { 6038 this.requestManager = rm; 6039 }; 6040 6041 /** 6042 * Should be called to format input args of method 6043 * 6044 * @method formatInput 6045 * @param {Array} 6046 * @return {Array} 6047 */ 6048 Property.prototype.formatInput = function (arg) { 6049 return this.inputFormatter ? this.inputFormatter(arg) : arg; 6050 }; 6051 6052 /** 6053 * Should be called to format output(result) of method 6054 * 6055 * @method formatOutput 6056 * @param {Object} 6057 * @return {Object} 6058 */ 6059 Property.prototype.formatOutput = function (result) { 6060 return this.outputFormatter && result !== null && result !== undefined ? this.outputFormatter(result) : result; 6061 }; 6062 6063 /** 6064 * Should be used to extract callback from array of arguments. Modifies input param 6065 * 6066 * @method extractCallback 6067 * @param {Array} arguments 6068 * @return {Function|Null} callback, if exists 6069 */ 6070 Property.prototype.extractCallback = function (args) { 6071 if (utils.isFunction(args[args.length - 1])) { 6072 return args.pop(); // modify the args array! 6073 } 6074 }; 6075 6076 6077 /** 6078 * Should attach function to method 6079 * 6080 * @method attachToObject 6081 * @param {Object} 6082 * @param {Function} 6083 */ 6084 Property.prototype.attachToObject = function (obj) { 6085 var proto = { 6086 get: this.buildGet(), 6087 enumerable: true 6088 }; 6089 6090 var names = this.name.split('.'); 6091 var name = names[0]; 6092 if (names.length > 1) { 6093 obj[names[0]] = obj[names[0]] || {}; 6094 obj = obj[names[0]]; 6095 name = names[1]; 6096 } 6097 6098 Object.defineProperty(obj, name, proto); 6099 obj[asyncGetterName(name)] = this.buildAsyncGet(); 6100 }; 6101 6102 var asyncGetterName = function (name) { 6103 return 'get' + name.charAt(0).toUpperCase() + name.slice(1); 6104 }; 6105 6106 Property.prototype.buildGet = function () { 6107 var property = this; 6108 return function get() { 6109 return property.formatOutput(property.requestManager.send({ 6110 method: property.getter 6111 })); 6112 }; 6113 }; 6114 6115 Property.prototype.buildAsyncGet = function () { 6116 var property = this; 6117 var get = function (callback) { 6118 property.requestManager.sendAsync({ 6119 method: property.getter 6120 }, function (err, result) { 6121 callback(err, property.formatOutput(result)); 6122 }); 6123 }; 6124 get.request = this.request.bind(this); 6125 return get; 6126 }; 6127 6128 /** 6129 * Should be called to create pure JSONRPC request which can be used in batch request 6130 * 6131 * @method request 6132 * @param {...} params 6133 * @return {Object} jsonrpc request 6134 */ 6135 Property.prototype.request = function () { 6136 var payload = { 6137 method: this.getter, 6138 params: [], 6139 callback: this.extractCallback(Array.prototype.slice.call(arguments)) 6140 }; 6141 payload.format = this.formatOutput.bind(this); 6142 return payload; 6143 }; 6144 6145 module.exports = Property; 6146 6147 6148 },{"../utils/utils":20}],46:[function(require,module,exports){ 6149 /* 6150 This file is part of web3.js. 6151 6152 web3.js is free software: you can redistribute it and/or modify 6153 it under the terms of the GNU Lesser General Public License as published by 6154 the Free Software Foundation, either version 3 of the License, or 6155 (at your option) any later version. 6156 6157 web3.js is distributed in the hope that it will be useful, 6158 but WITHOUT ANY WARRANTY; without even the implied warranty of 6159 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6160 GNU Lesser General Public License for more details. 6161 6162 You should have received a copy of the GNU Lesser General Public License 6163 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6164 */ 6165 /** 6166 * @file requestmanager.js 6167 * @author Jeffrey Wilcke <jeff@ethdev.com> 6168 * @author Marek Kotewicz <marek@ethdev.com> 6169 * @author Marian Oancea <marian@ethdev.com> 6170 * @author Fabian Vogelsteller <fabian@ethdev.com> 6171 * @author Gav Wood <g@ethdev.com> 6172 * @date 2014 6173 */ 6174 6175 var Jsonrpc = require('./jsonrpc'); 6176 var utils = require('../utils/utils'); 6177 var c = require('../utils/config'); 6178 var errors = require('./errors'); 6179 6180 /** 6181 * It's responsible for passing messages to providers 6182 * It's also responsible for polling the ethereum node for incoming messages 6183 * Default poll timeout is 1 second 6184 * Singleton 6185 */ 6186 var RequestManager = function (provider) { 6187 this.provider = provider; 6188 this.polls = {}; 6189 this.timeout = null; 6190 }; 6191 6192 /** 6193 * Should be used to synchronously send request 6194 * 6195 * @method send 6196 * @param {Object} data 6197 * @return {Object} 6198 */ 6199 RequestManager.prototype.send = function (data) { 6200 if (!this.provider) { 6201 console.error(errors.InvalidProvider()); 6202 return null; 6203 } 6204 6205 var payload = Jsonrpc.toPayload(data.method, data.params); 6206 var result = this.provider.send(payload); 6207 6208 if (!Jsonrpc.isValidResponse(result)) { 6209 throw errors.InvalidResponse(result); 6210 } 6211 6212 return result.result; 6213 }; 6214 6215 /** 6216 * Should be used to asynchronously send request 6217 * 6218 * @method sendAsync 6219 * @param {Object} data 6220 * @param {Function} callback 6221 */ 6222 RequestManager.prototype.sendAsync = function (data, callback) { 6223 if (!this.provider) { 6224 return callback(errors.InvalidProvider()); 6225 } 6226 6227 var payload = Jsonrpc.toPayload(data.method, data.params); 6228 this.provider.sendAsync(payload, function (err, result) { 6229 if (err) { 6230 return callback(err); 6231 } 6232 6233 if (!Jsonrpc.isValidResponse(result)) { 6234 return callback(errors.InvalidResponse(result)); 6235 } 6236 6237 callback(null, result.result); 6238 }); 6239 }; 6240 6241 /** 6242 * Should be called to asynchronously send batch request 6243 * 6244 * @method sendBatch 6245 * @param {Array} batch data 6246 * @param {Function} callback 6247 */ 6248 RequestManager.prototype.sendBatch = function (data, callback) { 6249 if (!this.provider) { 6250 return callback(errors.InvalidProvider()); 6251 } 6252 6253 var payload = Jsonrpc.toBatchPayload(data); 6254 6255 this.provider.sendAsync(payload, function (err, results) { 6256 if (err) { 6257 return callback(err); 6258 } 6259 6260 if (!utils.isArray(results)) { 6261 return callback(errors.InvalidResponse(results)); 6262 } 6263 6264 callback(err, results); 6265 }); 6266 }; 6267 6268 /** 6269 * Should be used to set provider of request manager 6270 * 6271 * @method setProvider 6272 * @param {Object} 6273 */ 6274 RequestManager.prototype.setProvider = function (p) { 6275 this.provider = p; 6276 }; 6277 6278 /** 6279 * Should be used to start polling 6280 * 6281 * @method startPolling 6282 * @param {Object} data 6283 * @param {Number} pollId 6284 * @param {Function} callback 6285 * @param {Function} uninstall 6286 * 6287 * @todo cleanup number of params 6288 */ 6289 RequestManager.prototype.startPolling = function (data, pollId, callback, uninstall) { 6290 this.polls[pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall}; 6291 6292 6293 // start polling 6294 if (!this.timeout) { 6295 this.poll(); 6296 } 6297 }; 6298 6299 /** 6300 * Should be used to stop polling for filter with given id 6301 * 6302 * @method stopPolling 6303 * @param {Number} pollId 6304 */ 6305 RequestManager.prototype.stopPolling = function (pollId) { 6306 delete this.polls[pollId]; 6307 6308 // stop polling 6309 if(Object.keys(this.polls).length === 0 && this.timeout) { 6310 clearTimeout(this.timeout); 6311 this.timeout = null; 6312 } 6313 }; 6314 6315 /** 6316 * Should be called to reset the polling mechanism of the request manager 6317 * 6318 * @method reset 6319 */ 6320 RequestManager.prototype.reset = function (keepIsSyncing) { 6321 /*jshint maxcomplexity:5 */ 6322 6323 for (var key in this.polls) { 6324 // remove all polls, except sync polls, 6325 // they need to be removed manually by calling syncing.stopWatching() 6326 if(!keepIsSyncing || key.indexOf('syncPoll_') === -1) { 6327 this.polls[key].uninstall(); 6328 delete this.polls[key]; 6329 } 6330 } 6331 6332 // stop polling 6333 if(Object.keys(this.polls).length === 0 && this.timeout) { 6334 clearTimeout(this.timeout); 6335 this.timeout = null; 6336 } 6337 }; 6338 6339 /** 6340 * Should be called to poll for changes on filter with given id 6341 * 6342 * @method poll 6343 */ 6344 RequestManager.prototype.poll = function () { 6345 /*jshint maxcomplexity: 6 */ 6346 this.timeout = setTimeout(this.poll.bind(this), c.ETH_POLLING_TIMEOUT); 6347 6348 if (Object.keys(this.polls).length === 0) { 6349 return; 6350 } 6351 6352 if (!this.provider) { 6353 console.error(errors.InvalidProvider()); 6354 return; 6355 } 6356 6357 var pollsData = []; 6358 var pollsIds = []; 6359 for (var key in this.polls) { 6360 pollsData.push(this.polls[key].data); 6361 pollsIds.push(key); 6362 } 6363 6364 if (pollsData.length === 0) { 6365 return; 6366 } 6367 6368 var payload = Jsonrpc.toBatchPayload(pollsData); 6369 6370 // map the request id to they poll id 6371 var pollsIdMap = {}; 6372 payload.forEach(function(load, index){ 6373 pollsIdMap[load.id] = pollsIds[index]; 6374 }); 6375 6376 6377 var self = this; 6378 this.provider.sendAsync(payload, function (error, results) { 6379 6380 6381 // TODO: console log? 6382 if (error) { 6383 return; 6384 } 6385 6386 if (!utils.isArray(results)) { 6387 throw errors.InvalidResponse(results); 6388 } 6389 results.map(function (result) { 6390 var id = pollsIdMap[result.id]; 6391 6392 // make sure the filter is still installed after arrival of the request 6393 if (self.polls[id]) { 6394 result.callback = self.polls[id].callback; 6395 return result; 6396 } else 6397 return false; 6398 }).filter(function (result) { 6399 return !!result; 6400 }).filter(function (result) { 6401 var valid = Jsonrpc.isValidResponse(result); 6402 if (!valid) { 6403 result.callback(errors.InvalidResponse(result)); 6404 } 6405 return valid; 6406 }).forEach(function (result) { 6407 result.callback(null, result.result); 6408 }); 6409 }); 6410 }; 6411 6412 module.exports = RequestManager; 6413 6414 6415 },{"../utils/config":18,"../utils/utils":20,"./errors":26,"./jsonrpc":35}],47:[function(require,module,exports){ 6416 6417 6418 var Settings = function () { 6419 this.defaultBlock = 'latest'; 6420 this.defaultAccount = undefined; 6421 }; 6422 6423 module.exports = Settings; 6424 6425 6426 },{}],48:[function(require,module,exports){ 6427 /* 6428 This file is part of web3.js. 6429 6430 web3.js is free software: you can redistribute it and/or modify 6431 it under the terms of the GNU Lesser General Public License as published by 6432 the Free Software Foundation, either version 3 of the License, or 6433 (at your option) any later version. 6434 6435 web3.js is distributed in the hope that it will be useful, 6436 but WITHOUT ANY WARRANTY; without even the implied warranty of 6437 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6438 GNU Lesser General Public License for more details. 6439 6440 You should have received a copy of the GNU Lesser General Public License 6441 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6442 */ 6443 /** @file syncing.js 6444 * @authors: 6445 * Fabian Vogelsteller <fabian@ethdev.com> 6446 * @date 2015 6447 */ 6448 6449 var formatters = require('./formatters'); 6450 var utils = require('../utils/utils'); 6451 6452 var count = 1; 6453 6454 /** 6455 Adds the callback and sets up the methods, to iterate over the results. 6456 6457 @method pollSyncing 6458 @param {Object} self 6459 */ 6460 var pollSyncing = function(self) { 6461 6462 var onMessage = function (error, sync) { 6463 if (error) { 6464 return self.callbacks.forEach(function (callback) { 6465 callback(error); 6466 }); 6467 } 6468 6469 if(utils.isObject(sync) && sync.startingBlock) 6470 sync = formatters.outputSyncingFormatter(sync); 6471 6472 self.callbacks.forEach(function (callback) { 6473 if (self.lastSyncState !== sync) { 6474 6475 // call the callback with true first so the app can stop anything, before receiving the sync data 6476 if(!self.lastSyncState && utils.isObject(sync)) 6477 callback(null, true); 6478 6479 // call on the next CPU cycle, so the actions of the sync stop can be processes first 6480 setTimeout(function() { 6481 callback(null, sync); 6482 }, 0); 6483 6484 self.lastSyncState = sync; 6485 } 6486 }); 6487 }; 6488 6489 self.requestManager.startPolling({ 6490 method: 'eth_syncing', 6491 params: [], 6492 }, self.pollId, onMessage, self.stopWatching.bind(self)); 6493 6494 }; 6495 6496 var IsSyncing = function (requestManager, callback) { 6497 this.requestManager = requestManager; 6498 this.pollId = 'syncPoll_'+ count++; 6499 this.callbacks = []; 6500 this.addCallback(callback); 6501 this.lastSyncState = false; 6502 pollSyncing(this); 6503 6504 return this; 6505 }; 6506 6507 IsSyncing.prototype.addCallback = function (callback) { 6508 if(callback) 6509 this.callbacks.push(callback); 6510 return this; 6511 }; 6512 6513 IsSyncing.prototype.stopWatching = function () { 6514 this.requestManager.stopPolling(this.pollId); 6515 this.callbacks = []; 6516 }; 6517 6518 module.exports = IsSyncing; 6519 6520 6521 },{"../utils/utils":20,"./formatters":30}],49:[function(require,module,exports){ 6522 /* 6523 This file is part of web3.js. 6524 6525 web3.js is free software: you can redistribute it and/or modify 6526 it under the terms of the GNU Lesser General Public License as published by 6527 the Free Software Foundation, either version 3 of the License, or 6528 (at your option) any later version. 6529 6530 web3.js is distributed in the hope that it will be useful, 6531 but WITHOUT ANY WARRANTY; without even the implied warranty of 6532 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 6533 GNU Lesser General Public License for more details. 6534 6535 You should have received a copy of the GNU Lesser General Public License 6536 along with web3.js. If not, see <http://www.gnu.org/licenses/>. 6537 */ 6538 /** 6539 * @file transfer.js 6540 * @author Marek Kotewicz <marek@ethdev.com> 6541 * @date 2015 6542 */ 6543 6544 var Iban = require('./iban'); 6545 var exchangeAbi = require('../contracts/SmartExchange.json'); 6546 6547 /** 6548 * Should be used to make Iban transfer 6549 * 6550 * @method transfer 6551 * @param {String} from 6552 * @param {String} to iban 6553 * @param {Value} value to be tranfered 6554 * @param {Function} callback, callback 6555 */ 6556 var transfer = function (eth, from, to, value, callback) { 6557 var iban = new Iban(to); 6558 if (!iban.isValid()) { 6559 throw new Error('invalid iban address'); 6560 } 6561 6562 if (iban.isDirect()) { 6563 return transferToAddress(eth, from, iban.address(), value, callback); 6564 } 6565 6566 if (!callback) { 6567 var address = eth.icapNamereg().addr(iban.institution()); 6568 return deposit(eth, from, address, value, iban.client()); 6569 } 6570 6571 eth.icapNamereg().addr(iban.institution(), function (err, address) { 6572 return deposit(eth, from, address, value, iban.client(), callback); 6573 }); 6574 6575 }; 6576 6577 /** 6578 * Should be used to transfer funds to certain address 6579 * 6580 * @method transferToAddress 6581 * @param {String} from 6582 * @param {String} to 6583 * @param {Value} value to be tranfered 6584 * @param {Function} callback, callback 6585 */ 6586 var transferToAddress = function (eth, from, to, value, callback) { 6587 return eth.sendTransaction({ 6588 address: to, 6589 from: from, 6590 value: value 6591 }, callback); 6592 }; 6593 6594 /** 6595 * Should be used to deposit funds to generic Exchange contract (must implement deposit(bytes32) method!) 6596 * 6597 * @method deposit 6598 * @param {String} from 6599 * @param {String} to 6600 * @param {Value} value to be transfered 6601 * @param {String} client unique identifier 6602 * @param {Function} callback, callback 6603 */ 6604 var deposit = function (eth, from, to, value, client, callback) { 6605 var abi = exchangeAbi; 6606 return eth.contract(abi).at(to).deposit(client, { 6607 from: from, 6608 value: value 6609 }, callback); 6610 }; 6611 6612 module.exports = transfer; 6613 6614 6615 },{"../contracts/SmartExchange.json":3,"./iban":33}],50:[function(require,module,exports){ 6616 6617 },{}],51:[function(require,module,exports){ 6618 ;(function (root, factory, undef) { 6619 if (typeof exports === "object") { 6620 // CommonJS 6621 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 6622 } 6623 else if (typeof define === "function" && define.amd) { 6624 // AMD 6625 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 6626 } 6627 else { 6628 // Global (browser) 6629 factory(root.CryptoJS); 6630 } 6631 }(this, function (CryptoJS) { 6632 6633 (function () { 6634 // Shortcuts 6635 var C = CryptoJS; 6636 var C_lib = C.lib; 6637 var BlockCipher = C_lib.BlockCipher; 6638 var C_algo = C.algo; 6639 6640 // Lookup tables 6641 var SBOX = []; 6642 var INV_SBOX = []; 6643 var SUB_MIX_0 = []; 6644 var SUB_MIX_1 = []; 6645 var SUB_MIX_2 = []; 6646 var SUB_MIX_3 = []; 6647 var INV_SUB_MIX_0 = []; 6648 var INV_SUB_MIX_1 = []; 6649 var INV_SUB_MIX_2 = []; 6650 var INV_SUB_MIX_3 = []; 6651 6652 // Compute lookup tables 6653 (function () { 6654 // Compute double table 6655 var d = []; 6656 for (var i = 0; i < 256; i++) { 6657 if (i < 128) { 6658 d[i] = i << 1; 6659 } else { 6660 d[i] = (i << 1) ^ 0x11b; 6661 } 6662 } 6663 6664 // Walk GF(2^8) 6665 var x = 0; 6666 var xi = 0; 6667 for (var i = 0; i < 256; i++) { 6668 // Compute sbox 6669 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); 6670 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; 6671 SBOX[x] = sx; 6672 INV_SBOX[sx] = x; 6673 6674 // Compute multiplication 6675 var x2 = d[x]; 6676 var x4 = d[x2]; 6677 var x8 = d[x4]; 6678 6679 // Compute sub bytes, mix columns tables 6680 var t = (d[sx] * 0x101) ^ (sx * 0x1010100); 6681 SUB_MIX_0[x] = (t << 24) | (t >>> 8); 6682 SUB_MIX_1[x] = (t << 16) | (t >>> 16); 6683 SUB_MIX_2[x] = (t << 8) | (t >>> 24); 6684 SUB_MIX_3[x] = t; 6685 6686 // Compute inv sub bytes, inv mix columns tables 6687 var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); 6688 INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); 6689 INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); 6690 INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); 6691 INV_SUB_MIX_3[sx] = t; 6692 6693 // Compute next counter 6694 if (!x) { 6695 x = xi = 1; 6696 } else { 6697 x = x2 ^ d[d[d[x8 ^ x2]]]; 6698 xi ^= d[d[xi]]; 6699 } 6700 } 6701 }()); 6702 6703 // Precomputed Rcon lookup 6704 var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; 6705 6706 /** 6707 * AES block cipher algorithm. 6708 */ 6709 var AES = C_algo.AES = BlockCipher.extend({ 6710 _doReset: function () { 6711 // Skip reset of nRounds has been set before and key did not change 6712 if (this._nRounds && this._keyPriorReset === this._key) { 6713 return; 6714 } 6715 6716 // Shortcuts 6717 var key = this._keyPriorReset = this._key; 6718 var keyWords = key.words; 6719 var keySize = key.sigBytes / 4; 6720 6721 // Compute number of rounds 6722 var nRounds = this._nRounds = keySize + 6; 6723 6724 // Compute number of key schedule rows 6725 var ksRows = (nRounds + 1) * 4; 6726 6727 // Compute key schedule 6728 var keySchedule = this._keySchedule = []; 6729 for (var ksRow = 0; ksRow < ksRows; ksRow++) { 6730 if (ksRow < keySize) { 6731 keySchedule[ksRow] = keyWords[ksRow]; 6732 } else { 6733 var t = keySchedule[ksRow - 1]; 6734 6735 if (!(ksRow % keySize)) { 6736 // Rot word 6737 t = (t << 8) | (t >>> 24); 6738 6739 // Sub word 6740 t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; 6741 6742 // Mix Rcon 6743 t ^= RCON[(ksRow / keySize) | 0] << 24; 6744 } else if (keySize > 6 && ksRow % keySize == 4) { 6745 // Sub word 6746 t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; 6747 } 6748 6749 keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; 6750 } 6751 } 6752 6753 // Compute inv key schedule 6754 var invKeySchedule = this._invKeySchedule = []; 6755 for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { 6756 var ksRow = ksRows - invKsRow; 6757 6758 if (invKsRow % 4) { 6759 var t = keySchedule[ksRow]; 6760 } else { 6761 var t = keySchedule[ksRow - 4]; 6762 } 6763 6764 if (invKsRow < 4 || ksRow <= 4) { 6765 invKeySchedule[invKsRow] = t; 6766 } else { 6767 invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ 6768 INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; 6769 } 6770 } 6771 }, 6772 6773 encryptBlock: function (M, offset) { 6774 this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); 6775 }, 6776 6777 decryptBlock: function (M, offset) { 6778 // Swap 2nd and 4th rows 6779 var t = M[offset + 1]; 6780 M[offset + 1] = M[offset + 3]; 6781 M[offset + 3] = t; 6782 6783 this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); 6784 6785 // Inv swap 2nd and 4th rows 6786 var t = M[offset + 1]; 6787 M[offset + 1] = M[offset + 3]; 6788 M[offset + 3] = t; 6789 }, 6790 6791 _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { 6792 // Shortcut 6793 var nRounds = this._nRounds; 6794 6795 // Get input, add round key 6796 var s0 = M[offset] ^ keySchedule[0]; 6797 var s1 = M[offset + 1] ^ keySchedule[1]; 6798 var s2 = M[offset + 2] ^ keySchedule[2]; 6799 var s3 = M[offset + 3] ^ keySchedule[3]; 6800 6801 // Key schedule row counter 6802 var ksRow = 4; 6803 6804 // Rounds 6805 for (var round = 1; round < nRounds; round++) { 6806 // Shift rows, sub bytes, mix columns, add round key 6807 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++]; 6808 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++]; 6809 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++]; 6810 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++]; 6811 6812 // Update state 6813 s0 = t0; 6814 s1 = t1; 6815 s2 = t2; 6816 s3 = t3; 6817 } 6818 6819 // Shift rows, sub bytes, add round key 6820 var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; 6821 var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; 6822 var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; 6823 var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; 6824 6825 // Set output 6826 M[offset] = t0; 6827 M[offset + 1] = t1; 6828 M[offset + 2] = t2; 6829 M[offset + 3] = t3; 6830 }, 6831 6832 keySize: 256/32 6833 }); 6834 6835 /** 6836 * Shortcut functions to the cipher's object interface. 6837 * 6838 * @example 6839 * 6840 * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); 6841 * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); 6842 */ 6843 C.AES = BlockCipher._createHelper(AES); 6844 }()); 6845 6846 6847 return CryptoJS.AES; 6848 6849 })); 6850 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],52:[function(require,module,exports){ 6851 ;(function (root, factory) { 6852 if (typeof exports === "object") { 6853 // CommonJS 6854 module.exports = exports = factory(require("./core")); 6855 } 6856 else if (typeof define === "function" && define.amd) { 6857 // AMD 6858 define(["./core"], factory); 6859 } 6860 else { 6861 // Global (browser) 6862 factory(root.CryptoJS); 6863 } 6864 }(this, function (CryptoJS) { 6865 6866 /** 6867 * Cipher core components. 6868 */ 6869 CryptoJS.lib.Cipher || (function (undefined) { 6870 // Shortcuts 6871 var C = CryptoJS; 6872 var C_lib = C.lib; 6873 var Base = C_lib.Base; 6874 var WordArray = C_lib.WordArray; 6875 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; 6876 var C_enc = C.enc; 6877 var Utf8 = C_enc.Utf8; 6878 var Base64 = C_enc.Base64; 6879 var C_algo = C.algo; 6880 var EvpKDF = C_algo.EvpKDF; 6881 6882 /** 6883 * Abstract base cipher template. 6884 * 6885 * @property {number} keySize This cipher's key size. Default: 4 (128 bits) 6886 * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) 6887 * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. 6888 * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. 6889 */ 6890 var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ 6891 /** 6892 * Configuration options. 6893 * 6894 * @property {WordArray} iv The IV to use for this operation. 6895 */ 6896 cfg: Base.extend(), 6897 6898 /** 6899 * Creates this cipher in encryption mode. 6900 * 6901 * @param {WordArray} key The key. 6902 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6903 * 6904 * @return {Cipher} A cipher instance. 6905 * 6906 * @static 6907 * 6908 * @example 6909 * 6910 * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); 6911 */ 6912 createEncryptor: function (key, cfg) { 6913 return this.create(this._ENC_XFORM_MODE, key, cfg); 6914 }, 6915 6916 /** 6917 * Creates this cipher in decryption mode. 6918 * 6919 * @param {WordArray} key The key. 6920 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6921 * 6922 * @return {Cipher} A cipher instance. 6923 * 6924 * @static 6925 * 6926 * @example 6927 * 6928 * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); 6929 */ 6930 createDecryptor: function (key, cfg) { 6931 return this.create(this._DEC_XFORM_MODE, key, cfg); 6932 }, 6933 6934 /** 6935 * Initializes a newly created cipher. 6936 * 6937 * @param {number} xformMode Either the encryption or decryption transormation mode constant. 6938 * @param {WordArray} key The key. 6939 * @param {Object} cfg (Optional) The configuration options to use for this operation. 6940 * 6941 * @example 6942 * 6943 * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); 6944 */ 6945 init: function (xformMode, key, cfg) { 6946 // Apply config defaults 6947 this.cfg = this.cfg.extend(cfg); 6948 6949 // Store transform mode and key 6950 this._xformMode = xformMode; 6951 this._key = key; 6952 6953 // Set initial values 6954 this.reset(); 6955 }, 6956 6957 /** 6958 * Resets this cipher to its initial state. 6959 * 6960 * @example 6961 * 6962 * cipher.reset(); 6963 */ 6964 reset: function () { 6965 // Reset data buffer 6966 BufferedBlockAlgorithm.reset.call(this); 6967 6968 // Perform concrete-cipher logic 6969 this._doReset(); 6970 }, 6971 6972 /** 6973 * Adds data to be encrypted or decrypted. 6974 * 6975 * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. 6976 * 6977 * @return {WordArray} The data after processing. 6978 * 6979 * @example 6980 * 6981 * var encrypted = cipher.process('data'); 6982 * var encrypted = cipher.process(wordArray); 6983 */ 6984 process: function (dataUpdate) { 6985 // Append 6986 this._append(dataUpdate); 6987 6988 // Process available blocks 6989 return this._process(); 6990 }, 6991 6992 /** 6993 * Finalizes the encryption or decryption process. 6994 * Note that the finalize operation is effectively a destructive, read-once operation. 6995 * 6996 * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. 6997 * 6998 * @return {WordArray} The data after final processing. 6999 * 7000 * @example 7001 * 7002 * var encrypted = cipher.finalize(); 7003 * var encrypted = cipher.finalize('data'); 7004 * var encrypted = cipher.finalize(wordArray); 7005 */ 7006 finalize: function (dataUpdate) { 7007 // Final data update 7008 if (dataUpdate) { 7009 this._append(dataUpdate); 7010 } 7011 7012 // Perform concrete-cipher logic 7013 var finalProcessedData = this._doFinalize(); 7014 7015 return finalProcessedData; 7016 }, 7017 7018 keySize: 128/32, 7019 7020 ivSize: 128/32, 7021 7022 _ENC_XFORM_MODE: 1, 7023 7024 _DEC_XFORM_MODE: 2, 7025 7026 /** 7027 * Creates shortcut functions to a cipher's object interface. 7028 * 7029 * @param {Cipher} cipher The cipher to create a helper for. 7030 * 7031 * @return {Object} An object with encrypt and decrypt shortcut functions. 7032 * 7033 * @static 7034 * 7035 * @example 7036 * 7037 * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); 7038 */ 7039 _createHelper: (function () { 7040 function selectCipherStrategy(key) { 7041 if (typeof key == 'string') { 7042 return PasswordBasedCipher; 7043 } else { 7044 return SerializableCipher; 7045 } 7046 } 7047 7048 return function (cipher) { 7049 return { 7050 encrypt: function (message, key, cfg) { 7051 return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); 7052 }, 7053 7054 decrypt: function (ciphertext, key, cfg) { 7055 return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); 7056 } 7057 }; 7058 }; 7059 }()) 7060 }); 7061 7062 /** 7063 * Abstract base stream cipher template. 7064 * 7065 * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) 7066 */ 7067 var StreamCipher = C_lib.StreamCipher = Cipher.extend({ 7068 _doFinalize: function () { 7069 // Process partial blocks 7070 var finalProcessedBlocks = this._process(!!'flush'); 7071 7072 return finalProcessedBlocks; 7073 }, 7074 7075 blockSize: 1 7076 }); 7077 7078 /** 7079 * Mode namespace. 7080 */ 7081 var C_mode = C.mode = {}; 7082 7083 /** 7084 * Abstract base block cipher mode template. 7085 */ 7086 var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ 7087 /** 7088 * Creates this mode for encryption. 7089 * 7090 * @param {Cipher} cipher A block cipher instance. 7091 * @param {Array} iv The IV words. 7092 * 7093 * @static 7094 * 7095 * @example 7096 * 7097 * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); 7098 */ 7099 createEncryptor: function (cipher, iv) { 7100 return this.Encryptor.create(cipher, iv); 7101 }, 7102 7103 /** 7104 * Creates this mode for decryption. 7105 * 7106 * @param {Cipher} cipher A block cipher instance. 7107 * @param {Array} iv The IV words. 7108 * 7109 * @static 7110 * 7111 * @example 7112 * 7113 * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); 7114 */ 7115 createDecryptor: function (cipher, iv) { 7116 return this.Decryptor.create(cipher, iv); 7117 }, 7118 7119 /** 7120 * Initializes a newly created mode. 7121 * 7122 * @param {Cipher} cipher A block cipher instance. 7123 * @param {Array} iv The IV words. 7124 * 7125 * @example 7126 * 7127 * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); 7128 */ 7129 init: function (cipher, iv) { 7130 this._cipher = cipher; 7131 this._iv = iv; 7132 } 7133 }); 7134 7135 /** 7136 * Cipher Block Chaining mode. 7137 */ 7138 var CBC = C_mode.CBC = (function () { 7139 /** 7140 * Abstract base CBC mode. 7141 */ 7142 var CBC = BlockCipherMode.extend(); 7143 7144 /** 7145 * CBC encryptor. 7146 */ 7147 CBC.Encryptor = CBC.extend({ 7148 /** 7149 * Processes the data block at offset. 7150 * 7151 * @param {Array} words The data words to operate on. 7152 * @param {number} offset The offset where the block starts. 7153 * 7154 * @example 7155 * 7156 * mode.processBlock(data.words, offset); 7157 */ 7158 processBlock: function (words, offset) { 7159 // Shortcuts 7160 var cipher = this._cipher; 7161 var blockSize = cipher.blockSize; 7162 7163 // XOR and encrypt 7164 xorBlock.call(this, words, offset, blockSize); 7165 cipher.encryptBlock(words, offset); 7166 7167 // Remember this block to use with next block 7168 this._prevBlock = words.slice(offset, offset + blockSize); 7169 } 7170 }); 7171 7172 /** 7173 * CBC decryptor. 7174 */ 7175 CBC.Decryptor = CBC.extend({ 7176 /** 7177 * Processes the data block at offset. 7178 * 7179 * @param {Array} words The data words to operate on. 7180 * @param {number} offset The offset where the block starts. 7181 * 7182 * @example 7183 * 7184 * mode.processBlock(data.words, offset); 7185 */ 7186 processBlock: function (words, offset) { 7187 // Shortcuts 7188 var cipher = this._cipher; 7189 var blockSize = cipher.blockSize; 7190 7191 // Remember this block to use with next block 7192 var thisBlock = words.slice(offset, offset + blockSize); 7193 7194 // Decrypt and XOR 7195 cipher.decryptBlock(words, offset); 7196 xorBlock.call(this, words, offset, blockSize); 7197 7198 // This block becomes the previous block 7199 this._prevBlock = thisBlock; 7200 } 7201 }); 7202 7203 function xorBlock(words, offset, blockSize) { 7204 // Shortcut 7205 var iv = this._iv; 7206 7207 // Choose mixing block 7208 if (iv) { 7209 var block = iv; 7210 7211 // Remove IV for subsequent blocks 7212 this._iv = undefined; 7213 } else { 7214 var block = this._prevBlock; 7215 } 7216 7217 // XOR blocks 7218 for (var i = 0; i < blockSize; i++) { 7219 words[offset + i] ^= block[i]; 7220 } 7221 } 7222 7223 return CBC; 7224 }()); 7225 7226 /** 7227 * Padding namespace. 7228 */ 7229 var C_pad = C.pad = {}; 7230 7231 /** 7232 * PKCS #5/7 padding strategy. 7233 */ 7234 var Pkcs7 = C_pad.Pkcs7 = { 7235 /** 7236 * Pads data using the algorithm defined in PKCS #5/7. 7237 * 7238 * @param {WordArray} data The data to pad. 7239 * @param {number} blockSize The multiple that the data should be padded to. 7240 * 7241 * @static 7242 * 7243 * @example 7244 * 7245 * CryptoJS.pad.Pkcs7.pad(wordArray, 4); 7246 */ 7247 pad: function (data, blockSize) { 7248 // Shortcut 7249 var blockSizeBytes = blockSize * 4; 7250 7251 // Count padding bytes 7252 var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; 7253 7254 // Create padding word 7255 var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; 7256 7257 // Create padding 7258 var paddingWords = []; 7259 for (var i = 0; i < nPaddingBytes; i += 4) { 7260 paddingWords.push(paddingWord); 7261 } 7262 var padding = WordArray.create(paddingWords, nPaddingBytes); 7263 7264 // Add padding 7265 data.concat(padding); 7266 }, 7267 7268 /** 7269 * Unpads data that had been padded using the algorithm defined in PKCS #5/7. 7270 * 7271 * @param {WordArray} data The data to unpad. 7272 * 7273 * @static 7274 * 7275 * @example 7276 * 7277 * CryptoJS.pad.Pkcs7.unpad(wordArray); 7278 */ 7279 unpad: function (data) { 7280 // Get number of padding bytes from last byte 7281 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 7282 7283 // Remove padding 7284 data.sigBytes -= nPaddingBytes; 7285 } 7286 }; 7287 7288 /** 7289 * Abstract base block cipher template. 7290 * 7291 * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) 7292 */ 7293 var BlockCipher = C_lib.BlockCipher = Cipher.extend({ 7294 /** 7295 * Configuration options. 7296 * 7297 * @property {Mode} mode The block mode to use. Default: CBC 7298 * @property {Padding} padding The padding strategy to use. Default: Pkcs7 7299 */ 7300 cfg: Cipher.cfg.extend({ 7301 mode: CBC, 7302 padding: Pkcs7 7303 }), 7304 7305 reset: function () { 7306 // Reset cipher 7307 Cipher.reset.call(this); 7308 7309 // Shortcuts 7310 var cfg = this.cfg; 7311 var iv = cfg.iv; 7312 var mode = cfg.mode; 7313 7314 // Reset block mode 7315 if (this._xformMode == this._ENC_XFORM_MODE) { 7316 var modeCreator = mode.createEncryptor; 7317 } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { 7318 var modeCreator = mode.createDecryptor; 7319 7320 // Keep at least one block in the buffer for unpadding 7321 this._minBufferSize = 1; 7322 } 7323 this._mode = modeCreator.call(mode, this, iv && iv.words); 7324 }, 7325 7326 _doProcessBlock: function (words, offset) { 7327 this._mode.processBlock(words, offset); 7328 }, 7329 7330 _doFinalize: function () { 7331 // Shortcut 7332 var padding = this.cfg.padding; 7333 7334 // Finalize 7335 if (this._xformMode == this._ENC_XFORM_MODE) { 7336 // Pad data 7337 padding.pad(this._data, this.blockSize); 7338 7339 // Process final blocks 7340 var finalProcessedBlocks = this._process(!!'flush'); 7341 } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { 7342 // Process final blocks 7343 var finalProcessedBlocks = this._process(!!'flush'); 7344 7345 // Unpad data 7346 padding.unpad(finalProcessedBlocks); 7347 } 7348 7349 return finalProcessedBlocks; 7350 }, 7351 7352 blockSize: 128/32 7353 }); 7354 7355 /** 7356 * A collection of cipher parameters. 7357 * 7358 * @property {WordArray} ciphertext The raw ciphertext. 7359 * @property {WordArray} key The key to this ciphertext. 7360 * @property {WordArray} iv The IV used in the ciphering operation. 7361 * @property {WordArray} salt The salt used with a key derivation function. 7362 * @property {Cipher} algorithm The cipher algorithm. 7363 * @property {Mode} mode The block mode used in the ciphering operation. 7364 * @property {Padding} padding The padding scheme used in the ciphering operation. 7365 * @property {number} blockSize The block size of the cipher. 7366 * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. 7367 */ 7368 var CipherParams = C_lib.CipherParams = Base.extend({ 7369 /** 7370 * Initializes a newly created cipher params object. 7371 * 7372 * @param {Object} cipherParams An object with any of the possible cipher parameters. 7373 * 7374 * @example 7375 * 7376 * var cipherParams = CryptoJS.lib.CipherParams.create({ 7377 * ciphertext: ciphertextWordArray, 7378 * key: keyWordArray, 7379 * iv: ivWordArray, 7380 * salt: saltWordArray, 7381 * algorithm: CryptoJS.algo.AES, 7382 * mode: CryptoJS.mode.CBC, 7383 * padding: CryptoJS.pad.PKCS7, 7384 * blockSize: 4, 7385 * formatter: CryptoJS.format.OpenSSL 7386 * }); 7387 */ 7388 init: function (cipherParams) { 7389 this.mixIn(cipherParams); 7390 }, 7391 7392 /** 7393 * Converts this cipher params object to a string. 7394 * 7395 * @param {Format} formatter (Optional) The formatting strategy to use. 7396 * 7397 * @return {string} The stringified cipher params. 7398 * 7399 * @throws Error If neither the formatter nor the default formatter is set. 7400 * 7401 * @example 7402 * 7403 * var string = cipherParams + ''; 7404 * var string = cipherParams.toString(); 7405 * var string = cipherParams.toString(CryptoJS.format.OpenSSL); 7406 */ 7407 toString: function (formatter) { 7408 return (formatter || this.formatter).stringify(this); 7409 } 7410 }); 7411 7412 /** 7413 * Format namespace. 7414 */ 7415 var C_format = C.format = {}; 7416 7417 /** 7418 * OpenSSL formatting strategy. 7419 */ 7420 var OpenSSLFormatter = C_format.OpenSSL = { 7421 /** 7422 * Converts a cipher params object to an OpenSSL-compatible string. 7423 * 7424 * @param {CipherParams} cipherParams The cipher params object. 7425 * 7426 * @return {string} The OpenSSL-compatible string. 7427 * 7428 * @static 7429 * 7430 * @example 7431 * 7432 * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); 7433 */ 7434 stringify: function (cipherParams) { 7435 // Shortcuts 7436 var ciphertext = cipherParams.ciphertext; 7437 var salt = cipherParams.salt; 7438 7439 // Format 7440 if (salt) { 7441 var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); 7442 } else { 7443 var wordArray = ciphertext; 7444 } 7445 7446 return wordArray.toString(Base64); 7447 }, 7448 7449 /** 7450 * Converts an OpenSSL-compatible string to a cipher params object. 7451 * 7452 * @param {string} openSSLStr The OpenSSL-compatible string. 7453 * 7454 * @return {CipherParams} The cipher params object. 7455 * 7456 * @static 7457 * 7458 * @example 7459 * 7460 * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); 7461 */ 7462 parse: function (openSSLStr) { 7463 // Parse base64 7464 var ciphertext = Base64.parse(openSSLStr); 7465 7466 // Shortcut 7467 var ciphertextWords = ciphertext.words; 7468 7469 // Test for salt 7470 if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { 7471 // Extract salt 7472 var salt = WordArray.create(ciphertextWords.slice(2, 4)); 7473 7474 // Remove salt from ciphertext 7475 ciphertextWords.splice(0, 4); 7476 ciphertext.sigBytes -= 16; 7477 } 7478 7479 return CipherParams.create({ ciphertext: ciphertext, salt: salt }); 7480 } 7481 }; 7482 7483 /** 7484 * A cipher wrapper that returns ciphertext as a serializable cipher params object. 7485 */ 7486 var SerializableCipher = C_lib.SerializableCipher = Base.extend({ 7487 /** 7488 * Configuration options. 7489 * 7490 * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL 7491 */ 7492 cfg: Base.extend({ 7493 format: OpenSSLFormatter 7494 }), 7495 7496 /** 7497 * Encrypts a message. 7498 * 7499 * @param {Cipher} cipher The cipher algorithm to use. 7500 * @param {WordArray|string} message The message to encrypt. 7501 * @param {WordArray} key The key. 7502 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7503 * 7504 * @return {CipherParams} A cipher params object. 7505 * 7506 * @static 7507 * 7508 * @example 7509 * 7510 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); 7511 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); 7512 * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7513 */ 7514 encrypt: function (cipher, message, key, cfg) { 7515 // Apply config defaults 7516 cfg = this.cfg.extend(cfg); 7517 7518 // Encrypt 7519 var encryptor = cipher.createEncryptor(key, cfg); 7520 var ciphertext = encryptor.finalize(message); 7521 7522 // Shortcut 7523 var cipherCfg = encryptor.cfg; 7524 7525 // Create and return serializable cipher params 7526 return CipherParams.create({ 7527 ciphertext: ciphertext, 7528 key: key, 7529 iv: cipherCfg.iv, 7530 algorithm: cipher, 7531 mode: cipherCfg.mode, 7532 padding: cipherCfg.padding, 7533 blockSize: cipher.blockSize, 7534 formatter: cfg.format 7535 }); 7536 }, 7537 7538 /** 7539 * Decrypts serialized ciphertext. 7540 * 7541 * @param {Cipher} cipher The cipher algorithm to use. 7542 * @param {CipherParams|string} ciphertext The ciphertext to decrypt. 7543 * @param {WordArray} key The key. 7544 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7545 * 7546 * @return {WordArray} The plaintext. 7547 * 7548 * @static 7549 * 7550 * @example 7551 * 7552 * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7553 * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); 7554 */ 7555 decrypt: function (cipher, ciphertext, key, cfg) { 7556 // Apply config defaults 7557 cfg = this.cfg.extend(cfg); 7558 7559 // Convert string to CipherParams 7560 ciphertext = this._parse(ciphertext, cfg.format); 7561 7562 // Decrypt 7563 var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); 7564 7565 return plaintext; 7566 }, 7567 7568 /** 7569 * Converts serialized ciphertext to CipherParams, 7570 * else assumed CipherParams already and returns ciphertext unchanged. 7571 * 7572 * @param {CipherParams|string} ciphertext The ciphertext. 7573 * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. 7574 * 7575 * @return {CipherParams} The unserialized ciphertext. 7576 * 7577 * @static 7578 * 7579 * @example 7580 * 7581 * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); 7582 */ 7583 _parse: function (ciphertext, format) { 7584 if (typeof ciphertext == 'string') { 7585 return format.parse(ciphertext, this); 7586 } else { 7587 return ciphertext; 7588 } 7589 } 7590 }); 7591 7592 /** 7593 * Key derivation function namespace. 7594 */ 7595 var C_kdf = C.kdf = {}; 7596 7597 /** 7598 * OpenSSL key derivation function. 7599 */ 7600 var OpenSSLKdf = C_kdf.OpenSSL = { 7601 /** 7602 * Derives a key and IV from a password. 7603 * 7604 * @param {string} password The password to derive from. 7605 * @param {number} keySize The size in words of the key to generate. 7606 * @param {number} ivSize The size in words of the IV to generate. 7607 * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. 7608 * 7609 * @return {CipherParams} A cipher params object with the key, IV, and salt. 7610 * 7611 * @static 7612 * 7613 * @example 7614 * 7615 * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); 7616 * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); 7617 */ 7618 execute: function (password, keySize, ivSize, salt) { 7619 // Generate random salt 7620 if (!salt) { 7621 salt = WordArray.random(64/8); 7622 } 7623 7624 // Derive key and IV 7625 var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); 7626 7627 // Separate key and IV 7628 var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); 7629 key.sigBytes = keySize * 4; 7630 7631 // Return params 7632 return CipherParams.create({ key: key, iv: iv, salt: salt }); 7633 } 7634 }; 7635 7636 /** 7637 * A serializable cipher wrapper that derives the key from a password, 7638 * and returns ciphertext as a serializable cipher params object. 7639 */ 7640 var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ 7641 /** 7642 * Configuration options. 7643 * 7644 * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL 7645 */ 7646 cfg: SerializableCipher.cfg.extend({ 7647 kdf: OpenSSLKdf 7648 }), 7649 7650 /** 7651 * Encrypts a message using a password. 7652 * 7653 * @param {Cipher} cipher The cipher algorithm to use. 7654 * @param {WordArray|string} message The message to encrypt. 7655 * @param {string} password The password. 7656 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7657 * 7658 * @return {CipherParams} A cipher params object. 7659 * 7660 * @static 7661 * 7662 * @example 7663 * 7664 * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); 7665 * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); 7666 */ 7667 encrypt: function (cipher, message, password, cfg) { 7668 // Apply config defaults 7669 cfg = this.cfg.extend(cfg); 7670 7671 // Derive key and other params 7672 var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); 7673 7674 // Add IV to config 7675 cfg.iv = derivedParams.iv; 7676 7677 // Encrypt 7678 var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); 7679 7680 // Mix in derived params 7681 ciphertext.mixIn(derivedParams); 7682 7683 return ciphertext; 7684 }, 7685 7686 /** 7687 * Decrypts serialized ciphertext using a password. 7688 * 7689 * @param {Cipher} cipher The cipher algorithm to use. 7690 * @param {CipherParams|string} ciphertext The ciphertext to decrypt. 7691 * @param {string} password The password. 7692 * @param {Object} cfg (Optional) The configuration options to use for this operation. 7693 * 7694 * @return {WordArray} The plaintext. 7695 * 7696 * @static 7697 * 7698 * @example 7699 * 7700 * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); 7701 * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); 7702 */ 7703 decrypt: function (cipher, ciphertext, password, cfg) { 7704 // Apply config defaults 7705 cfg = this.cfg.extend(cfg); 7706 7707 // Convert string to CipherParams 7708 ciphertext = this._parse(ciphertext, cfg.format); 7709 7710 // Derive key and other params 7711 var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); 7712 7713 // Add IV to config 7714 cfg.iv = derivedParams.iv; 7715 7716 // Decrypt 7717 var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); 7718 7719 return plaintext; 7720 } 7721 }); 7722 }()); 7723 7724 7725 })); 7726 },{"./core":53}],53:[function(require,module,exports){ 7727 ;(function (root, factory) { 7728 if (typeof exports === "object") { 7729 // CommonJS 7730 module.exports = exports = factory(); 7731 } 7732 else if (typeof define === "function" && define.amd) { 7733 // AMD 7734 define([], factory); 7735 } 7736 else { 7737 // Global (browser) 7738 root.CryptoJS = factory(); 7739 } 7740 }(this, function () { 7741 7742 /** 7743 * CryptoJS core components. 7744 */ 7745 var CryptoJS = CryptoJS || (function (Math, undefined) { 7746 /* 7747 * Local polyfil of Object.create 7748 */ 7749 var create = Object.create || (function () { 7750 function F() {}; 7751 7752 return function (obj) { 7753 var subtype; 7754 7755 F.prototype = obj; 7756 7757 subtype = new F(); 7758 7759 F.prototype = null; 7760 7761 return subtype; 7762 }; 7763 }()) 7764 7765 /** 7766 * CryptoJS namespace. 7767 */ 7768 var C = {}; 7769 7770 /** 7771 * Library namespace. 7772 */ 7773 var C_lib = C.lib = {}; 7774 7775 /** 7776 * Base object for prototypal inheritance. 7777 */ 7778 var Base = C_lib.Base = (function () { 7779 7780 7781 return { 7782 /** 7783 * Creates a new object that inherits from this object. 7784 * 7785 * @param {Object} overrides Properties to copy into the new object. 7786 * 7787 * @return {Object} The new object. 7788 * 7789 * @static 7790 * 7791 * @example 7792 * 7793 * var MyType = CryptoJS.lib.Base.extend({ 7794 * field: 'value', 7795 * 7796 * method: function () { 7797 * } 7798 * }); 7799 */ 7800 extend: function (overrides) { 7801 // Spawn 7802 var subtype = create(this); 7803 7804 // Augment 7805 if (overrides) { 7806 subtype.mixIn(overrides); 7807 } 7808 7809 // Create default initializer 7810 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { 7811 subtype.init = function () { 7812 subtype.$super.init.apply(this, arguments); 7813 }; 7814 } 7815 7816 // Initializer's prototype is the subtype object 7817 subtype.init.prototype = subtype; 7818 7819 // Reference supertype 7820 subtype.$super = this; 7821 7822 return subtype; 7823 }, 7824 7825 /** 7826 * Extends this object and runs the init method. 7827 * Arguments to create() will be passed to init(). 7828 * 7829 * @return {Object} The new object. 7830 * 7831 * @static 7832 * 7833 * @example 7834 * 7835 * var instance = MyType.create(); 7836 */ 7837 create: function () { 7838 var instance = this.extend(); 7839 instance.init.apply(instance, arguments); 7840 7841 return instance; 7842 }, 7843 7844 /** 7845 * Initializes a newly created object. 7846 * Override this method to add some logic when your objects are created. 7847 * 7848 * @example 7849 * 7850 * var MyType = CryptoJS.lib.Base.extend({ 7851 * init: function () { 7852 * // ... 7853 * } 7854 * }); 7855 */ 7856 init: function () { 7857 }, 7858 7859 /** 7860 * Copies properties into this object. 7861 * 7862 * @param {Object} properties The properties to mix in. 7863 * 7864 * @example 7865 * 7866 * MyType.mixIn({ 7867 * field: 'value' 7868 * }); 7869 */ 7870 mixIn: function (properties) { 7871 for (var propertyName in properties) { 7872 if (properties.hasOwnProperty(propertyName)) { 7873 this[propertyName] = properties[propertyName]; 7874 } 7875 } 7876 7877 // IE won't copy toString using the loop above 7878 if (properties.hasOwnProperty('toString')) { 7879 this.toString = properties.toString; 7880 } 7881 }, 7882 7883 /** 7884 * Creates a copy of this object. 7885 * 7886 * @return {Object} The clone. 7887 * 7888 * @example 7889 * 7890 * var clone = instance.clone(); 7891 */ 7892 clone: function () { 7893 return this.init.prototype.extend(this); 7894 } 7895 }; 7896 }()); 7897 7898 /** 7899 * An array of 32-bit words. 7900 * 7901 * @property {Array} words The array of 32-bit words. 7902 * @property {number} sigBytes The number of significant bytes in this word array. 7903 */ 7904 var WordArray = C_lib.WordArray = Base.extend({ 7905 /** 7906 * Initializes a newly created word array. 7907 * 7908 * @param {Array} words (Optional) An array of 32-bit words. 7909 * @param {number} sigBytes (Optional) The number of significant bytes in the words. 7910 * 7911 * @example 7912 * 7913 * var wordArray = CryptoJS.lib.WordArray.create(); 7914 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); 7915 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); 7916 */ 7917 init: function (words, sigBytes) { 7918 words = this.words = words || []; 7919 7920 if (sigBytes != undefined) { 7921 this.sigBytes = sigBytes; 7922 } else { 7923 this.sigBytes = words.length * 4; 7924 } 7925 }, 7926 7927 /** 7928 * Converts this word array to a string. 7929 * 7930 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex 7931 * 7932 * @return {string} The stringified word array. 7933 * 7934 * @example 7935 * 7936 * var string = wordArray + ''; 7937 * var string = wordArray.toString(); 7938 * var string = wordArray.toString(CryptoJS.enc.Utf8); 7939 */ 7940 toString: function (encoder) { 7941 return (encoder || Hex).stringify(this); 7942 }, 7943 7944 /** 7945 * Concatenates a word array to this word array. 7946 * 7947 * @param {WordArray} wordArray The word array to append. 7948 * 7949 * @return {WordArray} This word array. 7950 * 7951 * @example 7952 * 7953 * wordArray1.concat(wordArray2); 7954 */ 7955 concat: function (wordArray) { 7956 // Shortcuts 7957 var thisWords = this.words; 7958 var thatWords = wordArray.words; 7959 var thisSigBytes = this.sigBytes; 7960 var thatSigBytes = wordArray.sigBytes; 7961 7962 // Clamp excess bits 7963 this.clamp(); 7964 7965 // Concat 7966 if (thisSigBytes % 4) { 7967 // Copy one byte at a time 7968 for (var i = 0; i < thatSigBytes; i++) { 7969 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 7970 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); 7971 } 7972 } else { 7973 // Copy one word at a time 7974 for (var i = 0; i < thatSigBytes; i += 4) { 7975 thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; 7976 } 7977 } 7978 this.sigBytes += thatSigBytes; 7979 7980 // Chainable 7981 return this; 7982 }, 7983 7984 /** 7985 * Removes insignificant bits. 7986 * 7987 * @example 7988 * 7989 * wordArray.clamp(); 7990 */ 7991 clamp: function () { 7992 // Shortcuts 7993 var words = this.words; 7994 var sigBytes = this.sigBytes; 7995 7996 // Clamp 7997 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); 7998 words.length = Math.ceil(sigBytes / 4); 7999 }, 8000 8001 /** 8002 * Creates a copy of this word array. 8003 * 8004 * @return {WordArray} The clone. 8005 * 8006 * @example 8007 * 8008 * var clone = wordArray.clone(); 8009 */ 8010 clone: function () { 8011 var clone = Base.clone.call(this); 8012 clone.words = this.words.slice(0); 8013 8014 return clone; 8015 }, 8016 8017 /** 8018 * Creates a word array filled with random bytes. 8019 * 8020 * @param {number} nBytes The number of random bytes to generate. 8021 * 8022 * @return {WordArray} The random word array. 8023 * 8024 * @static 8025 * 8026 * @example 8027 * 8028 * var wordArray = CryptoJS.lib.WordArray.random(16); 8029 */ 8030 random: function (nBytes) { 8031 var words = []; 8032 8033 var r = (function (m_w) { 8034 var m_w = m_w; 8035 var m_z = 0x3ade68b1; 8036 var mask = 0xffffffff; 8037 8038 return function () { 8039 m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; 8040 m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; 8041 var result = ((m_z << 0x10) + m_w) & mask; 8042 result /= 0x100000000; 8043 result += 0.5; 8044 return result * (Math.random() > .5 ? 1 : -1); 8045 } 8046 }); 8047 8048 for (var i = 0, rcache; i < nBytes; i += 4) { 8049 var _r = r((rcache || Math.random()) * 0x100000000); 8050 8051 rcache = _r() * 0x3ade67b7; 8052 words.push((_r() * 0x100000000) | 0); 8053 } 8054 8055 return new WordArray.init(words, nBytes); 8056 } 8057 }); 8058 8059 /** 8060 * Encoder namespace. 8061 */ 8062 var C_enc = C.enc = {}; 8063 8064 /** 8065 * Hex encoding strategy. 8066 */ 8067 var Hex = C_enc.Hex = { 8068 /** 8069 * Converts a word array to a hex string. 8070 * 8071 * @param {WordArray} wordArray The word array. 8072 * 8073 * @return {string} The hex string. 8074 * 8075 * @static 8076 * 8077 * @example 8078 * 8079 * var hexString = CryptoJS.enc.Hex.stringify(wordArray); 8080 */ 8081 stringify: function (wordArray) { 8082 // Shortcuts 8083 var words = wordArray.words; 8084 var sigBytes = wordArray.sigBytes; 8085 8086 // Convert 8087 var hexChars = []; 8088 for (var i = 0; i < sigBytes; i++) { 8089 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 8090 hexChars.push((bite >>> 4).toString(16)); 8091 hexChars.push((bite & 0x0f).toString(16)); 8092 } 8093 8094 return hexChars.join(''); 8095 }, 8096 8097 /** 8098 * Converts a hex string to a word array. 8099 * 8100 * @param {string} hexStr The hex string. 8101 * 8102 * @return {WordArray} The word array. 8103 * 8104 * @static 8105 * 8106 * @example 8107 * 8108 * var wordArray = CryptoJS.enc.Hex.parse(hexString); 8109 */ 8110 parse: function (hexStr) { 8111 // Shortcut 8112 var hexStrLength = hexStr.length; 8113 8114 // Convert 8115 var words = []; 8116 for (var i = 0; i < hexStrLength; i += 2) { 8117 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); 8118 } 8119 8120 return new WordArray.init(words, hexStrLength / 2); 8121 } 8122 }; 8123 8124 /** 8125 * Latin1 encoding strategy. 8126 */ 8127 var Latin1 = C_enc.Latin1 = { 8128 /** 8129 * Converts a word array to a Latin1 string. 8130 * 8131 * @param {WordArray} wordArray The word array. 8132 * 8133 * @return {string} The Latin1 string. 8134 * 8135 * @static 8136 * 8137 * @example 8138 * 8139 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); 8140 */ 8141 stringify: function (wordArray) { 8142 // Shortcuts 8143 var words = wordArray.words; 8144 var sigBytes = wordArray.sigBytes; 8145 8146 // Convert 8147 var latin1Chars = []; 8148 for (var i = 0; i < sigBytes; i++) { 8149 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 8150 latin1Chars.push(String.fromCharCode(bite)); 8151 } 8152 8153 return latin1Chars.join(''); 8154 }, 8155 8156 /** 8157 * Converts a Latin1 string to a word array. 8158 * 8159 * @param {string} latin1Str The Latin1 string. 8160 * 8161 * @return {WordArray} The word array. 8162 * 8163 * @static 8164 * 8165 * @example 8166 * 8167 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); 8168 */ 8169 parse: function (latin1Str) { 8170 // Shortcut 8171 var latin1StrLength = latin1Str.length; 8172 8173 // Convert 8174 var words = []; 8175 for (var i = 0; i < latin1StrLength; i++) { 8176 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); 8177 } 8178 8179 return new WordArray.init(words, latin1StrLength); 8180 } 8181 }; 8182 8183 /** 8184 * UTF-8 encoding strategy. 8185 */ 8186 var Utf8 = C_enc.Utf8 = { 8187 /** 8188 * Converts a word array to a UTF-8 string. 8189 * 8190 * @param {WordArray} wordArray The word array. 8191 * 8192 * @return {string} The UTF-8 string. 8193 * 8194 * @static 8195 * 8196 * @example 8197 * 8198 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); 8199 */ 8200 stringify: function (wordArray) { 8201 try { 8202 return decodeURIComponent(escape(Latin1.stringify(wordArray))); 8203 } catch (e) { 8204 throw new Error('Malformed UTF-8 data'); 8205 } 8206 }, 8207 8208 /** 8209 * Converts a UTF-8 string to a word array. 8210 * 8211 * @param {string} utf8Str The UTF-8 string. 8212 * 8213 * @return {WordArray} The word array. 8214 * 8215 * @static 8216 * 8217 * @example 8218 * 8219 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); 8220 */ 8221 parse: function (utf8Str) { 8222 return Latin1.parse(unescape(encodeURIComponent(utf8Str))); 8223 } 8224 }; 8225 8226 /** 8227 * Abstract buffered block algorithm template. 8228 * 8229 * The property blockSize must be implemented in a concrete subtype. 8230 * 8231 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 8232 */ 8233 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ 8234 /** 8235 * Resets this block algorithm's data buffer to its initial state. 8236 * 8237 * @example 8238 * 8239 * bufferedBlockAlgorithm.reset(); 8240 */ 8241 reset: function () { 8242 // Initial values 8243 this._data = new WordArray.init(); 8244 this._nDataBytes = 0; 8245 }, 8246 8247 /** 8248 * Adds new data to this block algorithm's buffer. 8249 * 8250 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. 8251 * 8252 * @example 8253 * 8254 * bufferedBlockAlgorithm._append('data'); 8255 * bufferedBlockAlgorithm._append(wordArray); 8256 */ 8257 _append: function (data) { 8258 // Convert string to WordArray, else assume WordArray already 8259 if (typeof data == 'string') { 8260 data = Utf8.parse(data); 8261 } 8262 8263 // Append 8264 this._data.concat(data); 8265 this._nDataBytes += data.sigBytes; 8266 }, 8267 8268 /** 8269 * Processes available data blocks. 8270 * 8271 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. 8272 * 8273 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. 8274 * 8275 * @return {WordArray} The processed data. 8276 * 8277 * @example 8278 * 8279 * var processedData = bufferedBlockAlgorithm._process(); 8280 * var processedData = bufferedBlockAlgorithm._process(!!'flush'); 8281 */ 8282 _process: function (doFlush) { 8283 // Shortcuts 8284 var data = this._data; 8285 var dataWords = data.words; 8286 var dataSigBytes = data.sigBytes; 8287 var blockSize = this.blockSize; 8288 var blockSizeBytes = blockSize * 4; 8289 8290 // Count blocks ready 8291 var nBlocksReady = dataSigBytes / blockSizeBytes; 8292 if (doFlush) { 8293 // Round up to include partial blocks 8294 nBlocksReady = Math.ceil(nBlocksReady); 8295 } else { 8296 // Round down to include only full blocks, 8297 // less the number of blocks that must remain in the buffer 8298 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); 8299 } 8300 8301 // Count words ready 8302 var nWordsReady = nBlocksReady * blockSize; 8303 8304 // Count bytes ready 8305 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); 8306 8307 // Process blocks 8308 if (nWordsReady) { 8309 for (var offset = 0; offset < nWordsReady; offset += blockSize) { 8310 // Perform concrete-algorithm logic 8311 this._doProcessBlock(dataWords, offset); 8312 } 8313 8314 // Remove processed words 8315 var processedWords = dataWords.splice(0, nWordsReady); 8316 data.sigBytes -= nBytesReady; 8317 } 8318 8319 // Return processed words 8320 return new WordArray.init(processedWords, nBytesReady); 8321 }, 8322 8323 /** 8324 * Creates a copy of this object. 8325 * 8326 * @return {Object} The clone. 8327 * 8328 * @example 8329 * 8330 * var clone = bufferedBlockAlgorithm.clone(); 8331 */ 8332 clone: function () { 8333 var clone = Base.clone.call(this); 8334 clone._data = this._data.clone(); 8335 8336 return clone; 8337 }, 8338 8339 _minBufferSize: 0 8340 }); 8341 8342 /** 8343 * Abstract hasher template. 8344 * 8345 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) 8346 */ 8347 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ 8348 /** 8349 * Configuration options. 8350 */ 8351 cfg: Base.extend(), 8352 8353 /** 8354 * Initializes a newly created hasher. 8355 * 8356 * @param {Object} cfg (Optional) The configuration options to use for this hash computation. 8357 * 8358 * @example 8359 * 8360 * var hasher = CryptoJS.algo.SHA256.create(); 8361 */ 8362 init: function (cfg) { 8363 // Apply config defaults 8364 this.cfg = this.cfg.extend(cfg); 8365 8366 // Set initial values 8367 this.reset(); 8368 }, 8369 8370 /** 8371 * Resets this hasher to its initial state. 8372 * 8373 * @example 8374 * 8375 * hasher.reset(); 8376 */ 8377 reset: function () { 8378 // Reset data buffer 8379 BufferedBlockAlgorithm.reset.call(this); 8380 8381 // Perform concrete-hasher logic 8382 this._doReset(); 8383 }, 8384 8385 /** 8386 * Updates this hasher with a message. 8387 * 8388 * @param {WordArray|string} messageUpdate The message to append. 8389 * 8390 * @return {Hasher} This hasher. 8391 * 8392 * @example 8393 * 8394 * hasher.update('message'); 8395 * hasher.update(wordArray); 8396 */ 8397 update: function (messageUpdate) { 8398 // Append 8399 this._append(messageUpdate); 8400 8401 // Update the hash 8402 this._process(); 8403 8404 // Chainable 8405 return this; 8406 }, 8407 8408 /** 8409 * Finalizes the hash computation. 8410 * Note that the finalize operation is effectively a destructive, read-once operation. 8411 * 8412 * @param {WordArray|string} messageUpdate (Optional) A final message update. 8413 * 8414 * @return {WordArray} The hash. 8415 * 8416 * @example 8417 * 8418 * var hash = hasher.finalize(); 8419 * var hash = hasher.finalize('message'); 8420 * var hash = hasher.finalize(wordArray); 8421 */ 8422 finalize: function (messageUpdate) { 8423 // Final message update 8424 if (messageUpdate) { 8425 this._append(messageUpdate); 8426 } 8427 8428 // Perform concrete-hasher logic 8429 var hash = this._doFinalize(); 8430 8431 return hash; 8432 }, 8433 8434 blockSize: 512/32, 8435 8436 /** 8437 * Creates a shortcut function to a hasher's object interface. 8438 * 8439 * @param {Hasher} hasher The hasher to create a helper for. 8440 * 8441 * @return {Function} The shortcut function. 8442 * 8443 * @static 8444 * 8445 * @example 8446 * 8447 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); 8448 */ 8449 _createHelper: function (hasher) { 8450 return function (message, cfg) { 8451 return new hasher.init(cfg).finalize(message); 8452 }; 8453 }, 8454 8455 /** 8456 * Creates a shortcut function to the HMAC's object interface. 8457 * 8458 * @param {Hasher} hasher The hasher to use in this HMAC helper. 8459 * 8460 * @return {Function} The shortcut function. 8461 * 8462 * @static 8463 * 8464 * @example 8465 * 8466 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); 8467 */ 8468 _createHmacHelper: function (hasher) { 8469 return function (message, key) { 8470 return new C_algo.HMAC.init(hasher, key).finalize(message); 8471 }; 8472 } 8473 }); 8474 8475 /** 8476 * Algorithm namespace. 8477 */ 8478 var C_algo = C.algo = {}; 8479 8480 return C; 8481 }(Math)); 8482 8483 8484 return CryptoJS; 8485 8486 })); 8487 },{}],54:[function(require,module,exports){ 8488 ;(function (root, factory) { 8489 if (typeof exports === "object") { 8490 // CommonJS 8491 module.exports = exports = factory(require("./core")); 8492 } 8493 else if (typeof define === "function" && define.amd) { 8494 // AMD 8495 define(["./core"], factory); 8496 } 8497 else { 8498 // Global (browser) 8499 factory(root.CryptoJS); 8500 } 8501 }(this, function (CryptoJS) { 8502 8503 (function () { 8504 // Shortcuts 8505 var C = CryptoJS; 8506 var C_lib = C.lib; 8507 var WordArray = C_lib.WordArray; 8508 var C_enc = C.enc; 8509 8510 /** 8511 * Base64 encoding strategy. 8512 */ 8513 var Base64 = C_enc.Base64 = { 8514 /** 8515 * Converts a word array to a Base64 string. 8516 * 8517 * @param {WordArray} wordArray The word array. 8518 * 8519 * @return {string} The Base64 string. 8520 * 8521 * @static 8522 * 8523 * @example 8524 * 8525 * var base64String = CryptoJS.enc.Base64.stringify(wordArray); 8526 */ 8527 stringify: function (wordArray) { 8528 // Shortcuts 8529 var words = wordArray.words; 8530 var sigBytes = wordArray.sigBytes; 8531 var map = this._map; 8532 8533 // Clamp excess bits 8534 wordArray.clamp(); 8535 8536 // Convert 8537 var base64Chars = []; 8538 for (var i = 0; i < sigBytes; i += 3) { 8539 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; 8540 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; 8541 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; 8542 8543 var triplet = (byte1 << 16) | (byte2 << 8) | byte3; 8544 8545 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { 8546 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); 8547 } 8548 } 8549 8550 // Add padding 8551 var paddingChar = map.charAt(64); 8552 if (paddingChar) { 8553 while (base64Chars.length % 4) { 8554 base64Chars.push(paddingChar); 8555 } 8556 } 8557 8558 return base64Chars.join(''); 8559 }, 8560 8561 /** 8562 * Converts a Base64 string to a word array. 8563 * 8564 * @param {string} base64Str The Base64 string. 8565 * 8566 * @return {WordArray} The word array. 8567 * 8568 * @static 8569 * 8570 * @example 8571 * 8572 * var wordArray = CryptoJS.enc.Base64.parse(base64String); 8573 */ 8574 parse: function (base64Str) { 8575 // Shortcuts 8576 var base64StrLength = base64Str.length; 8577 var map = this._map; 8578 var reverseMap = this._reverseMap; 8579 8580 if (!reverseMap) { 8581 reverseMap = this._reverseMap = []; 8582 for (var j = 0; j < map.length; j++) { 8583 reverseMap[map.charCodeAt(j)] = j; 8584 } 8585 } 8586 8587 // Ignore padding 8588 var paddingChar = map.charAt(64); 8589 if (paddingChar) { 8590 var paddingIndex = base64Str.indexOf(paddingChar); 8591 if (paddingIndex !== -1) { 8592 base64StrLength = paddingIndex; 8593 } 8594 } 8595 8596 // Convert 8597 return parseLoop(base64Str, base64StrLength, reverseMap); 8598 8599 }, 8600 8601 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' 8602 }; 8603 8604 function parseLoop(base64Str, base64StrLength, reverseMap) { 8605 var words = []; 8606 var nBytes = 0; 8607 for (var i = 0; i < base64StrLength; i++) { 8608 if (i % 4) { 8609 var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); 8610 var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); 8611 words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); 8612 nBytes++; 8613 } 8614 } 8615 return WordArray.create(words, nBytes); 8616 } 8617 }()); 8618 8619 8620 return CryptoJS.enc.Base64; 8621 8622 })); 8623 },{"./core":53}],55:[function(require,module,exports){ 8624 ;(function (root, factory) { 8625 if (typeof exports === "object") { 8626 // CommonJS 8627 module.exports = exports = factory(require("./core")); 8628 } 8629 else if (typeof define === "function" && define.amd) { 8630 // AMD 8631 define(["./core"], factory); 8632 } 8633 else { 8634 // Global (browser) 8635 factory(root.CryptoJS); 8636 } 8637 }(this, function (CryptoJS) { 8638 8639 (function () { 8640 // Shortcuts 8641 var C = CryptoJS; 8642 var C_lib = C.lib; 8643 var WordArray = C_lib.WordArray; 8644 var C_enc = C.enc; 8645 8646 /** 8647 * UTF-16 BE encoding strategy. 8648 */ 8649 var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { 8650 /** 8651 * Converts a word array to a UTF-16 BE string. 8652 * 8653 * @param {WordArray} wordArray The word array. 8654 * 8655 * @return {string} The UTF-16 BE string. 8656 * 8657 * @static 8658 * 8659 * @example 8660 * 8661 * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); 8662 */ 8663 stringify: function (wordArray) { 8664 // Shortcuts 8665 var words = wordArray.words; 8666 var sigBytes = wordArray.sigBytes; 8667 8668 // Convert 8669 var utf16Chars = []; 8670 for (var i = 0; i < sigBytes; i += 2) { 8671 var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; 8672 utf16Chars.push(String.fromCharCode(codePoint)); 8673 } 8674 8675 return utf16Chars.join(''); 8676 }, 8677 8678 /** 8679 * Converts a UTF-16 BE string to a word array. 8680 * 8681 * @param {string} utf16Str The UTF-16 BE string. 8682 * 8683 * @return {WordArray} The word array. 8684 * 8685 * @static 8686 * 8687 * @example 8688 * 8689 * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); 8690 */ 8691 parse: function (utf16Str) { 8692 // Shortcut 8693 var utf16StrLength = utf16Str.length; 8694 8695 // Convert 8696 var words = []; 8697 for (var i = 0; i < utf16StrLength; i++) { 8698 words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); 8699 } 8700 8701 return WordArray.create(words, utf16StrLength * 2); 8702 } 8703 }; 8704 8705 /** 8706 * UTF-16 LE encoding strategy. 8707 */ 8708 C_enc.Utf16LE = { 8709 /** 8710 * Converts a word array to a UTF-16 LE string. 8711 * 8712 * @param {WordArray} wordArray The word array. 8713 * 8714 * @return {string} The UTF-16 LE string. 8715 * 8716 * @static 8717 * 8718 * @example 8719 * 8720 * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); 8721 */ 8722 stringify: function (wordArray) { 8723 // Shortcuts 8724 var words = wordArray.words; 8725 var sigBytes = wordArray.sigBytes; 8726 8727 // Convert 8728 var utf16Chars = []; 8729 for (var i = 0; i < sigBytes; i += 2) { 8730 var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); 8731 utf16Chars.push(String.fromCharCode(codePoint)); 8732 } 8733 8734 return utf16Chars.join(''); 8735 }, 8736 8737 /** 8738 * Converts a UTF-16 LE string to a word array. 8739 * 8740 * @param {string} utf16Str The UTF-16 LE string. 8741 * 8742 * @return {WordArray} The word array. 8743 * 8744 * @static 8745 * 8746 * @example 8747 * 8748 * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); 8749 */ 8750 parse: function (utf16Str) { 8751 // Shortcut 8752 var utf16StrLength = utf16Str.length; 8753 8754 // Convert 8755 var words = []; 8756 for (var i = 0; i < utf16StrLength; i++) { 8757 words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); 8758 } 8759 8760 return WordArray.create(words, utf16StrLength * 2); 8761 } 8762 }; 8763 8764 function swapEndian(word) { 8765 return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); 8766 } 8767 }()); 8768 8769 8770 return CryptoJS.enc.Utf16; 8771 8772 })); 8773 },{"./core":53}],56:[function(require,module,exports){ 8774 ;(function (root, factory, undef) { 8775 if (typeof exports === "object") { 8776 // CommonJS 8777 module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); 8778 } 8779 else if (typeof define === "function" && define.amd) { 8780 // AMD 8781 define(["./core", "./sha1", "./hmac"], factory); 8782 } 8783 else { 8784 // Global (browser) 8785 factory(root.CryptoJS); 8786 } 8787 }(this, function (CryptoJS) { 8788 8789 (function () { 8790 // Shortcuts 8791 var C = CryptoJS; 8792 var C_lib = C.lib; 8793 var Base = C_lib.Base; 8794 var WordArray = C_lib.WordArray; 8795 var C_algo = C.algo; 8796 var MD5 = C_algo.MD5; 8797 8798 /** 8799 * This key derivation function is meant to conform with EVP_BytesToKey. 8800 * www.openssl.org/docs/crypto/EVP_BytesToKey.html 8801 */ 8802 var EvpKDF = C_algo.EvpKDF = Base.extend({ 8803 /** 8804 * Configuration options. 8805 * 8806 * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) 8807 * @property {Hasher} hasher The hash algorithm to use. Default: MD5 8808 * @property {number} iterations The number of iterations to perform. Default: 1 8809 */ 8810 cfg: Base.extend({ 8811 keySize: 128/32, 8812 hasher: MD5, 8813 iterations: 1 8814 }), 8815 8816 /** 8817 * Initializes a newly created key derivation function. 8818 * 8819 * @param {Object} cfg (Optional) The configuration options to use for the derivation. 8820 * 8821 * @example 8822 * 8823 * var kdf = CryptoJS.algo.EvpKDF.create(); 8824 * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); 8825 * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); 8826 */ 8827 init: function (cfg) { 8828 this.cfg = this.cfg.extend(cfg); 8829 }, 8830 8831 /** 8832 * Derives a key from a password. 8833 * 8834 * @param {WordArray|string} password The password. 8835 * @param {WordArray|string} salt A salt. 8836 * 8837 * @return {WordArray} The derived key. 8838 * 8839 * @example 8840 * 8841 * var key = kdf.compute(password, salt); 8842 */ 8843 compute: function (password, salt) { 8844 // Shortcut 8845 var cfg = this.cfg; 8846 8847 // Init hasher 8848 var hasher = cfg.hasher.create(); 8849 8850 // Initial values 8851 var derivedKey = WordArray.create(); 8852 8853 // Shortcuts 8854 var derivedKeyWords = derivedKey.words; 8855 var keySize = cfg.keySize; 8856 var iterations = cfg.iterations; 8857 8858 // Generate key 8859 while (derivedKeyWords.length < keySize) { 8860 if (block) { 8861 hasher.update(block); 8862 } 8863 var block = hasher.update(password).finalize(salt); 8864 hasher.reset(); 8865 8866 // Iterations 8867 for (var i = 1; i < iterations; i++) { 8868 block = hasher.finalize(block); 8869 hasher.reset(); 8870 } 8871 8872 derivedKey.concat(block); 8873 } 8874 derivedKey.sigBytes = keySize * 4; 8875 8876 return derivedKey; 8877 } 8878 }); 8879 8880 /** 8881 * Derives a key from a password. 8882 * 8883 * @param {WordArray|string} password The password. 8884 * @param {WordArray|string} salt A salt. 8885 * @param {Object} cfg (Optional) The configuration options to use for this computation. 8886 * 8887 * @return {WordArray} The derived key. 8888 * 8889 * @static 8890 * 8891 * @example 8892 * 8893 * var key = CryptoJS.EvpKDF(password, salt); 8894 * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); 8895 * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); 8896 */ 8897 C.EvpKDF = function (password, salt, cfg) { 8898 return EvpKDF.create(cfg).compute(password, salt); 8899 }; 8900 }()); 8901 8902 8903 return CryptoJS.EvpKDF; 8904 8905 })); 8906 },{"./core":53,"./hmac":58,"./sha1":77}],57:[function(require,module,exports){ 8907 ;(function (root, factory, undef) { 8908 if (typeof exports === "object") { 8909 // CommonJS 8910 module.exports = exports = factory(require("./core"), require("./cipher-core")); 8911 } 8912 else if (typeof define === "function" && define.amd) { 8913 // AMD 8914 define(["./core", "./cipher-core"], factory); 8915 } 8916 else { 8917 // Global (browser) 8918 factory(root.CryptoJS); 8919 } 8920 }(this, function (CryptoJS) { 8921 8922 (function (undefined) { 8923 // Shortcuts 8924 var C = CryptoJS; 8925 var C_lib = C.lib; 8926 var CipherParams = C_lib.CipherParams; 8927 var C_enc = C.enc; 8928 var Hex = C_enc.Hex; 8929 var C_format = C.format; 8930 8931 var HexFormatter = C_format.Hex = { 8932 /** 8933 * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. 8934 * 8935 * @param {CipherParams} cipherParams The cipher params object. 8936 * 8937 * @return {string} The hexadecimally encoded string. 8938 * 8939 * @static 8940 * 8941 * @example 8942 * 8943 * var hexString = CryptoJS.format.Hex.stringify(cipherParams); 8944 */ 8945 stringify: function (cipherParams) { 8946 return cipherParams.ciphertext.toString(Hex); 8947 }, 8948 8949 /** 8950 * Converts a hexadecimally encoded ciphertext string to a cipher params object. 8951 * 8952 * @param {string} input The hexadecimally encoded string. 8953 * 8954 * @return {CipherParams} The cipher params object. 8955 * 8956 * @static 8957 * 8958 * @example 8959 * 8960 * var cipherParams = CryptoJS.format.Hex.parse(hexString); 8961 */ 8962 parse: function (input) { 8963 var ciphertext = Hex.parse(input); 8964 return CipherParams.create({ ciphertext: ciphertext }); 8965 } 8966 }; 8967 }()); 8968 8969 8970 return CryptoJS.format.Hex; 8971 8972 })); 8973 },{"./cipher-core":52,"./core":53}],58:[function(require,module,exports){ 8974 ;(function (root, factory) { 8975 if (typeof exports === "object") { 8976 // CommonJS 8977 module.exports = exports = factory(require("./core")); 8978 } 8979 else if (typeof define === "function" && define.amd) { 8980 // AMD 8981 define(["./core"], factory); 8982 } 8983 else { 8984 // Global (browser) 8985 factory(root.CryptoJS); 8986 } 8987 }(this, function (CryptoJS) { 8988 8989 (function () { 8990 // Shortcuts 8991 var C = CryptoJS; 8992 var C_lib = C.lib; 8993 var Base = C_lib.Base; 8994 var C_enc = C.enc; 8995 var Utf8 = C_enc.Utf8; 8996 var C_algo = C.algo; 8997 8998 /** 8999 * HMAC algorithm. 9000 */ 9001 var HMAC = C_algo.HMAC = Base.extend({ 9002 /** 9003 * Initializes a newly created HMAC. 9004 * 9005 * @param {Hasher} hasher The hash algorithm to use. 9006 * @param {WordArray|string} key The secret key. 9007 * 9008 * @example 9009 * 9010 * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); 9011 */ 9012 init: function (hasher, key) { 9013 // Init hasher 9014 hasher = this._hasher = new hasher.init(); 9015 9016 // Convert string to WordArray, else assume WordArray already 9017 if (typeof key == 'string') { 9018 key = Utf8.parse(key); 9019 } 9020 9021 // Shortcuts 9022 var hasherBlockSize = hasher.blockSize; 9023 var hasherBlockSizeBytes = hasherBlockSize * 4; 9024 9025 // Allow arbitrary length keys 9026 if (key.sigBytes > hasherBlockSizeBytes) { 9027 key = hasher.finalize(key); 9028 } 9029 9030 // Clamp excess bits 9031 key.clamp(); 9032 9033 // Clone key for inner and outer pads 9034 var oKey = this._oKey = key.clone(); 9035 var iKey = this._iKey = key.clone(); 9036 9037 // Shortcuts 9038 var oKeyWords = oKey.words; 9039 var iKeyWords = iKey.words; 9040 9041 // XOR keys with pad constants 9042 for (var i = 0; i < hasherBlockSize; i++) { 9043 oKeyWords[i] ^= 0x5c5c5c5c; 9044 iKeyWords[i] ^= 0x36363636; 9045 } 9046 oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; 9047 9048 // Set initial values 9049 this.reset(); 9050 }, 9051 9052 /** 9053 * Resets this HMAC to its initial state. 9054 * 9055 * @example 9056 * 9057 * hmacHasher.reset(); 9058 */ 9059 reset: function () { 9060 // Shortcut 9061 var hasher = this._hasher; 9062 9063 // Reset 9064 hasher.reset(); 9065 hasher.update(this._iKey); 9066 }, 9067 9068 /** 9069 * Updates this HMAC with a message. 9070 * 9071 * @param {WordArray|string} messageUpdate The message to append. 9072 * 9073 * @return {HMAC} This HMAC instance. 9074 * 9075 * @example 9076 * 9077 * hmacHasher.update('message'); 9078 * hmacHasher.update(wordArray); 9079 */ 9080 update: function (messageUpdate) { 9081 this._hasher.update(messageUpdate); 9082 9083 // Chainable 9084 return this; 9085 }, 9086 9087 /** 9088 * Finalizes the HMAC computation. 9089 * Note that the finalize operation is effectively a destructive, read-once operation. 9090 * 9091 * @param {WordArray|string} messageUpdate (Optional) A final message update. 9092 * 9093 * @return {WordArray} The HMAC. 9094 * 9095 * @example 9096 * 9097 * var hmac = hmacHasher.finalize(); 9098 * var hmac = hmacHasher.finalize('message'); 9099 * var hmac = hmacHasher.finalize(wordArray); 9100 */ 9101 finalize: function (messageUpdate) { 9102 // Shortcut 9103 var hasher = this._hasher; 9104 9105 // Compute HMAC 9106 var innerHash = hasher.finalize(messageUpdate); 9107 hasher.reset(); 9108 var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); 9109 9110 return hmac; 9111 } 9112 }); 9113 }()); 9114 9115 9116 })); 9117 },{"./core":53}],59:[function(require,module,exports){ 9118 ;(function (root, factory, undef) { 9119 if (typeof exports === "object") { 9120 // CommonJS 9121 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")); 9122 } 9123 else if (typeof define === "function" && define.amd) { 9124 // AMD 9125 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); 9126 } 9127 else { 9128 // Global (browser) 9129 root.CryptoJS = factory(root.CryptoJS); 9130 } 9131 }(this, function (CryptoJS) { 9132 9133 return CryptoJS; 9134 9135 })); 9136 },{"./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){ 9137 ;(function (root, factory) { 9138 if (typeof exports === "object") { 9139 // CommonJS 9140 module.exports = exports = factory(require("./core")); 9141 } 9142 else if (typeof define === "function" && define.amd) { 9143 // AMD 9144 define(["./core"], factory); 9145 } 9146 else { 9147 // Global (browser) 9148 factory(root.CryptoJS); 9149 } 9150 }(this, function (CryptoJS) { 9151 9152 (function () { 9153 // Check if typed arrays are supported 9154 if (typeof ArrayBuffer != 'function') { 9155 return; 9156 } 9157 9158 // Shortcuts 9159 var C = CryptoJS; 9160 var C_lib = C.lib; 9161 var WordArray = C_lib.WordArray; 9162 9163 // Reference original init 9164 var superInit = WordArray.init; 9165 9166 // Augment WordArray.init to handle typed arrays 9167 var subInit = WordArray.init = function (typedArray) { 9168 // Convert buffers to uint8 9169 if (typedArray instanceof ArrayBuffer) { 9170 typedArray = new Uint8Array(typedArray); 9171 } 9172 9173 // Convert other array views to uint8 9174 if ( 9175 typedArray instanceof Int8Array || 9176 (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || 9177 typedArray instanceof Int16Array || 9178 typedArray instanceof Uint16Array || 9179 typedArray instanceof Int32Array || 9180 typedArray instanceof Uint32Array || 9181 typedArray instanceof Float32Array || 9182 typedArray instanceof Float64Array 9183 ) { 9184 typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); 9185 } 9186 9187 // Handle Uint8Array 9188 if (typedArray instanceof Uint8Array) { 9189 // Shortcut 9190 var typedArrayByteLength = typedArray.byteLength; 9191 9192 // Extract bytes 9193 var words = []; 9194 for (var i = 0; i < typedArrayByteLength; i++) { 9195 words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); 9196 } 9197 9198 // Initialize this word array 9199 superInit.call(this, words, typedArrayByteLength); 9200 } else { 9201 // Else call normal init 9202 superInit.apply(this, arguments); 9203 } 9204 }; 9205 9206 subInit.prototype = WordArray; 9207 }()); 9208 9209 9210 return CryptoJS.lib.WordArray; 9211 9212 })); 9213 },{"./core":53}],61:[function(require,module,exports){ 9214 ;(function (root, factory) { 9215 if (typeof exports === "object") { 9216 // CommonJS 9217 module.exports = exports = factory(require("./core")); 9218 } 9219 else if (typeof define === "function" && define.amd) { 9220 // AMD 9221 define(["./core"], factory); 9222 } 9223 else { 9224 // Global (browser) 9225 factory(root.CryptoJS); 9226 } 9227 }(this, function (CryptoJS) { 9228 9229 (function (Math) { 9230 // Shortcuts 9231 var C = CryptoJS; 9232 var C_lib = C.lib; 9233 var WordArray = C_lib.WordArray; 9234 var Hasher = C_lib.Hasher; 9235 var C_algo = C.algo; 9236 9237 // Constants table 9238 var T = []; 9239 9240 // Compute constants 9241 (function () { 9242 for (var i = 0; i < 64; i++) { 9243 T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; 9244 } 9245 }()); 9246 9247 /** 9248 * MD5 hash algorithm. 9249 */ 9250 var MD5 = C_algo.MD5 = Hasher.extend({ 9251 _doReset: function () { 9252 this._hash = new WordArray.init([ 9253 0x67452301, 0xefcdab89, 9254 0x98badcfe, 0x10325476 9255 ]); 9256 }, 9257 9258 _doProcessBlock: function (M, offset) { 9259 // Swap endian 9260 for (var i = 0; i < 16; i++) { 9261 // Shortcuts 9262 var offset_i = offset + i; 9263 var M_offset_i = M[offset_i]; 9264 9265 M[offset_i] = ( 9266 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | 9267 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) 9268 ); 9269 } 9270 9271 // Shortcuts 9272 var H = this._hash.words; 9273 9274 var M_offset_0 = M[offset + 0]; 9275 var M_offset_1 = M[offset + 1]; 9276 var M_offset_2 = M[offset + 2]; 9277 var M_offset_3 = M[offset + 3]; 9278 var M_offset_4 = M[offset + 4]; 9279 var M_offset_5 = M[offset + 5]; 9280 var M_offset_6 = M[offset + 6]; 9281 var M_offset_7 = M[offset + 7]; 9282 var M_offset_8 = M[offset + 8]; 9283 var M_offset_9 = M[offset + 9]; 9284 var M_offset_10 = M[offset + 10]; 9285 var M_offset_11 = M[offset + 11]; 9286 var M_offset_12 = M[offset + 12]; 9287 var M_offset_13 = M[offset + 13]; 9288 var M_offset_14 = M[offset + 14]; 9289 var M_offset_15 = M[offset + 15]; 9290 9291 // Working varialbes 9292 var a = H[0]; 9293 var b = H[1]; 9294 var c = H[2]; 9295 var d = H[3]; 9296 9297 // Computation 9298 a = FF(a, b, c, d, M_offset_0, 7, T[0]); 9299 d = FF(d, a, b, c, M_offset_1, 12, T[1]); 9300 c = FF(c, d, a, b, M_offset_2, 17, T[2]); 9301 b = FF(b, c, d, a, M_offset_3, 22, T[3]); 9302 a = FF(a, b, c, d, M_offset_4, 7, T[4]); 9303 d = FF(d, a, b, c, M_offset_5, 12, T[5]); 9304 c = FF(c, d, a, b, M_offset_6, 17, T[6]); 9305 b = FF(b, c, d, a, M_offset_7, 22, T[7]); 9306 a = FF(a, b, c, d, M_offset_8, 7, T[8]); 9307 d = FF(d, a, b, c, M_offset_9, 12, T[9]); 9308 c = FF(c, d, a, b, M_offset_10, 17, T[10]); 9309 b = FF(b, c, d, a, M_offset_11, 22, T[11]); 9310 a = FF(a, b, c, d, M_offset_12, 7, T[12]); 9311 d = FF(d, a, b, c, M_offset_13, 12, T[13]); 9312 c = FF(c, d, a, b, M_offset_14, 17, T[14]); 9313 b = FF(b, c, d, a, M_offset_15, 22, T[15]); 9314 9315 a = GG(a, b, c, d, M_offset_1, 5, T[16]); 9316 d = GG(d, a, b, c, M_offset_6, 9, T[17]); 9317 c = GG(c, d, a, b, M_offset_11, 14, T[18]); 9318 b = GG(b, c, d, a, M_offset_0, 20, T[19]); 9319 a = GG(a, b, c, d, M_offset_5, 5, T[20]); 9320 d = GG(d, a, b, c, M_offset_10, 9, T[21]); 9321 c = GG(c, d, a, b, M_offset_15, 14, T[22]); 9322 b = GG(b, c, d, a, M_offset_4, 20, T[23]); 9323 a = GG(a, b, c, d, M_offset_9, 5, T[24]); 9324 d = GG(d, a, b, c, M_offset_14, 9, T[25]); 9325 c = GG(c, d, a, b, M_offset_3, 14, T[26]); 9326 b = GG(b, c, d, a, M_offset_8, 20, T[27]); 9327 a = GG(a, b, c, d, M_offset_13, 5, T[28]); 9328 d = GG(d, a, b, c, M_offset_2, 9, T[29]); 9329 c = GG(c, d, a, b, M_offset_7, 14, T[30]); 9330 b = GG(b, c, d, a, M_offset_12, 20, T[31]); 9331 9332 a = HH(a, b, c, d, M_offset_5, 4, T[32]); 9333 d = HH(d, a, b, c, M_offset_8, 11, T[33]); 9334 c = HH(c, d, a, b, M_offset_11, 16, T[34]); 9335 b = HH(b, c, d, a, M_offset_14, 23, T[35]); 9336 a = HH(a, b, c, d, M_offset_1, 4, T[36]); 9337 d = HH(d, a, b, c, M_offset_4, 11, T[37]); 9338 c = HH(c, d, a, b, M_offset_7, 16, T[38]); 9339 b = HH(b, c, d, a, M_offset_10, 23, T[39]); 9340 a = HH(a, b, c, d, M_offset_13, 4, T[40]); 9341 d = HH(d, a, b, c, M_offset_0, 11, T[41]); 9342 c = HH(c, d, a, b, M_offset_3, 16, T[42]); 9343 b = HH(b, c, d, a, M_offset_6, 23, T[43]); 9344 a = HH(a, b, c, d, M_offset_9, 4, T[44]); 9345 d = HH(d, a, b, c, M_offset_12, 11, T[45]); 9346 c = HH(c, d, a, b, M_offset_15, 16, T[46]); 9347 b = HH(b, c, d, a, M_offset_2, 23, T[47]); 9348 9349 a = II(a, b, c, d, M_offset_0, 6, T[48]); 9350 d = II(d, a, b, c, M_offset_7, 10, T[49]); 9351 c = II(c, d, a, b, M_offset_14, 15, T[50]); 9352 b = II(b, c, d, a, M_offset_5, 21, T[51]); 9353 a = II(a, b, c, d, M_offset_12, 6, T[52]); 9354 d = II(d, a, b, c, M_offset_3, 10, T[53]); 9355 c = II(c, d, a, b, M_offset_10, 15, T[54]); 9356 b = II(b, c, d, a, M_offset_1, 21, T[55]); 9357 a = II(a, b, c, d, M_offset_8, 6, T[56]); 9358 d = II(d, a, b, c, M_offset_15, 10, T[57]); 9359 c = II(c, d, a, b, M_offset_6, 15, T[58]); 9360 b = II(b, c, d, a, M_offset_13, 21, T[59]); 9361 a = II(a, b, c, d, M_offset_4, 6, T[60]); 9362 d = II(d, a, b, c, M_offset_11, 10, T[61]); 9363 c = II(c, d, a, b, M_offset_2, 15, T[62]); 9364 b = II(b, c, d, a, M_offset_9, 21, T[63]); 9365 9366 // Intermediate hash value 9367 H[0] = (H[0] + a) | 0; 9368 H[1] = (H[1] + b) | 0; 9369 H[2] = (H[2] + c) | 0; 9370 H[3] = (H[3] + d) | 0; 9371 }, 9372 9373 _doFinalize: function () { 9374 // Shortcuts 9375 var data = this._data; 9376 var dataWords = data.words; 9377 9378 var nBitsTotal = this._nDataBytes * 8; 9379 var nBitsLeft = data.sigBytes * 8; 9380 9381 // Add padding 9382 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 9383 9384 var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); 9385 var nBitsTotalL = nBitsTotal; 9386 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( 9387 (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | 9388 (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) 9389 ); 9390 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( 9391 (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | 9392 (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) 9393 ); 9394 9395 data.sigBytes = (dataWords.length + 1) * 4; 9396 9397 // Hash final blocks 9398 this._process(); 9399 9400 // Shortcuts 9401 var hash = this._hash; 9402 var H = hash.words; 9403 9404 // Swap endian 9405 for (var i = 0; i < 4; i++) { 9406 // Shortcut 9407 var H_i = H[i]; 9408 9409 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | 9410 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); 9411 } 9412 9413 // Return final computed hash 9414 return hash; 9415 }, 9416 9417 clone: function () { 9418 var clone = Hasher.clone.call(this); 9419 clone._hash = this._hash.clone(); 9420 9421 return clone; 9422 } 9423 }); 9424 9425 function FF(a, b, c, d, x, s, t) { 9426 var n = a + ((b & c) | (~b & d)) + x + t; 9427 return ((n << s) | (n >>> (32 - s))) + b; 9428 } 9429 9430 function GG(a, b, c, d, x, s, t) { 9431 var n = a + ((b & d) | (c & ~d)) + x + t; 9432 return ((n << s) | (n >>> (32 - s))) + b; 9433 } 9434 9435 function HH(a, b, c, d, x, s, t) { 9436 var n = a + (b ^ c ^ d) + x + t; 9437 return ((n << s) | (n >>> (32 - s))) + b; 9438 } 9439 9440 function II(a, b, c, d, x, s, t) { 9441 var n = a + (c ^ (b | ~d)) + x + t; 9442 return ((n << s) | (n >>> (32 - s))) + b; 9443 } 9444 9445 /** 9446 * Shortcut function to the hasher's object interface. 9447 * 9448 * @param {WordArray|string} message The message to hash. 9449 * 9450 * @return {WordArray} The hash. 9451 * 9452 * @static 9453 * 9454 * @example 9455 * 9456 * var hash = CryptoJS.MD5('message'); 9457 * var hash = CryptoJS.MD5(wordArray); 9458 */ 9459 C.MD5 = Hasher._createHelper(MD5); 9460 9461 /** 9462 * Shortcut function to the HMAC's object interface. 9463 * 9464 * @param {WordArray|string} message The message to hash. 9465 * @param {WordArray|string} key The secret key. 9466 * 9467 * @return {WordArray} The HMAC. 9468 * 9469 * @static 9470 * 9471 * @example 9472 * 9473 * var hmac = CryptoJS.HmacMD5(message, key); 9474 */ 9475 C.HmacMD5 = Hasher._createHmacHelper(MD5); 9476 }(Math)); 9477 9478 9479 return CryptoJS.MD5; 9480 9481 })); 9482 },{"./core":53}],62:[function(require,module,exports){ 9483 ;(function (root, factory, undef) { 9484 if (typeof exports === "object") { 9485 // CommonJS 9486 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9487 } 9488 else if (typeof define === "function" && define.amd) { 9489 // AMD 9490 define(["./core", "./cipher-core"], factory); 9491 } 9492 else { 9493 // Global (browser) 9494 factory(root.CryptoJS); 9495 } 9496 }(this, function (CryptoJS) { 9497 9498 /** 9499 * Cipher Feedback block mode. 9500 */ 9501 CryptoJS.mode.CFB = (function () { 9502 var CFB = CryptoJS.lib.BlockCipherMode.extend(); 9503 9504 CFB.Encryptor = CFB.extend({ 9505 processBlock: function (words, offset) { 9506 // Shortcuts 9507 var cipher = this._cipher; 9508 var blockSize = cipher.blockSize; 9509 9510 generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); 9511 9512 // Remember this block to use with next block 9513 this._prevBlock = words.slice(offset, offset + blockSize); 9514 } 9515 }); 9516 9517 CFB.Decryptor = CFB.extend({ 9518 processBlock: function (words, offset) { 9519 // Shortcuts 9520 var cipher = this._cipher; 9521 var blockSize = cipher.blockSize; 9522 9523 // Remember this block to use with next block 9524 var thisBlock = words.slice(offset, offset + blockSize); 9525 9526 generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); 9527 9528 // This block becomes the previous block 9529 this._prevBlock = thisBlock; 9530 } 9531 }); 9532 9533 function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { 9534 // Shortcut 9535 var iv = this._iv; 9536 9537 // Generate keystream 9538 if (iv) { 9539 var keystream = iv.slice(0); 9540 9541 // Remove IV for subsequent blocks 9542 this._iv = undefined; 9543 } else { 9544 var keystream = this._prevBlock; 9545 } 9546 cipher.encryptBlock(keystream, 0); 9547 9548 // Encrypt 9549 for (var i = 0; i < blockSize; i++) { 9550 words[offset + i] ^= keystream[i]; 9551 } 9552 } 9553 9554 return CFB; 9555 }()); 9556 9557 9558 return CryptoJS.mode.CFB; 9559 9560 })); 9561 },{"./cipher-core":52,"./core":53}],63:[function(require,module,exports){ 9562 ;(function (root, factory, undef) { 9563 if (typeof exports === "object") { 9564 // CommonJS 9565 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9566 } 9567 else if (typeof define === "function" && define.amd) { 9568 // AMD 9569 define(["./core", "./cipher-core"], factory); 9570 } 9571 else { 9572 // Global (browser) 9573 factory(root.CryptoJS); 9574 } 9575 }(this, function (CryptoJS) { 9576 9577 /** @preserve 9578 * Counter block mode compatible with Dr Brian Gladman fileenc.c 9579 * derived from CryptoJS.mode.CTR 9580 * Jan Hruby jhruby.web@gmail.com 9581 */ 9582 CryptoJS.mode.CTRGladman = (function () { 9583 var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); 9584 9585 function incWord(word) 9586 { 9587 if (((word >> 24) & 0xff) === 0xff) { //overflow 9588 var b1 = (word >> 16)&0xff; 9589 var b2 = (word >> 8)&0xff; 9590 var b3 = word & 0xff; 9591 9592 if (b1 === 0xff) // overflow b1 9593 { 9594 b1 = 0; 9595 if (b2 === 0xff) 9596 { 9597 b2 = 0; 9598 if (b3 === 0xff) 9599 { 9600 b3 = 0; 9601 } 9602 else 9603 { 9604 ++b3; 9605 } 9606 } 9607 else 9608 { 9609 ++b2; 9610 } 9611 } 9612 else 9613 { 9614 ++b1; 9615 } 9616 9617 word = 0; 9618 word += (b1 << 16); 9619 word += (b2 << 8); 9620 word += b3; 9621 } 9622 else 9623 { 9624 word += (0x01 << 24); 9625 } 9626 return word; 9627 } 9628 9629 function incCounter(counter) 9630 { 9631 if ((counter[0] = incWord(counter[0])) === 0) 9632 { 9633 // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 9634 counter[1] = incWord(counter[1]); 9635 } 9636 return counter; 9637 } 9638 9639 var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ 9640 processBlock: function (words, offset) { 9641 // Shortcuts 9642 var cipher = this._cipher 9643 var blockSize = cipher.blockSize; 9644 var iv = this._iv; 9645 var counter = this._counter; 9646 9647 // Generate keystream 9648 if (iv) { 9649 counter = this._counter = iv.slice(0); 9650 9651 // Remove IV for subsequent blocks 9652 this._iv = undefined; 9653 } 9654 9655 incCounter(counter); 9656 9657 var keystream = counter.slice(0); 9658 cipher.encryptBlock(keystream, 0); 9659 9660 // Encrypt 9661 for (var i = 0; i < blockSize; i++) { 9662 words[offset + i] ^= keystream[i]; 9663 } 9664 } 9665 }); 9666 9667 CTRGladman.Decryptor = Encryptor; 9668 9669 return CTRGladman; 9670 }()); 9671 9672 9673 9674 9675 return CryptoJS.mode.CTRGladman; 9676 9677 })); 9678 },{"./cipher-core":52,"./core":53}],64:[function(require,module,exports){ 9679 ;(function (root, factory, undef) { 9680 if (typeof exports === "object") { 9681 // CommonJS 9682 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9683 } 9684 else if (typeof define === "function" && define.amd) { 9685 // AMD 9686 define(["./core", "./cipher-core"], factory); 9687 } 9688 else { 9689 // Global (browser) 9690 factory(root.CryptoJS); 9691 } 9692 }(this, function (CryptoJS) { 9693 9694 /** 9695 * Counter block mode. 9696 */ 9697 CryptoJS.mode.CTR = (function () { 9698 var CTR = CryptoJS.lib.BlockCipherMode.extend(); 9699 9700 var Encryptor = CTR.Encryptor = CTR.extend({ 9701 processBlock: function (words, offset) { 9702 // Shortcuts 9703 var cipher = this._cipher 9704 var blockSize = cipher.blockSize; 9705 var iv = this._iv; 9706 var counter = this._counter; 9707 9708 // Generate keystream 9709 if (iv) { 9710 counter = this._counter = iv.slice(0); 9711 9712 // Remove IV for subsequent blocks 9713 this._iv = undefined; 9714 } 9715 var keystream = counter.slice(0); 9716 cipher.encryptBlock(keystream, 0); 9717 9718 // Increment counter 9719 counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 9720 9721 // Encrypt 9722 for (var i = 0; i < blockSize; i++) { 9723 words[offset + i] ^= keystream[i]; 9724 } 9725 } 9726 }); 9727 9728 CTR.Decryptor = Encryptor; 9729 9730 return CTR; 9731 }()); 9732 9733 9734 return CryptoJS.mode.CTR; 9735 9736 })); 9737 },{"./cipher-core":52,"./core":53}],65:[function(require,module,exports){ 9738 ;(function (root, factory, undef) { 9739 if (typeof exports === "object") { 9740 // CommonJS 9741 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9742 } 9743 else if (typeof define === "function" && define.amd) { 9744 // AMD 9745 define(["./core", "./cipher-core"], factory); 9746 } 9747 else { 9748 // Global (browser) 9749 factory(root.CryptoJS); 9750 } 9751 }(this, function (CryptoJS) { 9752 9753 /** 9754 * Electronic Codebook block mode. 9755 */ 9756 CryptoJS.mode.ECB = (function () { 9757 var ECB = CryptoJS.lib.BlockCipherMode.extend(); 9758 9759 ECB.Encryptor = ECB.extend({ 9760 processBlock: function (words, offset) { 9761 this._cipher.encryptBlock(words, offset); 9762 } 9763 }); 9764 9765 ECB.Decryptor = ECB.extend({ 9766 processBlock: function (words, offset) { 9767 this._cipher.decryptBlock(words, offset); 9768 } 9769 }); 9770 9771 return ECB; 9772 }()); 9773 9774 9775 return CryptoJS.mode.ECB; 9776 9777 })); 9778 },{"./cipher-core":52,"./core":53}],66:[function(require,module,exports){ 9779 ;(function (root, factory, undef) { 9780 if (typeof exports === "object") { 9781 // CommonJS 9782 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9783 } 9784 else if (typeof define === "function" && define.amd) { 9785 // AMD 9786 define(["./core", "./cipher-core"], factory); 9787 } 9788 else { 9789 // Global (browser) 9790 factory(root.CryptoJS); 9791 } 9792 }(this, function (CryptoJS) { 9793 9794 /** 9795 * Output Feedback block mode. 9796 */ 9797 CryptoJS.mode.OFB = (function () { 9798 var OFB = CryptoJS.lib.BlockCipherMode.extend(); 9799 9800 var Encryptor = OFB.Encryptor = OFB.extend({ 9801 processBlock: function (words, offset) { 9802 // Shortcuts 9803 var cipher = this._cipher 9804 var blockSize = cipher.blockSize; 9805 var iv = this._iv; 9806 var keystream = this._keystream; 9807 9808 // Generate keystream 9809 if (iv) { 9810 keystream = this._keystream = iv.slice(0); 9811 9812 // Remove IV for subsequent blocks 9813 this._iv = undefined; 9814 } 9815 cipher.encryptBlock(keystream, 0); 9816 9817 // Encrypt 9818 for (var i = 0; i < blockSize; i++) { 9819 words[offset + i] ^= keystream[i]; 9820 } 9821 } 9822 }); 9823 9824 OFB.Decryptor = Encryptor; 9825 9826 return OFB; 9827 }()); 9828 9829 9830 return CryptoJS.mode.OFB; 9831 9832 })); 9833 },{"./cipher-core":52,"./core":53}],67:[function(require,module,exports){ 9834 ;(function (root, factory, undef) { 9835 if (typeof exports === "object") { 9836 // CommonJS 9837 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9838 } 9839 else if (typeof define === "function" && define.amd) { 9840 // AMD 9841 define(["./core", "./cipher-core"], factory); 9842 } 9843 else { 9844 // Global (browser) 9845 factory(root.CryptoJS); 9846 } 9847 }(this, function (CryptoJS) { 9848 9849 /** 9850 * ANSI X.923 padding strategy. 9851 */ 9852 CryptoJS.pad.AnsiX923 = { 9853 pad: function (data, blockSize) { 9854 // Shortcuts 9855 var dataSigBytes = data.sigBytes; 9856 var blockSizeBytes = blockSize * 4; 9857 9858 // Count padding bytes 9859 var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; 9860 9861 // Compute last byte position 9862 var lastBytePos = dataSigBytes + nPaddingBytes - 1; 9863 9864 // Pad 9865 data.clamp(); 9866 data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); 9867 data.sigBytes += nPaddingBytes; 9868 }, 9869 9870 unpad: function (data) { 9871 // Get number of padding bytes from last byte 9872 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 9873 9874 // Remove padding 9875 data.sigBytes -= nPaddingBytes; 9876 } 9877 }; 9878 9879 9880 return CryptoJS.pad.Ansix923; 9881 9882 })); 9883 },{"./cipher-core":52,"./core":53}],68:[function(require,module,exports){ 9884 ;(function (root, factory, undef) { 9885 if (typeof exports === "object") { 9886 // CommonJS 9887 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9888 } 9889 else if (typeof define === "function" && define.amd) { 9890 // AMD 9891 define(["./core", "./cipher-core"], factory); 9892 } 9893 else { 9894 // Global (browser) 9895 factory(root.CryptoJS); 9896 } 9897 }(this, function (CryptoJS) { 9898 9899 /** 9900 * ISO 10126 padding strategy. 9901 */ 9902 CryptoJS.pad.Iso10126 = { 9903 pad: function (data, blockSize) { 9904 // Shortcut 9905 var blockSizeBytes = blockSize * 4; 9906 9907 // Count padding bytes 9908 var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; 9909 9910 // Pad 9911 data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). 9912 concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); 9913 }, 9914 9915 unpad: function (data) { 9916 // Get number of padding bytes from last byte 9917 var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; 9918 9919 // Remove padding 9920 data.sigBytes -= nPaddingBytes; 9921 } 9922 }; 9923 9924 9925 return CryptoJS.pad.Iso10126; 9926 9927 })); 9928 },{"./cipher-core":52,"./core":53}],69:[function(require,module,exports){ 9929 ;(function (root, factory, undef) { 9930 if (typeof exports === "object") { 9931 // CommonJS 9932 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9933 } 9934 else if (typeof define === "function" && define.amd) { 9935 // AMD 9936 define(["./core", "./cipher-core"], factory); 9937 } 9938 else { 9939 // Global (browser) 9940 factory(root.CryptoJS); 9941 } 9942 }(this, function (CryptoJS) { 9943 9944 /** 9945 * ISO/IEC 9797-1 Padding Method 2. 9946 */ 9947 CryptoJS.pad.Iso97971 = { 9948 pad: function (data, blockSize) { 9949 // Add 0x80 byte 9950 data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); 9951 9952 // Zero pad the rest 9953 CryptoJS.pad.ZeroPadding.pad(data, blockSize); 9954 }, 9955 9956 unpad: function (data) { 9957 // Remove zero padding 9958 CryptoJS.pad.ZeroPadding.unpad(data); 9959 9960 // Remove one more byte -- the 0x80 byte 9961 data.sigBytes--; 9962 } 9963 }; 9964 9965 9966 return CryptoJS.pad.Iso97971; 9967 9968 })); 9969 },{"./cipher-core":52,"./core":53}],70:[function(require,module,exports){ 9970 ;(function (root, factory, undef) { 9971 if (typeof exports === "object") { 9972 // CommonJS 9973 module.exports = exports = factory(require("./core"), require("./cipher-core")); 9974 } 9975 else if (typeof define === "function" && define.amd) { 9976 // AMD 9977 define(["./core", "./cipher-core"], factory); 9978 } 9979 else { 9980 // Global (browser) 9981 factory(root.CryptoJS); 9982 } 9983 }(this, function (CryptoJS) { 9984 9985 /** 9986 * A noop padding strategy. 9987 */ 9988 CryptoJS.pad.NoPadding = { 9989 pad: function () { 9990 }, 9991 9992 unpad: function () { 9993 } 9994 }; 9995 9996 9997 return CryptoJS.pad.NoPadding; 9998 9999 })); 10000 },{"./cipher-core":52,"./core":53}],71:[function(require,module,exports){ 10001 ;(function (root, factory, undef) { 10002 if (typeof exports === "object") { 10003 // CommonJS 10004 module.exports = exports = factory(require("./core"), require("./cipher-core")); 10005 } 10006 else if (typeof define === "function" && define.amd) { 10007 // AMD 10008 define(["./core", "./cipher-core"], factory); 10009 } 10010 else { 10011 // Global (browser) 10012 factory(root.CryptoJS); 10013 } 10014 }(this, function (CryptoJS) { 10015 10016 /** 10017 * Zero padding strategy. 10018 */ 10019 CryptoJS.pad.ZeroPadding = { 10020 pad: function (data, blockSize) { 10021 // Shortcut 10022 var blockSizeBytes = blockSize * 4; 10023 10024 // Pad 10025 data.clamp(); 10026 data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); 10027 }, 10028 10029 unpad: function (data) { 10030 // Shortcut 10031 var dataWords = data.words; 10032 10033 // Unpad 10034 var i = data.sigBytes - 1; 10035 while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { 10036 i--; 10037 } 10038 data.sigBytes = i + 1; 10039 } 10040 }; 10041 10042 10043 return CryptoJS.pad.ZeroPadding; 10044 10045 })); 10046 },{"./cipher-core":52,"./core":53}],72:[function(require,module,exports){ 10047 ;(function (root, factory, undef) { 10048 if (typeof exports === "object") { 10049 // CommonJS 10050 module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); 10051 } 10052 else if (typeof define === "function" && define.amd) { 10053 // AMD 10054 define(["./core", "./sha1", "./hmac"], factory); 10055 } 10056 else { 10057 // Global (browser) 10058 factory(root.CryptoJS); 10059 } 10060 }(this, function (CryptoJS) { 10061 10062 (function () { 10063 // Shortcuts 10064 var C = CryptoJS; 10065 var C_lib = C.lib; 10066 var Base = C_lib.Base; 10067 var WordArray = C_lib.WordArray; 10068 var C_algo = C.algo; 10069 var SHA1 = C_algo.SHA1; 10070 var HMAC = C_algo.HMAC; 10071 10072 /** 10073 * Password-Based Key Derivation Function 2 algorithm. 10074 */ 10075 var PBKDF2 = C_algo.PBKDF2 = Base.extend({ 10076 /** 10077 * Configuration options. 10078 * 10079 * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) 10080 * @property {Hasher} hasher The hasher to use. Default: SHA1 10081 * @property {number} iterations The number of iterations to perform. Default: 1 10082 */ 10083 cfg: Base.extend({ 10084 keySize: 128/32, 10085 hasher: SHA1, 10086 iterations: 1 10087 }), 10088 10089 /** 10090 * Initializes a newly created key derivation function. 10091 * 10092 * @param {Object} cfg (Optional) The configuration options to use for the derivation. 10093 * 10094 * @example 10095 * 10096 * var kdf = CryptoJS.algo.PBKDF2.create(); 10097 * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); 10098 * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); 10099 */ 10100 init: function (cfg) { 10101 this.cfg = this.cfg.extend(cfg); 10102 }, 10103 10104 /** 10105 * Computes the Password-Based Key Derivation Function 2. 10106 * 10107 * @param {WordArray|string} password The password. 10108 * @param {WordArray|string} salt A salt. 10109 * 10110 * @return {WordArray} The derived key. 10111 * 10112 * @example 10113 * 10114 * var key = kdf.compute(password, salt); 10115 */ 10116 compute: function (password, salt) { 10117 // Shortcut 10118 var cfg = this.cfg; 10119 10120 // Init HMAC 10121 var hmac = HMAC.create(cfg.hasher, password); 10122 10123 // Initial values 10124 var derivedKey = WordArray.create(); 10125 var blockIndex = WordArray.create([0x00000001]); 10126 10127 // Shortcuts 10128 var derivedKeyWords = derivedKey.words; 10129 var blockIndexWords = blockIndex.words; 10130 var keySize = cfg.keySize; 10131 var iterations = cfg.iterations; 10132 10133 // Generate key 10134 while (derivedKeyWords.length < keySize) { 10135 var block = hmac.update(salt).finalize(blockIndex); 10136 hmac.reset(); 10137 10138 // Shortcuts 10139 var blockWords = block.words; 10140 var blockWordsLength = blockWords.length; 10141 10142 // Iterations 10143 var intermediate = block; 10144 for (var i = 1; i < iterations; i++) { 10145 intermediate = hmac.finalize(intermediate); 10146 hmac.reset(); 10147 10148 // Shortcut 10149 var intermediateWords = intermediate.words; 10150 10151 // XOR intermediate with block 10152 for (var j = 0; j < blockWordsLength; j++) { 10153 blockWords[j] ^= intermediateWords[j]; 10154 } 10155 } 10156 10157 derivedKey.concat(block); 10158 blockIndexWords[0]++; 10159 } 10160 derivedKey.sigBytes = keySize * 4; 10161 10162 return derivedKey; 10163 } 10164 }); 10165 10166 /** 10167 * Computes the Password-Based Key Derivation Function 2. 10168 * 10169 * @param {WordArray|string} password The password. 10170 * @param {WordArray|string} salt A salt. 10171 * @param {Object} cfg (Optional) The configuration options to use for this computation. 10172 * 10173 * @return {WordArray} The derived key. 10174 * 10175 * @static 10176 * 10177 * @example 10178 * 10179 * var key = CryptoJS.PBKDF2(password, salt); 10180 * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); 10181 * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); 10182 */ 10183 C.PBKDF2 = function (password, salt, cfg) { 10184 return PBKDF2.create(cfg).compute(password, salt); 10185 }; 10186 }()); 10187 10188 10189 return CryptoJS.PBKDF2; 10190 10191 })); 10192 },{"./core":53,"./hmac":58,"./sha1":77}],73:[function(require,module,exports){ 10193 ;(function (root, factory, undef) { 10194 if (typeof exports === "object") { 10195 // CommonJS 10196 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10197 } 10198 else if (typeof define === "function" && define.amd) { 10199 // AMD 10200 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10201 } 10202 else { 10203 // Global (browser) 10204 factory(root.CryptoJS); 10205 } 10206 }(this, function (CryptoJS) { 10207 10208 (function () { 10209 // Shortcuts 10210 var C = CryptoJS; 10211 var C_lib = C.lib; 10212 var StreamCipher = C_lib.StreamCipher; 10213 var C_algo = C.algo; 10214 10215 // Reusable objects 10216 var S = []; 10217 var C_ = []; 10218 var G = []; 10219 10220 /** 10221 * Rabbit stream cipher algorithm. 10222 * 10223 * This is a legacy version that neglected to convert the key to little-endian. 10224 * This error doesn't affect the cipher's security, 10225 * but it does affect its compatibility with other implementations. 10226 */ 10227 var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ 10228 _doReset: function () { 10229 // Shortcuts 10230 var K = this._key.words; 10231 var iv = this.cfg.iv; 10232 10233 // Generate initial state values 10234 var X = this._X = [ 10235 K[0], (K[3] << 16) | (K[2] >>> 16), 10236 K[1], (K[0] << 16) | (K[3] >>> 16), 10237 K[2], (K[1] << 16) | (K[0] >>> 16), 10238 K[3], (K[2] << 16) | (K[1] >>> 16) 10239 ]; 10240 10241 // Generate initial counter values 10242 var C = this._C = [ 10243 (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), 10244 (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), 10245 (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), 10246 (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) 10247 ]; 10248 10249 // Carry bit 10250 this._b = 0; 10251 10252 // Iterate the system four times 10253 for (var i = 0; i < 4; i++) { 10254 nextState.call(this); 10255 } 10256 10257 // Modify the counters 10258 for (var i = 0; i < 8; i++) { 10259 C[i] ^= X[(i + 4) & 7]; 10260 } 10261 10262 // IV setup 10263 if (iv) { 10264 // Shortcuts 10265 var IV = iv.words; 10266 var IV_0 = IV[0]; 10267 var IV_1 = IV[1]; 10268 10269 // Generate four subvectors 10270 var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); 10271 var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); 10272 var i1 = (i0 >>> 16) | (i2 & 0xffff0000); 10273 var i3 = (i2 << 16) | (i0 & 0x0000ffff); 10274 10275 // Modify counter values 10276 C[0] ^= i0; 10277 C[1] ^= i1; 10278 C[2] ^= i2; 10279 C[3] ^= i3; 10280 C[4] ^= i0; 10281 C[5] ^= i1; 10282 C[6] ^= i2; 10283 C[7] ^= i3; 10284 10285 // Iterate the system four times 10286 for (var i = 0; i < 4; i++) { 10287 nextState.call(this); 10288 } 10289 } 10290 }, 10291 10292 _doProcessBlock: function (M, offset) { 10293 // Shortcut 10294 var X = this._X; 10295 10296 // Iterate the system 10297 nextState.call(this); 10298 10299 // Generate four keystream words 10300 S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); 10301 S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); 10302 S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); 10303 S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); 10304 10305 for (var i = 0; i < 4; i++) { 10306 // Swap endian 10307 S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | 10308 (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); 10309 10310 // Encrypt 10311 M[offset + i] ^= S[i]; 10312 } 10313 }, 10314 10315 blockSize: 128/32, 10316 10317 ivSize: 64/32 10318 }); 10319 10320 function nextState() { 10321 // Shortcuts 10322 var X = this._X; 10323 var C = this._C; 10324 10325 // Save old counter values 10326 for (var i = 0; i < 8; i++) { 10327 C_[i] = C[i]; 10328 } 10329 10330 // Calculate new counter values 10331 C[0] = (C[0] + 0x4d34d34d + this._b) | 0; 10332 C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; 10333 C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; 10334 C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; 10335 C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; 10336 C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; 10337 C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; 10338 C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; 10339 this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; 10340 10341 // Calculate the g-values 10342 for (var i = 0; i < 8; i++) { 10343 var gx = X[i] + C[i]; 10344 10345 // Construct high and low argument for squaring 10346 var ga = gx & 0xffff; 10347 var gb = gx >>> 16; 10348 10349 // Calculate high and low result of squaring 10350 var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; 10351 var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); 10352 10353 // High XOR low 10354 G[i] = gh ^ gl; 10355 } 10356 10357 // Calculate new state values 10358 X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; 10359 X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; 10360 X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; 10361 X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; 10362 X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; 10363 X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; 10364 X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; 10365 X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; 10366 } 10367 10368 /** 10369 * Shortcut functions to the cipher's object interface. 10370 * 10371 * @example 10372 * 10373 * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); 10374 * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); 10375 */ 10376 C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); 10377 }()); 10378 10379 10380 return CryptoJS.RabbitLegacy; 10381 10382 })); 10383 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],74:[function(require,module,exports){ 10384 ;(function (root, factory, undef) { 10385 if (typeof exports === "object") { 10386 // CommonJS 10387 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10388 } 10389 else if (typeof define === "function" && define.amd) { 10390 // AMD 10391 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10392 } 10393 else { 10394 // Global (browser) 10395 factory(root.CryptoJS); 10396 } 10397 }(this, function (CryptoJS) { 10398 10399 (function () { 10400 // Shortcuts 10401 var C = CryptoJS; 10402 var C_lib = C.lib; 10403 var StreamCipher = C_lib.StreamCipher; 10404 var C_algo = C.algo; 10405 10406 // Reusable objects 10407 var S = []; 10408 var C_ = []; 10409 var G = []; 10410 10411 /** 10412 * Rabbit stream cipher algorithm 10413 */ 10414 var Rabbit = C_algo.Rabbit = StreamCipher.extend({ 10415 _doReset: function () { 10416 // Shortcuts 10417 var K = this._key.words; 10418 var iv = this.cfg.iv; 10419 10420 // Swap endian 10421 for (var i = 0; i < 4; i++) { 10422 K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | 10423 (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); 10424 } 10425 10426 // Generate initial state values 10427 var X = this._X = [ 10428 K[0], (K[3] << 16) | (K[2] >>> 16), 10429 K[1], (K[0] << 16) | (K[3] >>> 16), 10430 K[2], (K[1] << 16) | (K[0] >>> 16), 10431 K[3], (K[2] << 16) | (K[1] >>> 16) 10432 ]; 10433 10434 // Generate initial counter values 10435 var C = this._C = [ 10436 (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), 10437 (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), 10438 (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), 10439 (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) 10440 ]; 10441 10442 // Carry bit 10443 this._b = 0; 10444 10445 // Iterate the system four times 10446 for (var i = 0; i < 4; i++) { 10447 nextState.call(this); 10448 } 10449 10450 // Modify the counters 10451 for (var i = 0; i < 8; i++) { 10452 C[i] ^= X[(i + 4) & 7]; 10453 } 10454 10455 // IV setup 10456 if (iv) { 10457 // Shortcuts 10458 var IV = iv.words; 10459 var IV_0 = IV[0]; 10460 var IV_1 = IV[1]; 10461 10462 // Generate four subvectors 10463 var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); 10464 var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); 10465 var i1 = (i0 >>> 16) | (i2 & 0xffff0000); 10466 var i3 = (i2 << 16) | (i0 & 0x0000ffff); 10467 10468 // Modify counter values 10469 C[0] ^= i0; 10470 C[1] ^= i1; 10471 C[2] ^= i2; 10472 C[3] ^= i3; 10473 C[4] ^= i0; 10474 C[5] ^= i1; 10475 C[6] ^= i2; 10476 C[7] ^= i3; 10477 10478 // Iterate the system four times 10479 for (var i = 0; i < 4; i++) { 10480 nextState.call(this); 10481 } 10482 } 10483 }, 10484 10485 _doProcessBlock: function (M, offset) { 10486 // Shortcut 10487 var X = this._X; 10488 10489 // Iterate the system 10490 nextState.call(this); 10491 10492 // Generate four keystream words 10493 S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); 10494 S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); 10495 S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); 10496 S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); 10497 10498 for (var i = 0; i < 4; i++) { 10499 // Swap endian 10500 S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | 10501 (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); 10502 10503 // Encrypt 10504 M[offset + i] ^= S[i]; 10505 } 10506 }, 10507 10508 blockSize: 128/32, 10509 10510 ivSize: 64/32 10511 }); 10512 10513 function nextState() { 10514 // Shortcuts 10515 var X = this._X; 10516 var C = this._C; 10517 10518 // Save old counter values 10519 for (var i = 0; i < 8; i++) { 10520 C_[i] = C[i]; 10521 } 10522 10523 // Calculate new counter values 10524 C[0] = (C[0] + 0x4d34d34d + this._b) | 0; 10525 C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; 10526 C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; 10527 C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; 10528 C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; 10529 C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; 10530 C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; 10531 C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; 10532 this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; 10533 10534 // Calculate the g-values 10535 for (var i = 0; i < 8; i++) { 10536 var gx = X[i] + C[i]; 10537 10538 // Construct high and low argument for squaring 10539 var ga = gx & 0xffff; 10540 var gb = gx >>> 16; 10541 10542 // Calculate high and low result of squaring 10543 var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; 10544 var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); 10545 10546 // High XOR low 10547 G[i] = gh ^ gl; 10548 } 10549 10550 // Calculate new state values 10551 X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; 10552 X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; 10553 X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; 10554 X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; 10555 X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; 10556 X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; 10557 X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; 10558 X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; 10559 } 10560 10561 /** 10562 * Shortcut functions to the cipher's object interface. 10563 * 10564 * @example 10565 * 10566 * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); 10567 * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); 10568 */ 10569 C.Rabbit = StreamCipher._createHelper(Rabbit); 10570 }()); 10571 10572 10573 return CryptoJS.Rabbit; 10574 10575 })); 10576 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],75:[function(require,module,exports){ 10577 ;(function (root, factory, undef) { 10578 if (typeof exports === "object") { 10579 // CommonJS 10580 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 10581 } 10582 else if (typeof define === "function" && define.amd) { 10583 // AMD 10584 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 10585 } 10586 else { 10587 // Global (browser) 10588 factory(root.CryptoJS); 10589 } 10590 }(this, function (CryptoJS) { 10591 10592 (function () { 10593 // Shortcuts 10594 var C = CryptoJS; 10595 var C_lib = C.lib; 10596 var StreamCipher = C_lib.StreamCipher; 10597 var C_algo = C.algo; 10598 10599 /** 10600 * RC4 stream cipher algorithm. 10601 */ 10602 var RC4 = C_algo.RC4 = StreamCipher.extend({ 10603 _doReset: function () { 10604 // Shortcuts 10605 var key = this._key; 10606 var keyWords = key.words; 10607 var keySigBytes = key.sigBytes; 10608 10609 // Init sbox 10610 var S = this._S = []; 10611 for (var i = 0; i < 256; i++) { 10612 S[i] = i; 10613 } 10614 10615 // Key setup 10616 for (var i = 0, j = 0; i < 256; i++) { 10617 var keyByteIndex = i % keySigBytes; 10618 var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; 10619 10620 j = (j + S[i] + keyByte) % 256; 10621 10622 // Swap 10623 var t = S[i]; 10624 S[i] = S[j]; 10625 S[j] = t; 10626 } 10627 10628 // Counters 10629 this._i = this._j = 0; 10630 }, 10631 10632 _doProcessBlock: function (M, offset) { 10633 M[offset] ^= generateKeystreamWord.call(this); 10634 }, 10635 10636 keySize: 256/32, 10637 10638 ivSize: 0 10639 }); 10640 10641 function generateKeystreamWord() { 10642 // Shortcuts 10643 var S = this._S; 10644 var i = this._i; 10645 var j = this._j; 10646 10647 // Generate keystream word 10648 var keystreamWord = 0; 10649 for (var n = 0; n < 4; n++) { 10650 i = (i + 1) % 256; 10651 j = (j + S[i]) % 256; 10652 10653 // Swap 10654 var t = S[i]; 10655 S[i] = S[j]; 10656 S[j] = t; 10657 10658 keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); 10659 } 10660 10661 // Update counters 10662 this._i = i; 10663 this._j = j; 10664 10665 return keystreamWord; 10666 } 10667 10668 /** 10669 * Shortcut functions to the cipher's object interface. 10670 * 10671 * @example 10672 * 10673 * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); 10674 * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); 10675 */ 10676 C.RC4 = StreamCipher._createHelper(RC4); 10677 10678 /** 10679 * Modified RC4 stream cipher algorithm. 10680 */ 10681 var RC4Drop = C_algo.RC4Drop = RC4.extend({ 10682 /** 10683 * Configuration options. 10684 * 10685 * @property {number} drop The number of keystream words to drop. Default 192 10686 */ 10687 cfg: RC4.cfg.extend({ 10688 drop: 192 10689 }), 10690 10691 _doReset: function () { 10692 RC4._doReset.call(this); 10693 10694 // Drop 10695 for (var i = this.cfg.drop; i > 0; i--) { 10696 generateKeystreamWord.call(this); 10697 } 10698 } 10699 }); 10700 10701 /** 10702 * Shortcut functions to the cipher's object interface. 10703 * 10704 * @example 10705 * 10706 * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); 10707 * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); 10708 */ 10709 C.RC4Drop = StreamCipher._createHelper(RC4Drop); 10710 }()); 10711 10712 10713 return CryptoJS.RC4; 10714 10715 })); 10716 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],76:[function(require,module,exports){ 10717 ;(function (root, factory) { 10718 if (typeof exports === "object") { 10719 // CommonJS 10720 module.exports = exports = factory(require("./core")); 10721 } 10722 else if (typeof define === "function" && define.amd) { 10723 // AMD 10724 define(["./core"], factory); 10725 } 10726 else { 10727 // Global (browser) 10728 factory(root.CryptoJS); 10729 } 10730 }(this, function (CryptoJS) { 10731 10732 /** @preserve 10733 (c) 2012 by Cédric Mesnil. All rights reserved. 10734 10735 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 10736 10737 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 10738 - 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. 10739 10740 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. 10741 */ 10742 10743 (function (Math) { 10744 // Shortcuts 10745 var C = CryptoJS; 10746 var C_lib = C.lib; 10747 var WordArray = C_lib.WordArray; 10748 var Hasher = C_lib.Hasher; 10749 var C_algo = C.algo; 10750 10751 // Constants table 10752 var _zl = WordArray.create([ 10753 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 10754 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 10755 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 10756 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 10757 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); 10758 var _zr = WordArray.create([ 10759 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 10760 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 10761 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 10762 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 10763 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); 10764 var _sl = WordArray.create([ 10765 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 10766 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 10767 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 10768 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 10769 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); 10770 var _sr = WordArray.create([ 10771 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 10772 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 10773 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 10774 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 10775 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); 10776 10777 var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); 10778 var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); 10779 10780 /** 10781 * RIPEMD160 hash algorithm. 10782 */ 10783 var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ 10784 _doReset: function () { 10785 this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); 10786 }, 10787 10788 _doProcessBlock: function (M, offset) { 10789 10790 // Swap endian 10791 for (var i = 0; i < 16; i++) { 10792 // Shortcuts 10793 var offset_i = offset + i; 10794 var M_offset_i = M[offset_i]; 10795 10796 // Swap 10797 M[offset_i] = ( 10798 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | 10799 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) 10800 ); 10801 } 10802 // Shortcut 10803 var H = this._hash.words; 10804 var hl = _hl.words; 10805 var hr = _hr.words; 10806 var zl = _zl.words; 10807 var zr = _zr.words; 10808 var sl = _sl.words; 10809 var sr = _sr.words; 10810 10811 // Working variables 10812 var al, bl, cl, dl, el; 10813 var ar, br, cr, dr, er; 10814 10815 ar = al = H[0]; 10816 br = bl = H[1]; 10817 cr = cl = H[2]; 10818 dr = dl = H[3]; 10819 er = el = H[4]; 10820 // Computation 10821 var t; 10822 for (var i = 0; i < 80; i += 1) { 10823 t = (al + M[offset+zl[i]])|0; 10824 if (i<16){ 10825 t += f1(bl,cl,dl) + hl[0]; 10826 } else if (i<32) { 10827 t += f2(bl,cl,dl) + hl[1]; 10828 } else if (i<48) { 10829 t += f3(bl,cl,dl) + hl[2]; 10830 } else if (i<64) { 10831 t += f4(bl,cl,dl) + hl[3]; 10832 } else {// if (i<80) { 10833 t += f5(bl,cl,dl) + hl[4]; 10834 } 10835 t = t|0; 10836 t = rotl(t,sl[i]); 10837 t = (t+el)|0; 10838 al = el; 10839 el = dl; 10840 dl = rotl(cl, 10); 10841 cl = bl; 10842 bl = t; 10843 10844 t = (ar + M[offset+zr[i]])|0; 10845 if (i<16){ 10846 t += f5(br,cr,dr) + hr[0]; 10847 } else if (i<32) { 10848 t += f4(br,cr,dr) + hr[1]; 10849 } else if (i<48) { 10850 t += f3(br,cr,dr) + hr[2]; 10851 } else if (i<64) { 10852 t += f2(br,cr,dr) + hr[3]; 10853 } else {// if (i<80) { 10854 t += f1(br,cr,dr) + hr[4]; 10855 } 10856 t = t|0; 10857 t = rotl(t,sr[i]) ; 10858 t = (t+er)|0; 10859 ar = er; 10860 er = dr; 10861 dr = rotl(cr, 10); 10862 cr = br; 10863 br = t; 10864 } 10865 // Intermediate hash value 10866 t = (H[1] + cl + dr)|0; 10867 H[1] = (H[2] + dl + er)|0; 10868 H[2] = (H[3] + el + ar)|0; 10869 H[3] = (H[4] + al + br)|0; 10870 H[4] = (H[0] + bl + cr)|0; 10871 H[0] = t; 10872 }, 10873 10874 _doFinalize: function () { 10875 // Shortcuts 10876 var data = this._data; 10877 var dataWords = data.words; 10878 10879 var nBitsTotal = this._nDataBytes * 8; 10880 var nBitsLeft = data.sigBytes * 8; 10881 10882 // Add padding 10883 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 10884 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( 10885 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | 10886 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) 10887 ); 10888 data.sigBytes = (dataWords.length + 1) * 4; 10889 10890 // Hash final blocks 10891 this._process(); 10892 10893 // Shortcuts 10894 var hash = this._hash; 10895 var H = hash.words; 10896 10897 // Swap endian 10898 for (var i = 0; i < 5; i++) { 10899 // Shortcut 10900 var H_i = H[i]; 10901 10902 // Swap 10903 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | 10904 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); 10905 } 10906 10907 // Return final computed hash 10908 return hash; 10909 }, 10910 10911 clone: function () { 10912 var clone = Hasher.clone.call(this); 10913 clone._hash = this._hash.clone(); 10914 10915 return clone; 10916 } 10917 }); 10918 10919 10920 function f1(x, y, z) { 10921 return ((x) ^ (y) ^ (z)); 10922 10923 } 10924 10925 function f2(x, y, z) { 10926 return (((x)&(y)) | ((~x)&(z))); 10927 } 10928 10929 function f3(x, y, z) { 10930 return (((x) | (~(y))) ^ (z)); 10931 } 10932 10933 function f4(x, y, z) { 10934 return (((x) & (z)) | ((y)&(~(z)))); 10935 } 10936 10937 function f5(x, y, z) { 10938 return ((x) ^ ((y) |(~(z)))); 10939 10940 } 10941 10942 function rotl(x,n) { 10943 return (x<<n) | (x>>>(32-n)); 10944 } 10945 10946 10947 /** 10948 * Shortcut function to the hasher's object interface. 10949 * 10950 * @param {WordArray|string} message The message to hash. 10951 * 10952 * @return {WordArray} The hash. 10953 * 10954 * @static 10955 * 10956 * @example 10957 * 10958 * var hash = CryptoJS.RIPEMD160('message'); 10959 * var hash = CryptoJS.RIPEMD160(wordArray); 10960 */ 10961 C.RIPEMD160 = Hasher._createHelper(RIPEMD160); 10962 10963 /** 10964 * Shortcut function to the HMAC's object interface. 10965 * 10966 * @param {WordArray|string} message The message to hash. 10967 * @param {WordArray|string} key The secret key. 10968 * 10969 * @return {WordArray} The HMAC. 10970 * 10971 * @static 10972 * 10973 * @example 10974 * 10975 * var hmac = CryptoJS.HmacRIPEMD160(message, key); 10976 */ 10977 C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); 10978 }(Math)); 10979 10980 10981 return CryptoJS.RIPEMD160; 10982 10983 })); 10984 },{"./core":53}],77:[function(require,module,exports){ 10985 ;(function (root, factory) { 10986 if (typeof exports === "object") { 10987 // CommonJS 10988 module.exports = exports = factory(require("./core")); 10989 } 10990 else if (typeof define === "function" && define.amd) { 10991 // AMD 10992 define(["./core"], factory); 10993 } 10994 else { 10995 // Global (browser) 10996 factory(root.CryptoJS); 10997 } 10998 }(this, function (CryptoJS) { 10999 11000 (function () { 11001 // Shortcuts 11002 var C = CryptoJS; 11003 var C_lib = C.lib; 11004 var WordArray = C_lib.WordArray; 11005 var Hasher = C_lib.Hasher; 11006 var C_algo = C.algo; 11007 11008 // Reusable object 11009 var W = []; 11010 11011 /** 11012 * SHA-1 hash algorithm. 11013 */ 11014 var SHA1 = C_algo.SHA1 = Hasher.extend({ 11015 _doReset: function () { 11016 this._hash = new WordArray.init([ 11017 0x67452301, 0xefcdab89, 11018 0x98badcfe, 0x10325476, 11019 0xc3d2e1f0 11020 ]); 11021 }, 11022 11023 _doProcessBlock: function (M, offset) { 11024 // Shortcut 11025 var H = this._hash.words; 11026 11027 // Working variables 11028 var a = H[0]; 11029 var b = H[1]; 11030 var c = H[2]; 11031 var d = H[3]; 11032 var e = H[4]; 11033 11034 // Computation 11035 for (var i = 0; i < 80; i++) { 11036 if (i < 16) { 11037 W[i] = M[offset + i] | 0; 11038 } else { 11039 var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; 11040 W[i] = (n << 1) | (n >>> 31); 11041 } 11042 11043 var t = ((a << 5) | (a >>> 27)) + e + W[i]; 11044 if (i < 20) { 11045 t += ((b & c) | (~b & d)) + 0x5a827999; 11046 } else if (i < 40) { 11047 t += (b ^ c ^ d) + 0x6ed9eba1; 11048 } else if (i < 60) { 11049 t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; 11050 } else /* if (i < 80) */ { 11051 t += (b ^ c ^ d) - 0x359d3e2a; 11052 } 11053 11054 e = d; 11055 d = c; 11056 c = (b << 30) | (b >>> 2); 11057 b = a; 11058 a = t; 11059 } 11060 11061 // Intermediate hash value 11062 H[0] = (H[0] + a) | 0; 11063 H[1] = (H[1] + b) | 0; 11064 H[2] = (H[2] + c) | 0; 11065 H[3] = (H[3] + d) | 0; 11066 H[4] = (H[4] + e) | 0; 11067 }, 11068 11069 _doFinalize: function () { 11070 // Shortcuts 11071 var data = this._data; 11072 var dataWords = data.words; 11073 11074 var nBitsTotal = this._nDataBytes * 8; 11075 var nBitsLeft = data.sigBytes * 8; 11076 11077 // Add padding 11078 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 11079 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); 11080 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; 11081 data.sigBytes = dataWords.length * 4; 11082 11083 // Hash final blocks 11084 this._process(); 11085 11086 // Return final computed hash 11087 return this._hash; 11088 }, 11089 11090 clone: function () { 11091 var clone = Hasher.clone.call(this); 11092 clone._hash = this._hash.clone(); 11093 11094 return clone; 11095 } 11096 }); 11097 11098 /** 11099 * Shortcut function to the hasher's object interface. 11100 * 11101 * @param {WordArray|string} message The message to hash. 11102 * 11103 * @return {WordArray} The hash. 11104 * 11105 * @static 11106 * 11107 * @example 11108 * 11109 * var hash = CryptoJS.SHA1('message'); 11110 * var hash = CryptoJS.SHA1(wordArray); 11111 */ 11112 C.SHA1 = Hasher._createHelper(SHA1); 11113 11114 /** 11115 * Shortcut function to the HMAC's object interface. 11116 * 11117 * @param {WordArray|string} message The message to hash. 11118 * @param {WordArray|string} key The secret key. 11119 * 11120 * @return {WordArray} The HMAC. 11121 * 11122 * @static 11123 * 11124 * @example 11125 * 11126 * var hmac = CryptoJS.HmacSHA1(message, key); 11127 */ 11128 C.HmacSHA1 = Hasher._createHmacHelper(SHA1); 11129 }()); 11130 11131 11132 return CryptoJS.SHA1; 11133 11134 })); 11135 },{"./core":53}],78:[function(require,module,exports){ 11136 ;(function (root, factory, undef) { 11137 if (typeof exports === "object") { 11138 // CommonJS 11139 module.exports = exports = factory(require("./core"), require("./sha256")); 11140 } 11141 else if (typeof define === "function" && define.amd) { 11142 // AMD 11143 define(["./core", "./sha256"], factory); 11144 } 11145 else { 11146 // Global (browser) 11147 factory(root.CryptoJS); 11148 } 11149 }(this, function (CryptoJS) { 11150 11151 (function () { 11152 // Shortcuts 11153 var C = CryptoJS; 11154 var C_lib = C.lib; 11155 var WordArray = C_lib.WordArray; 11156 var C_algo = C.algo; 11157 var SHA256 = C_algo.SHA256; 11158 11159 /** 11160 * SHA-224 hash algorithm. 11161 */ 11162 var SHA224 = C_algo.SHA224 = SHA256.extend({ 11163 _doReset: function () { 11164 this._hash = new WordArray.init([ 11165 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 11166 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 11167 ]); 11168 }, 11169 11170 _doFinalize: function () { 11171 var hash = SHA256._doFinalize.call(this); 11172 11173 hash.sigBytes -= 4; 11174 11175 return hash; 11176 } 11177 }); 11178 11179 /** 11180 * Shortcut function to the hasher's object interface. 11181 * 11182 * @param {WordArray|string} message The message to hash. 11183 * 11184 * @return {WordArray} The hash. 11185 * 11186 * @static 11187 * 11188 * @example 11189 * 11190 * var hash = CryptoJS.SHA224('message'); 11191 * var hash = CryptoJS.SHA224(wordArray); 11192 */ 11193 C.SHA224 = SHA256._createHelper(SHA224); 11194 11195 /** 11196 * Shortcut function to the HMAC's object interface. 11197 * 11198 * @param {WordArray|string} message The message to hash. 11199 * @param {WordArray|string} key The secret key. 11200 * 11201 * @return {WordArray} The HMAC. 11202 * 11203 * @static 11204 * 11205 * @example 11206 * 11207 * var hmac = CryptoJS.HmacSHA224(message, key); 11208 */ 11209 C.HmacSHA224 = SHA256._createHmacHelper(SHA224); 11210 }()); 11211 11212 11213 return CryptoJS.SHA224; 11214 11215 })); 11216 },{"./core":53,"./sha256":79}],79:[function(require,module,exports){ 11217 ;(function (root, factory) { 11218 if (typeof exports === "object") { 11219 // CommonJS 11220 module.exports = exports = factory(require("./core")); 11221 } 11222 else if (typeof define === "function" && define.amd) { 11223 // AMD 11224 define(["./core"], factory); 11225 } 11226 else { 11227 // Global (browser) 11228 factory(root.CryptoJS); 11229 } 11230 }(this, function (CryptoJS) { 11231 11232 (function (Math) { 11233 // Shortcuts 11234 var C = CryptoJS; 11235 var C_lib = C.lib; 11236 var WordArray = C_lib.WordArray; 11237 var Hasher = C_lib.Hasher; 11238 var C_algo = C.algo; 11239 11240 // Initialization and round constants tables 11241 var H = []; 11242 var K = []; 11243 11244 // Compute constants 11245 (function () { 11246 function isPrime(n) { 11247 var sqrtN = Math.sqrt(n); 11248 for (var factor = 2; factor <= sqrtN; factor++) { 11249 if (!(n % factor)) { 11250 return false; 11251 } 11252 } 11253 11254 return true; 11255 } 11256 11257 function getFractionalBits(n) { 11258 return ((n - (n | 0)) * 0x100000000) | 0; 11259 } 11260 11261 var n = 2; 11262 var nPrime = 0; 11263 while (nPrime < 64) { 11264 if (isPrime(n)) { 11265 if (nPrime < 8) { 11266 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); 11267 } 11268 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); 11269 11270 nPrime++; 11271 } 11272 11273 n++; 11274 } 11275 }()); 11276 11277 // Reusable object 11278 var W = []; 11279 11280 /** 11281 * SHA-256 hash algorithm. 11282 */ 11283 var SHA256 = C_algo.SHA256 = Hasher.extend({ 11284 _doReset: function () { 11285 this._hash = new WordArray.init(H.slice(0)); 11286 }, 11287 11288 _doProcessBlock: function (M, offset) { 11289 // Shortcut 11290 var H = this._hash.words; 11291 11292 // Working variables 11293 var a = H[0]; 11294 var b = H[1]; 11295 var c = H[2]; 11296 var d = H[3]; 11297 var e = H[4]; 11298 var f = H[5]; 11299 var g = H[6]; 11300 var h = H[7]; 11301 11302 // Computation 11303 for (var i = 0; i < 64; i++) { 11304 if (i < 16) { 11305 W[i] = M[offset + i] | 0; 11306 } else { 11307 var gamma0x = W[i - 15]; 11308 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ 11309 ((gamma0x << 14) | (gamma0x >>> 18)) ^ 11310 (gamma0x >>> 3); 11311 11312 var gamma1x = W[i - 2]; 11313 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ 11314 ((gamma1x << 13) | (gamma1x >>> 19)) ^ 11315 (gamma1x >>> 10); 11316 11317 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; 11318 } 11319 11320 var ch = (e & f) ^ (~e & g); 11321 var maj = (a & b) ^ (a & c) ^ (b & c); 11322 11323 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); 11324 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); 11325 11326 var t1 = h + sigma1 + ch + K[i] + W[i]; 11327 var t2 = sigma0 + maj; 11328 11329 h = g; 11330 g = f; 11331 f = e; 11332 e = (d + t1) | 0; 11333 d = c; 11334 c = b; 11335 b = a; 11336 a = (t1 + t2) | 0; 11337 } 11338 11339 // Intermediate hash value 11340 H[0] = (H[0] + a) | 0; 11341 H[1] = (H[1] + b) | 0; 11342 H[2] = (H[2] + c) | 0; 11343 H[3] = (H[3] + d) | 0; 11344 H[4] = (H[4] + e) | 0; 11345 H[5] = (H[5] + f) | 0; 11346 H[6] = (H[6] + g) | 0; 11347 H[7] = (H[7] + h) | 0; 11348 }, 11349 11350 _doFinalize: function () { 11351 // Shortcuts 11352 var data = this._data; 11353 var dataWords = data.words; 11354 11355 var nBitsTotal = this._nDataBytes * 8; 11356 var nBitsLeft = data.sigBytes * 8; 11357 11358 // Add padding 11359 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 11360 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); 11361 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; 11362 data.sigBytes = dataWords.length * 4; 11363 11364 // Hash final blocks 11365 this._process(); 11366 11367 // Return final computed hash 11368 return this._hash; 11369 }, 11370 11371 clone: function () { 11372 var clone = Hasher.clone.call(this); 11373 clone._hash = this._hash.clone(); 11374 11375 return clone; 11376 } 11377 }); 11378 11379 /** 11380 * Shortcut function to the hasher's object interface. 11381 * 11382 * @param {WordArray|string} message The message to hash. 11383 * 11384 * @return {WordArray} The hash. 11385 * 11386 * @static 11387 * 11388 * @example 11389 * 11390 * var hash = CryptoJS.SHA256('message'); 11391 * var hash = CryptoJS.SHA256(wordArray); 11392 */ 11393 C.SHA256 = Hasher._createHelper(SHA256); 11394 11395 /** 11396 * Shortcut function to the HMAC's object interface. 11397 * 11398 * @param {WordArray|string} message The message to hash. 11399 * @param {WordArray|string} key The secret key. 11400 * 11401 * @return {WordArray} The HMAC. 11402 * 11403 * @static 11404 * 11405 * @example 11406 * 11407 * var hmac = CryptoJS.HmacSHA256(message, key); 11408 */ 11409 C.HmacSHA256 = Hasher._createHmacHelper(SHA256); 11410 }(Math)); 11411 11412 11413 return CryptoJS.SHA256; 11414 11415 })); 11416 },{"./core":53}],80:[function(require,module,exports){ 11417 ;(function (root, factory, undef) { 11418 if (typeof exports === "object") { 11419 // CommonJS 11420 module.exports = exports = factory(require("./core"), require("./x64-core")); 11421 } 11422 else if (typeof define === "function" && define.amd) { 11423 // AMD 11424 define(["./core", "./x64-core"], factory); 11425 } 11426 else { 11427 // Global (browser) 11428 factory(root.CryptoJS); 11429 } 11430 }(this, function (CryptoJS) { 11431 11432 (function (Math) { 11433 // Shortcuts 11434 var C = CryptoJS; 11435 var C_lib = C.lib; 11436 var WordArray = C_lib.WordArray; 11437 var Hasher = C_lib.Hasher; 11438 var C_x64 = C.x64; 11439 var X64Word = C_x64.Word; 11440 var C_algo = C.algo; 11441 11442 // Constants tables 11443 var RHO_OFFSETS = []; 11444 var PI_INDEXES = []; 11445 var ROUND_CONSTANTS = []; 11446 11447 // Compute Constants 11448 (function () { 11449 // Compute rho offset constants 11450 var x = 1, y = 0; 11451 for (var t = 0; t < 24; t++) { 11452 RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; 11453 11454 var newX = y % 5; 11455 var newY = (2 * x + 3 * y) % 5; 11456 x = newX; 11457 y = newY; 11458 } 11459 11460 // Compute pi index constants 11461 for (var x = 0; x < 5; x++) { 11462 for (var y = 0; y < 5; y++) { 11463 PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; 11464 } 11465 } 11466 11467 // Compute round constants 11468 var LFSR = 0x01; 11469 for (var i = 0; i < 24; i++) { 11470 var roundConstantMsw = 0; 11471 var roundConstantLsw = 0; 11472 11473 for (var j = 0; j < 7; j++) { 11474 if (LFSR & 0x01) { 11475 var bitPosition = (1 << j) - 1; 11476 if (bitPosition < 32) { 11477 roundConstantLsw ^= 1 << bitPosition; 11478 } else /* if (bitPosition >= 32) */ { 11479 roundConstantMsw ^= 1 << (bitPosition - 32); 11480 } 11481 } 11482 11483 // Compute next LFSR 11484 if (LFSR & 0x80) { 11485 // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 11486 LFSR = (LFSR << 1) ^ 0x71; 11487 } else { 11488 LFSR <<= 1; 11489 } 11490 } 11491 11492 ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); 11493 } 11494 }()); 11495 11496 // Reusable objects for temporary values 11497 var T = []; 11498 (function () { 11499 for (var i = 0; i < 25; i++) { 11500 T[i] = X64Word.create(); 11501 } 11502 }()); 11503 11504 /** 11505 * SHA-3 hash algorithm. 11506 */ 11507 var SHA3 = C_algo.SHA3 = Hasher.extend({ 11508 /** 11509 * Configuration options. 11510 * 11511 * @property {number} outputLength 11512 * The desired number of bits in the output hash. 11513 * Only values permitted are: 224, 256, 384, 512. 11514 * Default: 512 11515 */ 11516 cfg: Hasher.cfg.extend({ 11517 outputLength: 512 11518 }), 11519 11520 _doReset: function () { 11521 var state = this._state = [] 11522 for (var i = 0; i < 25; i++) { 11523 state[i] = new X64Word.init(); 11524 } 11525 11526 this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; 11527 }, 11528 11529 _doProcessBlock: function (M, offset) { 11530 // Shortcuts 11531 var state = this._state; 11532 var nBlockSizeLanes = this.blockSize / 2; 11533 11534 // Absorb 11535 for (var i = 0; i < nBlockSizeLanes; i++) { 11536 // Shortcuts 11537 var M2i = M[offset + 2 * i]; 11538 var M2i1 = M[offset + 2 * i + 1]; 11539 11540 // Swap endian 11541 M2i = ( 11542 (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | 11543 (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) 11544 ); 11545 M2i1 = ( 11546 (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | 11547 (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) 11548 ); 11549 11550 // Absorb message into state 11551 var lane = state[i]; 11552 lane.high ^= M2i1; 11553 lane.low ^= M2i; 11554 } 11555 11556 // Rounds 11557 for (var round = 0; round < 24; round++) { 11558 // Theta 11559 for (var x = 0; x < 5; x++) { 11560 // Mix column lanes 11561 var tMsw = 0, tLsw = 0; 11562 for (var y = 0; y < 5; y++) { 11563 var lane = state[x + 5 * y]; 11564 tMsw ^= lane.high; 11565 tLsw ^= lane.low; 11566 } 11567 11568 // Temporary values 11569 var Tx = T[x]; 11570 Tx.high = tMsw; 11571 Tx.low = tLsw; 11572 } 11573 for (var x = 0; x < 5; x++) { 11574 // Shortcuts 11575 var Tx4 = T[(x + 4) % 5]; 11576 var Tx1 = T[(x + 1) % 5]; 11577 var Tx1Msw = Tx1.high; 11578 var Tx1Lsw = Tx1.low; 11579 11580 // Mix surrounding columns 11581 var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); 11582 var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); 11583 for (var y = 0; y < 5; y++) { 11584 var lane = state[x + 5 * y]; 11585 lane.high ^= tMsw; 11586 lane.low ^= tLsw; 11587 } 11588 } 11589 11590 // Rho Pi 11591 for (var laneIndex = 1; laneIndex < 25; laneIndex++) { 11592 // Shortcuts 11593 var lane = state[laneIndex]; 11594 var laneMsw = lane.high; 11595 var laneLsw = lane.low; 11596 var rhoOffset = RHO_OFFSETS[laneIndex]; 11597 11598 // Rotate lanes 11599 if (rhoOffset < 32) { 11600 var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); 11601 var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); 11602 } else /* if (rhoOffset >= 32) */ { 11603 var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); 11604 var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); 11605 } 11606 11607 // Transpose lanes 11608 var TPiLane = T[PI_INDEXES[laneIndex]]; 11609 TPiLane.high = tMsw; 11610 TPiLane.low = tLsw; 11611 } 11612 11613 // Rho pi at x = y = 0 11614 var T0 = T[0]; 11615 var state0 = state[0]; 11616 T0.high = state0.high; 11617 T0.low = state0.low; 11618 11619 // Chi 11620 for (var x = 0; x < 5; x++) { 11621 for (var y = 0; y < 5; y++) { 11622 // Shortcuts 11623 var laneIndex = x + 5 * y; 11624 var lane = state[laneIndex]; 11625 var TLane = T[laneIndex]; 11626 var Tx1Lane = T[((x + 1) % 5) + 5 * y]; 11627 var Tx2Lane = T[((x + 2) % 5) + 5 * y]; 11628 11629 // Mix rows 11630 lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); 11631 lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); 11632 } 11633 } 11634 11635 // Iota 11636 var lane = state[0]; 11637 var roundConstant = ROUND_CONSTANTS[round]; 11638 lane.high ^= roundConstant.high; 11639 lane.low ^= roundConstant.low;; 11640 } 11641 }, 11642 11643 _doFinalize: function () { 11644 // Shortcuts 11645 var data = this._data; 11646 var dataWords = data.words; 11647 var nBitsTotal = this._nDataBytes * 8; 11648 var nBitsLeft = data.sigBytes * 8; 11649 var blockSizeBits = this.blockSize * 32; 11650 11651 // Add padding 11652 dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); 11653 dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; 11654 data.sigBytes = dataWords.length * 4; 11655 11656 // Hash final blocks 11657 this._process(); 11658 11659 // Shortcuts 11660 var state = this._state; 11661 var outputLengthBytes = this.cfg.outputLength / 8; 11662 var outputLengthLanes = outputLengthBytes / 8; 11663 11664 // Squeeze 11665 var hashWords = []; 11666 for (var i = 0; i < outputLengthLanes; i++) { 11667 // Shortcuts 11668 var lane = state[i]; 11669 var laneMsw = lane.high; 11670 var laneLsw = lane.low; 11671 11672 // Swap endian 11673 laneMsw = ( 11674 (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | 11675 (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) 11676 ); 11677 laneLsw = ( 11678 (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | 11679 (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) 11680 ); 11681 11682 // Squeeze state to retrieve hash 11683 hashWords.push(laneLsw); 11684 hashWords.push(laneMsw); 11685 } 11686 11687 // Return final computed hash 11688 return new WordArray.init(hashWords, outputLengthBytes); 11689 }, 11690 11691 clone: function () { 11692 var clone = Hasher.clone.call(this); 11693 11694 var state = clone._state = this._state.slice(0); 11695 for (var i = 0; i < 25; i++) { 11696 state[i] = state[i].clone(); 11697 } 11698 11699 return clone; 11700 } 11701 }); 11702 11703 /** 11704 * Shortcut function to the hasher's object interface. 11705 * 11706 * @param {WordArray|string} message The message to hash. 11707 * 11708 * @return {WordArray} The hash. 11709 * 11710 * @static 11711 * 11712 * @example 11713 * 11714 * var hash = CryptoJS.SHA3('message'); 11715 * var hash = CryptoJS.SHA3(wordArray); 11716 */ 11717 C.SHA3 = Hasher._createHelper(SHA3); 11718 11719 /** 11720 * Shortcut function to the HMAC's object interface. 11721 * 11722 * @param {WordArray|string} message The message to hash. 11723 * @param {WordArray|string} key The secret key. 11724 * 11725 * @return {WordArray} The HMAC. 11726 * 11727 * @static 11728 * 11729 * @example 11730 * 11731 * var hmac = CryptoJS.HmacSHA3(message, key); 11732 */ 11733 C.HmacSHA3 = Hasher._createHmacHelper(SHA3); 11734 }(Math)); 11735 11736 11737 return CryptoJS.SHA3; 11738 11739 })); 11740 },{"./core":53,"./x64-core":84}],81:[function(require,module,exports){ 11741 ;(function (root, factory, undef) { 11742 if (typeof exports === "object") { 11743 // CommonJS 11744 module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512")); 11745 } 11746 else if (typeof define === "function" && define.amd) { 11747 // AMD 11748 define(["./core", "./x64-core", "./sha512"], factory); 11749 } 11750 else { 11751 // Global (browser) 11752 factory(root.CryptoJS); 11753 } 11754 }(this, function (CryptoJS) { 11755 11756 (function () { 11757 // Shortcuts 11758 var C = CryptoJS; 11759 var C_x64 = C.x64; 11760 var X64Word = C_x64.Word; 11761 var X64WordArray = C_x64.WordArray; 11762 var C_algo = C.algo; 11763 var SHA512 = C_algo.SHA512; 11764 11765 /** 11766 * SHA-384 hash algorithm. 11767 */ 11768 var SHA384 = C_algo.SHA384 = SHA512.extend({ 11769 _doReset: function () { 11770 this._hash = new X64WordArray.init([ 11771 new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), 11772 new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), 11773 new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), 11774 new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) 11775 ]); 11776 }, 11777 11778 _doFinalize: function () { 11779 var hash = SHA512._doFinalize.call(this); 11780 11781 hash.sigBytes -= 16; 11782 11783 return hash; 11784 } 11785 }); 11786 11787 /** 11788 * Shortcut function to the hasher's object interface. 11789 * 11790 * @param {WordArray|string} message The message to hash. 11791 * 11792 * @return {WordArray} The hash. 11793 * 11794 * @static 11795 * 11796 * @example 11797 * 11798 * var hash = CryptoJS.SHA384('message'); 11799 * var hash = CryptoJS.SHA384(wordArray); 11800 */ 11801 C.SHA384 = SHA512._createHelper(SHA384); 11802 11803 /** 11804 * Shortcut function to the HMAC's object interface. 11805 * 11806 * @param {WordArray|string} message The message to hash. 11807 * @param {WordArray|string} key The secret key. 11808 * 11809 * @return {WordArray} The HMAC. 11810 * 11811 * @static 11812 * 11813 * @example 11814 * 11815 * var hmac = CryptoJS.HmacSHA384(message, key); 11816 */ 11817 C.HmacSHA384 = SHA512._createHmacHelper(SHA384); 11818 }()); 11819 11820 11821 return CryptoJS.SHA384; 11822 11823 })); 11824 },{"./core":53,"./sha512":82,"./x64-core":84}],82:[function(require,module,exports){ 11825 ;(function (root, factory, undef) { 11826 if (typeof exports === "object") { 11827 // CommonJS 11828 module.exports = exports = factory(require("./core"), require("./x64-core")); 11829 } 11830 else if (typeof define === "function" && define.amd) { 11831 // AMD 11832 define(["./core", "./x64-core"], factory); 11833 } 11834 else { 11835 // Global (browser) 11836 factory(root.CryptoJS); 11837 } 11838 }(this, function (CryptoJS) { 11839 11840 (function () { 11841 // Shortcuts 11842 var C = CryptoJS; 11843 var C_lib = C.lib; 11844 var Hasher = C_lib.Hasher; 11845 var C_x64 = C.x64; 11846 var X64Word = C_x64.Word; 11847 var X64WordArray = C_x64.WordArray; 11848 var C_algo = C.algo; 11849 11850 function X64Word_create() { 11851 return X64Word.create.apply(X64Word, arguments); 11852 } 11853 11854 // Constants 11855 var K = [ 11856 X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), 11857 X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), 11858 X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), 11859 X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), 11860 X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), 11861 X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), 11862 X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), 11863 X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), 11864 X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), 11865 X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), 11866 X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), 11867 X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), 11868 X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), 11869 X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), 11870 X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), 11871 X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), 11872 X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), 11873 X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), 11874 X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), 11875 X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), 11876 X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), 11877 X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), 11878 X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), 11879 X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), 11880 X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), 11881 X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), 11882 X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), 11883 X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), 11884 X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), 11885 X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), 11886 X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), 11887 X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), 11888 X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), 11889 X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), 11890 X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), 11891 X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), 11892 X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), 11893 X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), 11894 X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), 11895 X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) 11896 ]; 11897 11898 // Reusable objects 11899 var W = []; 11900 (function () { 11901 for (var i = 0; i < 80; i++) { 11902 W[i] = X64Word_create(); 11903 } 11904 }()); 11905 11906 /** 11907 * SHA-512 hash algorithm. 11908 */ 11909 var SHA512 = C_algo.SHA512 = Hasher.extend({ 11910 _doReset: function () { 11911 this._hash = new X64WordArray.init([ 11912 new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), 11913 new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), 11914 new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), 11915 new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) 11916 ]); 11917 }, 11918 11919 _doProcessBlock: function (M, offset) { 11920 // Shortcuts 11921 var H = this._hash.words; 11922 11923 var H0 = H[0]; 11924 var H1 = H[1]; 11925 var H2 = H[2]; 11926 var H3 = H[3]; 11927 var H4 = H[4]; 11928 var H5 = H[5]; 11929 var H6 = H[6]; 11930 var H7 = H[7]; 11931 11932 var H0h = H0.high; 11933 var H0l = H0.low; 11934 var H1h = H1.high; 11935 var H1l = H1.low; 11936 var H2h = H2.high; 11937 var H2l = H2.low; 11938 var H3h = H3.high; 11939 var H3l = H3.low; 11940 var H4h = H4.high; 11941 var H4l = H4.low; 11942 var H5h = H5.high; 11943 var H5l = H5.low; 11944 var H6h = H6.high; 11945 var H6l = H6.low; 11946 var H7h = H7.high; 11947 var H7l = H7.low; 11948 11949 // Working variables 11950 var ah = H0h; 11951 var al = H0l; 11952 var bh = H1h; 11953 var bl = H1l; 11954 var ch = H2h; 11955 var cl = H2l; 11956 var dh = H3h; 11957 var dl = H3l; 11958 var eh = H4h; 11959 var el = H4l; 11960 var fh = H5h; 11961 var fl = H5l; 11962 var gh = H6h; 11963 var gl = H6l; 11964 var hh = H7h; 11965 var hl = H7l; 11966 11967 // Rounds 11968 for (var i = 0; i < 80; i++) { 11969 // Shortcut 11970 var Wi = W[i]; 11971 11972 // Extend message 11973 if (i < 16) { 11974 var Wih = Wi.high = M[offset + i * 2] | 0; 11975 var Wil = Wi.low = M[offset + i * 2 + 1] | 0; 11976 } else { 11977 // Gamma0 11978 var gamma0x = W[i - 15]; 11979 var gamma0xh = gamma0x.high; 11980 var gamma0xl = gamma0x.low; 11981 var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); 11982 var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); 11983 11984 // Gamma1 11985 var gamma1x = W[i - 2]; 11986 var gamma1xh = gamma1x.high; 11987 var gamma1xl = gamma1x.low; 11988 var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); 11989 var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); 11990 11991 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] 11992 var Wi7 = W[i - 7]; 11993 var Wi7h = Wi7.high; 11994 var Wi7l = Wi7.low; 11995 11996 var Wi16 = W[i - 16]; 11997 var Wi16h = Wi16.high; 11998 var Wi16l = Wi16.low; 11999 12000 var Wil = gamma0l + Wi7l; 12001 var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); 12002 var Wil = Wil + gamma1l; 12003 var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); 12004 var Wil = Wil + Wi16l; 12005 var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); 12006 12007 Wi.high = Wih; 12008 Wi.low = Wil; 12009 } 12010 12011 var chh = (eh & fh) ^ (~eh & gh); 12012 var chl = (el & fl) ^ (~el & gl); 12013 var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); 12014 var majl = (al & bl) ^ (al & cl) ^ (bl & cl); 12015 12016 var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); 12017 var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); 12018 var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); 12019 var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); 12020 12021 // t1 = h + sigma1 + ch + K[i] + W[i] 12022 var Ki = K[i]; 12023 var Kih = Ki.high; 12024 var Kil = Ki.low; 12025 12026 var t1l = hl + sigma1l; 12027 var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); 12028 var t1l = t1l + chl; 12029 var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); 12030 var t1l = t1l + Kil; 12031 var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); 12032 var t1l = t1l + Wil; 12033 var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); 12034 12035 // t2 = sigma0 + maj 12036 var t2l = sigma0l + majl; 12037 var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); 12038 12039 // Update working variables 12040 hh = gh; 12041 hl = gl; 12042 gh = fh; 12043 gl = fl; 12044 fh = eh; 12045 fl = el; 12046 el = (dl + t1l) | 0; 12047 eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; 12048 dh = ch; 12049 dl = cl; 12050 ch = bh; 12051 cl = bl; 12052 bh = ah; 12053 bl = al; 12054 al = (t1l + t2l) | 0; 12055 ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; 12056 } 12057 12058 // Intermediate hash value 12059 H0l = H0.low = (H0l + al); 12060 H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); 12061 H1l = H1.low = (H1l + bl); 12062 H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); 12063 H2l = H2.low = (H2l + cl); 12064 H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); 12065 H3l = H3.low = (H3l + dl); 12066 H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); 12067 H4l = H4.low = (H4l + el); 12068 H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); 12069 H5l = H5.low = (H5l + fl); 12070 H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); 12071 H6l = H6.low = (H6l + gl); 12072 H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); 12073 H7l = H7.low = (H7l + hl); 12074 H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); 12075 }, 12076 12077 _doFinalize: function () { 12078 // Shortcuts 12079 var data = this._data; 12080 var dataWords = data.words; 12081 12082 var nBitsTotal = this._nDataBytes * 8; 12083 var nBitsLeft = data.sigBytes * 8; 12084 12085 // Add padding 12086 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); 12087 dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); 12088 dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; 12089 data.sigBytes = dataWords.length * 4; 12090 12091 // Hash final blocks 12092 this._process(); 12093 12094 // Convert hash to 32-bit word array before returning 12095 var hash = this._hash.toX32(); 12096 12097 // Return final computed hash 12098 return hash; 12099 }, 12100 12101 clone: function () { 12102 var clone = Hasher.clone.call(this); 12103 clone._hash = this._hash.clone(); 12104 12105 return clone; 12106 }, 12107 12108 blockSize: 1024/32 12109 }); 12110 12111 /** 12112 * Shortcut function to the hasher's object interface. 12113 * 12114 * @param {WordArray|string} message The message to hash. 12115 * 12116 * @return {WordArray} The hash. 12117 * 12118 * @static 12119 * 12120 * @example 12121 * 12122 * var hash = CryptoJS.SHA512('message'); 12123 * var hash = CryptoJS.SHA512(wordArray); 12124 */ 12125 C.SHA512 = Hasher._createHelper(SHA512); 12126 12127 /** 12128 * Shortcut function to the HMAC's object interface. 12129 * 12130 * @param {WordArray|string} message The message to hash. 12131 * @param {WordArray|string} key The secret key. 12132 * 12133 * @return {WordArray} The HMAC. 12134 * 12135 * @static 12136 * 12137 * @example 12138 * 12139 * var hmac = CryptoJS.HmacSHA512(message, key); 12140 */ 12141 C.HmacSHA512 = Hasher._createHmacHelper(SHA512); 12142 }()); 12143 12144 12145 return CryptoJS.SHA512; 12146 12147 })); 12148 },{"./core":53,"./x64-core":84}],83:[function(require,module,exports){ 12149 ;(function (root, factory, undef) { 12150 if (typeof exports === "object") { 12151 // CommonJS 12152 module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); 12153 } 12154 else if (typeof define === "function" && define.amd) { 12155 // AMD 12156 define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); 12157 } 12158 else { 12159 // Global (browser) 12160 factory(root.CryptoJS); 12161 } 12162 }(this, function (CryptoJS) { 12163 12164 (function () { 12165 // Shortcuts 12166 var C = CryptoJS; 12167 var C_lib = C.lib; 12168 var WordArray = C_lib.WordArray; 12169 var BlockCipher = C_lib.BlockCipher; 12170 var C_algo = C.algo; 12171 12172 // Permuted Choice 1 constants 12173 var PC1 = [ 12174 57, 49, 41, 33, 25, 17, 9, 1, 12175 58, 50, 42, 34, 26, 18, 10, 2, 12176 59, 51, 43, 35, 27, 19, 11, 3, 12177 60, 52, 44, 36, 63, 55, 47, 39, 12178 31, 23, 15, 7, 62, 54, 46, 38, 12179 30, 22, 14, 6, 61, 53, 45, 37, 12180 29, 21, 13, 5, 28, 20, 12, 4 12181 ]; 12182 12183 // Permuted Choice 2 constants 12184 var PC2 = [ 12185 14, 17, 11, 24, 1, 5, 12186 3, 28, 15, 6, 21, 10, 12187 23, 19, 12, 4, 26, 8, 12188 16, 7, 27, 20, 13, 2, 12189 41, 52, 31, 37, 47, 55, 12190 30, 40, 51, 45, 33, 48, 12191 44, 49, 39, 56, 34, 53, 12192 46, 42, 50, 36, 29, 32 12193 ]; 12194 12195 // Cumulative bit shift constants 12196 var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; 12197 12198 // SBOXes and round permutation constants 12199 var SBOX_P = [ 12200 { 12201 0x0: 0x808200, 12202 0x10000000: 0x8000, 12203 0x20000000: 0x808002, 12204 0x30000000: 0x2, 12205 0x40000000: 0x200, 12206 0x50000000: 0x808202, 12207 0x60000000: 0x800202, 12208 0x70000000: 0x800000, 12209 0x80000000: 0x202, 12210 0x90000000: 0x800200, 12211 0xa0000000: 0x8200, 12212 0xb0000000: 0x808000, 12213 0xc0000000: 0x8002, 12214 0xd0000000: 0x800002, 12215 0xe0000000: 0x0, 12216 0xf0000000: 0x8202, 12217 0x8000000: 0x0, 12218 0x18000000: 0x808202, 12219 0x28000000: 0x8202, 12220 0x38000000: 0x8000, 12221 0x48000000: 0x808200, 12222 0x58000000: 0x200, 12223 0x68000000: 0x808002, 12224 0x78000000: 0x2, 12225 0x88000000: 0x800200, 12226 0x98000000: 0x8200, 12227 0xa8000000: 0x808000, 12228 0xb8000000: 0x800202, 12229 0xc8000000: 0x800002, 12230 0xd8000000: 0x8002, 12231 0xe8000000: 0x202, 12232 0xf8000000: 0x800000, 12233 0x1: 0x8000, 12234 0x10000001: 0x2, 12235 0x20000001: 0x808200, 12236 0x30000001: 0x800000, 12237 0x40000001: 0x808002, 12238 0x50000001: 0x8200, 12239 0x60000001: 0x200, 12240 0x70000001: 0x800202, 12241 0x80000001: 0x808202, 12242 0x90000001: 0x808000, 12243 0xa0000001: 0x800002, 12244 0xb0000001: 0x8202, 12245 0xc0000001: 0x202, 12246 0xd0000001: 0x800200, 12247 0xe0000001: 0x8002, 12248 0xf0000001: 0x0, 12249 0x8000001: 0x808202, 12250 0x18000001: 0x808000, 12251 0x28000001: 0x800000, 12252 0x38000001: 0x200, 12253 0x48000001: 0x8000, 12254 0x58000001: 0x800002, 12255 0x68000001: 0x2, 12256 0x78000001: 0x8202, 12257 0x88000001: 0x8002, 12258 0x98000001: 0x800202, 12259 0xa8000001: 0x202, 12260 0xb8000001: 0x808200, 12261 0xc8000001: 0x800200, 12262 0xd8000001: 0x0, 12263 0xe8000001: 0x8200, 12264 0xf8000001: 0x808002 12265 }, 12266 { 12267 0x0: 0x40084010, 12268 0x1000000: 0x4000, 12269 0x2000000: 0x80000, 12270 0x3000000: 0x40080010, 12271 0x4000000: 0x40000010, 12272 0x5000000: 0x40084000, 12273 0x6000000: 0x40004000, 12274 0x7000000: 0x10, 12275 0x8000000: 0x84000, 12276 0x9000000: 0x40004010, 12277 0xa000000: 0x40000000, 12278 0xb000000: 0x84010, 12279 0xc000000: 0x80010, 12280 0xd000000: 0x0, 12281 0xe000000: 0x4010, 12282 0xf000000: 0x40080000, 12283 0x800000: 0x40004000, 12284 0x1800000: 0x84010, 12285 0x2800000: 0x10, 12286 0x3800000: 0x40004010, 12287 0x4800000: 0x40084010, 12288 0x5800000: 0x40000000, 12289 0x6800000: 0x80000, 12290 0x7800000: 0x40080010, 12291 0x8800000: 0x80010, 12292 0x9800000: 0x0, 12293 0xa800000: 0x4000, 12294 0xb800000: 0x40080000, 12295 0xc800000: 0x40000010, 12296 0xd800000: 0x84000, 12297 0xe800000: 0x40084000, 12298 0xf800000: 0x4010, 12299 0x10000000: 0x0, 12300 0x11000000: 0x40080010, 12301 0x12000000: 0x40004010, 12302 0x13000000: 0x40084000, 12303 0x14000000: 0x40080000, 12304 0x15000000: 0x10, 12305 0x16000000: 0x84010, 12306 0x17000000: 0x4000, 12307 0x18000000: 0x4010, 12308 0x19000000: 0x80000, 12309 0x1a000000: 0x80010, 12310 0x1b000000: 0x40000010, 12311 0x1c000000: 0x84000, 12312 0x1d000000: 0x40004000, 12313 0x1e000000: 0x40000000, 12314 0x1f000000: 0x40084010, 12315 0x10800000: 0x84010, 12316 0x11800000: 0x80000, 12317 0x12800000: 0x40080000, 12318 0x13800000: 0x4000, 12319 0x14800000: 0x40004000, 12320 0x15800000: 0x40084010, 12321 0x16800000: 0x10, 12322 0x17800000: 0x40000000, 12323 0x18800000: 0x40084000, 12324 0x19800000: 0x40000010, 12325 0x1a800000: 0x40004010, 12326 0x1b800000: 0x80010, 12327 0x1c800000: 0x0, 12328 0x1d800000: 0x4010, 12329 0x1e800000: 0x40080010, 12330 0x1f800000: 0x84000 12331 }, 12332 { 12333 0x0: 0x104, 12334 0x100000: 0x0, 12335 0x200000: 0x4000100, 12336 0x300000: 0x10104, 12337 0x400000: 0x10004, 12338 0x500000: 0x4000004, 12339 0x600000: 0x4010104, 12340 0x700000: 0x4010000, 12341 0x800000: 0x4000000, 12342 0x900000: 0x4010100, 12343 0xa00000: 0x10100, 12344 0xb00000: 0x4010004, 12345 0xc00000: 0x4000104, 12346 0xd00000: 0x10000, 12347 0xe00000: 0x4, 12348 0xf00000: 0x100, 12349 0x80000: 0x4010100, 12350 0x180000: 0x4010004, 12351 0x280000: 0x0, 12352 0x380000: 0x4000100, 12353 0x480000: 0x4000004, 12354 0x580000: 0x10000, 12355 0x680000: 0x10004, 12356 0x780000: 0x104, 12357 0x880000: 0x4, 12358 0x980000: 0x100, 12359 0xa80000: 0x4010000, 12360 0xb80000: 0x10104, 12361 0xc80000: 0x10100, 12362 0xd80000: 0x4000104, 12363 0xe80000: 0x4010104, 12364 0xf80000: 0x4000000, 12365 0x1000000: 0x4010100, 12366 0x1100000: 0x10004, 12367 0x1200000: 0x10000, 12368 0x1300000: 0x4000100, 12369 0x1400000: 0x100, 12370 0x1500000: 0x4010104, 12371 0x1600000: 0x4000004, 12372 0x1700000: 0x0, 12373 0x1800000: 0x4000104, 12374 0x1900000: 0x4000000, 12375 0x1a00000: 0x4, 12376 0x1b00000: 0x10100, 12377 0x1c00000: 0x4010000, 12378 0x1d00000: 0x104, 12379 0x1e00000: 0x10104, 12380 0x1f00000: 0x4010004, 12381 0x1080000: 0x4000000, 12382 0x1180000: 0x104, 12383 0x1280000: 0x4010100, 12384 0x1380000: 0x0, 12385 0x1480000: 0x10004, 12386 0x1580000: 0x4000100, 12387 0x1680000: 0x100, 12388 0x1780000: 0x4010004, 12389 0x1880000: 0x10000, 12390 0x1980000: 0x4010104, 12391 0x1a80000: 0x10104, 12392 0x1b80000: 0x4000004, 12393 0x1c80000: 0x4000104, 12394 0x1d80000: 0x4010000, 12395 0x1e80000: 0x4, 12396 0x1f80000: 0x10100 12397 }, 12398 { 12399 0x0: 0x80401000, 12400 0x10000: 0x80001040, 12401 0x20000: 0x401040, 12402 0x30000: 0x80400000, 12403 0x40000: 0x0, 12404 0x50000: 0x401000, 12405 0x60000: 0x80000040, 12406 0x70000: 0x400040, 12407 0x80000: 0x80000000, 12408 0x90000: 0x400000, 12409 0xa0000: 0x40, 12410 0xb0000: 0x80001000, 12411 0xc0000: 0x80400040, 12412 0xd0000: 0x1040, 12413 0xe0000: 0x1000, 12414 0xf0000: 0x80401040, 12415 0x8000: 0x80001040, 12416 0x18000: 0x40, 12417 0x28000: 0x80400040, 12418 0x38000: 0x80001000, 12419 0x48000: 0x401000, 12420 0x58000: 0x80401040, 12421 0x68000: 0x0, 12422 0x78000: 0x80400000, 12423 0x88000: 0x1000, 12424 0x98000: 0x80401000, 12425 0xa8000: 0x400000, 12426 0xb8000: 0x1040, 12427 0xc8000: 0x80000000, 12428 0xd8000: 0x400040, 12429 0xe8000: 0x401040, 12430 0xf8000: 0x80000040, 12431 0x100000: 0x400040, 12432 0x110000: 0x401000, 12433 0x120000: 0x80000040, 12434 0x130000: 0x0, 12435 0x140000: 0x1040, 12436 0x150000: 0x80400040, 12437 0x160000: 0x80401000, 12438 0x170000: 0x80001040, 12439 0x180000: 0x80401040, 12440 0x190000: 0x80000000, 12441 0x1a0000: 0x80400000, 12442 0x1b0000: 0x401040, 12443 0x1c0000: 0x80001000, 12444 0x1d0000: 0x400000, 12445 0x1e0000: 0x40, 12446 0x1f0000: 0x1000, 12447 0x108000: 0x80400000, 12448 0x118000: 0x80401040, 12449 0x128000: 0x0, 12450 0x138000: 0x401000, 12451 0x148000: 0x400040, 12452 0x158000: 0x80000000, 12453 0x168000: 0x80001040, 12454 0x178000: 0x40, 12455 0x188000: 0x80000040, 12456 0x198000: 0x1000, 12457 0x1a8000: 0x80001000, 12458 0x1b8000: 0x80400040, 12459 0x1c8000: 0x1040, 12460 0x1d8000: 0x80401000, 12461 0x1e8000: 0x400000, 12462 0x1f8000: 0x401040 12463 }, 12464 { 12465 0x0: 0x80, 12466 0x1000: 0x1040000, 12467 0x2000: 0x40000, 12468 0x3000: 0x20000000, 12469 0x4000: 0x20040080, 12470 0x5000: 0x1000080, 12471 0x6000: 0x21000080, 12472 0x7000: 0x40080, 12473 0x8000: 0x1000000, 12474 0x9000: 0x20040000, 12475 0xa000: 0x20000080, 12476 0xb000: 0x21040080, 12477 0xc000: 0x21040000, 12478 0xd000: 0x0, 12479 0xe000: 0x1040080, 12480 0xf000: 0x21000000, 12481 0x800: 0x1040080, 12482 0x1800: 0x21000080, 12483 0x2800: 0x80, 12484 0x3800: 0x1040000, 12485 0x4800: 0x40000, 12486 0x5800: 0x20040080, 12487 0x6800: 0x21040000, 12488 0x7800: 0x20000000, 12489 0x8800: 0x20040000, 12490 0x9800: 0x0, 12491 0xa800: 0x21040080, 12492 0xb800: 0x1000080, 12493 0xc800: 0x20000080, 12494 0xd800: 0x21000000, 12495 0xe800: 0x1000000, 12496 0xf800: 0x40080, 12497 0x10000: 0x40000, 12498 0x11000: 0x80, 12499 0x12000: 0x20000000, 12500 0x13000: 0x21000080, 12501 0x14000: 0x1000080, 12502 0x15000: 0x21040000, 12503 0x16000: 0x20040080, 12504 0x17000: 0x1000000, 12505 0x18000: 0x21040080, 12506 0x19000: 0x21000000, 12507 0x1a000: 0x1040000, 12508 0x1b000: 0x20040000, 12509 0x1c000: 0x40080, 12510 0x1d000: 0x20000080, 12511 0x1e000: 0x0, 12512 0x1f000: 0x1040080, 12513 0x10800: 0x21000080, 12514 0x11800: 0x1000000, 12515 0x12800: 0x1040000, 12516 0x13800: 0x20040080, 12517 0x14800: 0x20000000, 12518 0x15800: 0x1040080, 12519 0x16800: 0x80, 12520 0x17800: 0x21040000, 12521 0x18800: 0x40080, 12522 0x19800: 0x21040080, 12523 0x1a800: 0x0, 12524 0x1b800: 0x21000000, 12525 0x1c800: 0x1000080, 12526 0x1d800: 0x40000, 12527 0x1e800: 0x20040000, 12528 0x1f800: 0x20000080 12529 }, 12530 { 12531 0x0: 0x10000008, 12532 0x100: 0x2000, 12533 0x200: 0x10200000, 12534 0x300: 0x10202008, 12535 0x400: 0x10002000, 12536 0x500: 0x200000, 12537 0x600: 0x200008, 12538 0x700: 0x10000000, 12539 0x800: 0x0, 12540 0x900: 0x10002008, 12541 0xa00: 0x202000, 12542 0xb00: 0x8, 12543 0xc00: 0x10200008, 12544 0xd00: 0x202008, 12545 0xe00: 0x2008, 12546 0xf00: 0x10202000, 12547 0x80: 0x10200000, 12548 0x180: 0x10202008, 12549 0x280: 0x8, 12550 0x380: 0x200000, 12551 0x480: 0x202008, 12552 0x580: 0x10000008, 12553 0x680: 0x10002000, 12554 0x780: 0x2008, 12555 0x880: 0x200008, 12556 0x980: 0x2000, 12557 0xa80: 0x10002008, 12558 0xb80: 0x10200008, 12559 0xc80: 0x0, 12560 0xd80: 0x10202000, 12561 0xe80: 0x202000, 12562 0xf80: 0x10000000, 12563 0x1000: 0x10002000, 12564 0x1100: 0x10200008, 12565 0x1200: 0x10202008, 12566 0x1300: 0x2008, 12567 0x1400: 0x200000, 12568 0x1500: 0x10000000, 12569 0x1600: 0x10000008, 12570 0x1700: 0x202000, 12571 0x1800: 0x202008, 12572 0x1900: 0x0, 12573 0x1a00: 0x8, 12574 0x1b00: 0x10200000, 12575 0x1c00: 0x2000, 12576 0x1d00: 0x10002008, 12577 0x1e00: 0x10202000, 12578 0x1f00: 0x200008, 12579 0x1080: 0x8, 12580 0x1180: 0x202000, 12581 0x1280: 0x200000, 12582 0x1380: 0x10000008, 12583 0x1480: 0x10002000, 12584 0x1580: 0x2008, 12585 0x1680: 0x10202008, 12586 0x1780: 0x10200000, 12587 0x1880: 0x10202000, 12588 0x1980: 0x10200008, 12589 0x1a80: 0x2000, 12590 0x1b80: 0x202008, 12591 0x1c80: 0x200008, 12592 0x1d80: 0x0, 12593 0x1e80: 0x10000000, 12594 0x1f80: 0x10002008 12595 }, 12596 { 12597 0x0: 0x100000, 12598 0x10: 0x2000401, 12599 0x20: 0x400, 12600 0x30: 0x100401, 12601 0x40: 0x2100401, 12602 0x50: 0x0, 12603 0x60: 0x1, 12604 0x70: 0x2100001, 12605 0x80: 0x2000400, 12606 0x90: 0x100001, 12607 0xa0: 0x2000001, 12608 0xb0: 0x2100400, 12609 0xc0: 0x2100000, 12610 0xd0: 0x401, 12611 0xe0: 0x100400, 12612 0xf0: 0x2000000, 12613 0x8: 0x2100001, 12614 0x18: 0x0, 12615 0x28: 0x2000401, 12616 0x38: 0x2100400, 12617 0x48: 0x100000, 12618 0x58: 0x2000001, 12619 0x68: 0x2000000, 12620 0x78: 0x401, 12621 0x88: 0x100401, 12622 0x98: 0x2000400, 12623 0xa8: 0x2100000, 12624 0xb8: 0x100001, 12625 0xc8: 0x400, 12626 0xd8: 0x2100401, 12627 0xe8: 0x1, 12628 0xf8: 0x100400, 12629 0x100: 0x2000000, 12630 0x110: 0x100000, 12631 0x120: 0x2000401, 12632 0x130: 0x2100001, 12633 0x140: 0x100001, 12634 0x150: 0x2000400, 12635 0x160: 0x2100400, 12636 0x170: 0x100401, 12637 0x180: 0x401, 12638 0x190: 0x2100401, 12639 0x1a0: 0x100400, 12640 0x1b0: 0x1, 12641 0x1c0: 0x0, 12642 0x1d0: 0x2100000, 12643 0x1e0: 0x2000001, 12644 0x1f0: 0x400, 12645 0x108: 0x100400, 12646 0x118: 0x2000401, 12647 0x128: 0x2100001, 12648 0x138: 0x1, 12649 0x148: 0x2000000, 12650 0x158: 0x100000, 12651 0x168: 0x401, 12652 0x178: 0x2100400, 12653 0x188: 0x2000001, 12654 0x198: 0x2100000, 12655 0x1a8: 0x0, 12656 0x1b8: 0x2100401, 12657 0x1c8: 0x100401, 12658 0x1d8: 0x400, 12659 0x1e8: 0x2000400, 12660 0x1f8: 0x100001 12661 }, 12662 { 12663 0x0: 0x8000820, 12664 0x1: 0x20000, 12665 0x2: 0x8000000, 12666 0x3: 0x20, 12667 0x4: 0x20020, 12668 0x5: 0x8020820, 12669 0x6: 0x8020800, 12670 0x7: 0x800, 12671 0x8: 0x8020000, 12672 0x9: 0x8000800, 12673 0xa: 0x20800, 12674 0xb: 0x8020020, 12675 0xc: 0x820, 12676 0xd: 0x0, 12677 0xe: 0x8000020, 12678 0xf: 0x20820, 12679 0x80000000: 0x800, 12680 0x80000001: 0x8020820, 12681 0x80000002: 0x8000820, 12682 0x80000003: 0x8000000, 12683 0x80000004: 0x8020000, 12684 0x80000005: 0x20800, 12685 0x80000006: 0x20820, 12686 0x80000007: 0x20, 12687 0x80000008: 0x8000020, 12688 0x80000009: 0x820, 12689 0x8000000a: 0x20020, 12690 0x8000000b: 0x8020800, 12691 0x8000000c: 0x0, 12692 0x8000000d: 0x8020020, 12693 0x8000000e: 0x8000800, 12694 0x8000000f: 0x20000, 12695 0x10: 0x20820, 12696 0x11: 0x8020800, 12697 0x12: 0x20, 12698 0x13: 0x800, 12699 0x14: 0x8000800, 12700 0x15: 0x8000020, 12701 0x16: 0x8020020, 12702 0x17: 0x20000, 12703 0x18: 0x0, 12704 0x19: 0x20020, 12705 0x1a: 0x8020000, 12706 0x1b: 0x8000820, 12707 0x1c: 0x8020820, 12708 0x1d: 0x20800, 12709 0x1e: 0x820, 12710 0x1f: 0x8000000, 12711 0x80000010: 0x20000, 12712 0x80000011: 0x800, 12713 0x80000012: 0x8020020, 12714 0x80000013: 0x20820, 12715 0x80000014: 0x20, 12716 0x80000015: 0x8020000, 12717 0x80000016: 0x8000000, 12718 0x80000017: 0x8000820, 12719 0x80000018: 0x8020820, 12720 0x80000019: 0x8000020, 12721 0x8000001a: 0x8000800, 12722 0x8000001b: 0x0, 12723 0x8000001c: 0x20800, 12724 0x8000001d: 0x820, 12725 0x8000001e: 0x20020, 12726 0x8000001f: 0x8020800 12727 } 12728 ]; 12729 12730 // Masks that select the SBOX input 12731 var SBOX_MASK = [ 12732 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 12733 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f 12734 ]; 12735 12736 /** 12737 * DES block cipher algorithm. 12738 */ 12739 var DES = C_algo.DES = BlockCipher.extend({ 12740 _doReset: function () { 12741 // Shortcuts 12742 var key = this._key; 12743 var keyWords = key.words; 12744 12745 // Select 56 bits according to PC1 12746 var keyBits = []; 12747 for (var i = 0; i < 56; i++) { 12748 var keyBitPos = PC1[i] - 1; 12749 keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; 12750 } 12751 12752 // Assemble 16 subkeys 12753 var subKeys = this._subKeys = []; 12754 for (var nSubKey = 0; nSubKey < 16; nSubKey++) { 12755 // Create subkey 12756 var subKey = subKeys[nSubKey] = []; 12757 12758 // Shortcut 12759 var bitShift = BIT_SHIFTS[nSubKey]; 12760 12761 // Select 48 bits according to PC2 12762 for (var i = 0; i < 24; i++) { 12763 // Select from the left 28 key bits 12764 subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); 12765 12766 // Select from the right 28 key bits 12767 subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); 12768 } 12769 12770 // Since each subkey is applied to an expanded 32-bit input, 12771 // the subkey can be broken into 8 values scaled to 32-bits, 12772 // which allows the key to be used without expansion 12773 subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); 12774 for (var i = 1; i < 7; i++) { 12775 subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); 12776 } 12777 subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); 12778 } 12779 12780 // Compute inverse subkeys 12781 var invSubKeys = this._invSubKeys = []; 12782 for (var i = 0; i < 16; i++) { 12783 invSubKeys[i] = subKeys[15 - i]; 12784 } 12785 }, 12786 12787 encryptBlock: function (M, offset) { 12788 this._doCryptBlock(M, offset, this._subKeys); 12789 }, 12790 12791 decryptBlock: function (M, offset) { 12792 this._doCryptBlock(M, offset, this._invSubKeys); 12793 }, 12794 12795 _doCryptBlock: function (M, offset, subKeys) { 12796 // Get input 12797 this._lBlock = M[offset]; 12798 this._rBlock = M[offset + 1]; 12799 12800 // Initial permutation 12801 exchangeLR.call(this, 4, 0x0f0f0f0f); 12802 exchangeLR.call(this, 16, 0x0000ffff); 12803 exchangeRL.call(this, 2, 0x33333333); 12804 exchangeRL.call(this, 8, 0x00ff00ff); 12805 exchangeLR.call(this, 1, 0x55555555); 12806 12807 // Rounds 12808 for (var round = 0; round < 16; round++) { 12809 // Shortcuts 12810 var subKey = subKeys[round]; 12811 var lBlock = this._lBlock; 12812 var rBlock = this._rBlock; 12813 12814 // Feistel function 12815 var f = 0; 12816 for (var i = 0; i < 8; i++) { 12817 f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; 12818 } 12819 this._lBlock = rBlock; 12820 this._rBlock = lBlock ^ f; 12821 } 12822 12823 // Undo swap from last round 12824 var t = this._lBlock; 12825 this._lBlock = this._rBlock; 12826 this._rBlock = t; 12827 12828 // Final permutation 12829 exchangeLR.call(this, 1, 0x55555555); 12830 exchangeRL.call(this, 8, 0x00ff00ff); 12831 exchangeRL.call(this, 2, 0x33333333); 12832 exchangeLR.call(this, 16, 0x0000ffff); 12833 exchangeLR.call(this, 4, 0x0f0f0f0f); 12834 12835 // Set output 12836 M[offset] = this._lBlock; 12837 M[offset + 1] = this._rBlock; 12838 }, 12839 12840 keySize: 64/32, 12841 12842 ivSize: 64/32, 12843 12844 blockSize: 64/32 12845 }); 12846 12847 // Swap bits across the left and right words 12848 function exchangeLR(offset, mask) { 12849 var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; 12850 this._rBlock ^= t; 12851 this._lBlock ^= t << offset; 12852 } 12853 12854 function exchangeRL(offset, mask) { 12855 var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; 12856 this._lBlock ^= t; 12857 this._rBlock ^= t << offset; 12858 } 12859 12860 /** 12861 * Shortcut functions to the cipher's object interface. 12862 * 12863 * @example 12864 * 12865 * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); 12866 * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); 12867 */ 12868 C.DES = BlockCipher._createHelper(DES); 12869 12870 /** 12871 * Triple-DES block cipher algorithm. 12872 */ 12873 var TripleDES = C_algo.TripleDES = BlockCipher.extend({ 12874 _doReset: function () { 12875 // Shortcuts 12876 var key = this._key; 12877 var keyWords = key.words; 12878 12879 // Create DES instances 12880 this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); 12881 this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); 12882 this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); 12883 }, 12884 12885 encryptBlock: function (M, offset) { 12886 this._des1.encryptBlock(M, offset); 12887 this._des2.decryptBlock(M, offset); 12888 this._des3.encryptBlock(M, offset); 12889 }, 12890 12891 decryptBlock: function (M, offset) { 12892 this._des3.decryptBlock(M, offset); 12893 this._des2.encryptBlock(M, offset); 12894 this._des1.decryptBlock(M, offset); 12895 }, 12896 12897 keySize: 192/32, 12898 12899 ivSize: 64/32, 12900 12901 blockSize: 64/32 12902 }); 12903 12904 /** 12905 * Shortcut functions to the cipher's object interface. 12906 * 12907 * @example 12908 * 12909 * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); 12910 * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); 12911 */ 12912 C.TripleDES = BlockCipher._createHelper(TripleDES); 12913 }()); 12914 12915 12916 return CryptoJS.TripleDES; 12917 12918 })); 12919 },{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],84:[function(require,module,exports){ 12920 ;(function (root, factory) { 12921 if (typeof exports === "object") { 12922 // CommonJS 12923 module.exports = exports = factory(require("./core")); 12924 } 12925 else if (typeof define === "function" && define.amd) { 12926 // AMD 12927 define(["./core"], factory); 12928 } 12929 else { 12930 // Global (browser) 12931 factory(root.CryptoJS); 12932 } 12933 }(this, function (CryptoJS) { 12934 12935 (function (undefined) { 12936 // Shortcuts 12937 var C = CryptoJS; 12938 var C_lib = C.lib; 12939 var Base = C_lib.Base; 12940 var X32WordArray = C_lib.WordArray; 12941 12942 /** 12943 * x64 namespace. 12944 */ 12945 var C_x64 = C.x64 = {}; 12946 12947 /** 12948 * A 64-bit word. 12949 */ 12950 var X64Word = C_x64.Word = Base.extend({ 12951 /** 12952 * Initializes a newly created 64-bit word. 12953 * 12954 * @param {number} high The high 32 bits. 12955 * @param {number} low The low 32 bits. 12956 * 12957 * @example 12958 * 12959 * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); 12960 */ 12961 init: function (high, low) { 12962 this.high = high; 12963 this.low = low; 12964 } 12965 12966 /** 12967 * Bitwise NOTs this word. 12968 * 12969 * @return {X64Word} A new x64-Word object after negating. 12970 * 12971 * @example 12972 * 12973 * var negated = x64Word.not(); 12974 */ 12975 // not: function () { 12976 // var high = ~this.high; 12977 // var low = ~this.low; 12978 12979 // return X64Word.create(high, low); 12980 // }, 12981 12982 /** 12983 * Bitwise ANDs this word with the passed word. 12984 * 12985 * @param {X64Word} word The x64-Word to AND with this word. 12986 * 12987 * @return {X64Word} A new x64-Word object after ANDing. 12988 * 12989 * @example 12990 * 12991 * var anded = x64Word.and(anotherX64Word); 12992 */ 12993 // and: function (word) { 12994 // var high = this.high & word.high; 12995 // var low = this.low & word.low; 12996 12997 // return X64Word.create(high, low); 12998 // }, 12999 13000 /** 13001 * Bitwise ORs this word with the passed word. 13002 * 13003 * @param {X64Word} word The x64-Word to OR with this word. 13004 * 13005 * @return {X64Word} A new x64-Word object after ORing. 13006 * 13007 * @example 13008 * 13009 * var ored = x64Word.or(anotherX64Word); 13010 */ 13011 // or: function (word) { 13012 // var high = this.high | word.high; 13013 // var low = this.low | word.low; 13014 13015 // return X64Word.create(high, low); 13016 // }, 13017 13018 /** 13019 * Bitwise XORs this word with the passed word. 13020 * 13021 * @param {X64Word} word The x64-Word to XOR with this word. 13022 * 13023 * @return {X64Word} A new x64-Word object after XORing. 13024 * 13025 * @example 13026 * 13027 * var xored = x64Word.xor(anotherX64Word); 13028 */ 13029 // xor: function (word) { 13030 // var high = this.high ^ word.high; 13031 // var low = this.low ^ word.low; 13032 13033 // return X64Word.create(high, low); 13034 // }, 13035 13036 /** 13037 * Shifts this word n bits to the left. 13038 * 13039 * @param {number} n The number of bits to shift. 13040 * 13041 * @return {X64Word} A new x64-Word object after shifting. 13042 * 13043 * @example 13044 * 13045 * var shifted = x64Word.shiftL(25); 13046 */ 13047 // shiftL: function (n) { 13048 // if (n < 32) { 13049 // var high = (this.high << n) | (this.low >>> (32 - n)); 13050 // var low = this.low << n; 13051 // } else { 13052 // var high = this.low << (n - 32); 13053 // var low = 0; 13054 // } 13055 13056 // return X64Word.create(high, low); 13057 // }, 13058 13059 /** 13060 * Shifts this word n bits to the right. 13061 * 13062 * @param {number} n The number of bits to shift. 13063 * 13064 * @return {X64Word} A new x64-Word object after shifting. 13065 * 13066 * @example 13067 * 13068 * var shifted = x64Word.shiftR(7); 13069 */ 13070 // shiftR: function (n) { 13071 // if (n < 32) { 13072 // var low = (this.low >>> n) | (this.high << (32 - n)); 13073 // var high = this.high >>> n; 13074 // } else { 13075 // var low = this.high >>> (n - 32); 13076 // var high = 0; 13077 // } 13078 13079 // return X64Word.create(high, low); 13080 // }, 13081 13082 /** 13083 * Rotates this word n bits to the left. 13084 * 13085 * @param {number} n The number of bits to rotate. 13086 * 13087 * @return {X64Word} A new x64-Word object after rotating. 13088 * 13089 * @example 13090 * 13091 * var rotated = x64Word.rotL(25); 13092 */ 13093 // rotL: function (n) { 13094 // return this.shiftL(n).or(this.shiftR(64 - n)); 13095 // }, 13096 13097 /** 13098 * Rotates this word n bits to the right. 13099 * 13100 * @param {number} n The number of bits to rotate. 13101 * 13102 * @return {X64Word} A new x64-Word object after rotating. 13103 * 13104 * @example 13105 * 13106 * var rotated = x64Word.rotR(7); 13107 */ 13108 // rotR: function (n) { 13109 // return this.shiftR(n).or(this.shiftL(64 - n)); 13110 // }, 13111 13112 /** 13113 * Adds this word with the passed word. 13114 * 13115 * @param {X64Word} word The x64-Word to add with this word. 13116 * 13117 * @return {X64Word} A new x64-Word object after adding. 13118 * 13119 * @example 13120 * 13121 * var added = x64Word.add(anotherX64Word); 13122 */ 13123 // add: function (word) { 13124 // var low = (this.low + word.low) | 0; 13125 // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; 13126 // var high = (this.high + word.high + carry) | 0; 13127 13128 // return X64Word.create(high, low); 13129 // } 13130 }); 13131 13132 /** 13133 * An array of 64-bit words. 13134 * 13135 * @property {Array} words The array of CryptoJS.x64.Word objects. 13136 * @property {number} sigBytes The number of significant bytes in this word array. 13137 */ 13138 var X64WordArray = C_x64.WordArray = Base.extend({ 13139 /** 13140 * Initializes a newly created word array. 13141 * 13142 * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. 13143 * @param {number} sigBytes (Optional) The number of significant bytes in the words. 13144 * 13145 * @example 13146 * 13147 * var wordArray = CryptoJS.x64.WordArray.create(); 13148 * 13149 * var wordArray = CryptoJS.x64.WordArray.create([ 13150 * CryptoJS.x64.Word.create(0x00010203, 0x04050607), 13151 * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) 13152 * ]); 13153 * 13154 * var wordArray = CryptoJS.x64.WordArray.create([ 13155 * CryptoJS.x64.Word.create(0x00010203, 0x04050607), 13156 * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) 13157 * ], 10); 13158 */ 13159 init: function (words, sigBytes) { 13160 words = this.words = words || []; 13161 13162 if (sigBytes != undefined) { 13163 this.sigBytes = sigBytes; 13164 } else { 13165 this.sigBytes = words.length * 8; 13166 } 13167 }, 13168 13169 /** 13170 * Converts this 64-bit word array to a 32-bit word array. 13171 * 13172 * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. 13173 * 13174 * @example 13175 * 13176 * var x32WordArray = x64WordArray.toX32(); 13177 */ 13178 toX32: function () { 13179 // Shortcuts 13180 var x64Words = this.words; 13181 var x64WordsLength = x64Words.length; 13182 13183 // Convert 13184 var x32Words = []; 13185 for (var i = 0; i < x64WordsLength; i++) { 13186 var x64Word = x64Words[i]; 13187 x32Words.push(x64Word.high); 13188 x32Words.push(x64Word.low); 13189 } 13190 13191 return X32WordArray.create(x32Words, this.sigBytes); 13192 }, 13193 13194 /** 13195 * Creates a copy of this word array. 13196 * 13197 * @return {X64WordArray} The clone. 13198 * 13199 * @example 13200 * 13201 * var clone = x64WordArray.clone(); 13202 */ 13203 clone: function () { 13204 var clone = Base.clone.call(this); 13205 13206 // Clone "words" array 13207 var words = clone.words = this.words.slice(0); 13208 13209 // Clone each X64Word object 13210 var wordsLength = words.length; 13211 for (var i = 0; i < wordsLength; i++) { 13212 words[i] = words[i].clone(); 13213 } 13214 13215 return clone; 13216 } 13217 }); 13218 }()); 13219 13220 13221 return CryptoJS; 13222 13223 })); 13224 },{"./core":53}],85:[function(require,module,exports){ 13225 /*! https://mths.be/utf8js v2.1.2 by @mathias */ 13226 ;(function(root) { 13227 13228 // Detect free variables `exports` 13229 var freeExports = typeof exports == 'object' && exports; 13230 13231 // Detect free variable `module` 13232 var freeModule = typeof module == 'object' && module && 13233 module.exports == freeExports && module; 13234 13235 // Detect free variable `global`, from Node.js or Browserified code, 13236 // and use it as `root` 13237 var freeGlobal = typeof global == 'object' && global; 13238 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { 13239 root = freeGlobal; 13240 } 13241 13242 /*--------------------------------------------------------------------------*/ 13243 13244 var stringFromCharCode = String.fromCharCode; 13245 13246 // Taken from https://mths.be/punycode 13247 function ucs2decode(string) { 13248 var output = []; 13249 var counter = 0; 13250 var length = string.length; 13251 var value; 13252 var extra; 13253 while (counter < length) { 13254 value = string.charCodeAt(counter++); 13255 if (value >= 0xD800 && value <= 0xDBFF && counter < length) { 13256 // high surrogate, and there is a next character 13257 extra = string.charCodeAt(counter++); 13258 if ((extra & 0xFC00) == 0xDC00) { // low surrogate 13259 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); 13260 } else { 13261 // unmatched surrogate; only append this code unit, in case the next 13262 // code unit is the high surrogate of a surrogate pair 13263 output.push(value); 13264 counter--; 13265 } 13266 } else { 13267 output.push(value); 13268 } 13269 } 13270 return output; 13271 } 13272 13273 // Taken from https://mths.be/punycode 13274 function ucs2encode(array) { 13275 var length = array.length; 13276 var index = -1; 13277 var value; 13278 var output = ''; 13279 while (++index < length) { 13280 value = array[index]; 13281 if (value > 0xFFFF) { 13282 value -= 0x10000; 13283 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); 13284 value = 0xDC00 | value & 0x3FF; 13285 } 13286 output += stringFromCharCode(value); 13287 } 13288 return output; 13289 } 13290 13291 function checkScalarValue(codePoint) { 13292 if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { 13293 throw Error( 13294 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + 13295 ' is not a scalar value' 13296 ); 13297 } 13298 } 13299 /*--------------------------------------------------------------------------*/ 13300 13301 function createByte(codePoint, shift) { 13302 return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); 13303 } 13304 13305 function encodeCodePoint(codePoint) { 13306 if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence 13307 return stringFromCharCode(codePoint); 13308 } 13309 var symbol = ''; 13310 if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence 13311 symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); 13312 } 13313 else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence 13314 checkScalarValue(codePoint); 13315 symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); 13316 symbol += createByte(codePoint, 6); 13317 } 13318 else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence 13319 symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); 13320 symbol += createByte(codePoint, 12); 13321 symbol += createByte(codePoint, 6); 13322 } 13323 symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); 13324 return symbol; 13325 } 13326 13327 function utf8encode(string) { 13328 var codePoints = ucs2decode(string); 13329 var length = codePoints.length; 13330 var index = -1; 13331 var codePoint; 13332 var byteString = ''; 13333 while (++index < length) { 13334 codePoint = codePoints[index]; 13335 byteString += encodeCodePoint(codePoint); 13336 } 13337 return byteString; 13338 } 13339 13340 /*--------------------------------------------------------------------------*/ 13341 13342 function readContinuationByte() { 13343 if (byteIndex >= byteCount) { 13344 throw Error('Invalid byte index'); 13345 } 13346 13347 var continuationByte = byteArray[byteIndex] & 0xFF; 13348 byteIndex++; 13349 13350 if ((continuationByte & 0xC0) == 0x80) { 13351 return continuationByte & 0x3F; 13352 } 13353 13354 // If we end up here, it’s not a continuation byte 13355 throw Error('Invalid continuation byte'); 13356 } 13357 13358 function decodeSymbol() { 13359 var byte1; 13360 var byte2; 13361 var byte3; 13362 var byte4; 13363 var codePoint; 13364 13365 if (byteIndex > byteCount) { 13366 throw Error('Invalid byte index'); 13367 } 13368 13369 if (byteIndex == byteCount) { 13370 return false; 13371 } 13372 13373 // Read first byte 13374 byte1 = byteArray[byteIndex] & 0xFF; 13375 byteIndex++; 13376 13377 // 1-byte sequence (no continuation bytes) 13378 if ((byte1 & 0x80) == 0) { 13379 return byte1; 13380 } 13381 13382 // 2-byte sequence 13383 if ((byte1 & 0xE0) == 0xC0) { 13384 byte2 = readContinuationByte(); 13385 codePoint = ((byte1 & 0x1F) << 6) | byte2; 13386 if (codePoint >= 0x80) { 13387 return codePoint; 13388 } else { 13389 throw Error('Invalid continuation byte'); 13390 } 13391 } 13392 13393 // 3-byte sequence (may include unpaired surrogates) 13394 if ((byte1 & 0xF0) == 0xE0) { 13395 byte2 = readContinuationByte(); 13396 byte3 = readContinuationByte(); 13397 codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; 13398 if (codePoint >= 0x0800) { 13399 checkScalarValue(codePoint); 13400 return codePoint; 13401 } else { 13402 throw Error('Invalid continuation byte'); 13403 } 13404 } 13405 13406 // 4-byte sequence 13407 if ((byte1 & 0xF8) == 0xF0) { 13408 byte2 = readContinuationByte(); 13409 byte3 = readContinuationByte(); 13410 byte4 = readContinuationByte(); 13411 codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | 13412 (byte3 << 0x06) | byte4; 13413 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { 13414 return codePoint; 13415 } 13416 } 13417 13418 throw Error('Invalid UTF-8 detected'); 13419 } 13420 13421 var byteArray; 13422 var byteCount; 13423 var byteIndex; 13424 function utf8decode(byteString) { 13425 byteArray = ucs2decode(byteString); 13426 byteCount = byteArray.length; 13427 byteIndex = 0; 13428 var codePoints = []; 13429 var tmp; 13430 while ((tmp = decodeSymbol()) !== false) { 13431 codePoints.push(tmp); 13432 } 13433 return ucs2encode(codePoints); 13434 } 13435 13436 /*--------------------------------------------------------------------------*/ 13437 13438 var utf8 = { 13439 'version': '2.1.2', 13440 'encode': utf8encode, 13441 'decode': utf8decode 13442 }; 13443 13444 // Some AMD build optimizers, like r.js, check for specific condition patterns 13445 // like the following: 13446 if ( 13447 typeof define == 'function' && 13448 typeof define.amd == 'object' && 13449 define.amd 13450 ) { 13451 define(function() { 13452 return utf8; 13453 }); 13454 } else if (freeExports && !freeExports.nodeType) { 13455 if (freeModule) { // in Node.js or RingoJS v0.8.0+ 13456 freeModule.exports = utf8; 13457 } else { // in Narwhal or RingoJS v0.7.0- 13458 var object = {}; 13459 var hasOwnProperty = object.hasOwnProperty; 13460 for (var key in utf8) { 13461 hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); 13462 } 13463 } 13464 } else { // in Rhino or a web browser 13465 root.utf8 = utf8; 13466 } 13467 13468 }(this)); 13469 13470 },{}],86:[function(require,module,exports){ 13471 module.exports = XMLHttpRequest; 13472 13473 },{}],"bignumber.js":[function(require,module,exports){ 13474 /*! bignumber.js v2.0.7 https://github.com/MikeMcl/bignumber.js/LICENCE */ 13475 13476 ;(function (global) { 13477 'use strict'; 13478 13479 /* 13480 bignumber.js v2.0.7 13481 A JavaScript library for arbitrary-precision arithmetic. 13482 https://github.com/MikeMcl/bignumber.js 13483 Copyright (c) 2015 Michael Mclaughlin <M8ch88l@gmail.com> 13484 MIT Expat Licence 13485 */ 13486 13487 13488 var BigNumber, crypto, parseNumeric, 13489 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, 13490 mathceil = Math.ceil, 13491 mathfloor = Math.floor, 13492 notBool = ' not a boolean or binary digit', 13493 roundingMode = 'rounding mode', 13494 tooManyDigits = 'number type has more than 15 significant digits', 13495 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_', 13496 BASE = 1e14, 13497 LOG_BASE = 14, 13498 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 13499 // MAX_INT32 = 0x7fffffff, // 2^31 - 1 13500 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], 13501 SQRT_BASE = 1e7, 13502 13503 /* 13504 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and 13505 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an 13506 * exception is thrown (if ERRORS is true). 13507 */ 13508 MAX = 1E9; // 0 to MAX_INT32 13509 13510 13511 /* 13512 * Create and return a BigNumber constructor. 13513 */ 13514 function another(configObj) { 13515 var div, 13516 13517 // id tracks the caller function, so its name can be included in error messages. 13518 id = 0, 13519 P = BigNumber.prototype, 13520 ONE = new BigNumber(1), 13521 13522 13523 /********************************* EDITABLE DEFAULTS **********************************/ 13524 13525 13526 /* 13527 * The default values below must be integers within the inclusive ranges stated. 13528 * The values can also be changed at run-time using BigNumber.config. 13529 */ 13530 13531 // The maximum number of decimal places for operations involving division. 13532 DECIMAL_PLACES = 20, // 0 to MAX 13533 13534 /* 13535 * The rounding mode used when rounding to the above decimal places, and when using 13536 * toExponential, toFixed, toFormat and toPrecision, and round (default value). 13537 * UP 0 Away from zero. 13538 * DOWN 1 Towards zero. 13539 * CEIL 2 Towards +Infinity. 13540 * FLOOR 3 Towards -Infinity. 13541 * HALF_UP 4 Towards nearest neighbour. If equidistant, up. 13542 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. 13543 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. 13544 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. 13545 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. 13546 */ 13547 ROUNDING_MODE = 4, // 0 to 8 13548 13549 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] 13550 13551 // The exponent value at and beneath which toString returns exponential notation. 13552 // Number type: -7 13553 TO_EXP_NEG = -7, // 0 to -MAX 13554 13555 // The exponent value at and above which toString returns exponential notation. 13556 // Number type: 21 13557 TO_EXP_POS = 21, // 0 to MAX 13558 13559 // RANGE : [MIN_EXP, MAX_EXP] 13560 13561 // The minimum exponent value, beneath which underflow to zero occurs. 13562 // Number type: -324 (5e-324) 13563 MIN_EXP = -1e7, // -1 to -MAX 13564 13565 // The maximum exponent value, above which overflow to Infinity occurs. 13566 // Number type: 308 (1.7976931348623157e+308) 13567 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. 13568 MAX_EXP = 1e7, // 1 to MAX 13569 13570 // Whether BigNumber Errors are ever thrown. 13571 ERRORS = true, // true or false 13572 13573 // Change to intValidatorNoErrors if ERRORS is false. 13574 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors 13575 13576 // Whether to use cryptographically-secure random number generation, if available. 13577 CRYPTO = false, // true or false 13578 13579 /* 13580 * The modulo mode used when calculating the modulus: a mod n. 13581 * The quotient (q = a / n) is calculated according to the corresponding rounding mode. 13582 * The remainder (r) is calculated as: r = a - n * q. 13583 * 13584 * UP 0 The remainder is positive if the dividend is negative, else is negative. 13585 * DOWN 1 The remainder has the same sign as the dividend. 13586 * This modulo mode is commonly known as 'truncated division' and is 13587 * equivalent to (a % n) in JavaScript. 13588 * FLOOR 3 The remainder has the same sign as the divisor (Python %). 13589 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. 13590 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). 13591 * The remainder is always positive. 13592 * 13593 * The truncated division, floored division, Euclidian division and IEEE 754 remainder 13594 * modes are commonly used for the modulus operation. 13595 * Although the other rounding modes can also be used, they may not give useful results. 13596 */ 13597 MODULO_MODE = 1, // 0 to 9 13598 13599 // The maximum number of significant digits of the result of the toPower operation. 13600 // If POW_PRECISION is 0, there will be unlimited significant digits. 13601 POW_PRECISION = 100, // 0 to MAX 13602 13603 // The format specification used by the BigNumber.prototype.toFormat method. 13604 FORMAT = { 13605 decimalSeparator: '.', 13606 groupSeparator: ',', 13607 groupSize: 3, 13608 secondaryGroupSize: 0, 13609 fractionGroupSeparator: '\xA0', // non-breaking space 13610 fractionGroupSize: 0 13611 }; 13612 13613 13614 /******************************************************************************************/ 13615 13616 13617 // CONSTRUCTOR 13618 13619 13620 /* 13621 * The BigNumber constructor and exported function. 13622 * Create and return a new instance of a BigNumber object. 13623 * 13624 * n {number|string|BigNumber} A numeric value. 13625 * [b] {number} The base of n. Integer, 2 to 64 inclusive. 13626 */ 13627 function BigNumber( n, b ) { 13628 var c, e, i, num, len, str, 13629 x = this; 13630 13631 // Enable constructor usage without new. 13632 if ( !( x instanceof BigNumber ) ) { 13633 13634 // 'BigNumber() constructor call without new: {n}' 13635 if (ERRORS) raise( 26, 'constructor call without new', n ); 13636 return new BigNumber( n, b ); 13637 } 13638 13639 // 'new BigNumber() base not an integer: {b}' 13640 // 'new BigNumber() base out of range: {b}' 13641 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { 13642 13643 // Duplicate. 13644 if ( n instanceof BigNumber ) { 13645 x.s = n.s; 13646 x.e = n.e; 13647 x.c = ( n = n.c ) ? n.slice() : n; 13648 id = 0; 13649 return; 13650 } 13651 13652 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { 13653 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; 13654 13655 // Fast path for integers. 13656 if ( n === ~~n ) { 13657 for ( e = 0, i = n; i >= 10; i /= 10, e++ ); 13658 x.e = e; 13659 x.c = [n]; 13660 id = 0; 13661 return; 13662 } 13663 13664 str = n + ''; 13665 } else { 13666 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); 13667 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; 13668 } 13669 } else { 13670 b = b | 0; 13671 str = n + ''; 13672 13673 // Ensure return value is rounded to DECIMAL_PLACES as with other bases. 13674 // Allow exponential notation to be used with base 10 argument. 13675 if ( b == 10 ) { 13676 x = new BigNumber( n instanceof BigNumber ? n : str ); 13677 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); 13678 } 13679 13680 // Avoid potential interpretation of Infinity and NaN as base 44+ values. 13681 // Any number in exponential form will fail due to the [Ee][+-]. 13682 if ( ( num = typeof n == 'number' ) && n * 0 != 0 || 13683 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + 13684 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { 13685 return parseNumeric( x, str, num, b ); 13686 } 13687 13688 if (num) { 13689 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; 13690 13691 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { 13692 13693 // 'new BigNumber() number type has more than 15 significant digits: {n}' 13694 raise( id, tooManyDigits, n ); 13695 } 13696 13697 // Prevent later check for length on converted number. 13698 num = false; 13699 } else { 13700 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; 13701 } 13702 13703 str = convertBase( str, 10, b, x.s ); 13704 } 13705 13706 // Decimal point? 13707 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); 13708 13709 // Exponential form? 13710 if ( ( i = str.search( /e/i ) ) > 0 ) { 13711 13712 // Determine exponent. 13713 if ( e < 0 ) e = i; 13714 e += +str.slice( i + 1 ); 13715 str = str.substring( 0, i ); 13716 } else if ( e < 0 ) { 13717 13718 // Integer. 13719 e = str.length; 13720 } 13721 13722 // Determine leading zeros. 13723 for ( i = 0; str.charCodeAt(i) === 48; i++ ); 13724 13725 // Determine trailing zeros. 13726 for ( len = str.length; str.charCodeAt(--len) === 48; ); 13727 str = str.slice( i, len + 1 ); 13728 13729 if (str) { 13730 len = str.length; 13731 13732 // Disallow numbers with over 15 significant digits if number type. 13733 // 'new BigNumber() number type has more than 15 significant digits: {n}' 13734 if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n ); 13735 13736 e = e - i - 1; 13737 13738 // Overflow? 13739 if ( e > MAX_EXP ) { 13740 13741 // Infinity. 13742 x.c = x.e = null; 13743 13744 // Underflow? 13745 } else if ( e < MIN_EXP ) { 13746 13747 // Zero. 13748 x.c = [ x.e = 0 ]; 13749 } else { 13750 x.e = e; 13751 x.c = []; 13752 13753 // Transform base 13754 13755 // e is the base 10 exponent. 13756 // i is where to slice str to get the first element of the coefficient array. 13757 i = ( e + 1 ) % LOG_BASE; 13758 if ( e < 0 ) i += LOG_BASE; 13759 13760 if ( i < len ) { 13761 if (i) x.c.push( +str.slice( 0, i ) ); 13762 13763 for ( len -= LOG_BASE; i < len; ) { 13764 x.c.push( +str.slice( i, i += LOG_BASE ) ); 13765 } 13766 13767 str = str.slice(i); 13768 i = LOG_BASE - str.length; 13769 } else { 13770 i -= len; 13771 } 13772 13773 for ( ; i--; str += '0' ); 13774 x.c.push( +str ); 13775 } 13776 } else { 13777 13778 // Zero. 13779 x.c = [ x.e = 0 ]; 13780 } 13781 13782 id = 0; 13783 } 13784 13785 13786 // CONSTRUCTOR PROPERTIES 13787 13788 13789 BigNumber.another = another; 13790 13791 BigNumber.ROUND_UP = 0; 13792 BigNumber.ROUND_DOWN = 1; 13793 BigNumber.ROUND_CEIL = 2; 13794 BigNumber.ROUND_FLOOR = 3; 13795 BigNumber.ROUND_HALF_UP = 4; 13796 BigNumber.ROUND_HALF_DOWN = 5; 13797 BigNumber.ROUND_HALF_EVEN = 6; 13798 BigNumber.ROUND_HALF_CEIL = 7; 13799 BigNumber.ROUND_HALF_FLOOR = 8; 13800 BigNumber.EUCLID = 9; 13801 13802 13803 /* 13804 * Configure infrequently-changing library-wide settings. 13805 * 13806 * Accept an object or an argument list, with one or many of the following properties or 13807 * parameters respectively: 13808 * 13809 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive 13810 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive 13811 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or 13812 * [integer -MAX to 0 incl., 0 to MAX incl.] 13813 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or 13814 * [integer -MAX to -1 incl., integer 1 to MAX incl.] 13815 * ERRORS {boolean|number} true, false, 1 or 0 13816 * CRYPTO {boolean|number} true, false, 1 or 0 13817 * MODULO_MODE {number} 0 to 9 inclusive 13818 * POW_PRECISION {number} 0 to MAX inclusive 13819 * FORMAT {object} See BigNumber.prototype.toFormat 13820 * decimalSeparator {string} 13821 * groupSeparator {string} 13822 * groupSize {number} 13823 * secondaryGroupSize {number} 13824 * fractionGroupSeparator {string} 13825 * fractionGroupSize {number} 13826 * 13827 * (The values assigned to the above FORMAT object properties are not checked for validity.) 13828 * 13829 * E.g. 13830 * BigNumber.config(20, 4) is equivalent to 13831 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) 13832 * 13833 * Ignore properties/parameters set to null or undefined. 13834 * Return an object with the properties current values. 13835 */ 13836 BigNumber.config = function () { 13837 var v, p, 13838 i = 0, 13839 r = {}, 13840 a = arguments, 13841 o = a[0], 13842 has = o && typeof o == 'object' 13843 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; } 13844 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; }; 13845 13846 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. 13847 // 'config() DECIMAL_PLACES not an integer: {v}' 13848 // 'config() DECIMAL_PLACES out of range: {v}' 13849 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) { 13850 DECIMAL_PLACES = v | 0; 13851 } 13852 r[p] = DECIMAL_PLACES; 13853 13854 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. 13855 // 'config() ROUNDING_MODE not an integer: {v}' 13856 // 'config() ROUNDING_MODE out of range: {v}' 13857 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) { 13858 ROUNDING_MODE = v | 0; 13859 } 13860 r[p] = ROUNDING_MODE; 13861 13862 // EXPONENTIAL_AT {number|number[]} 13863 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive]. 13864 // 'config() EXPONENTIAL_AT not an integer: {v}' 13865 // 'config() EXPONENTIAL_AT out of range: {v}' 13866 if ( has( p = 'EXPONENTIAL_AT' ) ) { 13867 13868 if ( isArray(v) ) { 13869 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) { 13870 TO_EXP_NEG = v[0] | 0; 13871 TO_EXP_POS = v[1] | 0; 13872 } 13873 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { 13874 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); 13875 } 13876 } 13877 r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; 13878 13879 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or 13880 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. 13881 // 'config() RANGE not an integer: {v}' 13882 // 'config() RANGE cannot be zero: {v}' 13883 // 'config() RANGE out of range: {v}' 13884 if ( has( p = 'RANGE' ) ) { 13885 13886 if ( isArray(v) ) { 13887 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { 13888 MIN_EXP = v[0] | 0; 13889 MAX_EXP = v[1] | 0; 13890 } 13891 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { 13892 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 ); 13893 else if (ERRORS) raise( 2, p + ' cannot be zero', v ); 13894 } 13895 } 13896 r[p] = [ MIN_EXP, MAX_EXP ]; 13897 13898 // ERRORS {boolean|number} true, false, 1 or 0. 13899 // 'config() ERRORS not a boolean or binary digit: {v}' 13900 if ( has( p = 'ERRORS' ) ) { 13901 13902 if ( v === !!v || v === 1 || v === 0 ) { 13903 id = 0; 13904 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; 13905 } else if (ERRORS) { 13906 raise( 2, p + notBool, v ); 13907 } 13908 } 13909 r[p] = ERRORS; 13910 13911 // CRYPTO {boolean|number} true, false, 1 or 0. 13912 // 'config() CRYPTO not a boolean or binary digit: {v}' 13913 // 'config() crypto unavailable: {crypto}' 13914 if ( has( p = 'CRYPTO' ) ) { 13915 13916 if ( v === !!v || v === 1 || v === 0 ) { 13917 CRYPTO = !!( v && crypto && typeof crypto == 'object' ); 13918 if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', crypto ); 13919 } else if (ERRORS) { 13920 raise( 2, p + notBool, v ); 13921 } 13922 } 13923 r[p] = CRYPTO; 13924 13925 // MODULO_MODE {number} Integer, 0 to 9 inclusive. 13926 // 'config() MODULO_MODE not an integer: {v}' 13927 // 'config() MODULO_MODE out of range: {v}' 13928 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) { 13929 MODULO_MODE = v | 0; 13930 } 13931 r[p] = MODULO_MODE; 13932 13933 // POW_PRECISION {number} Integer, 0 to MAX inclusive. 13934 // 'config() POW_PRECISION not an integer: {v}' 13935 // 'config() POW_PRECISION out of range: {v}' 13936 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) { 13937 POW_PRECISION = v | 0; 13938 } 13939 r[p] = POW_PRECISION; 13940 13941 // FORMAT {object} 13942 // 'config() FORMAT not an object: {v}' 13943 if ( has( p = 'FORMAT' ) ) { 13944 13945 if ( typeof v == 'object' ) { 13946 FORMAT = v; 13947 } else if (ERRORS) { 13948 raise( 2, p + ' not an object', v ); 13949 } 13950 } 13951 r[p] = FORMAT; 13952 13953 return r; 13954 }; 13955 13956 13957 /* 13958 * Return a new BigNumber whose value is the maximum of the arguments. 13959 * 13960 * arguments {number|string|BigNumber} 13961 */ 13962 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); }; 13963 13964 13965 /* 13966 * Return a new BigNumber whose value is the minimum of the arguments. 13967 * 13968 * arguments {number|string|BigNumber} 13969 */ 13970 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); }; 13971 13972 13973 /* 13974 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, 13975 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing 13976 * zeros are produced). 13977 * 13978 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 13979 * 13980 * 'random() decimal places not an integer: {dp}' 13981 * 'random() decimal places out of range: {dp}' 13982 * 'random() crypto unavailable: {crypto}' 13983 */ 13984 BigNumber.random = (function () { 13985 var pow2_53 = 0x20000000000000; 13986 13987 // Return a 53 bit integer n, where 0 <= n < 9007199254740992. 13988 // Check if Math.random() produces more than 32 bits of randomness. 13989 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. 13990 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. 13991 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff 13992 ? function () { return mathfloor( Math.random() * pow2_53 ); } 13993 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + 13994 (Math.random() * 0x800000 | 0); }; 13995 13996 return function (dp) { 13997 var a, b, e, k, v, 13998 i = 0, 13999 c = [], 14000 rand = new BigNumber(ONE); 14001 14002 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; 14003 k = mathceil( dp / LOG_BASE ); 14004 14005 if (CRYPTO) { 14006 14007 // Browsers supporting crypto.getRandomValues. 14008 if ( crypto && crypto.getRandomValues ) { 14009 14010 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); 14011 14012 for ( ; i < k; ) { 14013 14014 // 53 bits: 14015 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) 14016 // 11111 11111111 11111111 11111111 11100000 00000000 00000000 14017 // ((Math.pow(2, 32) - 1) >>> 11).toString(2) 14018 // 11111 11111111 11111111 14019 // 0x20000 is 2^21. 14020 v = a[i] * 0x20000 + (a[i + 1] >>> 11); 14021 14022 // Rejection sampling: 14023 // 0 <= v < 9007199254740992 14024 // Probability that v >= 9e15, is 14025 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 14026 if ( v >= 9e15 ) { 14027 b = crypto.getRandomValues( new Uint32Array(2) ); 14028 a[i] = b[0]; 14029 a[i + 1] = b[1]; 14030 } else { 14031 14032 // 0 <= v <= 8999999999999999 14033 // 0 <= (v % 1e14) <= 99999999999999 14034 c.push( v % 1e14 ); 14035 i += 2; 14036 } 14037 } 14038 i = k / 2; 14039 14040 // Node.js supporting crypto.randomBytes. 14041 } else if ( crypto && crypto.randomBytes ) { 14042 14043 // buffer 14044 a = crypto.randomBytes( k *= 7 ); 14045 14046 for ( ; i < k; ) { 14047 14048 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 14049 // 0x100000000 is 2^32, 0x1000000 is 2^24 14050 // 11111 11111111 11111111 11111111 11111111 11111111 11111111 14051 // 0 <= v < 9007199254740992 14052 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + 14053 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + 14054 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; 14055 14056 if ( v >= 9e15 ) { 14057 crypto.randomBytes(7).copy( a, i ); 14058 } else { 14059 14060 // 0 <= (v % 1e14) <= 99999999999999 14061 c.push( v % 1e14 ); 14062 i += 7; 14063 } 14064 } 14065 i = k / 7; 14066 } else if (ERRORS) { 14067 raise( 14, 'crypto unavailable', crypto ); 14068 } 14069 } 14070 14071 // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false. 14072 if (!i) { 14073 14074 for ( ; i < k; ) { 14075 v = random53bitInt(); 14076 if ( v < 9e15 ) c[i++] = v % 1e14; 14077 } 14078 } 14079 14080 k = c[--i]; 14081 dp %= LOG_BASE; 14082 14083 // Convert trailing digits to zeros according to dp. 14084 if ( k && dp ) { 14085 v = POWS_TEN[LOG_BASE - dp]; 14086 c[i] = mathfloor( k / v ) * v; 14087 } 14088 14089 // Remove trailing elements which are zero. 14090 for ( ; c[i] === 0; c.pop(), i-- ); 14091 14092 // Zero? 14093 if ( i < 0 ) { 14094 c = [ e = 0 ]; 14095 } else { 14096 14097 // Remove leading elements which are zero and adjust exponent accordingly. 14098 for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE); 14099 14100 // Count the digits of the first element of c to determine leading zeros, and... 14101 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); 14102 14103 // adjust the exponent accordingly. 14104 if ( i < LOG_BASE ) e -= LOG_BASE - i; 14105 } 14106 14107 rand.e = e; 14108 rand.c = c; 14109 return rand; 14110 }; 14111 })(); 14112 14113 14114 // PRIVATE FUNCTIONS 14115 14116 14117 // Convert a numeric string of baseIn to a numeric string of baseOut. 14118 function convertBase( str, baseOut, baseIn, sign ) { 14119 var d, e, k, r, x, xc, y, 14120 i = str.indexOf( '.' ), 14121 dp = DECIMAL_PLACES, 14122 rm = ROUNDING_MODE; 14123 14124 if ( baseIn < 37 ) str = str.toLowerCase(); 14125 14126 // Non-integer. 14127 if ( i >= 0 ) { 14128 k = POW_PRECISION; 14129 14130 // Unlimited precision. 14131 POW_PRECISION = 0; 14132 str = str.replace( '.', '' ); 14133 y = new BigNumber(baseIn); 14134 x = y.pow( str.length - i ); 14135 POW_PRECISION = k; 14136 14137 // Convert str as if an integer, then restore the fraction part by dividing the 14138 // result by its base raised to a power. 14139 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut ); 14140 y.e = y.c.length; 14141 } 14142 14143 // Convert the number as integer. 14144 xc = toBaseOut( str, baseIn, baseOut ); 14145 e = k = xc.length; 14146 14147 // Remove trailing zeros. 14148 for ( ; xc[--k] == 0; xc.pop() ); 14149 if ( !xc[0] ) return '0'; 14150 14151 if ( i < 0 ) { 14152 --e; 14153 } else { 14154 x.c = xc; 14155 x.e = e; 14156 14157 // sign is needed for correct rounding. 14158 x.s = sign; 14159 x = div( x, y, dp, rm, baseOut ); 14160 xc = x.c; 14161 r = x.r; 14162 e = x.e; 14163 } 14164 14165 d = e + dp + 1; 14166 14167 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up. 14168 i = xc[d]; 14169 k = baseOut / 2; 14170 r = r || d < 0 || xc[d + 1] != null; 14171 14172 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) 14173 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || 14174 rm == ( x.s < 0 ? 8 : 7 ) ); 14175 14176 if ( d < 1 || !xc[0] ) { 14177 14178 // 1^-dp or 0. 14179 str = r ? toFixedPoint( '1', -dp ) : '0'; 14180 } else { 14181 xc.length = d; 14182 14183 if (r) { 14184 14185 // Rounding up may mean the previous digit has to be rounded up and so on. 14186 for ( --baseOut; ++xc[--d] > baseOut; ) { 14187 xc[d] = 0; 14188 14189 if ( !d ) { 14190 ++e; 14191 xc.unshift(1); 14192 } 14193 } 14194 } 14195 14196 // Determine trailing zeros. 14197 for ( k = xc.length; !xc[--k]; ); 14198 14199 // E.g. [4, 11, 15] becomes 4bf. 14200 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) ); 14201 str = toFixedPoint( str, e ); 14202 } 14203 14204 // The caller will add the sign. 14205 return str; 14206 } 14207 14208 14209 // Perform division in the specified base. Called by div and convertBase. 14210 div = (function () { 14211 14212 // Assume non-zero x and k. 14213 function multiply( x, k, base ) { 14214 var m, temp, xlo, xhi, 14215 carry = 0, 14216 i = x.length, 14217 klo = k % SQRT_BASE, 14218 khi = k / SQRT_BASE | 0; 14219 14220 for ( x = x.slice(); i--; ) { 14221 xlo = x[i] % SQRT_BASE; 14222 xhi = x[i] / SQRT_BASE | 0; 14223 m = khi * xlo + xhi * klo; 14224 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry; 14225 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi; 14226 x[i] = temp % base; 14227 } 14228 14229 if (carry) x.unshift(carry); 14230 14231 return x; 14232 } 14233 14234 function compare( a, b, aL, bL ) { 14235 var i, cmp; 14236 14237 if ( aL != bL ) { 14238 cmp = aL > bL ? 1 : -1; 14239 } else { 14240 14241 for ( i = cmp = 0; i < aL; i++ ) { 14242 14243 if ( a[i] != b[i] ) { 14244 cmp = a[i] > b[i] ? 1 : -1; 14245 break; 14246 } 14247 } 14248 } 14249 return cmp; 14250 } 14251 14252 function subtract( a, b, aL, base ) { 14253 var i = 0; 14254 14255 // Subtract b from a. 14256 for ( ; aL--; ) { 14257 a[aL] -= i; 14258 i = a[aL] < b[aL] ? 1 : 0; 14259 a[aL] = i * base + a[aL] - b[aL]; 14260 } 14261 14262 // Remove leading zeros. 14263 for ( ; !a[0] && a.length > 1; a.shift() ); 14264 } 14265 14266 // x: dividend, y: divisor. 14267 return function ( x, y, dp, rm, base ) { 14268 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, 14269 yL, yz, 14270 s = x.s == y.s ? 1 : -1, 14271 xc = x.c, 14272 yc = y.c; 14273 14274 // Either NaN, Infinity or 0? 14275 if ( !xc || !xc[0] || !yc || !yc[0] ) { 14276 14277 return new BigNumber( 14278 14279 // Return NaN if either NaN, or both Infinity or 0. 14280 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : 14281 14282 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. 14283 xc && xc[0] == 0 || !yc ? s * 0 : s / 0 14284 ); 14285 } 14286 14287 q = new BigNumber(s); 14288 qc = q.c = []; 14289 e = x.e - y.e; 14290 s = dp + e + 1; 14291 14292 if ( !base ) { 14293 base = BASE; 14294 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); 14295 s = s / LOG_BASE | 0; 14296 } 14297 14298 // Result exponent may be one less then the current value of e. 14299 // The coefficients of the BigNumbers from convertBase may have trailing zeros. 14300 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ ); 14301 if ( yc[i] > ( xc[i] || 0 ) ) e--; 14302 14303 if ( s < 0 ) { 14304 qc.push(1); 14305 more = true; 14306 } else { 14307 xL = xc.length; 14308 yL = yc.length; 14309 i = 0; 14310 s += 2; 14311 14312 // Normalise xc and yc so highest order digit of yc is >= base / 2. 14313 14314 n = mathfloor( base / ( yc[0] + 1 ) ); 14315 14316 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. 14317 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { 14318 if ( n > 1 ) { 14319 yc = multiply( yc, n, base ); 14320 xc = multiply( xc, n, base ); 14321 yL = yc.length; 14322 xL = xc.length; 14323 } 14324 14325 xi = yL; 14326 rem = xc.slice( 0, yL ); 14327 remL = rem.length; 14328 14329 // Add zeros to make remainder as long as divisor. 14330 for ( ; remL < yL; rem[remL++] = 0 ); 14331 yz = yc.slice(); 14332 yz.unshift(0); 14333 yc0 = yc[0]; 14334 if ( yc[1] >= base / 2 ) yc0++; 14335 // Not necessary, but to prevent trial digit n > base, when using base 3. 14336 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15; 14337 14338 do { 14339 n = 0; 14340 14341 // Compare divisor and remainder. 14342 cmp = compare( yc, rem, yL, remL ); 14343 14344 // If divisor < remainder. 14345 if ( cmp < 0 ) { 14346 14347 // Calculate trial digit, n. 14348 14349 rem0 = rem[0]; 14350 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); 14351 14352 // n is how many times the divisor goes into the current remainder. 14353 n = mathfloor( rem0 / yc0 ); 14354 14355 // Algorithm: 14356 // 1. product = divisor * trial digit (n) 14357 // 2. if product > remainder: product -= divisor, n-- 14358 // 3. remainder -= product 14359 // 4. if product was < remainder at 2: 14360 // 5. compare new remainder and divisor 14361 // 6. If remainder > divisor: remainder -= divisor, n++ 14362 14363 if ( n > 1 ) { 14364 14365 // n may be > base only when base is 3. 14366 if (n >= base) n = base - 1; 14367 14368 // product = divisor * trial digit. 14369 prod = multiply( yc, n, base ); 14370 prodL = prod.length; 14371 remL = rem.length; 14372 14373 // Compare product and remainder. 14374 // If product > remainder. 14375 // Trial digit n too high. 14376 // n is 1 too high about 5% of the time, and is not known to have 14377 // ever been more than 1 too high. 14378 while ( compare( prod, rem, prodL, remL ) == 1 ) { 14379 n--; 14380 14381 // Subtract divisor from product. 14382 subtract( prod, yL < prodL ? yz : yc, prodL, base ); 14383 prodL = prod.length; 14384 cmp = 1; 14385 } 14386 } else { 14387 14388 // n is 0 or 1, cmp is -1. 14389 // If n is 0, there is no need to compare yc and rem again below, 14390 // so change cmp to 1 to avoid it. 14391 // If n is 1, leave cmp as -1, so yc and rem are compared again. 14392 if ( n == 0 ) { 14393 14394 // divisor < remainder, so n must be at least 1. 14395 cmp = n = 1; 14396 } 14397 14398 // product = divisor 14399 prod = yc.slice(); 14400 prodL = prod.length; 14401 } 14402 14403 if ( prodL < remL ) prod.unshift(0); 14404 14405 // Subtract product from remainder. 14406 subtract( rem, prod, remL, base ); 14407 remL = rem.length; 14408 14409 // If product was < remainder. 14410 if ( cmp == -1 ) { 14411 14412 // Compare divisor and new remainder. 14413 // If divisor < new remainder, subtract divisor from remainder. 14414 // Trial digit n too low. 14415 // n is 1 too low about 5% of the time, and very rarely 2 too low. 14416 while ( compare( yc, rem, yL, remL ) < 1 ) { 14417 n++; 14418 14419 // Subtract divisor from remainder. 14420 subtract( rem, yL < remL ? yz : yc, remL, base ); 14421 remL = rem.length; 14422 } 14423 } 14424 } else if ( cmp === 0 ) { 14425 n++; 14426 rem = [0]; 14427 } // else cmp === 1 and n will be 0 14428 14429 // Add the next digit, n, to the result array. 14430 qc[i++] = n; 14431 14432 // Update the remainder. 14433 if ( rem[0] ) { 14434 rem[remL++] = xc[xi] || 0; 14435 } else { 14436 rem = [ xc[xi] ]; 14437 remL = 1; 14438 } 14439 } while ( ( xi++ < xL || rem[0] != null ) && s-- ); 14440 14441 more = rem[0] != null; 14442 14443 // Leading zero? 14444 if ( !qc[0] ) qc.shift(); 14445 } 14446 14447 if ( base == BASE ) { 14448 14449 // To calculate q.e, first get the number of digits of qc[0]. 14450 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ ); 14451 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more ); 14452 14453 // Caller is convertBase. 14454 } else { 14455 q.e = e; 14456 q.r = +more; 14457 } 14458 14459 return q; 14460 }; 14461 })(); 14462 14463 14464 /* 14465 * Return a string representing the value of BigNumber n in fixed-point or exponential 14466 * notation rounded to the specified decimal places or significant digits. 14467 * 14468 * n is a BigNumber. 14469 * i is the index of the last digit required (i.e. the digit that may be rounded up). 14470 * rm is the rounding mode. 14471 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24. 14472 */ 14473 function format( n, i, rm, caller ) { 14474 var c0, e, ne, len, str; 14475 14476 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode ) 14477 ? rm | 0 : ROUNDING_MODE; 14478 14479 if ( !n.c ) return n.toString(); 14480 c0 = n.c[0]; 14481 ne = n.e; 14482 14483 if ( i == null ) { 14484 str = coeffToString( n.c ); 14485 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG 14486 ? toExponential( str, ne ) 14487 : toFixedPoint( str, ne ); 14488 } else { 14489 n = round( new BigNumber(n), i, rm ); 14490 14491 // n.e may have changed if the value was rounded up. 14492 e = n.e; 14493 14494 str = coeffToString( n.c ); 14495 len = str.length; 14496 14497 // toPrecision returns exponential notation if the number of significant digits 14498 // specified is less than the number of digits necessary to represent the integer 14499 // part of the value in fixed-point notation. 14500 14501 // Exponential notation. 14502 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) { 14503 14504 // Append zeros? 14505 for ( ; len < i; str += '0', len++ ); 14506 str = toExponential( str, e ); 14507 14508 // Fixed-point notation. 14509 } else { 14510 i -= ne; 14511 str = toFixedPoint( str, e ); 14512 14513 // Append zeros? 14514 if ( e + 1 > len ) { 14515 if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); 14516 } else { 14517 i += e - len; 14518 if ( i > 0 ) { 14519 if ( e + 1 == len ) str += '.'; 14520 for ( ; i--; str += '0' ); 14521 } 14522 } 14523 } 14524 } 14525 14526 return n.s < 0 && c0 ? '-' + str : str; 14527 } 14528 14529 14530 // Handle BigNumber.max and BigNumber.min. 14531 function maxOrMin( args, method ) { 14532 var m, n, 14533 i = 0; 14534 14535 if ( isArray( args[0] ) ) args = args[0]; 14536 m = new BigNumber( args[0] ); 14537 14538 for ( ; ++i < args.length; ) { 14539 n = new BigNumber( args[i] ); 14540 14541 // If any number is NaN, return NaN. 14542 if ( !n.s ) { 14543 m = n; 14544 break; 14545 } else if ( method.call( m, n ) ) { 14546 m = n; 14547 } 14548 } 14549 14550 return m; 14551 } 14552 14553 14554 /* 14555 * Return true if n is an integer in range, otherwise throw. 14556 * Use for argument validation when ERRORS is true. 14557 */ 14558 function intValidatorWithErrors( n, min, max, caller, name ) { 14559 if ( n < min || n > max || n != truncate(n) ) { 14560 raise( caller, ( name || 'decimal places' ) + 14561 ( n < min || n > max ? ' out of range' : ' not an integer' ), n ); 14562 } 14563 14564 return true; 14565 } 14566 14567 14568 /* 14569 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. 14570 * Called by minus, plus and times. 14571 */ 14572 function normalise( n, c, e ) { 14573 var i = 1, 14574 j = c.length; 14575 14576 // Remove trailing zeros. 14577 for ( ; !c[--j]; c.pop() ); 14578 14579 // Calculate the base 10 exponent. First get the number of digits of c[0]. 14580 for ( j = c[0]; j >= 10; j /= 10, i++ ); 14581 14582 // Overflow? 14583 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { 14584 14585 // Infinity. 14586 n.c = n.e = null; 14587 14588 // Underflow? 14589 } else if ( e < MIN_EXP ) { 14590 14591 // Zero. 14592 n.c = [ n.e = 0 ]; 14593 } else { 14594 n.e = e; 14595 n.c = c; 14596 } 14597 14598 return n; 14599 } 14600 14601 14602 // Handle values that fail the validity test in BigNumber. 14603 parseNumeric = (function () { 14604 var basePrefix = /^(-?)0([xbo])/i, 14605 dotAfter = /^([^.]+)\.$/, 14606 dotBefore = /^\.([^.]+)$/, 14607 isInfinityOrNaN = /^-?(Infinity|NaN)$/, 14608 whitespaceOrPlus = /^\s*\+|^\s+|\s+$/g; 14609 14610 return function ( x, str, num, b ) { 14611 var base, 14612 s = num ? str : str.replace( whitespaceOrPlus, '' ); 14613 14614 // No exception on ±Infinity or NaN. 14615 if ( isInfinityOrNaN.test(s) ) { 14616 x.s = isNaN(s) ? null : s < 0 ? -1 : 1; 14617 } else { 14618 if ( !num ) { 14619 14620 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i 14621 s = s.replace( basePrefix, function ( m, p1, p2 ) { 14622 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8; 14623 return !b || b == base ? p1 : m; 14624 }); 14625 14626 if (b) { 14627 base = b; 14628 14629 // E.g. '1.' to '1', '.1' to '0.1' 14630 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); 14631 } 14632 14633 if ( str != s ) return new BigNumber( s, base ); 14634 } 14635 14636 // 'new BigNumber() not a number: {n}' 14637 // 'new BigNumber() not a base {b} number: {n}' 14638 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str ); 14639 x.s = null; 14640 } 14641 14642 x.c = x.e = null; 14643 id = 0; 14644 } 14645 })(); 14646 14647 14648 // Throw a BigNumber Error. 14649 function raise( caller, msg, val ) { 14650 var error = new Error( [ 14651 'new BigNumber', // 0 14652 'cmp', // 1 14653 'config', // 2 14654 'div', // 3 14655 'divToInt', // 4 14656 'eq', // 5 14657 'gt', // 6 14658 'gte', // 7 14659 'lt', // 8 14660 'lte', // 9 14661 'minus', // 10 14662 'mod', // 11 14663 'plus', // 12 14664 'precision', // 13 14665 'random', // 14 14666 'round', // 15 14667 'shift', // 16 14668 'times', // 17 14669 'toDigits', // 18 14670 'toExponential', // 19 14671 'toFixed', // 20 14672 'toFormat', // 21 14673 'toFraction', // 22 14674 'pow', // 23 14675 'toPrecision', // 24 14676 'toString', // 25 14677 'BigNumber' // 26 14678 ][caller] + '() ' + msg + ': ' + val ); 14679 14680 error.name = 'BigNumber Error'; 14681 id = 0; 14682 throw error; 14683 } 14684 14685 14686 /* 14687 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. 14688 * If r is truthy, it is known that there are more digits after the rounding digit. 14689 */ 14690 function round( x, sd, rm, r ) { 14691 var d, i, j, k, n, ni, rd, 14692 xc = x.c, 14693 pows10 = POWS_TEN; 14694 14695 // if x is not Infinity or NaN... 14696 if (xc) { 14697 14698 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. 14699 // n is a base 1e14 number, the value of the element of array x.c containing rd. 14700 // ni is the index of n within x.c. 14701 // d is the number of digits of n. 14702 // i is the index of rd within n including leading zeros. 14703 // j is the actual index of rd within n (if < 0, rd is a leading zero). 14704 out: { 14705 14706 // Get the number of digits of the first element of xc. 14707 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); 14708 i = sd - d; 14709 14710 // If the rounding digit is in the first element of xc... 14711 if ( i < 0 ) { 14712 i += LOG_BASE; 14713 j = sd; 14714 n = xc[ ni = 0 ]; 14715 14716 // Get the rounding digit at index j of n. 14717 rd = n / pows10[ d - j - 1 ] % 10 | 0; 14718 } else { 14719 ni = mathceil( ( i + 1 ) / LOG_BASE ); 14720 14721 if ( ni >= xc.length ) { 14722 14723 if (r) { 14724 14725 // Needed by sqrt. 14726 for ( ; xc.length <= ni; xc.push(0) ); 14727 n = rd = 0; 14728 d = 1; 14729 i %= LOG_BASE; 14730 j = i - LOG_BASE + 1; 14731 } else { 14732 break out; 14733 } 14734 } else { 14735 n = k = xc[ni]; 14736 14737 // Get the number of digits of n. 14738 for ( d = 1; k >= 10; k /= 10, d++ ); 14739 14740 // Get the index of rd within n. 14741 i %= LOG_BASE; 14742 14743 // Get the index of rd within n, adjusted for leading zeros. 14744 // The number of leading zeros of n is given by LOG_BASE - d. 14745 j = i - LOG_BASE + d; 14746 14747 // Get the rounding digit at index j of n. 14748 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; 14749 } 14750 } 14751 14752 r = r || sd < 0 || 14753 14754 // Are there any non-zero digits after the rounding digit? 14755 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right 14756 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. 14757 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] ); 14758 14759 r = rm < 4 14760 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) 14761 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && 14762 14763 // Check whether the digit to the left of the rounding digit is odd. 14764 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 || 14765 rm == ( x.s < 0 ? 8 : 7 ) ); 14766 14767 if ( sd < 1 || !xc[0] ) { 14768 xc.length = 0; 14769 14770 if (r) { 14771 14772 // Convert sd to decimal places. 14773 sd -= x.e + 1; 14774 14775 // 1, 0.1, 0.01, 0.001, 0.0001 etc. 14776 xc[0] = pows10[ sd % LOG_BASE ]; 14777 x.e = -sd || 0; 14778 } else { 14779 14780 // Zero. 14781 xc[0] = x.e = 0; 14782 } 14783 14784 return x; 14785 } 14786 14787 // Remove excess digits. 14788 if ( i == 0 ) { 14789 xc.length = ni; 14790 k = 1; 14791 ni--; 14792 } else { 14793 xc.length = ni + 1; 14794 k = pows10[ LOG_BASE - i ]; 14795 14796 // E.g. 56700 becomes 56000 if 7 is the rounding digit. 14797 // j > 0 means i > number of leading zeros of n. 14798 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0; 14799 } 14800 14801 // Round up? 14802 if (r) { 14803 14804 for ( ; ; ) { 14805 14806 // If the digit to be rounded up is in the first element of xc... 14807 if ( ni == 0 ) { 14808 14809 // i will be the length of xc[0] before k is added. 14810 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ ); 14811 j = xc[0] += k; 14812 for ( k = 1; j >= 10; j /= 10, k++ ); 14813 14814 // if i != k the length has increased. 14815 if ( i != k ) { 14816 x.e++; 14817 if ( xc[0] == BASE ) xc[0] = 1; 14818 } 14819 14820 break; 14821 } else { 14822 xc[ni] += k; 14823 if ( xc[ni] != BASE ) break; 14824 xc[ni--] = 0; 14825 k = 1; 14826 } 14827 } 14828 } 14829 14830 // Remove trailing zeros. 14831 for ( i = xc.length; xc[--i] === 0; xc.pop() ); 14832 } 14833 14834 // Overflow? Infinity. 14835 if ( x.e > MAX_EXP ) { 14836 x.c = x.e = null; 14837 14838 // Underflow? Zero. 14839 } else if ( x.e < MIN_EXP ) { 14840 x.c = [ x.e = 0 ]; 14841 } 14842 } 14843 14844 return x; 14845 } 14846 14847 14848 // PROTOTYPE/INSTANCE METHODS 14849 14850 14851 /* 14852 * Return a new BigNumber whose value is the absolute value of this BigNumber. 14853 */ 14854 P.absoluteValue = P.abs = function () { 14855 var x = new BigNumber(this); 14856 if ( x.s < 0 ) x.s = 1; 14857 return x; 14858 }; 14859 14860 14861 /* 14862 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole 14863 * number in the direction of Infinity. 14864 */ 14865 P.ceil = function () { 14866 return round( new BigNumber(this), this.e + 1, 2 ); 14867 }; 14868 14869 14870 /* 14871 * Return 14872 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), 14873 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), 14874 * 0 if they have the same value, 14875 * or null if the value of either is NaN. 14876 */ 14877 P.comparedTo = P.cmp = function ( y, b ) { 14878 id = 1; 14879 return compare( this, new BigNumber( y, b ) ); 14880 }; 14881 14882 14883 /* 14884 * Return the number of decimal places of the value of this BigNumber, or null if the value 14885 * of this BigNumber is ±Infinity or NaN. 14886 */ 14887 P.decimalPlaces = P.dp = function () { 14888 var n, v, 14889 c = this.c; 14890 14891 if ( !c ) return null; 14892 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; 14893 14894 // Subtract the number of trailing zeros of the last number. 14895 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); 14896 if ( n < 0 ) n = 0; 14897 14898 return n; 14899 }; 14900 14901 14902 /* 14903 * n / 0 = I 14904 * n / N = N 14905 * n / I = 0 14906 * 0 / n = 0 14907 * 0 / 0 = N 14908 * 0 / N = N 14909 * 0 / I = 0 14910 * N / n = N 14911 * N / 0 = N 14912 * N / N = N 14913 * N / I = N 14914 * I / n = I 14915 * I / 0 = I 14916 * I / N = N 14917 * I / I = N 14918 * 14919 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of 14920 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. 14921 */ 14922 P.dividedBy = P.div = function ( y, b ) { 14923 id = 3; 14924 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); 14925 }; 14926 14927 14928 /* 14929 * Return a new BigNumber whose value is the integer part of dividing the value of this 14930 * BigNumber by the value of BigNumber(y, b). 14931 */ 14932 P.dividedToIntegerBy = P.divToInt = function ( y, b ) { 14933 id = 4; 14934 return div( this, new BigNumber( y, b ), 0, 1 ); 14935 }; 14936 14937 14938 /* 14939 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), 14940 * otherwise returns false. 14941 */ 14942 P.equals = P.eq = function ( y, b ) { 14943 id = 5; 14944 return compare( this, new BigNumber( y, b ) ) === 0; 14945 }; 14946 14947 14948 /* 14949 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole 14950 * number in the direction of -Infinity. 14951 */ 14952 P.floor = function () { 14953 return round( new BigNumber(this), this.e + 1, 3 ); 14954 }; 14955 14956 14957 /* 14958 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), 14959 * otherwise returns false. 14960 */ 14961 P.greaterThan = P.gt = function ( y, b ) { 14962 id = 6; 14963 return compare( this, new BigNumber( y, b ) ) > 0; 14964 }; 14965 14966 14967 /* 14968 * Return true if the value of this BigNumber is greater than or equal to the value of 14969 * BigNumber(y, b), otherwise returns false. 14970 */ 14971 P.greaterThanOrEqualTo = P.gte = function ( y, b ) { 14972 id = 7; 14973 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; 14974 14975 }; 14976 14977 14978 /* 14979 * Return true if the value of this BigNumber is a finite number, otherwise returns false. 14980 */ 14981 P.isFinite = function () { 14982 return !!this.c; 14983 }; 14984 14985 14986 /* 14987 * Return true if the value of this BigNumber is an integer, otherwise return false. 14988 */ 14989 P.isInteger = P.isInt = function () { 14990 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; 14991 }; 14992 14993 14994 /* 14995 * Return true if the value of this BigNumber is NaN, otherwise returns false. 14996 */ 14997 P.isNaN = function () { 14998 return !this.s; 14999 }; 15000 15001 15002 /* 15003 * Return true if the value of this BigNumber is negative, otherwise returns false. 15004 */ 15005 P.isNegative = P.isNeg = function () { 15006 return this.s < 0; 15007 }; 15008 15009 15010 /* 15011 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false. 15012 */ 15013 P.isZero = function () { 15014 return !!this.c && this.c[0] == 0; 15015 }; 15016 15017 15018 /* 15019 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), 15020 * otherwise returns false. 15021 */ 15022 P.lessThan = P.lt = function ( y, b ) { 15023 id = 8; 15024 return compare( this, new BigNumber( y, b ) ) < 0; 15025 }; 15026 15027 15028 /* 15029 * Return true if the value of this BigNumber is less than or equal to the value of 15030 * BigNumber(y, b), otherwise returns false. 15031 */ 15032 P.lessThanOrEqualTo = P.lte = function ( y, b ) { 15033 id = 9; 15034 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; 15035 }; 15036 15037 15038 /* 15039 * n - 0 = n 15040 * n - N = N 15041 * n - I = -I 15042 * 0 - n = -n 15043 * 0 - 0 = 0 15044 * 0 - N = N 15045 * 0 - I = -I 15046 * N - n = N 15047 * N - 0 = N 15048 * N - N = N 15049 * N - I = N 15050 * I - n = I 15051 * I - 0 = I 15052 * I - N = N 15053 * I - I = N 15054 * 15055 * Return a new BigNumber whose value is the value of this BigNumber minus the value of 15056 * BigNumber(y, b). 15057 */ 15058 P.minus = P.sub = function ( y, b ) { 15059 var i, j, t, xLTy, 15060 x = this, 15061 a = x.s; 15062 15063 id = 10; 15064 y = new BigNumber( y, b ); 15065 b = y.s; 15066 15067 // Either NaN? 15068 if ( !a || !b ) return new BigNumber(NaN); 15069 15070 // Signs differ? 15071 if ( a != b ) { 15072 y.s = -b; 15073 return x.plus(y); 15074 } 15075 15076 var xe = x.e / LOG_BASE, 15077 ye = y.e / LOG_BASE, 15078 xc = x.c, 15079 yc = y.c; 15080 15081 if ( !xe || !ye ) { 15082 15083 // Either Infinity? 15084 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); 15085 15086 // Either zero? 15087 if ( !xc[0] || !yc[0] ) { 15088 15089 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. 15090 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : 15091 15092 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity 15093 ROUNDING_MODE == 3 ? -0 : 0 ); 15094 } 15095 } 15096 15097 xe = bitFloor(xe); 15098 ye = bitFloor(ye); 15099 xc = xc.slice(); 15100 15101 // Determine which is the bigger number. 15102 if ( a = xe - ye ) { 15103 15104 if ( xLTy = a < 0 ) { 15105 a = -a; 15106 t = xc; 15107 } else { 15108 ye = xe; 15109 t = yc; 15110 } 15111 15112 t.reverse(); 15113 15114 // Prepend zeros to equalise exponents. 15115 for ( b = a; b--; t.push(0) ); 15116 t.reverse(); 15117 } else { 15118 15119 // Exponents equal. Check digit by digit. 15120 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; 15121 15122 for ( a = b = 0; b < j; b++ ) { 15123 15124 if ( xc[b] != yc[b] ) { 15125 xLTy = xc[b] < yc[b]; 15126 break; 15127 } 15128 } 15129 } 15130 15131 // x < y? Point xc to the array of the bigger number. 15132 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; 15133 15134 b = ( j = yc.length ) - ( i = xc.length ); 15135 15136 // Append zeros to xc if shorter. 15137 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. 15138 if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); 15139 b = BASE - 1; 15140 15141 // Subtract yc from xc. 15142 for ( ; j > a; ) { 15143 15144 if ( xc[--j] < yc[j] ) { 15145 for ( i = j; i && !xc[--i]; xc[i] = b ); 15146 --xc[i]; 15147 xc[j] += BASE; 15148 } 15149 15150 xc[j] -= yc[j]; 15151 } 15152 15153 // Remove leading zeros and adjust exponent accordingly. 15154 for ( ; xc[0] == 0; xc.shift(), --ye ); 15155 15156 // Zero? 15157 if ( !xc[0] ) { 15158 15159 // Following IEEE 754 (2008) 6.3, 15160 // n - n = +0 but n - n = -0 when rounding towards -Infinity. 15161 y.s = ROUNDING_MODE == 3 ? -1 : 1; 15162 y.c = [ y.e = 0 ]; 15163 return y; 15164 } 15165 15166 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity 15167 // for finite x and y. 15168 return normalise( y, xc, ye ); 15169 }; 15170 15171 15172 /* 15173 * n % 0 = N 15174 * n % N = N 15175 * n % I = n 15176 * 0 % n = 0 15177 * -0 % n = -0 15178 * 0 % 0 = N 15179 * 0 % N = N 15180 * 0 % I = 0 15181 * N % n = N 15182 * N % 0 = N 15183 * N % N = N 15184 * N % I = N 15185 * I % n = N 15186 * I % 0 = N 15187 * I % N = N 15188 * I % I = N 15189 * 15190 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of 15191 * BigNumber(y, b). The result depends on the value of MODULO_MODE. 15192 */ 15193 P.modulo = P.mod = function ( y, b ) { 15194 var q, s, 15195 x = this; 15196 15197 id = 11; 15198 y = new BigNumber( y, b ); 15199 15200 // Return NaN if x is Infinity or NaN, or y is NaN or zero. 15201 if ( !x.c || !y.s || y.c && !y.c[0] ) { 15202 return new BigNumber(NaN); 15203 15204 // Return x if y is Infinity or x is zero. 15205 } else if ( !y.c || x.c && !x.c[0] ) { 15206 return new BigNumber(x); 15207 } 15208 15209 if ( MODULO_MODE == 9 ) { 15210 15211 // Euclidian division: q = sign(y) * floor(x / abs(y)) 15212 // r = x - qy where 0 <= r < abs(y) 15213 s = y.s; 15214 y.s = 1; 15215 q = div( x, y, 0, 3 ); 15216 y.s = s; 15217 q.s *= s; 15218 } else { 15219 q = div( x, y, 0, MODULO_MODE ); 15220 } 15221 15222 return x.minus( q.times(y) ); 15223 }; 15224 15225 15226 /* 15227 * Return a new BigNumber whose value is the value of this BigNumber negated, 15228 * i.e. multiplied by -1. 15229 */ 15230 P.negated = P.neg = function () { 15231 var x = new BigNumber(this); 15232 x.s = -x.s || null; 15233 return x; 15234 }; 15235 15236 15237 /* 15238 * n + 0 = n 15239 * n + N = N 15240 * n + I = I 15241 * 0 + n = n 15242 * 0 + 0 = 0 15243 * 0 + N = N 15244 * 0 + I = I 15245 * N + n = N 15246 * N + 0 = N 15247 * N + N = N 15248 * N + I = N 15249 * I + n = I 15250 * I + 0 = I 15251 * I + N = N 15252 * I + I = I 15253 * 15254 * Return a new BigNumber whose value is the value of this BigNumber plus the value of 15255 * BigNumber(y, b). 15256 */ 15257 P.plus = P.add = function ( y, b ) { 15258 var t, 15259 x = this, 15260 a = x.s; 15261 15262 id = 12; 15263 y = new BigNumber( y, b ); 15264 b = y.s; 15265 15266 // Either NaN? 15267 if ( !a || !b ) return new BigNumber(NaN); 15268 15269 // Signs differ? 15270 if ( a != b ) { 15271 y.s = -b; 15272 return x.minus(y); 15273 } 15274 15275 var xe = x.e / LOG_BASE, 15276 ye = y.e / LOG_BASE, 15277 xc = x.c, 15278 yc = y.c; 15279 15280 if ( !xe || !ye ) { 15281 15282 // Return ±Infinity if either ±Infinity. 15283 if ( !xc || !yc ) return new BigNumber( a / 0 ); 15284 15285 // Either zero? 15286 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. 15287 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); 15288 } 15289 15290 xe = bitFloor(xe); 15291 ye = bitFloor(ye); 15292 xc = xc.slice(); 15293 15294 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. 15295 if ( a = xe - ye ) { 15296 if ( a > 0 ) { 15297 ye = xe; 15298 t = yc; 15299 } else { 15300 a = -a; 15301 t = xc; 15302 } 15303 15304 t.reverse(); 15305 for ( ; a--; t.push(0) ); 15306 t.reverse(); 15307 } 15308 15309 a = xc.length; 15310 b = yc.length; 15311 15312 // Point xc to the longer array, and b to the shorter length. 15313 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; 15314 15315 // Only start adding at yc.length - 1 as the further digits of xc can be ignored. 15316 for ( a = 0; b; ) { 15317 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; 15318 xc[b] %= BASE; 15319 } 15320 15321 if (a) { 15322 xc.unshift(a); 15323 ++ye; 15324 } 15325 15326 // No need to check for zero, as +x + +y != 0 && -x + -y != 0 15327 // ye = MAX_EXP + 1 possible 15328 return normalise( y, xc, ye ); 15329 }; 15330 15331 15332 /* 15333 * Return the number of significant digits of the value of this BigNumber. 15334 * 15335 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. 15336 */ 15337 P.precision = P.sd = function (z) { 15338 var n, v, 15339 x = this, 15340 c = x.c; 15341 15342 // 'precision() argument not a boolean or binary digit: {z}' 15343 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { 15344 if (ERRORS) raise( 13, 'argument' + notBool, z ); 15345 if ( z != !!z ) z = null; 15346 } 15347 15348 if ( !c ) return null; 15349 v = c.length - 1; 15350 n = v * LOG_BASE + 1; 15351 15352 if ( v = c[v] ) { 15353 15354 // Subtract the number of trailing zeros of the last element. 15355 for ( ; v % 10 == 0; v /= 10, n-- ); 15356 15357 // Add the number of digits of the first element. 15358 for ( v = c[0]; v >= 10; v /= 10, n++ ); 15359 } 15360 15361 if ( z && x.e + 1 > n ) n = x.e + 1; 15362 15363 return n; 15364 }; 15365 15366 15367 /* 15368 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of 15369 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if 15370 * omitted. 15371 * 15372 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15373 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15374 * 15375 * 'round() decimal places out of range: {dp}' 15376 * 'round() decimal places not an integer: {dp}' 15377 * 'round() rounding mode not an integer: {rm}' 15378 * 'round() rounding mode out of range: {rm}' 15379 */ 15380 P.round = function ( dp, rm ) { 15381 var n = new BigNumber(this); 15382 15383 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) { 15384 round( n, ~~dp + this.e + 1, rm == null || 15385 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 ); 15386 } 15387 15388 return n; 15389 }; 15390 15391 15392 /* 15393 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places 15394 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. 15395 * 15396 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. 15397 * 15398 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity 15399 * otherwise. 15400 * 15401 * 'shift() argument not an integer: {k}' 15402 * 'shift() argument out of range: {k}' 15403 */ 15404 P.shift = function (k) { 15405 var n = this; 15406 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) 15407 15408 // k < 1e+21, or truncate(k) will produce exponential notation. 15409 ? n.times( '1e' + truncate(k) ) 15410 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER ) 15411 ? n.s * ( k < 0 ? 0 : 1 / 0 ) 15412 : n ); 15413 }; 15414 15415 15416 /* 15417 * sqrt(-n) = N 15418 * sqrt( N) = N 15419 * sqrt(-I) = N 15420 * sqrt( I) = I 15421 * sqrt( 0) = 0 15422 * sqrt(-0) = -0 15423 * 15424 * Return a new BigNumber whose value is the square root of the value of this BigNumber, 15425 * rounded according to DECIMAL_PLACES and ROUNDING_MODE. 15426 */ 15427 P.squareRoot = P.sqrt = function () { 15428 var m, n, r, rep, t, 15429 x = this, 15430 c = x.c, 15431 s = x.s, 15432 e = x.e, 15433 dp = DECIMAL_PLACES + 4, 15434 half = new BigNumber('0.5'); 15435 15436 // Negative/NaN/Infinity/zero? 15437 if ( s !== 1 || !c || !c[0] ) { 15438 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); 15439 } 15440 15441 // Initial estimate. 15442 s = Math.sqrt( +x ); 15443 15444 // Math.sqrt underflow/overflow? 15445 // Pass x to Math.sqrt as integer, then adjust the exponent of the result. 15446 if ( s == 0 || s == 1 / 0 ) { 15447 n = coeffToString(c); 15448 if ( ( n.length + e ) % 2 == 0 ) n += '0'; 15449 s = Math.sqrt(n); 15450 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); 15451 15452 if ( s == 1 / 0 ) { 15453 n = '1e' + e; 15454 } else { 15455 n = s.toExponential(); 15456 n = n.slice( 0, n.indexOf('e') + 1 ) + e; 15457 } 15458 15459 r = new BigNumber(n); 15460 } else { 15461 r = new BigNumber( s + '' ); 15462 } 15463 15464 // Check for zero. 15465 // r could be zero if MIN_EXP is changed after the this value was created. 15466 // This would cause a division by zero (x/t) and hence Infinity below, which would cause 15467 // coeffToString to throw. 15468 if ( r.c[0] ) { 15469 e = r.e; 15470 s = e + dp; 15471 if ( s < 3 ) s = 0; 15472 15473 // Newton-Raphson iteration. 15474 for ( ; ; ) { 15475 t = r; 15476 r = half.times( t.plus( div( x, t, dp, 1 ) ) ); 15477 15478 if ( coeffToString( t.c ).slice( 0, s ) === ( n = 15479 coeffToString( r.c ) ).slice( 0, s ) ) { 15480 15481 // The exponent of r may here be one less than the final result exponent, 15482 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits 15483 // are indexed correctly. 15484 if ( r.e < e ) --s; 15485 n = n.slice( s - 3, s + 1 ); 15486 15487 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits 15488 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the 15489 // iteration. 15490 if ( n == '9999' || !rep && n == '4999' ) { 15491 15492 // On the first iteration only, check to see if rounding up gives the 15493 // exact result as the nines may infinitely repeat. 15494 if ( !rep ) { 15495 round( t, t.e + DECIMAL_PLACES + 2, 0 ); 15496 15497 if ( t.times(t).eq(x) ) { 15498 r = t; 15499 break; 15500 } 15501 } 15502 15503 dp += 4; 15504 s += 4; 15505 rep = 1; 15506 } else { 15507 15508 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact 15509 // result. If not, then there are further digits and m will be truthy. 15510 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { 15511 15512 // Truncate to the first rounding digit. 15513 round( r, r.e + DECIMAL_PLACES + 2, 1 ); 15514 m = !r.times(r).eq(x); 15515 } 15516 15517 break; 15518 } 15519 } 15520 } 15521 } 15522 15523 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); 15524 }; 15525 15526 15527 /* 15528 * n * 0 = 0 15529 * n * N = N 15530 * n * I = I 15531 * 0 * n = 0 15532 * 0 * 0 = 0 15533 * 0 * N = N 15534 * 0 * I = N 15535 * N * n = N 15536 * N * 0 = N 15537 * N * N = N 15538 * N * I = N 15539 * I * n = I 15540 * I * 0 = N 15541 * I * N = N 15542 * I * I = I 15543 * 15544 * Return a new BigNumber whose value is the value of this BigNumber times the value of 15545 * BigNumber(y, b). 15546 */ 15547 P.times = P.mul = function ( y, b ) { 15548 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, 15549 base, sqrtBase, 15550 x = this, 15551 xc = x.c, 15552 yc = ( id = 17, y = new BigNumber( y, b ) ).c; 15553 15554 // Either NaN, ±Infinity or ±0? 15555 if ( !xc || !yc || !xc[0] || !yc[0] ) { 15556 15557 // Return NaN if either is NaN, or one is 0 and the other is Infinity. 15558 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { 15559 y.c = y.e = y.s = null; 15560 } else { 15561 y.s *= x.s; 15562 15563 // Return ±Infinity if either is ±Infinity. 15564 if ( !xc || !yc ) { 15565 y.c = y.e = null; 15566 15567 // Return ±0 if either is ±0. 15568 } else { 15569 y.c = [0]; 15570 y.e = 0; 15571 } 15572 } 15573 15574 return y; 15575 } 15576 15577 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); 15578 y.s *= x.s; 15579 xcL = xc.length; 15580 ycL = yc.length; 15581 15582 // Ensure xc points to longer array and xcL to its length. 15583 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; 15584 15585 // Initialise the result array with zeros. 15586 for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); 15587 15588 base = BASE; 15589 sqrtBase = SQRT_BASE; 15590 15591 for ( i = ycL; --i >= 0; ) { 15592 c = 0; 15593 ylo = yc[i] % sqrtBase; 15594 yhi = yc[i] / sqrtBase | 0; 15595 15596 for ( k = xcL, j = i + k; j > i; ) { 15597 xlo = xc[--k] % sqrtBase; 15598 xhi = xc[k] / sqrtBase | 0; 15599 m = yhi * xlo + xhi * ylo; 15600 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; 15601 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; 15602 zc[j--] = xlo % base; 15603 } 15604 15605 zc[j] = c; 15606 } 15607 15608 if (c) { 15609 ++e; 15610 } else { 15611 zc.shift(); 15612 } 15613 15614 return normalise( y, zc, e ); 15615 }; 15616 15617 15618 /* 15619 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of 15620 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted. 15621 * 15622 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. 15623 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15624 * 15625 * 'toDigits() precision out of range: {sd}' 15626 * 'toDigits() precision not an integer: {sd}' 15627 * 'toDigits() rounding mode not an integer: {rm}' 15628 * 'toDigits() rounding mode out of range: {rm}' 15629 */ 15630 P.toDigits = function ( sd, rm ) { 15631 var n = new BigNumber(this); 15632 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0; 15633 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0; 15634 return sd ? round( n, sd, rm ) : n; 15635 }; 15636 15637 15638 /* 15639 * Return a string representing the value of this BigNumber in exponential notation and 15640 * rounded using ROUNDING_MODE to dp fixed decimal places. 15641 * 15642 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15643 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15644 * 15645 * 'toExponential() decimal places not an integer: {dp}' 15646 * 'toExponential() decimal places out of range: {dp}' 15647 * 'toExponential() rounding mode not an integer: {rm}' 15648 * 'toExponential() rounding mode out of range: {rm}' 15649 */ 15650 P.toExponential = function ( dp, rm ) { 15651 return format( this, 15652 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); 15653 }; 15654 15655 15656 /* 15657 * Return a string representing the value of this BigNumber in fixed-point notation rounding 15658 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. 15659 * 15660 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', 15661 * but e.g. (-0.00001).toFixed(0) is '-0'. 15662 * 15663 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15664 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15665 * 15666 * 'toFixed() decimal places not an integer: {dp}' 15667 * 'toFixed() decimal places out of range: {dp}' 15668 * 'toFixed() rounding mode not an integer: {rm}' 15669 * 'toFixed() rounding mode out of range: {rm}' 15670 */ 15671 P.toFixed = function ( dp, rm ) { 15672 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 ) 15673 ? ~~dp + this.e + 1 : null, rm, 20 ); 15674 }; 15675 15676 15677 /* 15678 * Return a string representing the value of this BigNumber in fixed-point notation rounded 15679 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties 15680 * of the FORMAT object (see BigNumber.config). 15681 * 15682 * FORMAT = { 15683 * decimalSeparator : '.', 15684 * groupSeparator : ',', 15685 * groupSize : 3, 15686 * secondaryGroupSize : 0, 15687 * fractionGroupSeparator : '\xA0', // non-breaking space 15688 * fractionGroupSize : 0 15689 * }; 15690 * 15691 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 15692 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15693 * 15694 * 'toFormat() decimal places not an integer: {dp}' 15695 * 'toFormat() decimal places out of range: {dp}' 15696 * 'toFormat() rounding mode not an integer: {rm}' 15697 * 'toFormat() rounding mode out of range: {rm}' 15698 */ 15699 P.toFormat = function ( dp, rm ) { 15700 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 ) 15701 ? ~~dp + this.e + 1 : null, rm, 21 ); 15702 15703 if ( this.c ) { 15704 var i, 15705 arr = str.split('.'), 15706 g1 = +FORMAT.groupSize, 15707 g2 = +FORMAT.secondaryGroupSize, 15708 groupSeparator = FORMAT.groupSeparator, 15709 intPart = arr[0], 15710 fractionPart = arr[1], 15711 isNeg = this.s < 0, 15712 intDigits = isNeg ? intPart.slice(1) : intPart, 15713 len = intDigits.length; 15714 15715 if (g2) i = g1, g1 = g2, g2 = i, len -= i; 15716 15717 if ( g1 > 0 && len > 0 ) { 15718 i = len % g1 || g1; 15719 intPart = intDigits.substr( 0, i ); 15720 15721 for ( ; i < len; i += g1 ) { 15722 intPart += groupSeparator + intDigits.substr( i, g1 ); 15723 } 15724 15725 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); 15726 if (isNeg) intPart = '-' + intPart; 15727 } 15728 15729 str = fractionPart 15730 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) 15731 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), 15732 '$&' + FORMAT.fractionGroupSeparator ) 15733 : fractionPart ) 15734 : intPart; 15735 } 15736 15737 return str; 15738 }; 15739 15740 15741 /* 15742 * Return a string array representing the value of this BigNumber as a simple fraction with 15743 * an integer numerator and an integer denominator. The denominator will be a positive 15744 * non-zero value less than or equal to the specified maximum denominator. If a maximum 15745 * denominator is not specified, the denominator will be the lowest value necessary to 15746 * represent the number exactly. 15747 * 15748 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. 15749 * 15750 * 'toFraction() max denominator not an integer: {md}' 15751 * 'toFraction() max denominator out of range: {md}' 15752 */ 15753 P.toFraction = function (md) { 15754 var arr, d0, d2, e, exp, n, n0, q, s, 15755 k = ERRORS, 15756 x = this, 15757 xc = x.c, 15758 d = new BigNumber(ONE), 15759 n1 = d0 = new BigNumber(ONE), 15760 d1 = n0 = new BigNumber(ONE); 15761 15762 if ( md != null ) { 15763 ERRORS = false; 15764 n = new BigNumber(md); 15765 ERRORS = k; 15766 15767 if ( !( k = n.isInt() ) || n.lt(ONE) ) { 15768 15769 if (ERRORS) { 15770 raise( 22, 15771 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); 15772 } 15773 15774 // ERRORS is false: 15775 // If md is a finite non-integer >= 1, round it to an integer and use it. 15776 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null; 15777 } 15778 } 15779 15780 if ( !xc ) return x.toString(); 15781 s = coeffToString(xc); 15782 15783 // Determine initial denominator. 15784 // d is a power of 10 and the minimum max denominator that specifies the value exactly. 15785 e = d.e = s.length - x.e - 1; 15786 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; 15787 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n; 15788 15789 exp = MAX_EXP; 15790 MAX_EXP = 1 / 0; 15791 n = new BigNumber(s); 15792 15793 // n0 = d1 = 0 15794 n0.c[0] = 0; 15795 15796 for ( ; ; ) { 15797 q = div( n, d, 0, 1 ); 15798 d2 = d0.plus( q.times(d1) ); 15799 if ( d2.cmp(md) == 1 ) break; 15800 d0 = d1; 15801 d1 = d2; 15802 n1 = n0.plus( q.times( d2 = n1 ) ); 15803 n0 = d2; 15804 d = n.minus( q.times( d2 = d ) ); 15805 n = d2; 15806 } 15807 15808 d2 = div( md.minus(d0), d1, 0, 1 ); 15809 n0 = n0.plus( d2.times(n1) ); 15810 d0 = d0.plus( d2.times(d1) ); 15811 n0.s = n1.s = x.s; 15812 e *= 2; 15813 15814 // Determine which fraction is closer to x, n0/d0 or n1/d1 15815 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp( 15816 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 15817 ? [ n1.toString(), d1.toString() ] 15818 : [ n0.toString(), d0.toString() ]; 15819 15820 MAX_EXP = exp; 15821 return arr; 15822 }; 15823 15824 15825 /* 15826 * Return the value of this BigNumber converted to a number primitive. 15827 */ 15828 P.toNumber = function () { 15829 var x = this; 15830 15831 // Ensure zero has correct sign. 15832 return +x || ( x.s ? x.s * 0 : NaN ); 15833 }; 15834 15835 15836 /* 15837 * Return a BigNumber whose value is the value of this BigNumber raised to the power n. 15838 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. 15839 * If POW_PRECISION is not 0, round to POW_PRECISION using ROUNDING_MODE. 15840 * 15841 * n {number} Integer, -9007199254740992 to 9007199254740992 inclusive. 15842 * (Performs 54 loop iterations for n of 9007199254740992.) 15843 * 15844 * 'pow() exponent not an integer: {n}' 15845 * 'pow() exponent out of range: {n}' 15846 */ 15847 P.toPower = P.pow = function (n) { 15848 var k, y, 15849 i = mathfloor( n < 0 ? -n : +n ), 15850 x = this; 15851 15852 // Pass ±Infinity to Math.pow if exponent is out of range. 15853 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && 15854 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || 15855 parseFloat(n) != n && !( n = NaN ) ) ) { 15856 return new BigNumber( Math.pow( +x, n ) ); 15857 } 15858 15859 // Truncating each coefficient array to a length of k after each multiplication equates 15860 // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a 15861 // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.) 15862 k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0; 15863 y = new BigNumber(ONE); 15864 15865 for ( ; ; ) { 15866 15867 if ( i % 2 ) { 15868 y = y.times(x); 15869 if ( !y.c ) break; 15870 if ( k && y.c.length > k ) y.c.length = k; 15871 } 15872 15873 i = mathfloor( i / 2 ); 15874 if ( !i ) break; 15875 15876 x = x.times(x); 15877 if ( k && x.c && x.c.length > k ) x.c.length = k; 15878 } 15879 15880 if ( n < 0 ) y = ONE.div(y); 15881 return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; 15882 }; 15883 15884 15885 /* 15886 * Return a string representing the value of this BigNumber rounded to sd significant digits 15887 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits 15888 * necessary to represent the integer part of the value in fixed-point notation, then use 15889 * exponential notation. 15890 * 15891 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. 15892 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 15893 * 15894 * 'toPrecision() precision not an integer: {sd}' 15895 * 'toPrecision() precision out of range: {sd}' 15896 * 'toPrecision() rounding mode not an integer: {rm}' 15897 * 'toPrecision() rounding mode out of range: {rm}' 15898 */ 15899 P.toPrecision = function ( sd, rm ) { 15900 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) 15901 ? sd | 0 : null, rm, 24 ); 15902 }; 15903 15904 15905 /* 15906 * Return a string representing the value of this BigNumber in base b, or base 10 if b is 15907 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and 15908 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent 15909 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than 15910 * TO_EXP_NEG, return exponential notation. 15911 * 15912 * [b] {number} Integer, 2 to 64 inclusive. 15913 * 15914 * 'toString() base not an integer: {b}' 15915 * 'toString() base out of range: {b}' 15916 */ 15917 P.toString = function (b) { 15918 var str, 15919 n = this, 15920 s = n.s, 15921 e = n.e; 15922 15923 // Infinity or NaN? 15924 if ( e === null ) { 15925 15926 if (s) { 15927 str = 'Infinity'; 15928 if ( s < 0 ) str = '-' + str; 15929 } else { 15930 str = 'NaN'; 15931 } 15932 } else { 15933 str = coeffToString( n.c ); 15934 15935 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) { 15936 str = e <= TO_EXP_NEG || e >= TO_EXP_POS 15937 ? toExponential( str, e ) 15938 : toFixedPoint( str, e ); 15939 } else { 15940 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); 15941 } 15942 15943 if ( s < 0 && n.c[0] ) str = '-' + str; 15944 } 15945 15946 return str; 15947 }; 15948 15949 15950 /* 15951 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole 15952 * number. 15953 */ 15954 P.truncated = P.trunc = function () { 15955 return round( new BigNumber(this), this.e + 1, 1 ); 15956 }; 15957 15958 15959 15960 /* 15961 * Return as toString, but do not accept a base argument. 15962 */ 15963 P.valueOf = P.toJSON = function () { 15964 return this.toString(); 15965 }; 15966 15967 15968 // Aliases for BigDecimal methods. 15969 //P.add = P.plus; // P.add included above 15970 //P.subtract = P.minus; // P.sub included above 15971 //P.multiply = P.times; // P.mul included above 15972 //P.divide = P.div; 15973 //P.remainder = P.mod; 15974 //P.compareTo = P.cmp; 15975 //P.negate = P.neg; 15976 15977 15978 if ( configObj != null ) BigNumber.config(configObj); 15979 15980 return BigNumber; 15981 } 15982 15983 15984 // PRIVATE HELPER FUNCTIONS 15985 15986 15987 function bitFloor(n) { 15988 var i = n | 0; 15989 return n > 0 || n === i ? i : i - 1; 15990 } 15991 15992 15993 // Return a coefficient array as a string of base 10 digits. 15994 function coeffToString(a) { 15995 var s, z, 15996 i = 1, 15997 j = a.length, 15998 r = a[0] + ''; 15999 16000 for ( ; i < j; ) { 16001 s = a[i++] + ''; 16002 z = LOG_BASE - s.length; 16003 for ( ; z--; s = '0' + s ); 16004 r += s; 16005 } 16006 16007 // Determine trailing zeros. 16008 for ( j = r.length; r.charCodeAt(--j) === 48; ); 16009 return r.slice( 0, j + 1 || 1 ); 16010 } 16011 16012 16013 // Compare the value of BigNumbers x and y. 16014 function compare( x, y ) { 16015 var a, b, 16016 xc = x.c, 16017 yc = y.c, 16018 i = x.s, 16019 j = y.s, 16020 k = x.e, 16021 l = y.e; 16022 16023 // Either NaN? 16024 if ( !i || !j ) return null; 16025 16026 a = xc && !xc[0]; 16027 b = yc && !yc[0]; 16028 16029 // Either zero? 16030 if ( a || b ) return a ? b ? 0 : -j : i; 16031 16032 // Signs differ? 16033 if ( i != j ) return i; 16034 16035 a = i < 0; 16036 b = k == l; 16037 16038 // Either Infinity? 16039 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; 16040 16041 // Compare exponents. 16042 if ( !b ) return k > l ^ a ? 1 : -1; 16043 16044 j = ( k = xc.length ) < ( l = yc.length ) ? k : l; 16045 16046 // Compare digit by digit. 16047 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1; 16048 16049 // Compare lengths. 16050 return k == l ? 0 : k > l ^ a ? 1 : -1; 16051 } 16052 16053 16054 /* 16055 * Return true if n is a valid number in range, otherwise false. 16056 * Use for argument validation when ERRORS is false. 16057 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10. 16058 */ 16059 function intValidatorNoErrors( n, min, max ) { 16060 return ( n = truncate(n) ) >= min && n <= max; 16061 } 16062 16063 16064 function isArray(obj) { 16065 return Object.prototype.toString.call(obj) == '[object Array]'; 16066 } 16067 16068 16069 /* 16070 * Convert string of baseIn to an array of numbers of baseOut. 16071 * Eg. convertBase('255', 10, 16) returns [15, 15]. 16072 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. 16073 */ 16074 function toBaseOut( str, baseIn, baseOut ) { 16075 var j, 16076 arr = [0], 16077 arrL, 16078 i = 0, 16079 len = str.length; 16080 16081 for ( ; i < len; ) { 16082 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); 16083 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) ); 16084 16085 for ( ; j < arr.length; j++ ) { 16086 16087 if ( arr[j] > baseOut - 1 ) { 16088 if ( arr[j + 1] == null ) arr[j + 1] = 0; 16089 arr[j + 1] += arr[j] / baseOut | 0; 16090 arr[j] %= baseOut; 16091 } 16092 } 16093 } 16094 16095 return arr.reverse(); 16096 } 16097 16098 16099 function toExponential( str, e ) { 16100 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + 16101 ( e < 0 ? 'e' : 'e+' ) + e; 16102 } 16103 16104 16105 function toFixedPoint( str, e ) { 16106 var len, z; 16107 16108 // Negative exponent? 16109 if ( e < 0 ) { 16110 16111 // Prepend zeros. 16112 for ( z = '0.'; ++e; z += '0' ); 16113 str = z + str; 16114 16115 // Positive exponent 16116 } else { 16117 len = str.length; 16118 16119 // Append zeros. 16120 if ( ++e > len ) { 16121 for ( z = '0', e -= len; --e; z += '0' ); 16122 str += z; 16123 } else if ( e < len ) { 16124 str = str.slice( 0, e ) + '.' + str.slice(e); 16125 } 16126 } 16127 16128 return str; 16129 } 16130 16131 16132 function truncate(n) { 16133 n = parseFloat(n); 16134 return n < 0 ? mathceil(n) : mathfloor(n); 16135 } 16136 16137 16138 // EXPORT 16139 16140 16141 BigNumber = another(); 16142 16143 // AMD. 16144 if ( typeof define == 'function' && define.amd ) { 16145 define( function () { return BigNumber; } ); 16146 16147 // Node and other environments that support module.exports. 16148 } else if ( typeof module != 'undefined' && module.exports ) { 16149 module.exports = BigNumber; 16150 if ( !crypto ) try { crypto = require('crypto'); } catch (e) {} 16151 16152 // Browser. 16153 } else { 16154 global.BigNumber = BigNumber; 16155 } 16156 })(this); 16157 16158 },{"crypto":50}],"web3":[function(require,module,exports){ 16159 var Web3 = require('./lib/web3'); 16160 16161 // dont override global variable 16162 if (typeof window !== 'undefined' && typeof window.Web3 === 'undefined') { 16163 window.Web3 = Web3; 16164 } 16165 16166 module.exports = Web3; 16167 16168 },{"./lib/web3":22}]},{},["web3"]) 16169 //# sourceMappingURL=web3.js.map