From 52042f86e144568ea81497b0268c34f848d229dc Mon Sep 17 00:00:00 2001 From: Yemel Jardi Date: Wed, 17 Dec 2014 19:07:16 -0300 Subject: [PATCH] Add dist folder and update bower file --- .gitignore | 1 - bower.json | 2 +- dist/bitcore.js | 51600 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 51601 insertions(+), 2 deletions(-) create mode 100644 dist/bitcore.js diff --git a/.gitignore b/.gitignore index 950aa35b3..f58ee8206 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,5 @@ npm-debug.log apiref bower_components -dist report .DS_Store diff --git a/bower.json b/bower.json index afc22548f..bb1da2a45 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "bitcore", - "main": "browser/bundle.js", + "main": "dist/bitcore.js", "version": "0.1.36", "homepage": "http://bitcore.io", "authors": [ diff --git a/dist/bitcore.js b/dist/bitcore.js new file mode 100644 index 000000000..31d94ffe5 --- /dev/null +++ b/dist/bitcore.js @@ -0,0 +1,51600 @@ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.bitcore=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o'; +}; + +module.exports = Address; + +}).call(this,require("buffer").Buffer) +},{"./crypto/hash":7,"./encoding/base58check":12,"./networks":20,"./script":30,"./util/js":49,"./util/preconditions":50,"buffer":69,"lodash":233}],3:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _ = require('lodash'); +var BlockHeader = require('./blockheader'); +var BN = require('./crypto/bn'); +var BufferUtil = require('./util/buffer'); +var BufferReader = require('./encoding/bufferreader'); +var BufferWriter = require('./encoding/bufferwriter'); +var Hash = require('./crypto/hash'); +var JSUtil = require('./util/js'); +var Transaction = require('./transaction'); +var Varint = require('./encoding/varint'); + +/** + * @class Block + * Instantiate a Block from a Buffer, JSON object, or Object with + * the properties of the Block + * + * @param {*} - A Buffer, JSON string, or Object + * @returns {Block} + * @constructor + */ +function Block(arg) { + if (!(this instanceof Block)) { + return new Block(arg); + } + _.extend(this, Block._from(arg)); + return this; +} + +// https://github.com/bitcoin/bitcoin/blob/b5fa132329f0377d787a4a21c1686609c2bfaece/src/primitives/block.h#L14 +Block.MAX_BLOCK_SIZE = 1000000; + +/** + * @param {*} - A Buffer, JSON string or Object + * @returns {Object} - An object representing block data + * @throws {TypeError} - If the argument was not recognized + * @private + */ +Block._from = function _from(arg) { + var info = {}; + if (BufferUtil.isBuffer(arg)) { + info = Block._fromBufferReader(BufferReader(arg)); + } else if (JSUtil.isValidJSON(arg)) { + info = Block._fromJSON(arg); + } else if (_.isObject(arg)) { + info = { + /** + * @name Block#magicnum + * @type number + */ + magicnum: arg.magicnum, + /** + * @name Block#size + * @type number + */ + size: arg.size, + /** + * @name Block#header + * @type {BlockHeader} + */ + header: arg.header, + txsvi: arg.txsvi, + /** + * @name Block#txs + * @type {Transaction[]} + */ + txs: arg.txs + }; + } else { + throw new TypeError('Unrecognized argument for Block'); + } + return info; +}; + +/** + * @param {String|Object} - A JSON string or object + * @returns {Object} - An object representing block data + * @private + */ +Block._fromJSON = function _fromJSON(data) { + if (JSUtil.isValidJSON(data)) { + data = JSON.parse(data); + } + var txs = []; + data.txs.forEach(function(tx) { + txs.push(Transaction().fromJSON(tx)); + }); + var info = { + magicnum: data.magicnum, + size: data.size, + header: BlockHeader.fromJSON(data.header), + txsvi: Varint().fromString(data.txsvi), + txs: txs + }; + return info; +}; + +/** + * @param {String|Object} - A JSON string or object + * @returns {Block} - An instance of block + */ +Block.fromJSON = function fromJSON(json) { + var info = Block._fromJSON(json); + return new Block(info); +}; + +/** + * @param {BufferReader} - Block data + * @returns {Object} - An object representing the block data + * @private + */ +Block._fromBufferReader = function _fromBufferReader(br) { + var info = {}; + info.magicnum = br.readUInt32LE(); + info.size = br.readUInt32LE(); + info.header = BlockHeader.fromBufferReader(br); + info.txsvi = Varint(br.readVarintBuf()); + var txslen = info.txsvi.toNumber(); + info.txs = []; + for (var i = 0; i < txslen; i++) { + info.txs.push(Transaction().fromBufferReader(br)); + } + return info; +}; + +/** + * @param {BufferReader} - A buffer reader of the block + * @returns {Block} - An instance of block + */ +Block.fromBufferReader = function fromBufferReader(br) { + var info = Block._fromBufferReader(br); + return new Block(info); +}; + +/** + * @param {Buffer} - A buffer of the block + * @returns {Block} - An instance of block + */ +Block.fromBuffer = function fromBuffer(buf) { + return Block.fromBufferReader(BufferReader(buf)); +}; + +/** + * @param {String} - str - A hex encoded string of the block + * @returns {Block} - A hex encoded string of the block + */ +Block.fromString = function fromString(str) { + var buf = new Buffer(str, 'hex'); + return Block.fromBuffer(buf); +}; + +/** + * @param {Binary} - Raw block binary data or buffer + * @returns {Block} - An instance of block + */ +Block.fromRawBlock = function fromRawBlock(data) { + if (!BufferUtil.isBuffer(data)) { + data = new Buffer(data, 'binary'); + } + var br = BufferReader(data); + var info = Block._fromBufferReader(br); + return new Block(info); +}; + +/** + * @returns {Object} - A plain object with the block properties + */ +Block.prototype.toObject = function toObject() { + var txs = []; + this.txs.forEach(function(tx) { + txs.push(tx.toObject()); + }); + return { + magicnum: this.magicnum, + size: this.size, + header: this.header.toObject(), + txsvi: this.txsvi.toString(), + txs: txs + }; +}; + +/** + * @returns {String} - A JSON string + */ +Block.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +/** + * @returns {Buffer} - A buffer of the block + */ +Block.prototype.toBuffer = function toBuffer() { + return this.toBufferWriter().concat(); +}; + +/** + * @returns {String} - A hex encoded string of the block + */ +Block.prototype.toString = function toString() { + return this.toBuffer().toString('hex'); +}; + +/** + * @param {BufferWriter} - An existing instance of BufferWriter + * @returns {BufferWriter} - An instance of BufferWriter representation of the Block + */ +Block.prototype.toBufferWriter = function toBufferWriter(bw) { + if (!bw) { + bw = new BufferWriter(); + } + bw.writeUInt32LE(this.magicnum); + bw.writeUInt32LE(this.size); + bw.write(this.header.toBuffer()); + bw.write(this.txsvi.buf); + var txslen = this.txsvi.toNumber(); + for (var i = 0; i < txslen; i++) { + this.txs[i].toBufferWriter(bw); + } + return bw; +}; + +/** + * Will iterate through each transaction and return an array of hashes + * @returns {Array} - An array with transaction hashes + */ +Block.prototype.getTransactionHashes = function getTransactionHashes() { + var hashes = []; + if (this.txs.length === 0) { + return [Block.Values.NULL_HASH]; + } + for (var t = 0; t < this.txs.length; t++) { + hashes.push(this.txs[t]._getHash()); + } + return hashes; +}; + +/** + * Will build a merkle tree of all the transactions, ultimately arriving at + * a single point, the merkle root. + * @link https://en.bitcoin.it/wiki/Protocol_specification#Merkle_Trees + * @returns {Array} - An array with each level of the tree after the other. + */ +Block.prototype.getMerkleTree = function getMerkleTree() { + + var tree = this.getTransactionHashes(); + + var j = 0; + for (var size = this.txs.length; size > 1; size = Math.floor((size + 1) / 2)) { + for (var i = 0; i < size; i += 2) { + var i2 = Math.min(i + 1, size - 1); + var buf = Buffer.concat([tree[j + i], tree[j + i2]]); + tree.push(Hash.sha256sha256(buf)); + } + j += size; + } + + return tree; +}; + +/** + * Calculates the merkleRoot from the transactions. + * @returns {Buffer} - A buffer of the merkle root hash + */ +Block.prototype.getMerkleRoot = function getMerkleRoot() { + var tree = this.getMerkleTree(); + return tree[tree.length - 1]; +}; + +/** + * Verifies that the transactions in the block match the header merkle root + * @returns {Boolean} - If the merkle roots match + */ +Block.prototype.validMerkleRoot = function validMerkleRoot() { + + var h = new BN(this.header.merkleRoot.toString('hex'), 'hex'); + var c = new BN(this.getMerkleRoot().toString('hex'), 'hex'); + + if (h.cmp(c) !== 0) { + return false; + } + + return true; +}; + +/** + * @returns {Buffer} - The little endian hash buffer of the header + */ +Block.prototype._getHash = function() { + return this.header._getHash(); +}; + +var idProperty = { + configurable: false, + writeable: false, + /** + * @returns {string} - The big endian hash buffer of the header + */ + get: function() { + if (!this._id) { + this._id = this.header.id; + } + return this._id; + }, + set: _.noop +}; +Object.defineProperty(Block.prototype, 'id', idProperty); +Object.defineProperty(Block.prototype, 'hash', idProperty); + +/** + * @returns {String} - A string formated for the console + */ +Block.prototype.inspect = function inspect() { + return ''; +}; + +Block.Values = { + NULL_HASH: new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex') +}; + +module.exports = Block; + +}).call(this,require("buffer").Buffer) +},{"./blockheader":4,"./crypto/bn":5,"./crypto/hash":7,"./encoding/bufferreader":13,"./encoding/bufferwriter":14,"./encoding/varint":15,"./transaction":33,"./util/buffer":48,"./util/js":49,"buffer":69,"lodash":233}],4:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _ = require('lodash'); +var BN = require('./crypto/bn'); +var BufferUtil = require('./util/buffer'); +var BufferReader = require('./encoding/bufferreader'); +var BufferWriter = require('./encoding/bufferwriter'); +var Hash = require('./crypto/hash'); +var JSUtil = require('./util/js'); + +/** + * Instantiate a BlockHeader from a Buffer, JSON object, or Object with + * the properties of the BlockHeader + * + * @param {*} - A Buffer, JSON string, or Object + * @returns {BlockHeader} - An instance of block header + * @constructor + */ +var BlockHeader = function BlockHeader(arg) { + if (!(this instanceof BlockHeader)) { + return new BlockHeader(arg); + } + _.extend(this, BlockHeader._from(arg)); + return this; +}; + +/** + * @param {*} - A Buffer, JSON string or Object + * @returns {Object} - An object representing block header data + * @throws {TypeError} - If the argument was not recognized + * @private + */ +BlockHeader._from = function _from(arg) { + var info = {}; + if (BufferUtil.isBuffer(arg)) { + info = BlockHeader._fromBufferReader(BufferReader(arg)); + } else if (JSUtil.isValidJSON(arg)) { + info = BlockHeader._fromJSON(arg); + } else if (_.isObject(arg)) { + info = { + version: arg.version, + prevHash: arg.prevHash, + merkleRoot: arg.merkleRoot, + time: arg.time, + bits: arg.bits, + nonce: arg.nonce + }; + } else { + throw new TypeError('Unrecognized argument for BlockHeader'); + } + return info; +}; + +/** + * @param {String|Object} - A JSON string or object + * @returns {Object} - An object representing block header data + * @private + */ +BlockHeader._fromJSON = function _fromJSON(data) { + if (JSUtil.isValidJSON(data)) { + data = JSON.parse(data); + } + var info = { + version: data.version, + prevHash: new Buffer(data.prevHash, 'hex'), + merkleRoot: new Buffer(data.merkleRoot, 'hex'), + time: data.time, + timestamp: data.time, + bits: data.bits, + nonce: data.nonce + }; + return info; +}; + +/** + * @param {String|Object} - A JSON string or object + * @returns {BlockHeader} - An instance of block header + */ +BlockHeader.fromJSON = function fromJSON(json) { + var info = BlockHeader._fromJSON(json); + return new BlockHeader(info); +}; + +/** + * @param {Binary} - Raw block binary data or buffer + * @returns {BlockHeader} - An instance of block header + */ +BlockHeader.fromRawBlock = function fromRawBlock(data) { + if (!BufferUtil.isBuffer(data)) { + data = new Buffer(data, 'binary'); + } + var br = BufferReader(data); + br.pos = BlockHeader.Constants.START_OF_HEADER; + var info = BlockHeader._fromBufferReader(br); + return new BlockHeader(info); +}; + +/** + * @param {Buffer} - A buffer of the block header + * @returns {BlockHeader} - An instance of block header + */ +BlockHeader.fromBuffer = function fromBuffer(buf) { + var info = BlockHeader._fromBufferReader(BufferReader(buf)); + return new BlockHeader(info); +}; + +/** + * @param {String} - A hex encoded buffer of the block header + * @returns {BlockHeader} - An instance of block header + */ +BlockHeader.fromString = function fromString(str) { + var buf = new Buffer(str, 'hex'); + return BlockHeader.fromBuffer(buf); +}; + +/** + * @param {BufferReader} - A BufferReader of the block header + * @returns {Object} - An object representing block header data + * @private + */ +BlockHeader._fromBufferReader = function _fromBufferReader(br) { + var info = { + version: br.readUInt32LE(), + prevHash: br.read(32), + merkleRoot: br.read(32), + time: br.readUInt32LE(), + bits: br.readUInt32LE(), + nonce: br.readUInt32LE() + }; + return info; +}; + +/** + * @param {BufferReader} - A BufferReader of the block header + * @returns {BlockHeader} - An instance of block header + */ +BlockHeader.fromBufferReader = function fromBufferReader(br) { + var info = BlockHeader._fromBufferReader(br); + return new BlockHeader(info); +}; + +/** + * @returns {Object} - A plain object of the BlockHeader + */ +BlockHeader.prototype.toObject = function toObject() { + return { + version: this.version, + prevHash: this.prevHash.toString('hex'), + merkleRoot: this.merkleRoot.toString('hex'), + time: this.time, + bits: this.bits, + nonce: this.nonce + }; +}; + +/** + * @returns {String} - A JSON string + */ +BlockHeader.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +/** + * @returns {Buffer} - A Buffer of the BlockHeader + */ +BlockHeader.prototype.toBuffer = function toBuffer() { + return this.toBufferWriter().concat(); +}; + +/** + * @returns {String} - A hex encoded string of the BlockHeader + */ +BlockHeader.prototype.toString = function toString() { + return this.toBuffer().toString('hex'); +}; + +/** + * @param {BufferWriter} - An existing instance BufferWriter + * @returns {BufferWriter} - An instance of BufferWriter representation of the BlockHeader + */ +BlockHeader.prototype.toBufferWriter = function toBufferWriter(bw) { + if (!bw) { + bw = new BufferWriter(); + } + bw.writeUInt32LE(this.version); + bw.write(this.prevHash); + bw.write(this.merkleRoot); + bw.writeUInt32LE(this.time); + bw.writeUInt32LE(this.bits); + bw.writeUInt32LE(this.nonce); + return bw; +}; + +/** + * @link https://en.bitcoin.it/wiki/Difficulty + * @returns {BN} - An instance of BN with the decoded difficulty bits + */ +BlockHeader.prototype.getTargetDifficulty = function getTargetDifficulty(info) { + var target = BN(this.bits & 0xffffff); + var mov = 8 * ((this.bits >>> 24) - 3); + while (mov-- > 0) { + target = target.mul(2); + } + return target; +}; + +/** + * @returns {Buffer} - The little endian hash buffer of the header + */ +BlockHeader.prototype._getHash = function hash() { + var buf = this.toBuffer(); + return Hash.sha256sha256(buf); +}; + +var idProperty = { + configurable: false, + writeable: false, + /** + * @returns {string} - The big endian hash buffer of the header + */ + get: function() { + if (!this._id) { + this._id = BufferReader(this._getHash()).readReverse().toString('hex'); + } + return this._id; + }, + set: _.noop +}; +Object.defineProperty(BlockHeader.prototype, 'id', idProperty); +Object.defineProperty(BlockHeader.prototype, 'hash', idProperty); + +/** + * @returns {Boolean} - If timestamp is not too far in the future + */ +BlockHeader.prototype.validTimestamp = function validTimestamp() { + var currentTime = Math.round(new Date().getTime() / 1000); + if (this.time > currentTime + BlockHeader.Constants.MAX_TIME_OFFSET) { + return false; + } + return true; +}; + +/** + * @returns {Boolean} - If the proof-of-work hash satisfies the target difficulty + */ +BlockHeader.prototype.validProofOfWork = function validProofOfWork() { + var pow = new BN(this.id, 'hex'); + var target = this.getTargetDifficulty(); + + if (pow.cmp(target) > 0) { + return false; + } + return true; +}; + +/** + * @returns {String} - A string formated for the console + */ +BlockHeader.prototype.inspect = function inspect() { + return ''; +}; + +BlockHeader.Constants = { + START_OF_HEADER: 8, // Start buffer position in raw block data + MAX_TIME_OFFSET: 2 * 60 * 60, // The max a timestamp can be in the future + LARGEST_HASH: new BN('10000000000000000000000000000000000000000000000000000000000000000', 'hex') +}; + +module.exports = BlockHeader; + +}).call(this,require("buffer").Buffer) +},{"./crypto/bn":5,"./crypto/hash":7,"./encoding/bufferreader":13,"./encoding/bufferwriter":14,"./util/buffer":48,"./util/js":49,"buffer":69,"lodash":233}],5:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _BN = require('bn.js'); + +var BN = function BN(n, base) { + if (!(this instanceof BN)) { + return new BN(n, base); + } + _BN.apply(this, arguments); +}; + +BN.prototype = _BN.prototype; + +var reversebuf = function(buf) { + var buf2 = new Buffer(buf.length); + for (var i = 0; i < buf.length; i++) { + buf2[i] = buf[buf.length-1-i]; + } + return buf2; +}; + +BN.prototype.fromNumber = function(n) { + var bn = BN(n); + bn.copy(this); + return this; +}; + +BN.prototype.toNumber = function() { + return parseInt(this['toString'](10), 10); +}; + +BN.prototype.fromString = function(str) { + var bn = BN(str); + bn.copy(this); + return this; +}; + +BN.fromBuffer = function(buf, opts) { + if (typeof opts !== 'undefined' && opts.endian === 'little') { + buf = reversebuf(buf); + } + var hex = buf.toString('hex'); + var bn = new BN(hex, 16); + return bn; +}; + +BN.prototype.fromBuffer = function(buf, opts) { + var bn = BN.fromBuffer(buf, opts); + bn.copy(this); + + return this; +}; + +BN.prototype.toBuffer = function(opts) { + var buf; + if (opts && opts.size) { + var hex = this.toString(16, 2); + var natlen = hex.length/2; + buf = new Buffer(hex, 'hex'); + + if (natlen == opts.size) + buf = buf; + + else if (natlen > opts.size) { + buf = buf.slice(natlen - buf.length, buf.length); + } + + else if (natlen < opts.size) { + var rbuf = new Buffer(opts.size); + for (var i = 0; i < buf.length; i++) + rbuf[rbuf.length-1-i] = buf[buf.length-1-i]; + for (var i = 0; i < opts.size - natlen; i++) + rbuf[i] = 0; + buf = rbuf; + } + } + else { + var hex = this.toString(16, 2); + buf = new Buffer(hex, 'hex'); + } + + if (typeof opts !== 'undefined' && opts.endian === 'little') { + buf = reversebuf(buf); + } + + return buf; +}; + +// signed magnitude buffer +// most significant bit represents sign (0 = positive, -1 = negative) +BN.prototype.fromSM = function(buf, opts) { + if (buf.length === 0) + this.fromBuffer(new Buffer([0])); + + var endian = 'big'; + if (opts) + endian = opts.endian; + + if (endian == 'little') + buf = reversebuf(buf); + + if (buf[0] & 0x80) { + buf[0] = buf[0] & 0x7f; + this.fromBuffer(buf); + this.neg().copy(this); + } else { + this.fromBuffer(buf); + } + return this; +}; + +BN.prototype.toSM = function(opts) { + var endian = 'big'; + if (opts) + endian = opts.endian; + + var buf; + if (this.cmp(0) == -1) { + buf = this.neg().toBuffer(); + if (buf[0] & 0x80) + buf = Buffer.concat([new Buffer([0x80]), buf]); + else + buf[0] = buf[0] | 0x80; + } else { + buf = this.toBuffer(); + if (buf[0] & 0x80) + buf = Buffer.concat([new Buffer([0x00]), buf]); + } + + if (buf.length === 1 & buf[0] === 0) + buf = new Buffer([]); + + if (endian == 'little') + buf = reversebuf(buf); + + return buf; +}; + +// This is analogous to the constructor for CScriptNum in bitcoind. Many ops in +// bitcoind's script interpreter use CScriptNum, which is not really a proper +// bignum. Instead, an error is thrown if trying to input a number bigger than +// 4 bytes. We copy that behavior here. +BN.prototype.fromScriptNumBuffer = function(buf, fRequireMinimal) { + var nMaxNumSize = 4; + if (buf.length > nMaxNumSize) + throw new Error('script number overflow'); + if (fRequireMinimal && buf.length > 0) { + // Check that the number is encoded with the minimum possible + // number of bytes. + // + // If the most-significant-byte - excluding the sign bit - is zero + // then we're not minimal. Note how this test also rejects the + // negative-zero encoding, 0x80. + if ((buf[buf.length - 1] & 0x7f) === 0) { + // One exception: if there's more than one byte and the most + // significant bit of the second-most-significant-byte is set + // it would conflict with the sign bit. An example of this case + // is +-255, which encode to 0xff00 and 0xff80 respectively. + // (big-endian). + if (buf.length <= 1 || (buf[buf.length - 2] & 0x80) === 0) { + throw new Error("non-minimally encoded script number"); + } + } + } + return this.fromSM(buf, {endian: 'little'}); +}; + +// The corollary to the above, with the notable exception that we do not throw +// an error if the output is larger than four bytes. (Which can happen if +// performing a numerical operation that results in an overflow to more than 4 +// bytes). +BN.prototype.toScriptNumBuffer = function(buf) { + return this.toSM({endian: 'little'}); +}; + +function decorate(name) { + BN.prototype['_' + name] = BN.prototype[name]; + var f = function(b) { + if (typeof b === 'string') + b = new BN(b); + else if (typeof b === 'number') + b = new BN(b.toString()); + return this['_' + name](b); + }; + BN.prototype[name] = f; +}; + +BN.prototype.gt = function(b) { + return this.cmp(b) > 0; +}; + +BN.prototype.lt = function(b) { + return this.cmp(b) < 0; +}; + +decorate('add'); +decorate('sub'); +decorate('mul'); +decorate('mod'); +decorate('div'); +decorate('cmp'); +decorate('gt'); +decorate('lt'); + +module.exports = BN; + +}).call(this,require("buffer").Buffer) +},{"bn.js":65,"buffer":69}],6:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var BN = require('./bn'); +var Point = require('./point'); +var Signature = require('./signature'); +var PublicKey = require('../publickey'); +var PrivateKey = require('../privatekey'); +var Random = require('./random'); +var Hash = require('./hash'); + +var ECDSA = function ECDSA(obj) { + if (!(this instanceof ECDSA)) { + return new ECDSA(obj); + } + if (obj) { + this.set(obj); + } +}; + +ECDSA.prototype.set = function(obj) { + this.hashbuf = obj.hashbuf || this.hashbuf; + this.endian = obj.endian || this.endian; //the endianness of hashbuf + this.privkey = obj.privkey || this.privkey; + this.pubkey = obj.pubkey || (this.privkey ? this.privkey.publicKey : this.pubkey); + this.sig = obj.sig || this.sig; + this.k = obj.k || this.k; + this.verified = obj.verified || this.verified; + return this; +}; + +ECDSA.prototype.privkey2pubkey = function() { + this.pubkey = this.privkey.toPublicKey(); +}; + +ECDSA.prototype.calci = function() { + for (var i = 0; i < 4; i++) { + this.sig.i = i; + var Qprime; + try { + Qprime = this.sig2pubkey(); + } catch (e) { + console.error(e); + continue; + } + + if (Qprime.point.eq(this.pubkey.point)) { + this.sig.compressed = this.pubkey.compressed; + return this; + } + } + + this.sig.i = undefined; + throw new Error('Unable to find valid recovery factor'); +}; + +ECDSA.prototype.fromString = function(str) { + var obj = JSON.parse(str); + if (obj.hashbuf) { + this.hashbuf = new Buffer(obj.hashbuf, 'hex'); + } + if (obj.pubkey) { + this.pubkey = PublicKey.fromString(obj.pubkey); + } + if (obj.privkey) { + this.privkey = PrivateKey.fromString(obj.privkey); + } + if (obj.sig) { + this.sig = Signature.fromString(obj.sig); + } + if (obj.k) { + this.k = BN(obj.k, 10); + } + return this; +}; + +ECDSA.prototype.randomK = function() { + var N = Point.getN(); + var k; + do { + k = BN().fromBuffer(Random.getRandomBuffer(32)); + } while (!(k.lt(N) && k.gt(0))); + this.k = k; + return this; +}; + +// https://tools.ietf.org/html/rfc6979#section-3.2 +ECDSA.prototype.deterministicK = function(badrs) { + var v = new Buffer(32); + v.fill(0x01); + var k = new Buffer(32); + k.fill(0x00); + var x = this.privkey.bn.toBuffer({size: 32}); + k = Hash.sha256hmac(Buffer.concat([v, new Buffer([0x00]), x, this.hashbuf]), k); + v = Hash.sha256hmac(v, k); + k = Hash.sha256hmac(Buffer.concat([v, new Buffer([0x01]), x, this.hashbuf]), k); + v = Hash.sha256hmac(v, k); + v = Hash.sha256hmac(v, k); + var T = BN().fromBuffer(v); + var N = Point.getN(); + + // if r or s were invalid when this function was used in signing, + // we do not want to actually compute r, s here for efficiency, so, + // we can increment badrs. explained at end of RFC 6979 section 3.2 + if (typeof badrs === 'undefined') + badrs = 0; + // also explained in 3.2, we must ensure T is in the proper range (0, N) + for (var i = 0; i < badrs || !(T.lt(N) && T.gt(0)); i++) { + k = Hash.sha256hmac(Buffer.concat([v, new Buffer([0x00])]), k); + v = Hash.sha256hmac(v, k); + T = BN().fromBuffer(v); + } + + this.k = T; + return this; +}; + +// Information about public key recovery: +// https://bitcointalk.org/index.php?topic=6430.0 +// http://stackoverflow.com/questions/19665491/how-do-i-get-an-ecdsa-public-key-from-just-a-bitcoin-signature-sec1-4-1-6-k +ECDSA.prototype.sig2pubkey = function() { + var i = this.sig.i; + if (!(i === 0 || i === 1 || i === 2 || i === 3)) + throw new Error('i must be equal to 0, 1, 2, or 3'); + + var e = BN().fromBuffer(this.hashbuf); + var r = this.sig.r; + var s = this.sig.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = i & 1; + + // The more significant bit specifies whether we should use the + // first or second candidate key. + var isSecondKey = i >> 1; + + var n = Point.getN(); + var G = Point.getG(); + + // 1.1 Let x = r + jn + var x = isSecondKey ? r.add(n) : r; + var R = Point.fromX(isYOdd, x); + + // 1.4 Check that nR is at infinity + var nR = R.mul(n); + + if (!nR.isInfinity()) + throw new Error('nR is not a valid curve point'); + + // Compute -e from e + var eNeg = e.neg().mod(n); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + var rInv = r.invm(n); + + //var Q = R.multiplyTwo(s, G, eNeg).mul(rInv); + var Q = R.mul(s).add(G.mul(eNeg)).mul(rInv); + + var pubkey = PublicKey.fromPoint(Q, this.sig.compressed); + + return pubkey; +}; + +ECDSA.prototype.sigError = function() { + if (!Buffer.isBuffer(this.hashbuf) || this.hashbuf.length !== 32) { + return 'hashbuf must be a 32 byte buffer'; + } + + var r = this.sig.r; + var s = this.sig.s; + if (!(r.gt(0) && r.lt(Point.getN())) + || !(s.gt(0) && s.lt(Point.getN()))) + return 'r and s not in range'; + + var e = BN().fromBuffer(this.hashbuf, this.endian ? {endian: this.endian} : undefined); + var n = Point.getN(); + var sinv = s.invm(n); + var u1 = sinv.mul(e).mod(n); + var u2 = sinv.mul(r).mod(n); + + var p = Point.getG().mulAdd(u1, this.pubkey.point, u2); + if (p.isInfinity()) + return 'p is infinity'; + + if (!(p.getX().mod(n).cmp(r) === 0)) + return 'Invalid signature'; + else + return false; +}; + +ECDSA.prototype.sign = function() { + var hashbuf = this.hashbuf; + var privkey = this.privkey; + + var d = privkey.bn; + + if (!hashbuf || !privkey || !d) + throw new Error('invalid parameters'); + + if (!Buffer.isBuffer(hashbuf) || hashbuf.length !== 32) + throw new Error('hashbuf must be a 32 byte buffer'); + + var N = Point.getN(); + var G = Point.getG(); + var e = BN().fromBuffer(hashbuf, this.endian ? {endian: this.endian} : undefined); + + // try different values of k until r, s are valid + var badrs = 0; + do { + if (!this.k || badrs > 0) + this.deterministicK(badrs); + badrs++; + var k = this.k; + var Q = G.mul(k); + var r = Q.x.mod(N); + var s = k.invm(N).mul(e.add(d.mul(r))).mod(N); + } while (r.cmp(0) <= 0 || s.cmp(0) <= 0); + + //enforce low s + //see BIP 62, "low S values in signatures" + if (s.gt(BN().fromBuffer(new Buffer('7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0', 'hex')))) { + s = Point.getN().sub(s); + } + + this.sig = new Signature({r: r, s: s, compressed: this.pubkey.compressed}); + return this; +}; + +ECDSA.prototype.signRandomK = function() { + this.randomK(); + return this.sign(); +}; + +ECDSA.prototype.toString = function() { + var obj = {}; + if (this.hashbuf) { + obj.hashbuf = this.hashbuf.toString('hex'); + } + if (this.privkey) { + obj.privkey = this.privkey.toString(); + } + if (this.pubkey) { + obj.pubkey = this.pubkey.toString(); + } + if (this.sig) { + obj.sig = this.sig.toString(); + } + if (this.k) { + obj.k = this.k.toString(); + } + return JSON.stringify(obj); +}; + +ECDSA.prototype.verify = function() { + if (!this.sigError()) + this.verified = true; + else + this.verified = false; + return this; +}; + +ECDSA.sign = function(hashbuf, privkey, endian) { + return ECDSA().set({ + hashbuf: hashbuf, + endian: endian, + privkey: privkey + }).sign().sig; +}; + +ECDSA.verify = function(hashbuf, sig, pubkey, endian) { + return ECDSA().set({ + hashbuf: hashbuf, + endian: endian, + sig: sig, + pubkey: pubkey + }).verify().verified; +}; + +module.exports = ECDSA; + +}).call(this,require("buffer").Buffer) +},{"../privatekey":28,"../publickey":29,"./bn":5,"./hash":7,"./point":8,"./random":9,"./signature":10,"buffer":69}],7:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var hashjs = require('hash.js'); +var sha512 = require('sha512'); +var crypto = require('crypto'); +var BufferUtil = require('../util/buffer'); +var $ = require('../util/preconditions'); + +var Hash = module.exports; + +Hash.sha1 = function(buf) { + $.checkArgument(BufferUtil.isBuffer(buf)); + return crypto.createHash('sha1').update(buf).digest(); +}; + +Hash.sha1.blocksize = 512; + +Hash.sha256 = function(buf) { + $.checkArgument(BufferUtil.isBuffer(buf)); + return crypto.createHash('sha256').update(buf).digest(); +}; + +Hash.sha256.blocksize = 512; + +Hash.sha256sha256 = function(buf) { + $.checkArgument(BufferUtil.isBuffer(buf)); + return Hash.sha256(Hash.sha256(buf)); +}; + +Hash.ripemd160 = function(buf) { + $.checkArgument(BufferUtil.isBuffer(buf)); + var hash = (new hashjs.ripemd160()).update(buf).digest(); + return new Buffer(hash); +}; + +Hash.sha256ripemd160 = function(buf) { + $.checkArgument(BufferUtil.isBuffer(buf)); + return Hash.ripemd160(Hash.sha256(buf)); +}; + +Hash.sha512 = function(buf) { + $.checkArgument(BufferUtil.isBuffer(buf)); + var hash = sha512(buf); + return new Buffer(hash); +}; + +Hash.sha512.blocksize = 1024; + +Hash.hmac = function(hashf, data, key) { + //http://en.wikipedia.org/wiki/Hash-based_message_authentication_code + //http://tools.ietf.org/html/rfc4868#section-2 + $.checkArgument(BufferUtil.isBuffer(data)); + $.checkArgument(BufferUtil.isBuffer(key)); + $.checkArgument(hashf.blocksize); + + var blocksize = hashf.blocksize / 8; + + if (key.length > blocksize) { + key = hashf(key); + } else if (key < blocksize) { + var fill = new Buffer(blocksize); + fill.fill(0); + key.copy(fill); + key = fill; + } + + var o_key = new Buffer(blocksize); + o_key.fill(0x5c); + + var i_key = new Buffer(blocksize); + i_key.fill(0x36); + + var o_key_pad = new Buffer(blocksize); + var i_key_pad = new Buffer(blocksize); + for (var i = 0; i < blocksize; i++) { + o_key_pad[i] = o_key[i] ^ key[i]; + i_key_pad[i] = i_key[i] ^ key[i]; + } + + return hashf(Buffer.concat([o_key_pad, hashf(Buffer.concat([i_key_pad, data]))])); +}; + +Hash.sha256hmac = function(data, key) { + return Hash.hmac(Hash.sha256, data, key); +}; + +Hash.sha512hmac = function(data, key) { + return Hash.hmac(Hash.sha512, data, key); +}; + +}).call(this,require("buffer").Buffer) +},{"../util/buffer":48,"../util/preconditions":50,"buffer":69,"crypto":76,"hash.js":225,"sha512":240}],8:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var BN = require('./bn'); +var bufferUtil = require('../util/buffer'); +var ec = require('elliptic').curves.secp256k1; +var ecPoint = ec.curve.point.bind(ec.curve); +var ecPointFromX = ec.curve.pointFromX.bind(ec.curve); + +/** + * + * Instantiate a valid secp256k1 Point from the X and Y coordinates. + * + * @param {BN|String} x - The X coordinate + * @param {BN|String} y - The Y coordinate + * @link https://github.com/indutny/elliptic + * @augments elliptic.curve.point + * @throws {Error} A validation error if exists + * @returns {Point} An instance of Point + * @constructor + */ +var Point = function Point(x, y, isRed) { + var point = ecPoint(x, y, isRed); + point.validate(); + return point; +}; + +Point.prototype = Object.getPrototypeOf(ec.curve.point()); + +/** + * + * Instantiate a valid secp256k1 Point from only the X coordinate + * + * @param {boolean} odd - If the Y coordinate is odd + * @param {BN|String} x - The X coordinate + * @throws {Error} A validation error if exists + * @returns {Point} An instance of Point + */ +Point.fromX = function fromX(odd, x){ + var point = ecPointFromX(odd, x); + point.validate(); + return point; +}; + +/** + * + * Will return a secp256k1 ECDSA base point. + * + * @link https://en.bitcoin.it/wiki/Secp256k1 + * @returns {Point} An instance of the base point. + */ +Point.getG = function getG() { + return Point(ec.curve.g.getX(), ec.curve.g.getY()); +}; + +/** + * + * Will return the max of range of valid private keys as governed by the secp256k1 ECDSA standard. + * + * @link https://en.bitcoin.it/wiki/Private_key#Range_of_valid_ECDSA_private_keys + * @returns {BN} A BN instance of the number of points on the curve + */ +Point.getN = function getN() { + return BN(ec.curve.n.toArray()); +}; + +Point.prototype._getX = Point.prototype.getX; + +/** + * + * Will return the X coordinate of the Point + * + * @returns {BN} A BN instance of the X coordinate + */ +Point.prototype.getX = function getX() { + return BN(this._getX().toArray()); +}; + +Point.prototype._getY = Point.prototype.getY; + +/** + * + * Will return the Y coordinate of the Point + * + * @returns {BN} A BN instance of the Y coordinate + */ +Point.prototype.getY = function getY() { + return BN(this._getY().toArray()); +}; + +/** + * + * Will determine if the point is valid + * + * @link https://www.iacr.org/archive/pkc2003/25670211/25670211.pdf + * @param {Point} An instance of Point + * @throws {Error} A validation error if exists + * @returns {Point} An instance of the same Point + */ +Point.prototype.validate = function validate() { + + if (this.isInfinity()){ + throw new Error('Point cannot be equal to Infinity'); + } + + if (this.getX().cmp(0) === 0 || this.getY().cmp(0) === 0){ + throw new Error('Invalid x,y value for curve, cannot equal 0.'); + } + + var p2 = ecPointFromX(this.getY().isOdd(), this.getX()); + + if (p2.y.cmp(this.y) !== 0) { + throw new Error('Invalid y value for curve.'); + } + + var xValidRange = (this.getX().gt(-1) && this.getX().lt(Point.getN())); + var yValidRange = (this.getY().gt(-1) && this.getY().lt(Point.getN())); + + if ( !xValidRange || !yValidRange ) { + throw new Error('Point does not lie on the curve'); + } + + //todo: needs test case + if (!(this.mul(Point.getN()).isInfinity())) { + throw new Error('Point times N must be infinity'); + } + + return this; + +}; + +Point.pointToCompressed = function pointToCompressed(point) { + var xbuf = point.getX().toBuffer({size: 32}); + var ybuf = point.getY().toBuffer({size: 32}); + + var prefix; + var odd = ybuf[ybuf.length - 1] % 2; + if (odd) { + prefix = new Buffer([0x03]); + } else { + prefix = new Buffer([0x02]); + } + return bufferUtil.concat([prefix, xbuf]); +}; + +module.exports = Point; + +}).call(this,require("buffer").Buffer) +},{"../util/buffer":48,"./bn":5,"buffer":69,"elliptic":211}],9:[function(require,module,exports){ +(function (process,Buffer){ +'use strict'; + +function Random() { +} + +/* secure random bytes that sometimes throws an error due to lack of entropy */ +Random.getRandomBuffer = function(size) { + if (process.browser) + return Random.getRandomBufferBrowser(size); + else + return Random.getRandomBufferNode(size); +}; + +Random.getRandomBufferNode = function(size) { + var crypto = require('crypto'); + return crypto.randomBytes(size); +}; + +Random.getRandomBufferBrowser = function(size) { + if (!window.crypto && !window.msCrypto) + throw new Error('window.crypto not available'); + + if (window.crypto && window.crypto.getRandomValues) + var crypto = window.crypto; + else if (window.msCrypto && window.msCrypto.getRandomValues) //internet explorer + var crypto = window.msCrypto; + else + throw new Error('window.crypto.getRandomValues not available'); + + var bbuf = new Uint8Array(size); + crypto.getRandomValues(bbuf); + var buf = new Buffer(bbuf); + + return buf; +}; + +/* insecure random bytes, but it never fails */ +Random.getPseudoRandomBuffer = function(size) { + var b32 = 0x100000000; + var b = new Buffer(size); + var r; + + for (var i = 0; i <= size; i++) { + var j = Math.floor(i / 4); + var k = i - j * 4; + if (k === 0) { + r = Math.random() * b32; + b[i] = r & 0xff; + } else { + b[i] = (r = r >>> 8) & 0xff; + } + } + + return b; +}; + +module.exports = Random; + +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":185,"buffer":69,"crypto":76}],10:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var BN = require('./bn'); + +var Signature = function Signature(r, s) { + if (!(this instanceof Signature)) + return new Signature(r, s); + if (r instanceof BN) { + this.set({ + r: r, + s: s + }); + } else if (r) { + var obj = r; + this.set(obj); + } +}; + +Signature.prototype.set = function(obj) { + this.r = obj.r || this.r || undefined; + this.s = obj.s || this.s || undefined; + this.i = typeof obj.i !== 'undefined' ? obj.i : this.i; //public key recovery parameter in range [0, 3] + this.compressed = typeof obj.compressed !== 'undefined' ? obj.compressed : this.compressed; //whether the recovered pubkey is compressed + return this; +}; + +Signature.fromCompact = function(buf) { + var sig = new Signature(); + var compressed = true; + var i = buf.slice(0, 1)[0] - 27 - 4; + //TODO: handle uncompressed pubkeys + + var b2 = buf.slice(1, 33); + var b3 = buf.slice(33, 65); + + if (!(i === 0 || i === 1 || i === 2 || i === 3)) { + throw new Error('i must be 0, 1, 2, or 3'); + } + if (b2.length !== 32) { + throw new Error('r must be 32 bytes'); + } + if (b3.length !== 32) { + throw new Error('s must be 32 bytes'); + } + + sig.compressed = compressed; + sig.i = i; + sig.r = BN().fromBuffer(b2); + sig.s = BN().fromBuffer(b3); + + return sig; +}; + +Signature.fromDER = function(buf, strict) { + var obj = Signature.parseDER(buf, strict); + var sig = new Signature(); + + sig.r = obj.r; + sig.s = obj.s; + + return sig; +}; + +// The format used in a tx +Signature.fromTxFormat = function(buf) { + var nhashtype = buf.readUInt8(buf.length - 1); + var derbuf = buf.slice(0, buf.length - 1); + var sig = new Signature.fromDER(derbuf, false); + sig.nhashtype = nhashtype; + return sig; +}; + +Signature.fromString = function(str) { + var buf = new Buffer(str, 'hex'); + return Signature.fromDER(buf); +}; + + +/** + * In order to mimic the non-strict DER encoding of OpenSSL, set strict = false. + */ +Signature.parseDER = function(buf, strict) { + if (typeof strict === 'undefined') { + strict = true; + } + + if (!Buffer.isBuffer(buf)) { + throw new Error('DER formatted signature should be a buffer'); + } + + var header = buf[0]; + + if (header !== 0x30) { + throw new Error('Header byte should be 0x30'); + } + + var length = buf[1]; + var buflength = buf.slice(2).length; + if (strict && length !== buflength) { + throw new Error('Length byte should length of what follows'); + } else { + length = length < buflength ? length : buflength; + } + + var rheader = buf[2 + 0]; + if (rheader !== 0x02) { + throw new Error('Integer byte for r should be 0x02'); + } + + var rlength = buf[2 + 1]; + var rbuf = buf.slice(2 + 2, 2 + 2 + rlength); + var r = BN().fromBuffer(rbuf); + var rneg = buf[2 + 1 + 1] === 0x00 ? true : false; + if (rlength !== rbuf.length) { + throw new Error('Length of r incorrect'); + } + + var sheader = buf[2 + 2 + rlength + 0]; + if (sheader !== 0x02) { + throw new Error('Integer byte for s should be 0x02'); + } + + var slength = buf[2 + 2 + rlength + 1]; + var sbuf = buf.slice(2 + 2 + rlength + 2, 2 + 2 + rlength + 2 + slength); + var s = BN().fromBuffer(sbuf); + var sneg = buf[2 + 2 + rlength + 2 + 2] === 0x00 ? true : false; + if (slength !== sbuf.length) { + throw new Error('Length of s incorrect'); + } + + var sumlength = 2 + 2 + rlength + 2 + slength; + if (length !== sumlength - 2) { + throw new Error('Length of signature incorrect'); + } + + var obj = { + header: header, + length: length, + rheader: rheader, + rlength: rlength, + rneg: rneg, + rbuf: rbuf, + r: r, + sheader: sheader, + slength: slength, + sneg: sneg, + sbuf: sbuf, + s: s + }; + + return obj; +}; + + +Signature.prototype.toCompact = function(i, compressed) { + i = typeof i === 'number' ? i : this.i; + compressed = typeof compressed === 'boolean' ? compressed : this.compressed; + + if (!(i === 0 || i === 1 || i === 2 || i === 3)) { + throw new Error('i must be equal to 0, 1, 2, or 3'); + } + + var val = i + 27 + 4; + if (compressed === false) + val = val - 4; + var b1 = new Buffer([val]); + var b2 = this.r.toBuffer({ + size: 32 + }); + var b3 = this.s.toBuffer({ + size: 32 + }); + return Buffer.concat([b1, b2, b3]); +}; + +Signature.prototype.toBuffer = Signature.prototype.toDER = function() { + var rnbuf = this.r.toBuffer(); + var snbuf = this.s.toBuffer(); + + var rneg = rnbuf[0] & 0x80 ? true : false; + var sneg = snbuf[0] & 0x80 ? true : false; + + var rbuf = rneg ? Buffer.concat([new Buffer([0x00]), rnbuf]) : rnbuf; + var sbuf = sneg ? Buffer.concat([new Buffer([0x00]), snbuf]) : snbuf; + + var rlength = rbuf.length; + var slength = sbuf.length; + var length = 2 + rlength + 2 + slength; + var rheader = 0x02; + var sheader = 0x02; + var header = 0x30; + + var der = Buffer.concat([new Buffer([header, length, rheader, rlength]), rbuf, new Buffer([sheader, slength]), sbuf]); + return der; +}; + +Signature.prototype.toString = function() { + var buf = this.toDER(); + return buf.toString('hex'); +}; + +/** + * This function is translated from bitcoind's IsDERSignature and is used in + * the script interpreter. This "DER" format actually includes an extra byte, + * the nhashtype, at the end. It is really the tx format, not DER format. + * + * A canonical signature exists of: [30] [total len] [02] [len R] [R] [02] [len S] [S] [hashtype] + * Where R and S are not negative (their first byte has its highest bit not set), and not + * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows, + * in which case a single 0 byte is necessary and even required). + * + * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623 + */ +Signature.isTxDER = function(buf) { + if (buf.length < 9) { + // Non-canonical signature: too short + return false; + } + if (buf.length > 73) { + // Non-canonical signature: too long + return false; + } + if (buf[0] !== 0x30) { + // Non-canonical signature: wrong type + return false; + } + if (buf[1] !== buf.length - 3) { + // Non-canonical signature: wrong length marker + return false; + } + var nLenR = buf[3]; + if (5 + nLenR >= buf.length) { + // Non-canonical signature: S length misplaced + return false; + } + var nLenS = buf[5 + nLenR]; + if ((nLenR + nLenS + 7) !== buf.length) { + // Non-canonical signature: R+S length mismatch + return false; + } + + var R = buf.slice(4); + if (buf[4 - 2] !== 0x02) { + // Non-canonical signature: R value type mismatch + return false; + } + if (nLenR === 0) { + // Non-canonical signature: R length is zero + return false; + } + if (R[0] & 0x80) { + // Non-canonical signature: R value negative + return false; + } + if (nLenR > 1 && (R[0] === 0x00) && !(R[1] & 0x80)) { + // Non-canonical signature: R value excessively padded + return false; + } + + var S = buf.slice(6 + nLenR); + if (buf[6 + nLenR - 2] !== 0x02) { + // Non-canonical signature: S value type mismatch + return false; + } + if (nLenS === 0) { + // Non-canonical signature: S length is zero + return false; + } + if (S[0] & 0x80) { + // Non-canonical signature: S value negative + return false; + } + if (nLenS > 1 && (S[0] === 0x00) && !(S[1] & 0x80)) { + // Non-canonical signature: S value excessively padded + return false; + } + return true; +}; + +/** + * Compares to bitcoind's IsLowDERSignature + * See also ECDSA signature algorithm which enforces this. + * See also BIP 62, "low S values in signatures" + */ +Signature.prototype.hasLowS = function() { + if (this.s.lt(1) || + this.s.gt(BN('7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0'))) { + return false; + } + return true; +}; + +/** + * @returns true if the nhashtype is exactly equal to one of the standard options or combinations thereof. + * Translated from bitcoind's IsDefinedHashtypeSignature + */ +Signature.prototype.hasDefinedHashtype = function() { + if (this.nhashtype < Signature.SIGHASH_ALL || this.nhashtype > Signature.SIGHASH_SINGLE) { + return false; + } + return true; +}; + +Signature.prototype.toTxFormat = function() { + var derbuf = this.toDER(); + var buf = new Buffer(1); + buf.writeUInt8(this.nhashtype, 0); + return Buffer.concat([derbuf, buf]); +}; + +Signature.SIGHASH_ALL = 0x01; +Signature.SIGHASH_NONE = 0x02; +Signature.SIGHASH_SINGLE = 0x03; +Signature.SIGHASH_ANYONECANPAY = 0x80; + +module.exports = Signature; + +}).call(this,require("buffer").Buffer) +},{"./bn":5,"buffer":69}],11:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _ = require('lodash'); +var bs58 = require('bs58'); +var buffer = require('buffer'); + +var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.split(''); + +var Base58 = function Base58(obj) { + /* jshint maxcomplexity: 8 */ + if (!(this instanceof Base58)) { + return new Base58(obj); + } + if (Buffer.isBuffer(obj)) { + var buf = obj; + this.fromBuffer(buf); + } else if (typeof obj === 'string') { + var str = obj; + this.fromString(str); + } else if (obj) { + this.set(obj); + } +}; + +Base58.validCharacters = function validCharacters(chars) { + if (buffer.Buffer.isBuffer(chars)) { + chars = chars.toString(); + } + return _.all(_.map(chars, function(char) { return _.contains(ALPHABET, char); })); +}; + +Base58.prototype.set = function(obj) { + this.buf = obj.buf || this.buf || undefined; + return this; +}; + +Base58.encode = function(buf) { + if (!buffer.Buffer.isBuffer(buf)) { + throw new Error('Input should be a buffer'); + } + return bs58.encode(buf); +}; + +Base58.decode = function(str) { + if (typeof str !== 'string') { + throw new Error('Input should be a string'); + } + return new Buffer(bs58.decode(str)); +}; + +Base58.prototype.fromBuffer = function(buf) { + this.buf = buf; + return this; +}; + +Base58.prototype.fromString = function(str) { + var buf = Base58.decode(str); + this.buf = buf; + return this; +}; + +Base58.prototype.toBuffer = function() { + return this.buf; +}; + +Base58.prototype.toString = function() { + return Base58.encode(this.buf); +}; + +module.exports = Base58; + +}).call(this,require("buffer").Buffer) +},{"bs58":208,"buffer":69,"lodash":233}],12:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _ = require('lodash'); +var base58 = require('./base58'); +var buffer = require('buffer'); +var sha256sha256 = require('../crypto/hash').sha256sha256; + +var Base58Check = function Base58Check(obj) { + if (!(this instanceof Base58Check)) + return new Base58Check(obj); + if (Buffer.isBuffer(obj)) { + var buf = obj; + this.fromBuffer(buf); + } else if (typeof obj === 'string') { + var str = obj; + this.fromString(str); + } else if (obj) { + this.set(obj); + } +}; + +Base58Check.prototype.set = function(obj) { + this.buf = obj.buf || this.buf || undefined; + return this; +}; + +Base58Check.validChecksum = function validChecksum(data, checksum) { + if (_.isString(data)) { + data = new buffer.Buffer(base58.decode(data)); + } + if (_.isString(checksum)) { + checksum = new buffer.Buffer(base58.decode(checksum)); + } + if (!checksum) { + checksum = data.slice(-4); + data = data.slice(0, -4); + } + return Base58Check.checksum(data).toString('hex') === checksum.toString('hex'); +}; + +Base58Check.decode = function(s) { + if (typeof s !== 'string') + throw new Error('Input must be a string'); + + var buf = new Buffer(base58.decode(s)); + + if (buf.length < 4) + throw new Error("Input string too short"); + + var data = buf.slice(0, -4); + var csum = buf.slice(-4); + + var hash = sha256sha256(data); + var hash4 = hash.slice(0, 4); + + if (csum.toString('hex') !== hash4.toString('hex')) + throw new Error("Checksum mismatch"); + + return data; +}; + +Base58Check.checksum = function(buffer) { + return sha256sha256(buffer).slice(0, 4); +}; + +Base58Check.encode = function(buf) { + if (!Buffer.isBuffer(buf)) + throw new Error('Input must be a buffer'); + var checkedBuf = new Buffer(buf.length + 4); + var hash = Base58Check.checksum(buf); + buf.copy(checkedBuf); + hash.copy(checkedBuf, buf.length); + return base58.encode(checkedBuf); +}; + +Base58Check.prototype.fromBuffer = function(buf) { + this.buf = buf; + return this; +}; + +Base58Check.prototype.fromString = function(str) { + var buf = Base58Check.decode(str); + this.buf = buf; + return this; +}; + +Base58Check.prototype.toBuffer = function() { + return this.buf; +}; + +Base58Check.prototype.toString = function() { + return Base58Check.encode(this.buf); +}; + +module.exports = Base58Check; + +}).call(this,require("buffer").Buffer) +},{"../crypto/hash":7,"./base58":11,"buffer":69,"lodash":233}],13:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _ = require('lodash'); +var $ = require('../util/preconditions'); +var bufferUtil = require('../util/buffer'); +var BN = require('../crypto/bn'); + +var BufferReader = function BufferReader(buf) { + if (!(this instanceof BufferReader)) { + return new BufferReader(buf); + } + if (Buffer.isBuffer(buf)) { + this.set({buf: buf}); + } + else if (buf) { + var obj = buf; + this.set(obj); + } +}; + +BufferReader.prototype.set = function(obj) { + this.buf = obj.buf || this.buf || undefined; + this.pos = obj.pos || this.pos || 0; + return this; +}; + +BufferReader.prototype.eof = function() { + return this.pos >= this.buf.length; +}; + +BufferReader.prototype.read = function(len) { + $.checkArgument(!_.isUndefined(len), 'Must specify a length'); + var buf = this.buf.slice(this.pos, this.pos + len); + this.pos = this.pos + len; + return buf; +}; + +BufferReader.prototype.readAll = function() { + var buf = this.buf.slice(this.pos, this.buf.length); + this.pos = this.buf.length; + return buf; +}; + +BufferReader.prototype.readUInt8 = function() { + var val = this.buf.readUInt8(this.pos); + this.pos = this.pos + 1; + return val; +}; + +BufferReader.prototype.readUInt16BE = function() { + var val = this.buf.readUInt16BE(this.pos); + this.pos = this.pos + 2; + return val; +}; + +BufferReader.prototype.readUInt16LE = function() { + var val = this.buf.readUInt16LE(this.pos); + this.pos = this.pos + 2; + return val; +}; + +BufferReader.prototype.readUInt32BE = function() { + var val = this.buf.readUInt32BE(this.pos); + this.pos = this.pos + 4; + return val; +}; + +BufferReader.prototype.readUInt32LE = function() { + var val = this.buf.readUInt32LE(this.pos); + this.pos = this.pos + 4; + return val; +}; + +BufferReader.prototype.readUInt64BEBN = function() { + var buf = this.buf.slice(this.pos, this.pos + 8); + var bn = BN().fromBuffer(buf); + this.pos = this.pos + 8; + return bn; +}; + +BufferReader.prototype.readUInt64LEBN = function() { + var buf = this.buf.slice(this.pos, this.pos + 8); + var reversebuf = BufferReader({buf: buf}).readReverse(); + var bn = BN().fromBuffer(reversebuf); + this.pos = this.pos + 8; + return bn; +}; + +BufferReader.prototype.readVarintNum = function() { + var first = this.readUInt8(); + switch (first) { + case 0xFD: + return this.readUInt16LE(); + case 0xFE: + return this.readUInt32LE(); + case 0xFF: + var bn = this.readUInt64LEBN(); + var n = bn.toNumber(); + if (n <= Math.pow(2, 53)) { + return n; + } else { + throw new Error('number too large to retain precision - use readVarintBN'); + } + break; + default: + return first; + } +}; + +BufferReader.prototype.readVarintBuf = function() { + var first = this.buf.readUInt8(this.pos); + switch (first) { + case 0xFD: + return this.read(1 + 2); + case 0xFE: + return this.read(1 + 4); + case 0xFF: + return this.read(1 + 8); + default: + return this.read(1); + } +}; + +BufferReader.prototype.readVarintBN = function() { + var first = this.readUInt8(); + switch (first) { + case 0xFD: + return BN(this.readUInt16LE()); + case 0xFE: + return BN(this.readUInt32LE()); + case 0xFF: + return this.readUInt64LEBN(); + default: + return BN(first); + } +}; + +BufferReader.prototype.reverse = function() { + var buf = new Buffer(this.buf.length); + for (var i = 0; i < buf.length; i++) { + buf[i] = this.buf[this.buf.length - 1 - i]; + } + this.buf = buf; + return this; +}; + +BufferReader.prototype.readReverse = function(len) { + if (_.isUndefined(len)) { + len = this.buf.length; + } + var buf = this.buf.slice(this.pos, this.pos + len); + this.pos = this.pos + len; + return bufferUtil.reverse(buf); +}; + +module.exports = BufferReader; + +}).call(this,require("buffer").Buffer) +},{"../crypto/bn":5,"../util/buffer":48,"../util/preconditions":50,"buffer":69,"lodash":233}],14:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var bufferUtil = require('../util/buffer'); +var assert = require('assert'); + +var BufferWriter = function BufferWriter(obj) { + if (!(this instanceof BufferWriter)) + return new BufferWriter(obj); + if (obj) + this.set(obj); + else + this.bufs = []; +}; + +BufferWriter.prototype.set = function(obj) { + this.bufs = obj.bufs || this.bufs || []; + return this; +}; + +BufferWriter.prototype.toBuffer = function() { + return this.concat(); +}; + +BufferWriter.prototype.concat = function() { + return Buffer.concat(this.bufs); +}; + +BufferWriter.prototype.write = function(buf) { + assert(bufferUtil.isBuffer(buf)); + this.bufs.push(buf); + return this; +}; + +BufferWriter.prototype.writeReverse = function(buf) { + assert(bufferUtil.isBuffer(buf)); + this.bufs.push(bufferUtil.reverse(buf)); + return this; +}; + +BufferWriter.prototype.writeUInt8 = function(n) { + var buf = new Buffer(1); + buf.writeUInt8(n, 0); + this.write(buf); + return this; +}; + +BufferWriter.prototype.writeUInt16BE = function(n) { + var buf = new Buffer(2); + buf.writeUInt16BE(n, 0); + this.write(buf); + return this; +}; + +BufferWriter.prototype.writeUInt16LE = function(n) { + var buf = new Buffer(2); + buf.writeUInt16LE(n, 0); + this.write(buf); + return this; +}; + +BufferWriter.prototype.writeUInt32BE = function(n) { + var buf = new Buffer(4); + buf.writeUInt32BE(n, 0); + this.write(buf); + return this; +}; + +BufferWriter.prototype.writeInt32LE = function(n) { + var buf = new Buffer(4); + buf.writeInt32LE(n, 0); + this.write(buf); + return this; +}; + +BufferWriter.prototype.writeUInt32LE = function(n) { + var buf = new Buffer(4); + buf.writeUInt32LE(n, 0); + this.write(buf); + return this; +}; + +BufferWriter.prototype.writeUInt64BEBN = function(bn) { + var buf = bn.toBuffer({size: 8}); + this.write(buf); + return this; +}; + +BufferWriter.prototype.writeUInt64LEBN = function(bn) { + var buf = bn.toBuffer({size: 8}); + var reversebuf = new Buffer(Array.apply(new Array(), buf).reverse()); + this.write(reversebuf); + return this; +}; + +BufferWriter.prototype.writeVarintNum = function(n) { + var buf = BufferWriter.varintBufNum(n); + this.write(buf); + return this; +}; + +BufferWriter.prototype.writeVarintBN = function(bn) { + var buf = BufferWriter.varintBufBN(bn); + this.write(buf); + return this; +}; + +BufferWriter.varintBufNum = function(n) { + var buf = undefined; + if (n < 253) { + buf = new Buffer(1); + buf.writeUInt8(n, 0); + } else if (n < 0x10000) { + buf = new Buffer(1 + 2); + buf.writeUInt8(253, 0); + buf.writeUInt16LE(n, 1); + } else if (n < 0x100000000) { + buf = new Buffer(1 + 4); + buf.writeUInt8(254, 0); + buf.writeUInt32LE(n, 1); + } else { + buf = new Buffer(1 + 8); + buf.writeUInt8(255, 0); + buf.writeInt32LE(n & -1, 1); + buf.writeUInt32LE(Math.floor(n / 0x100000000), 5); + } + return buf; +}; + +BufferWriter.varintBufBN = function(bn) { + var buf = undefined; + var n = bn.toNumber(); + if (n < 253) { + buf = new Buffer(1); + buf.writeUInt8(n, 0); + } else if (n < 0x10000) { + buf = new Buffer(1 + 2); + buf.writeUInt8(253, 0); + buf.writeUInt16LE(n, 1); + } else if (n < 0x100000000) { + buf = new Buffer(1 + 4); + buf.writeUInt8(254, 0); + buf.writeUInt32LE(n, 1); + } else { + var bw = new BufferWriter(); + bw.writeUInt8(255); + bw.writeUInt64LEBN(bn); + var buf = bw.concat(); + } + return buf; +}; + +module.exports = BufferWriter; + +}).call(this,require("buffer").Buffer) +},{"../util/buffer":48,"assert":67,"buffer":69}],15:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var BufferWriter = require('./bufferwriter'); +var BufferReader = require('./bufferreader'); +var BN = require('../crypto/bn'); + +var Varint = function Varint(buf) { + if (!(this instanceof Varint)) + return new Varint(buf); + if (Buffer.isBuffer(buf)) { + this.buf = buf; + } else if (typeof buf === 'number') { + var num = buf; + this.fromNumber(num); + } else if (buf instanceof BN) { + var bn = buf; + this.fromBN(bn); + } else if (buf) { + var obj = buf; + this.set(obj); + } +}; + +Varint.prototype.set = function(obj) { + this.buf = obj.buf || this.buf; + return this; +}; + +Varint.prototype.fromString = function(str) { + this.set({ + buf: new Buffer(str, 'hex') + }); + return this; +}; + +Varint.prototype.toString = function() { + return this.buf.toString('hex'); +}; + +Varint.prototype.fromBuffer = function(buf) { + this.buf = buf; + return this; +}; + +Varint.prototype.fromBufferReader = function(br) { + this.buf = br.readVarintBuf(); + return this; +}; + +Varint.prototype.fromBN = function(bn) { + this.buf = BufferWriter().writeVarintBN(bn).concat(); + return this; +}; + +Varint.prototype.fromNumber = function(num) { + this.buf = BufferWriter().writeVarintNum(num).concat(); + return this; +}; + +Varint.prototype.toBuffer = function() { + return this.buf; +}; + +Varint.prototype.toBN = function() { + return BufferReader(this.buf).readVarintBN(); +}; + +Varint.prototype.toNumber = function() { + return BufferReader(this.buf).readVarintNum(); +}; + +module.exports = Varint; + +}).call(this,require("buffer").Buffer) +},{"../crypto/bn":5,"./bufferreader":13,"./bufferwriter":14,"buffer":69}],16:[function(require,module,exports){ +'use strict'; + +var inherits = require('inherits'); + +/* AUTOGENERATED FILE. DON'T EDIT, MODIFY "lib/errors/spec.js" INSTEAD */ + +var bitcore = {}; + +bitcore.Error = function() { + this.message = 'Internal error'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.prototype = Object.create(Error.prototype); +bitcore.Error.prototype.name = "bitcore.Error"; + +bitcore.Error.InvalidB58Char = function() { + this.message = 'Invalid Base58 character: ' + arguments[0] + ' in ' + arguments[1] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.InvalidB58Char.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.InvalidB58Char.prototype.name = "bitcore.Error.InvalidB58Char"; + +bitcore.Error.InvalidB58Checksum = function() { + this.message = 'Invalid Base58 checksum for ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.InvalidB58Checksum.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.InvalidB58Checksum.prototype.name = "bitcore.Error.InvalidB58Checksum"; + +bitcore.Error.InvalidNetwork = function() { + this.message = 'Invalid version for network: got ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.InvalidNetwork.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.InvalidNetwork.prototype.name = "bitcore.Error.InvalidNetwork"; + +bitcore.Error.InvalidState = function() { + this.message = 'Invalid state: ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.InvalidState.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.InvalidState.prototype.name = "bitcore.Error.InvalidState"; + +bitcore.Error.NotImplemented = function() { + this.message = 'Function ' + arguments[0] + ' was not implemented yet'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.NotImplemented.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.NotImplemented.prototype.name = "bitcore.Error.NotImplemented"; + +bitcore.Error.InvalidNetworkArgument = function() { + this.message = 'Invalid network: must be "livenet" or "testnet", got ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.InvalidNetworkArgument.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.InvalidNetworkArgument.prototype.name = "bitcore.Error.InvalidNetworkArgument"; + +bitcore.Error.InvalidArgument = function() { + this.message = 'Invalid Argument' + (arguments[0] ? ': ' + arguments[0] + '' : '') + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.InvalidArgument.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.InvalidArgument.prototype.name = "bitcore.Error.InvalidArgument"; + +bitcore.Error.AbstractMethodInvoked = function() { + this.message = 'Abstract Method Invokation: ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.AbstractMethodInvoked.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.AbstractMethodInvoked.prototype.name = "bitcore.Error.AbstractMethodInvoked"; + +bitcore.Error.InvalidArgumentType = function() { + this.message = 'Invalid Argument for ' + arguments[2] + ', expected ' + arguments[1] + ' but got '+ typeof arguments[0]; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.InvalidArgumentType.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.InvalidArgumentType.prototype.name = "bitcore.Error.InvalidArgumentType"; + +bitcore.Error.Script = function() { + this.message = 'Internal Error on Script ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.Script.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.Script.prototype.name = "bitcore.Error.Script"; + +bitcore.Error.Script.UnrecognizedAddress = function() { + this.message = 'Expected argument ' + arguments[0] + ' to be an address'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.Script.UnrecognizedAddress.prototype = Object.create(bitcore.Error.Script.prototype); +bitcore.Error.Script.UnrecognizedAddress.prototype.name = "bitcore.Error.Script.UnrecognizedAddress"; + +bitcore.Error.HDPrivateKey = function() { + this.message = 'Internal Error on HDPrivateKey ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPrivateKey.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.HDPrivateKey.prototype.name = "bitcore.Error.HDPrivateKey"; + +bitcore.Error.HDPrivateKey.InvalidDerivationArgument = function() { + this.message = 'Invalid derivation argument ' + arguments[0] + ', expected string, or number and boolean'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPrivateKey.InvalidDerivationArgument.prototype = Object.create(bitcore.Error.HDPrivateKey.prototype); +bitcore.Error.HDPrivateKey.InvalidDerivationArgument.prototype.name = "bitcore.Error.HDPrivateKey.InvalidDerivationArgument"; + +bitcore.Error.HDPrivateKey.InvalidEntropyArgument = function() { + this.message = 'Invalid entropy: must be an hexa string or binary buffer, got ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPrivateKey.InvalidEntropyArgument.prototype = Object.create(bitcore.Error.HDPrivateKey.prototype); +bitcore.Error.HDPrivateKey.InvalidEntropyArgument.prototype.name = "bitcore.Error.HDPrivateKey.InvalidEntropyArgument"; + +bitcore.Error.HDPrivateKey.InvalidEntropyArgument.TooMuchEntropy = function() { + this.message = 'Invalid entropy: more than 512 bits is non standard, got "' + arguments[0] + '"'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPrivateKey.InvalidEntropyArgument.TooMuchEntropy.prototype = Object.create(bitcore.Error.HDPrivateKey.InvalidEntropyArgument.prototype); +bitcore.Error.HDPrivateKey.InvalidEntropyArgument.TooMuchEntropy.prototype.name = "bitcore.Error.HDPrivateKey.InvalidEntropyArgument.TooMuchEntropy"; + +bitcore.Error.HDPrivateKey.InvalidEntropyArgument.NotEnoughEntropy = function() { + this.message = 'Invalid entropy: at least 128 bits needed, got "' + arguments[0] + '"'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPrivateKey.InvalidEntropyArgument.NotEnoughEntropy.prototype = Object.create(bitcore.Error.HDPrivateKey.InvalidEntropyArgument.prototype); +bitcore.Error.HDPrivateKey.InvalidEntropyArgument.NotEnoughEntropy.prototype.name = "bitcore.Error.HDPrivateKey.InvalidEntropyArgument.NotEnoughEntropy"; + +bitcore.Error.HDPrivateKey.InvalidLength = function() { + this.message = 'Invalid length for xprivkey string in ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPrivateKey.InvalidLength.prototype = Object.create(bitcore.Error.HDPrivateKey.prototype); +bitcore.Error.HDPrivateKey.InvalidLength.prototype.name = "bitcore.Error.HDPrivateKey.InvalidLength"; + +bitcore.Error.HDPrivateKey.InvalidPath = function() { + this.message = 'Invalid derivation path: ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPrivateKey.InvalidPath.prototype = Object.create(bitcore.Error.HDPrivateKey.prototype); +bitcore.Error.HDPrivateKey.InvalidPath.prototype.name = "bitcore.Error.HDPrivateKey.InvalidPath"; + +bitcore.Error.HDPrivateKey.UnrecognizedArgument = function() { + this.message = 'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "' + arguments[0] + '"'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPrivateKey.UnrecognizedArgument.prototype = Object.create(bitcore.Error.HDPrivateKey.prototype); +bitcore.Error.HDPrivateKey.UnrecognizedArgument.prototype.name = "bitcore.Error.HDPrivateKey.UnrecognizedArgument"; + +bitcore.Error.HDPublicKey = function() { + this.message = 'Internal Error on HDPublicKey ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPublicKey.prototype = Object.create(bitcore.Error.prototype); +bitcore.Error.HDPublicKey.prototype.name = "bitcore.Error.HDPublicKey"; + +bitcore.Error.HDPublicKey.ArgumentIsPrivateExtended = function() { + this.message = 'Argument is an extended private key: ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPublicKey.ArgumentIsPrivateExtended.prototype = Object.create(bitcore.Error.HDPublicKey.prototype); +bitcore.Error.HDPublicKey.ArgumentIsPrivateExtended.prototype.name = "bitcore.Error.HDPublicKey.ArgumentIsPrivateExtended"; + +bitcore.Error.HDPublicKey.InvalidDerivationArgument = function() { + this.message = 'Invalid derivation argument: got ' + arguments[0] + ''; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPublicKey.InvalidDerivationArgument.prototype = Object.create(bitcore.Error.HDPublicKey.prototype); +bitcore.Error.HDPublicKey.InvalidDerivationArgument.prototype.name = "bitcore.Error.HDPublicKey.InvalidDerivationArgument"; + +bitcore.Error.HDPublicKey.InvalidLength = function() { + this.message = 'Invalid length for xpubkey: got "' + arguments[0] + '"'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPublicKey.InvalidLength.prototype = Object.create(bitcore.Error.HDPublicKey.prototype); +bitcore.Error.HDPublicKey.InvalidLength.prototype.name = "bitcore.Error.HDPublicKey.InvalidLength"; + +bitcore.Error.HDPublicKey.InvalidPath = function() { + this.message = 'Invalid derivation path, it should look like: "m/1/100", got "' + arguments[0] + '"'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPublicKey.InvalidPath.prototype = Object.create(bitcore.Error.HDPublicKey.prototype); +bitcore.Error.HDPublicKey.InvalidPath.prototype.name = "bitcore.Error.HDPublicKey.InvalidPath"; + +bitcore.Error.HDPublicKey.MustSupplyArgument = function() { + this.message = 'Must supply an argument to create a HDPublicKey'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPublicKey.MustSupplyArgument.prototype = Object.create(bitcore.Error.HDPublicKey.prototype); +bitcore.Error.HDPublicKey.MustSupplyArgument.prototype.name = "bitcore.Error.HDPublicKey.MustSupplyArgument"; + +bitcore.Error.HDPublicKey.UnrecognizedArgument = function() { + this.message = 'Invalid argument for creation, must be string, json, buffer, or object'; + this.stack = this.message + '\n' + (new Error()).stack; +}; +bitcore.Error.HDPublicKey.UnrecognizedArgument.prototype = Object.create(bitcore.Error.HDPublicKey.prototype); +bitcore.Error.HDPublicKey.UnrecognizedArgument.prototype.name = "bitcore.Error.HDPublicKey.UnrecognizedArgument"; + +module.exports = bitcore.Error; + +},{"inherits":231}],17:[function(require,module,exports){ +'use strict'; + +module.exports = { + _cache: {}, + _count: 0, + _eraseIndex: 0, + _usedList: {}, + _usedIndex: {}, + _CACHE_SIZE: 5000, + + get: function(xkey, number, hardened) { + hardened = !!hardened; + var key = xkey + '/' + number + '/' + hardened; + if (this._cache[key]) { + this._cacheHit(key); + return this._cache[key]; + } + }, + set: function(xkey, number, hardened, derived) { + hardened = !!hardened; + var key = xkey + '/' + number + '/' + hardened; + this._cache[key] = derived; + this._cacheHit(key); + }, + _cacheHit: function(key) { + if (this._usedIndex[key]) { + delete this._usedList[this._usedIndex[key]]; + } + this._usedList[this._count] = key; + this._usedIndex[key] = this._count; + this._count++; + this._cacheRemove(); + }, + _cacheRemove: function() { + while (this._eraseIndex < this._count - this._CACHE_SIZE) { + if (this._usedList[this._eraseIndex]) { + var removeKey = this._usedList[this._eraseIndex]; + delete this._usedIndex[removeKey]; + delete this._cache[removeKey]; + } + delete this._usedList[this._eraseIndex]; + this._eraseIndex++; + } + } +}; + +},{}],18:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + + +var assert = require('assert'); +var buffer = require('buffer'); +var _ = require('lodash'); + +var BN = require('./crypto/bn'); +var Base58 = require('./encoding/base58'); +var Base58Check = require('./encoding/base58check'); +var Hash = require('./crypto/hash'); +var Network = require('./networks'); +var HDKeyCache = require('./hdkeycache'); +var Point = require('./crypto/point'); +var PrivateKey = require('./privatekey'); +var Random = require('./crypto/random'); + +var errors = require('./errors'); +var hdErrors = errors.HDPrivateKey; +var BufferUtil = require('./util/buffer'); +var JSUtil = require('./util/js'); + +var MINIMUM_ENTROPY_BITS = 128; +var BITS_TO_BYTES = 1/8; +var MAXIMUM_ENTROPY_BITS = 512; + + +/** + * Represents an instance of an hierarchically derived private key. + * + * More info on https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki + * + * @constructor + * @param {string|Buffer|Object} arg + */ +function HDPrivateKey(arg) { + /* jshint maxcomplexity: 10 */ + if (arg instanceof HDPrivateKey) { + return arg; + } + if (!(this instanceof HDPrivateKey)) { + return new HDPrivateKey(arg); + } + if (arg) { + if (_.isString(arg) || BufferUtil.isBuffer(arg)) { + if (HDPrivateKey.isValidSerialized(arg)) { + this._buildFromSerialized(arg); + } else if (JSUtil.isValidJSON(arg)) { + this._buildFromJSON(arg); + } else { + throw HDPrivateKey.getSerializedError(arg); + } + } else { + if (_.isObject(arg)) { + this._buildFromObject(arg); + } else { + throw new hdErrors.UnrecognizedArgument(arg); + } + } + } else { + return this._generateRandomly(); + } +} + +/** + * Get a derivated child based on a string or number. + * + * If the first argument is a string, it's parsed as the full path of + * derivation. Valid values for this argument include "m" (which returns the + * same private key), "m/0/1/40/2'/1000", where the ' quote means a hardened + * derivation. + * + * If the first argument is a number, the child with that index will be + * derived. If the second argument is truthy, the hardened version will be + * derived. See the example usage for clarification. + * + * @example + * var parent = new HDPrivateKey('xprv...'); + * var child_0_1_2h = parent.derive(0).derive(1).derive(2, true); + * var copy_of_child_0_1_2h = parent.derive("m/0/1/2'"); + * assert(child_0_1_2h.xprivkey === copy_of_child_0_1_2h); + * + * @param {string|number} arg + * @param {boolean?} hardened + */ +HDPrivateKey.prototype.derive = function(arg, hardened) { + if (_.isNumber(arg)) { + return this._deriveWithNumber(arg, hardened); + } else if (_.isString(arg)) { + return this._deriveFromString(arg); + } else { + throw new hdErrors.InvalidDerivationArgument(arg); + } +}; + +HDPrivateKey.prototype._deriveWithNumber = function(index, hardened) { + /* jshint maxstatements: 20 */ + /* jshint maxcomplexity: 10 */ + if (index >= HDPrivateKey.Hardened) { + hardened = true; + } + if (index < HDPrivateKey.Hardened && hardened) { + index += HDPrivateKey.Hardened; + } + var cached = HDKeyCache.get(this.xprivkey, index, hardened); + if (cached) { + return cached; + } + + var indexBuffer = BufferUtil.integerAsBuffer(index); + var data; + if (hardened) { + data = BufferUtil.concat([new buffer.Buffer([0]), this.privateKey.toBuffer(), indexBuffer]); + } else { + data = BufferUtil.concat([this.publicKey.toBuffer(), indexBuffer]); + } + var hash = Hash.sha512hmac(data, this._buffers.chainCode); + var leftPart = BN().fromBuffer(hash.slice(0, 32), {size: 32}); + var chainCode = hash.slice(32, 64); + + var privateKey = leftPart.add(this.privateKey.toBigNumber()).mod(Point.getN()).toBuffer({size: 32}); + + var derived = new HDPrivateKey({ + network: this.network, + depth: this.depth + 1, + parentFingerPrint: this.fingerPrint, + childIndex: index, + chainCode: chainCode, + privateKey: privateKey + }); + HDKeyCache.set(this.xprivkey, index, hardened, derived); + return derived; +}; + +HDPrivateKey.prototype._deriveFromString = function(path) { + var steps = path.split('/'); + + // Special cases: + if (_.contains(HDPrivateKey.RootElementAlias, path)) { + return this; + } + if (!_.contains(HDPrivateKey.RootElementAlias, steps[0])) { + throw new hdErrors.InvalidPath(path); + } + steps = steps.slice(1); + + var result = this; + for (var step in steps) { + var index = parseInt(steps[step]); + var hardened = steps[step] !== index.toString(); + result = result._deriveWithNumber(index, hardened); + } + return result; +}; + +/** + * Verifies that a given serialized private key in base58 with checksum format + * is valid. + * + * @param {string|Buffer} data - the serialized private key + * @param {string|Network=} network - optional, if present, checks that the + * network provided matches the network serialized. + * @return {boolean} + */ +HDPrivateKey.isValidSerialized = function(data, network) { + return !HDPrivateKey.getSerializedError(data, network); +}; + +/** + * Checks what's the error that causes the validation of a serialized private key + * in base58 with checksum to fail. + * + * @param {string|Buffer} data - the serialized private key + * @param {string|Network=} network - optional, if present, checks that the + * network provided matches the network serialized. + * @return {errors.InvalidArgument|null} + */ +HDPrivateKey.getSerializedError = function(data, network) { + /* jshint maxcomplexity: 10 */ + if (!(_.isString(data) || BufferUtil.isBuffer(data))) { + return new hdErrors.UnrecognizedArgument('Expected string or buffer'); + } + if (!Base58.validCharacters(data)) { + return new errors.InvalidB58Char('(unknown)', data); + } + try { + data = Base58Check.decode(data); + } catch (e) { + return new errors.InvalidB58Checksum(data); + } + if (data.length !== HDPrivateKey.DataLength) { + return new hdErrors.InvalidLength(data); + } + if (!_.isUndefined(network)) { + var error = HDPrivateKey._validateNetwork(data, network); + if (error) { + return error; + } + } + return null; +}; + +HDPrivateKey._validateNetwork = function(data, networkArg) { + var network = Network.get(networkArg); + if (!network) { + return new errors.InvalidNetworkArgument(networkArg); + } + var version = data.slice(0, 4); + if (BufferUtil.integerFromBuffer(version) !== network.xprivkey) { + return new errors.InvalidNetwork(version); + } + return null; +}; + +HDPrivateKey.prototype._buildFromJSON = function(arg) { + return this._buildFromObject(JSON.parse(arg)); +}; + +HDPrivateKey.prototype._buildFromObject = function(arg) { + /* jshint maxcomplexity: 12 */ + // TODO: Type validation + var buffers = { + version: arg.network ? BufferUtil.integerAsBuffer(Network.get(arg.network).xprivkey) : arg.version, + depth: _.isNumber(arg.depth) ? BufferUtil.integerAsSingleByteBuffer(arg.depth) : arg.depth, + parentFingerPrint: _.isNumber(arg.parentFingerPrint) ? BufferUtil.integerAsBuffer(arg.parentFingerPrint) : arg.parentFingerPrint, + childIndex: _.isNumber(arg.childIndex) ? BufferUtil.integerAsBuffer(arg.childIndex) : arg.childIndex, + chainCode: _.isString(arg.chainCode) ? BufferUtil.hexToBuffer(arg.chainCode) : arg.chainCode, + privateKey: (_.isString(arg.privateKey) && JSUtil.isHexa(arg.privateKey)) ? BufferUtil.hexToBuffer(arg.privateKey) : arg.privateKey, + checksum: arg.checksum ? (arg.checksum.length ? arg.checksum : BufferUtil.integerAsBuffer(arg.checksum)) : undefined + }; + return this._buildFromBuffers(buffers); +}; + +HDPrivateKey.prototype._buildFromSerialized = function(arg) { + var decoded = Base58Check.decode(arg); + var buffers = { + version: decoded.slice(HDPrivateKey.VersionStart, HDPrivateKey.VersionEnd), + depth: decoded.slice(HDPrivateKey.DepthStart, HDPrivateKey.DepthEnd), + parentFingerPrint: decoded.slice(HDPrivateKey.ParentFingerPrintStart, + HDPrivateKey.ParentFingerPrintEnd), + childIndex: decoded.slice(HDPrivateKey.ChildIndexStart, HDPrivateKey.ChildIndexEnd), + chainCode: decoded.slice(HDPrivateKey.ChainCodeStart, HDPrivateKey.ChainCodeEnd), + privateKey: decoded.slice(HDPrivateKey.PrivateKeyStart, HDPrivateKey.PrivateKeyEnd), + checksum: decoded.slice(HDPrivateKey.ChecksumStart, HDPrivateKey.ChecksumEnd), + xprivkey: arg + }; + return this._buildFromBuffers(buffers); +}; + +HDPrivateKey.prototype._generateRandomly = function(network) { + return HDPrivateKey.fromSeed(Random.getRandomBuffer(64), network); +}; + +/** + * Generate a private key from a seed, as described in BIP32 + * + * @param {string|Buffer} hexa + * @param {*} network + * @return HDPrivateKey + */ +HDPrivateKey.fromSeed = function(hexa, network) { + /* jshint maxcomplexity: 8 */ + + if (JSUtil.isHexaString(hexa)) { + hexa = BufferUtil.hexToBuffer(hexa); + } + if (!Buffer.isBuffer(hexa)) { + throw new hdErrors.InvalidEntropyArgument(hexa); + } + if (hexa.length < MINIMUM_ENTROPY_BITS * BITS_TO_BYTES) { + throw new hdErrors.InvalidEntropyArgument.NotEnoughEntropy(hexa); + } + if (hexa.length > MAXIMUM_ENTROPY_BITS * BITS_TO_BYTES) { + throw new hdErrors.InvalidEntropyArgument.TooMuchEntropy(hexa); + } + var hash = Hash.sha512hmac(hexa, new buffer.Buffer('Bitcoin seed')); + + return new HDPrivateKey({ + network: Network.get(network) || Network.livenet, + depth: 0, + parentFingerPrint: 0, + childIndex: 0, + privateKey: hash.slice(0, 32), + chainCode: hash.slice(32, 64) + }); +}; + +/** + * Receives a object with buffers in all the properties and populates the + * internal structure + * + * @param {Object} arg + * @param {buffer.Buffer} arg.version + * @param {buffer.Buffer} arg.depth + * @param {buffer.Buffer} arg.parentFingerPrint + * @param {buffer.Buffer} arg.childIndex + * @param {buffer.Buffer} arg.chainCode + * @param {buffer.Buffer} arg.privateKey + * @param {buffer.Buffer} arg.checksum + * @param {string=} arg.xprivkey - if set, don't recalculate the base58 + * representation + * @return {HDPrivateKey} this + */ +HDPrivateKey.prototype._buildFromBuffers = function(arg) { + /* jshint maxcomplexity: 8 */ + /* jshint maxstatements: 20 */ + + HDPrivateKey._validateBufferArguments(arg); + Object.defineProperty(this, '_buffers', { + configurable: false, + value: arg + }); + + var sequence = [ + arg.version, arg.depth, arg.parentFingerPrint, arg.childIndex, arg.chainCode, + BufferUtil.emptyBuffer(1), arg.privateKey + ]; + var concat = buffer.Buffer.concat(sequence); + if (!arg.checksum || !arg.checksum.length) { + arg.checksum = Base58Check.checksum(concat); + } else { + if (arg.checksum.toString() !== Base58Check.checksum(concat).toString()) { + throw new errors.InvalidB58Checksum(concat); + } + } + + var xprivkey; + + if (!arg.xprivkey) { + xprivkey = Base58Check.encode(buffer.Buffer.concat(sequence)); + } else { + xprivkey = arg.xprivkey; + } + + var privateKey = new PrivateKey(BN().fromBuffer(arg.privateKey)); + var publicKey = privateKey.toPublicKey(); + var size = HDPrivateKey.ParentFingerPrintSize; + var fingerPrint = Hash.sha256ripemd160(publicKey.toBuffer()).slice(0, size); + + JSUtil.defineImmutable(this, { + xprivkey: xprivkey, + network: Network.get(BufferUtil.integerFromBuffer(arg.version)), + depth: BufferUtil.integerFromSingleByteBuffer(arg.depth), + privateKey: privateKey, + publicKey: publicKey, + fingerPrint: fingerPrint + }); + + var HDPublicKey = require('./hdpublickey'); + var hdPublicKey = new HDPublicKey(this); + + JSUtil.defineImmutable(this, { + hdPublicKey: hdPublicKey, + xpubkey: hdPublicKey.xpubkey + }); + + return this; +}; + +HDPrivateKey._validateBufferArguments = function(arg) { + var checkBuffer = function(name, size) { + var buff = arg[name]; + assert(BufferUtil.isBuffer(buff), name + ' argument is not a buffer'); + assert( + buff.length === size, + name + ' has not the expected size: found ' + buff.length + ', expected ' + size + ); + }; + checkBuffer('version', HDPrivateKey.VersionSize); + checkBuffer('depth', HDPrivateKey.DepthSize); + checkBuffer('parentFingerPrint', HDPrivateKey.ParentFingerPrintSize); + checkBuffer('childIndex', HDPrivateKey.ChildIndexSize); + checkBuffer('chainCode', HDPrivateKey.ChainCodeSize); + checkBuffer('privateKey', HDPrivateKey.PrivateKeySize); + if (arg.checksum && arg.checksum.length) { + checkBuffer('checksum', HDPrivateKey.CheckSumSize); + } +}; + +/** + * Returns the string representation of this private key (a string starting + * with "xprv..." + * + * @return string + */ +HDPrivateKey.prototype.toString = function() { + return this.xprivkey; +}; + +/** + * Returns the console representation of this extended private key. + * @return string + */ +HDPrivateKey.prototype.inspect = function() { + return ''; +}; + +/** + * Returns a plain object with a representation of this private key. + * + * Fields include:
    + *
  • network: either 'livenet' or 'testnet' + *
  • depth: a number ranging from 0 to 255 + *
  • fingerPrint: a number ranging from 0 to 2^32-1, taken from the hash of the + *
  • associated public key + *
  • parentFingerPrint: a number ranging from 0 to 2^32-1, taken from the hash + *
  • of this parent's associated public key or zero. + *
  • childIndex: the index from which this child was derived (or zero) + *
  • chainCode: an hexa string representing a number used in the derivation + *
  • privateKey: the private key associated, in hexa representation + *
  • xprivkey: the representation of this extended private key in checksum + *
  • base58 format + *
  • checksum: the base58 checksum of xprivkey + *
+ * @return {Object} + */ +HDPrivateKey.prototype.toObject = function toObject() { + return { + network: Network.get(BufferUtil.integerFromBuffer(this._buffers.version)).name, + depth: BufferUtil.integerFromSingleByteBuffer(this._buffers.depth), + fingerPrint: BufferUtil.integerFromBuffer(this.fingerPrint), + parentFingerPrint: BufferUtil.integerFromBuffer(this._buffers.parentFingerPrint), + childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex), + chainCode: BufferUtil.bufferToHex(this._buffers.chainCode), + privateKey: this.privateKey.toBuffer().toString('hex'), + checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), + xprivkey: this.xprivkey + }; +}; + +HDPrivateKey.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +HDPrivateKey.DefaultDepth = 0; +HDPrivateKey.DefaultFingerprint = 0; +HDPrivateKey.DefaultChildIndex = 0; +HDPrivateKey.DefaultNetwork = Network.livenet; +HDPrivateKey.Hardened = 0x80000000; +HDPrivateKey.RootElementAlias = ['m', 'M', 'm\'', 'M\'']; + +HDPrivateKey.VersionSize = 4; +HDPrivateKey.DepthSize = 1; +HDPrivateKey.ParentFingerPrintSize = 4; +HDPrivateKey.ChildIndexSize = 4; +HDPrivateKey.ChainCodeSize = 32; +HDPrivateKey.PrivateKeySize = 32; +HDPrivateKey.CheckSumSize = 4; + +HDPrivateKey.DataLength = 78; +HDPrivateKey.SerializedByteSize = 82; + +HDPrivateKey.VersionStart = 0; +HDPrivateKey.VersionEnd = HDPrivateKey.VersionStart + HDPrivateKey.VersionSize; +HDPrivateKey.DepthStart = HDPrivateKey.VersionEnd; +HDPrivateKey.DepthEnd = HDPrivateKey.DepthStart + HDPrivateKey.DepthSize; +HDPrivateKey.ParentFingerPrintStart = HDPrivateKey.DepthEnd; +HDPrivateKey.ParentFingerPrintEnd = HDPrivateKey.ParentFingerPrintStart + HDPrivateKey.ParentFingerPrintSize; +HDPrivateKey.ChildIndexStart = HDPrivateKey.ParentFingerPrintEnd; +HDPrivateKey.ChildIndexEnd = HDPrivateKey.ChildIndexStart + HDPrivateKey.ChildIndexSize; +HDPrivateKey.ChainCodeStart = HDPrivateKey.ChildIndexEnd; +HDPrivateKey.ChainCodeEnd = HDPrivateKey.ChainCodeStart + HDPrivateKey.ChainCodeSize; +HDPrivateKey.PrivateKeyStart = HDPrivateKey.ChainCodeEnd + 1; +HDPrivateKey.PrivateKeyEnd = HDPrivateKey.PrivateKeyStart + HDPrivateKey.PrivateKeySize; +HDPrivateKey.ChecksumStart = HDPrivateKey.PrivateKeyEnd; +HDPrivateKey.ChecksumEnd = HDPrivateKey.ChecksumStart + HDPrivateKey.CheckSumSize; + +assert(HDPrivateKey.ChecksumEnd === HDPrivateKey.SerializedByteSize); + +module.exports = HDPrivateKey; + +}).call(this,require("buffer").Buffer) +},{"./crypto/bn":5,"./crypto/hash":7,"./crypto/point":8,"./crypto/random":9,"./encoding/base58":11,"./encoding/base58check":12,"./errors":16,"./hdkeycache":17,"./hdpublickey":19,"./networks":20,"./privatekey":28,"./util/buffer":48,"./util/js":49,"assert":67,"buffer":69,"lodash":233}],19:[function(require,module,exports){ +'use strict'; + +var _ = require('lodash'); +var BN = require('./crypto/bn'); +var Base58 = require('./encoding/base58'); +var Base58Check = require('./encoding/base58check'); +var Hash = require('./crypto/hash'); +var HDPrivateKey = require('./hdprivatekey'); +var HDKeyCache = require('./hdkeycache'); +var Network = require('./networks'); +var Point = require('./crypto/point'); +var PublicKey = require('./publickey'); + +var bitcoreErrors = require('./errors'); +var errors = bitcoreErrors; +var hdErrors = bitcoreErrors.HDPublicKey; +var assert = require('assert'); + +var JSUtil = require('./util/js'); +var BufferUtil = require('./util/buffer'); + +/** + * The representation of an hierarchically derived public key. + * + * See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki + * + * @constructor + * @param {Object|string|Buffer} arg + */ +function HDPublicKey(arg) { + /* jshint maxcomplexity: 12 */ + /* jshint maxstatements: 20 */ + if (arg instanceof HDPublicKey) { + return arg; + } + if (!(this instanceof HDPublicKey)) { + return new HDPublicKey(arg); + } + if (arg) { + if (_.isString(arg) || BufferUtil.isBuffer(arg)) { + var error = HDPublicKey.getSerializedError(arg); + if (!error) { + return this._buildFromSerialized(arg); + } else if (JSUtil.isValidJSON(arg)) { + return this._buildFromJSON(arg); + } else { + if (error instanceof hdErrors.ArgumentIsPrivateExtended) { + return new HDPrivateKey(arg).hdPublicKey; + } + throw error; + } + } else { + if (_.isObject(arg)) { + if (arg instanceof HDPrivateKey) { + return this._buildFromPrivate(arg); + } else { + return this._buildFromObject(arg); + } + } else { + throw new hdErrors.UnrecognizedArgument(arg); + } + } + } else { + throw new hdErrors.MustSupplyArgument(); + } +} + +/** + * Get a derivated child based on a string or number. + * + * If the first argument is a string, it's parsed as the full path of + * derivation. Valid values for this argument include "m" (which returns the + * same private key), "m/0/1/40/2/1000". + * + * Note that hardened keys can't be derived from a public extended key. + * + * If the first argument is a number, the child with that index will be + * derived. See the example usage for clarification. + * + * @example + * var parent = new HDPublicKey('xpub...'); + * var child_0_1_2 = parent.derive(0).derive(1).derive(2); + * var copy_of_child_0_1_2 = parent.derive("m/0/1/2"); + * assert(child_0_1_2.xprivkey === copy_of_child_0_1_2); + * + * @param {string|number} arg + * @param {boolean?} hardened + */ +HDPublicKey.prototype.derive = function (arg, hardened) { + if (_.isNumber(arg)) { + return this._deriveWithNumber(arg, hardened); + } else if (_.isString(arg)) { + return this._deriveFromString(arg); + } else { + throw new hdErrors.InvalidDerivationArgument(arg); + } +}; + +HDPublicKey.prototype._deriveWithNumber = function (index, hardened) { + if (hardened || index >= HDPublicKey.Hardened) { + throw new hdErrors.InvalidIndexCantDeriveHardened(); + } + var cached = HDKeyCache.get(this.xpubkey, index, hardened); + if (cached) { + return cached; + } + + var indexBuffer = BufferUtil.integerAsBuffer(index); + var data = BufferUtil.concat([this.publicKey.toBuffer(), indexBuffer]); + var hash = Hash.sha512hmac(data, this._buffers.chainCode); + var leftPart = BN().fromBuffer(hash.slice(0, 32), {size: 32}); + var chainCode = hash.slice(32, 64); + + var publicKey = PublicKey.fromPoint(Point.getG().mul(leftPart).add(this.publicKey.point)); + + var derived = new HDPublicKey({ + network: this.network, + depth: this.depth + 1, + parentFingerPrint: this.fingerPrint, + childIndex: index, + chainCode: chainCode, + publicKey: publicKey + }); + HDKeyCache.set(this.xpubkey, index, hardened, derived); + return derived; +}; + +HDPublicKey.prototype._deriveFromString = function (path) { + /* jshint maxcomplexity: 8 */ + var steps = path.split('/'); + + // Special cases: + if (_.contains(HDPublicKey.RootElementAlias, path)) { + return this; + } + if (!_.contains(HDPublicKey.RootElementAlias, steps[0])) { + throw new hdErrors.InvalidPath(path); + } + steps = steps.slice(1); + + var result = this; + for (var step in steps) { + var index = parseInt(steps[step]); + var hardened = steps[step] !== index.toString(); + result = result._deriveWithNumber(index, hardened); + } + return result; +}; + +/** + * Verifies that a given serialized private key in base58 with checksum format + * is valid. + * + * @param {string|Buffer} data - the serialized private key + * @param {string|Network=} network - optional, if present, checks that the + * network provided matches the network serialized. + * @return {boolean} + */ +HDPublicKey.isValidSerialized = function (data, network) { + return _.isNull(HDPublicKey.getSerializedError(data, network)); +}; + +/** + * Checks what's the error that causes the validation of a serialized private key + * in base58 with checksum to fail. + * + * @param {string|Buffer} data - the serialized private key + * @param {string|Network=} network - optional, if present, checks that the + * network provided matches the network serialized. + * @return {errors|null} + */ +HDPublicKey.getSerializedError = function (data, network) { + /* jshint maxcomplexity: 10 */ + /* jshint maxstatements: 20 */ + if (!(_.isString(data) || BufferUtil.isBuffer(data))) { + return new hdErrors.UnrecognizedArgument('expected buffer or string'); + } + if (!Base58.validCharacters(data)) { + return new errors.InvalidB58Char('(unknown)', data); + } + try { + data = Base58Check.decode(data); + } catch (e) { + return new errors.InvalidB58Checksum(data); + } + if (data.length !== HDPublicKey.DataSize) { + return new errors.InvalidLength(data); + } + if (!_.isUndefined(network)) { + var error = HDPublicKey._validateNetwork(data, network); + if (error) { + return error; + } + } + network = Network.get(network) || Network.defaultNetwork; + if (BufferUtil.integerFromBuffer(data.slice(0, 4)) === network.xprivkey) { + return new hdErrors.ArgumentIsPrivateExtended(); + } + return null; +}; + +HDPublicKey._validateNetwork = function (data, networkArg) { + var network = Network.get(networkArg); + if (!network) { + return new errors.InvalidNetworkArgument(networkArg); + } + var version = data.slice(HDPublicKey.VersionStart, HDPublicKey.VersionEnd); + if (BufferUtil.integerFromBuffer(version) !== network.xpubkey) { + return new errors.InvalidNetwork(version); + } + return null; +}; + +HDPublicKey.prototype._buildFromJSON = function (arg) { + return this._buildFromObject(JSON.parse(arg)); +}; + +HDPublicKey.prototype._buildFromPrivate = function (arg) { + var args = _.clone(arg._buffers); + var point = Point.getG().mul(BN().fromBuffer(args.privateKey)); + args.publicKey = Point.pointToCompressed(point); + args.version = BufferUtil.integerAsBuffer(Network.get(BufferUtil.integerFromBuffer(args.version)).xpubkey); + args.privateKey = undefined; + args.checksum = undefined; + args.xprivkey = undefined; + return this._buildFromBuffers(args); +}; + +HDPublicKey.prototype._buildFromObject = function (arg) { + /* jshint maxcomplexity: 10 */ + // TODO: Type validation + var buffers = { + version: arg.network ? BufferUtil.integerAsBuffer(Network.get(arg.network).xpubkey) : arg.version, + depth: _.isNumber(arg.depth) ? BufferUtil.integerAsSingleByteBuffer(arg.depth) : arg.depth, + parentFingerPrint: _.isNumber(arg.parentFingerPrint) ? BufferUtil.integerAsBuffer(arg.parentFingerPrint) : arg.parentFingerPrint, + childIndex: _.isNumber(arg.childIndex) ? BufferUtil.integerAsBuffer(arg.childIndex) : arg.childIndex, + chainCode: _.isString(arg.chainCode) ? BufferUtil.hexToBuffer(arg.chainCode) : arg.chainCode, + publicKey: _.isString(arg.publicKey) ? BufferUtil.hexToBuffer(arg.publicKey) : + BufferUtil.isBuffer(arg.publicKey) ? arg.publicKey : arg.publicKey.toBuffer(), + checksum: _.isNumber(arg.checksum) ? BufferUtil.integerAsBuffer(arg.checksum) : arg.checksum + }; + return this._buildFromBuffers(buffers); +}; + +HDPublicKey.prototype._buildFromSerialized = function (arg) { + var decoded = Base58Check.decode(arg); + var buffers = { + version: decoded.slice(HDPublicKey.VersionStart, HDPublicKey.VersionEnd), + depth: decoded.slice(HDPublicKey.DepthStart, HDPublicKey.DepthEnd), + parentFingerPrint: decoded.slice(HDPublicKey.ParentFingerPrintStart, + HDPublicKey.ParentFingerPrintEnd), + childIndex: decoded.slice(HDPublicKey.ChildIndexStart, HDPublicKey.ChildIndexEnd), + chainCode: decoded.slice(HDPublicKey.ChainCodeStart, HDPublicKey.ChainCodeEnd), + publicKey: decoded.slice(HDPublicKey.PublicKeyStart, HDPublicKey.PublicKeyEnd), + checksum: decoded.slice(HDPublicKey.ChecksumStart, HDPublicKey.ChecksumEnd), + xpubkey: arg + }; + return this._buildFromBuffers(buffers); +}; + +/** + * Receives a object with buffers in all the properties and populates the + * internal structure + * + * @param {Object} arg + * @param {buffer.Buffer} arg.version + * @param {buffer.Buffer} arg.depth + * @param {buffer.Buffer} arg.parentFingerPrint + * @param {buffer.Buffer} arg.childIndex + * @param {buffer.Buffer} arg.chainCode + * @param {buffer.Buffer} arg.publicKey + * @param {buffer.Buffer} arg.checksum + * @param {string=} arg.xpubkey - if set, don't recalculate the base58 + * representation + * @return {HDPublicKey} this + */ +HDPublicKey.prototype._buildFromBuffers = function (arg) { + /* jshint maxcomplexity: 8 */ + /* jshint maxstatements: 20 */ + + HDPublicKey._validateBufferArguments(arg); + + Object.defineProperty(this, '_buffers', { + configurable: false, + value: arg + }); + + var sequence = [ + arg.version, arg.depth, arg.parentFingerPrint, arg.childIndex, arg.chainCode, + arg.publicKey + ]; + var concat = BufferUtil.concat(sequence); + var checksum = Base58Check.checksum(concat); + if (!arg.checksum || !arg.checksum.length) { + arg.checksum = checksum; + } else { + if (arg.checksum.toString('hex') !== checksum.toString('hex')) { + throw new errors.InvalidB58Checksum(concat, checksum); + } + } + + var xpubkey; + + if (!arg.xpubkey) { + xpubkey = Base58Check.encode(BufferUtil.concat(sequence)); + } else { + xpubkey = arg.xpubkey; + } + + var publicKey = PublicKey.fromString(arg.publicKey); + var size = HDPublicKey.ParentFingerPrintSize; + var fingerPrint = Hash.sha256ripemd160(publicKey.toBuffer()).slice(0, size); + + JSUtil.defineImmutable(this, { + xpubkey: xpubkey, + network: Network.get(BufferUtil.integerFromBuffer(arg.version)), + depth: BufferUtil.integerFromSingleByteBuffer(arg.depth), + publicKey: publicKey, + fingerPrint: fingerPrint + }); + + return this; +}; + +HDPublicKey._validateBufferArguments = function (arg) { + var checkBuffer = function(name, size) { + var buff = arg[name]; + assert(BufferUtil.isBuffer(buff), name + ' argument is not a buffer, it\'s ' + typeof buff); + assert( + buff.length === size, + name + ' has not the expected size: found ' + buff.length + ', expected ' + size + ); + }; + checkBuffer('version', HDPublicKey.VersionSize); + checkBuffer('depth', HDPublicKey.DepthSize); + checkBuffer('parentFingerPrint', HDPublicKey.ParentFingerPrintSize); + checkBuffer('childIndex', HDPublicKey.ChildIndexSize); + checkBuffer('chainCode', HDPublicKey.ChainCodeSize); + checkBuffer('publicKey', HDPublicKey.PublicKeySize); + if (arg.checksum && arg.checksum.length) { + checkBuffer('checksum', HDPublicKey.CheckSumSize); + } +}; + +/** + * Returns the base58 checked representation of the public key + * @return {string} a string starting with "xpub..." in livenet + */ +HDPublicKey.prototype.toString = function () { + return this.xpubkey; +}; + +/** + * Returns the console representation of this extended public key. + * @return string + */ +HDPublicKey.prototype.inspect = function() { + return ''; +}; + +/** + * Returns a plain javascript object with information to reconstruct a key. + * + * Fields are:
    + *
  • network: 'livenet' or 'testnet' + *
  • depth: a number from 0 to 255, the depth to the master extended key + *
  • fingerPrint: a number of 32 bits taken from the hash of the public key + *
  • fingerPrint: a number of 32 bits taken from the hash of this key's + *
  • parent's public key + *
  • childIndex: index with which this key was derived + *
  • chainCode: string in hexa encoding used for derivation + *
  • publicKey: string, hexa encoded, in compressed key format + *
  • checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), + *
  • xpubkey: the string with the base58 representation of this extended key + *
  • checksum: the base58 checksum of xpubkey + *
+ */ +HDPublicKey.prototype.toObject = function toObject() { + return { + network: Network.get(BufferUtil.integerFromBuffer(this._buffers.version)).name, + depth: BufferUtil.integerFromSingleByteBuffer(this._buffers.depth), + fingerPrint: BufferUtil.integerFromBuffer(this.fingerPrint), + parentFingerPrint: BufferUtil.integerFromBuffer(this._buffers.parentFingerPrint), + childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex), + chainCode: BufferUtil.bufferToHex(this._buffers.chainCode), + publicKey: this.publicKey.toString(), + checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), + xpubkey: this.xpubkey + }; +}; + +/** + * Serializes this object into a JSON string + * @return {string} + */ +HDPublicKey.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +HDPublicKey.Hardened = 0x80000000; +HDPublicKey.RootElementAlias = ['m', 'M']; + +HDPublicKey.VersionSize = 4; +HDPublicKey.DepthSize = 1; +HDPublicKey.ParentFingerPrintSize = 4; +HDPublicKey.ChildIndexSize = 4; +HDPublicKey.ChainCodeSize = 32; +HDPublicKey.PublicKeySize = 33; +HDPublicKey.CheckSumSize = 4; + +HDPublicKey.DataSize = 78; +HDPublicKey.SerializedByteSize = 82; + +HDPublicKey.VersionStart = 0; +HDPublicKey.VersionEnd = HDPublicKey.VersionStart + HDPublicKey.VersionSize; +HDPublicKey.DepthStart = HDPublicKey.VersionEnd; +HDPublicKey.DepthEnd = HDPublicKey.DepthStart + HDPublicKey.DepthSize; +HDPublicKey.ParentFingerPrintStart = HDPublicKey.DepthEnd; +HDPublicKey.ParentFingerPrintEnd = HDPublicKey.ParentFingerPrintStart + HDPublicKey.ParentFingerPrintSize; +HDPublicKey.ChildIndexStart = HDPublicKey.ParentFingerPrintEnd; +HDPublicKey.ChildIndexEnd = HDPublicKey.ChildIndexStart + HDPublicKey.ChildIndexSize; +HDPublicKey.ChainCodeStart = HDPublicKey.ChildIndexEnd; +HDPublicKey.ChainCodeEnd = HDPublicKey.ChainCodeStart + HDPublicKey.ChainCodeSize; +HDPublicKey.PublicKeyStart = HDPublicKey.ChainCodeEnd; +HDPublicKey.PublicKeyEnd = HDPublicKey.PublicKeyStart + HDPublicKey.PublicKeySize; +HDPublicKey.ChecksumStart = HDPublicKey.PublicKeyEnd; +HDPublicKey.ChecksumEnd = HDPublicKey.ChecksumStart + HDPublicKey.CheckSumSize; + +assert(HDPublicKey.PublicKeyEnd === HDPublicKey.DataSize); +assert(HDPublicKey.ChecksumEnd === HDPublicKey.SerializedByteSize); + +module.exports = HDPublicKey; + +},{"./crypto/bn":5,"./crypto/hash":7,"./crypto/point":8,"./encoding/base58":11,"./encoding/base58check":12,"./errors":16,"./hdkeycache":17,"./hdprivatekey":18,"./networks":20,"./publickey":29,"./util/buffer":48,"./util/js":49,"assert":67,"lodash":233}],20:[function(require,module,exports){ +'use strict'; +var _ = require('lodash'); + +var BufferUtil = require('./util/buffer'); + +/** + * A network is merely a map containing values that correspond to version + * numbers for each bitcoin network. Currently only supporting "livenet" + * (a.k.a. "mainnet") and "testnet". + * @constructor + */ +function Network() {} + +Network.prototype.toString = function toString() { + return this.name; +}; + +/** + * @instance + * @member Network#livenet + */ +var livenet = new Network(); +_.extend(livenet, { + name: 'livenet', + alias: 'mainnet', + pubkeyhash: 0x00, + privatekey: 0x80, + scripthash: 0x05, + xpubkey: 0x0488b21e, + xprivkey: 0x0488ade4, + networkMagic: BufferUtil.integerAsBuffer(0xf9beb4d9), + port: 8333, + dnsSeeds: [ + 'seed.bitcoin.sipa.be', + 'dnsseed.bluematt.me', + 'dnsseed.bitcoin.dashjr.org', + 'seed.bitcoinstats.com', + 'seed.bitnodes.io', + 'bitseed.xf2.org' + ] +}); + +/** + * @instance + * @member Network#testnet + */ +var testnet = new Network(); +_.extend(testnet, { + name: 'testnet', + alias: 'testnet', + pubkeyhash: 0x6f, + privatekey: 0xef, + scripthash: 0xc4, + xpubkey: 0x043587cf, + xprivkey: 0x04358394, + networkMagic: BufferUtil.integerAsBuffer(0x0b110907), + port: 18333, + dnsSeeds: [ + 'testnet-seed.bitcoin.petertodd.org', + 'testnet-seed.bluematt.me' + ], +}); + +var networkMaps = {}; + +_.each(_.values(livenet), function(value) { + if (!_.isObject(value)) { + networkMaps[value] = livenet; + } +}); +_.each(_.values(testnet), function(value) { + if (!_.isObject(value)) { + networkMaps[value] = testnet; + } +}); + +/** + * @function + * @member Network#getNetwork + * Retrieves the network associated with a magic number or string. + * @param {string|number|Network} arg + * @return Network + */ +function getNetwork(arg) { + if (arg === livenet || arg === testnet) { + return arg; + } + return networkMaps[arg]; +} + +/** + * @namespace Network + */ +module.exports = { + defaultNetwork: livenet, + livenet: livenet, + mainnet: livenet, + testnet: testnet, + get: getNetwork +}; + +},{"./util/buffer":48,"lodash":233}],21:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _ = require('lodash'); +var $ = require('./util/preconditions'); +var BufferUtil = require('./util/buffer'); + +function Opcode(num) { + if (!(this instanceof Opcode)) { + return new Opcode(num); + } + + var value; + + if (_.isNumber(num)) { + value = num; + } else if (_.isString(num)) { + value = Opcode.map[num]; + } else { + throw new TypeError('Unrecognized num type: "' + typeof(num) + '" for Opcode'); + } + + Object.defineProperty(this, 'num', { + configurable: false, + value: value + }); + + return this; +} + +Opcode.fromBuffer = function(buf) { + $.checkArgument(BufferUtil.isBuffer(buf)); + return new Opcode(Number('0x' + buf.toString('hex'))); +}; + +Opcode.fromNumber = function(num) { + $.checkArgument(_.isNumber(num)); + return new Opcode(num); +}; + +Opcode.fromString = function(str) { + $.checkArgument(_.isString(str)); + var value = Opcode.map[str]; + if (typeof value === 'undefined') { + throw new TypeError('Invalid opcodestr'); + } + return new Opcode(value); +}; + +Opcode.prototype.toHex = function() { + return this.num.toString(16); +}; + +Opcode.prototype.toBuffer = function() { + return new Buffer(this.toHex(), 'hex'); +}; + +Opcode.prototype.toNumber = function() { + return this.num; +}; + +Opcode.prototype.toString = function() { + var str = Opcode.reverseMap[this.num]; + if (typeof str === 'undefined') { + throw new Error('Opcode does not have a string representation'); + } + return str; +}; + +Opcode.smallInt = function(n) { + $.checkArgument(n >= 0 && n <= 16, 'Invalid Argument: n must be between 0 and 16'); + if (n === 0) { + return Opcode('OP_0'); + } + return new Opcode(Opcode.map.OP_1 + n - 1); +}; + +Opcode.map = { + // push value + OP_FALSE: 0, + OP_0: 0, + OP_PUSHDATA1: 76, + OP_PUSHDATA2: 77, + OP_PUSHDATA4: 78, + OP_1NEGATE: 79, + OP_RESERVED: 80, + OP_TRUE: 81, + OP_1: 81, + OP_2: 82, + OP_3: 83, + OP_4: 84, + OP_5: 85, + OP_6: 86, + OP_7: 87, + OP_8: 88, + OP_9: 89, + OP_10: 90, + OP_11: 91, + OP_12: 92, + OP_13: 93, + OP_14: 94, + OP_15: 95, + OP_16: 96, + + // control + OP_NOP: 97, + OP_VER: 98, + OP_IF: 99, + OP_NOTIF: 100, + OP_VERIF: 101, + OP_VERNOTIF: 102, + OP_ELSE: 103, + OP_ENDIF: 104, + OP_VERIFY: 105, + OP_RETURN: 106, + + // stack ops + OP_TOALTSTACK: 107, + OP_FROMALTSTACK: 108, + OP_2DROP: 109, + OP_2DUP: 110, + OP_3DUP: 111, + OP_2OVER: 112, + OP_2ROT: 113, + OP_2SWAP: 114, + OP_IFDUP: 115, + OP_DEPTH: 116, + OP_DROP: 117, + OP_DUP: 118, + OP_NIP: 119, + OP_OVER: 120, + OP_PICK: 121, + OP_ROLL: 122, + OP_ROT: 123, + OP_SWAP: 124, + OP_TUCK: 125, + + // splice ops + OP_CAT: 126, + OP_SUBSTR: 127, + OP_LEFT: 128, + OP_RIGHT: 129, + OP_SIZE: 130, + + // bit logic + OP_INVERT: 131, + OP_AND: 132, + OP_OR: 133, + OP_XOR: 134, + OP_EQUAL: 135, + OP_EQUALVERIFY: 136, + OP_RESERVED1: 137, + OP_RESERVED2: 138, + + // numeric + OP_1ADD: 139, + OP_1SUB: 140, + OP_2MUL: 141, + OP_2DIV: 142, + OP_NEGATE: 143, + OP_ABS: 144, + OP_NOT: 145, + OP_0NOTEQUAL: 146, + + OP_ADD: 147, + OP_SUB: 148, + OP_MUL: 149, + OP_DIV: 150, + OP_MOD: 151, + OP_LSHIFT: 152, + OP_RSHIFT: 153, + + OP_BOOLAND: 154, + OP_BOOLOR: 155, + OP_NUMEQUAL: 156, + OP_NUMEQUALVERIFY: 157, + OP_NUMNOTEQUAL: 158, + OP_LESSTHAN: 159, + OP_GREATERTHAN: 160, + OP_LESSTHANOREQUAL: 161, + OP_GREATERTHANOREQUAL: 162, + OP_MIN: 163, + OP_MAX: 164, + + OP_WITHIN: 165, + + // crypto + OP_RIPEMD160: 166, + OP_SHA1: 167, + OP_SHA256: 168, + OP_HASH160: 169, + OP_HASH256: 170, + OP_CODESEPARATOR: 171, + OP_CHECKSIG: 172, + OP_CHECKSIGVERIFY: 173, + OP_CHECKMULTISIG: 174, + OP_CHECKMULTISIGVERIFY: 175, + + // expansion + OP_NOP1: 176, + OP_NOP2: 177, + OP_NOP3: 178, + OP_NOP4: 179, + OP_NOP5: 180, + OP_NOP6: 181, + OP_NOP7: 182, + OP_NOP8: 183, + OP_NOP9: 184, + OP_NOP10: 185, + + // template matching params + OP_PUBKEYHASH: 253, + OP_PUBKEY: 254, + OP_INVALIDOPCODE: 255 +}; + +Opcode.reverseMap = []; + +for (var k in Opcode.map) { + Opcode.reverseMap[Opcode.map[k]] = k; +} + +// Easier access to opcodes +_.extend(Opcode, Opcode.map); + +/** + * @returns true if opcode is one of OP_0, OP_1, ..., OP_16 + */ +Opcode.isSmallIntOp = function(opcode) { + if (opcode instanceof Opcode) { + opcode = opcode.toNumber(); + } + return ((opcode === Opcode.map.OP_0) || + ((opcode >= Opcode.map.OP_1) && (opcode <= Opcode.map.OP_16))); +}; + +module.exports = Opcode; + +}).call(this,require("buffer").Buffer) +},{"./util/buffer":48,"./util/preconditions":50,"buffer":69,"lodash":233}],22:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var KJUR = require('jsrsasign'); +var PaymentProtocol = require('./common'); +var RootCerts = require('./rootcerts'); +var rfc3280 = require('asn1.js/rfc/3280'); + +// Documentation: +// http://kjur.github.io/jsrsasign/api/symbols/KJUR.crypto.Signature.html#.sign +// http://kjur.github.io/jsrsasign/api/symbols/RSAKey.html + +PaymentProtocol.prototype.x509Sign = function(key, returnTrust) { + var pki_type = this.get('pki_type'); + var pki_data = this.get('pki_data'); // contains one or more x509 certs + pki_data = PaymentProtocol.X509Certificates.decode(pki_data); + pki_data = pki_data.certificate; + var type = pki_type !== 'none' ? pki_type.split('+')[1].toUpperCase() : pki_type; + var buf = this.serializeForSig(); + + var rsa = new KJUR.RSAKey(); + rsa.readPrivateKeyFromPEMString(key.toString()); + key = rsa; + + var sig; + + if (type !== 'none') { + var jsrsaSig = new KJUR.crypto.Signature({ + alg: type + 'withRSA', + prov: 'cryptojs/jsrsa' + }); + + jsrsaSig.init(key); + + jsrsaSig.updateHex(buf.toString('hex')); + + sig = new Buffer(jsrsaSig.sign(), 'hex'); + } else { + sig = ''; + } + + if (returnTrust) { + var cert = pki_data[pki_data.length - 1]; + var der = cert.toString('hex'); + var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex(der, 'CERTIFICATE'); + var caName = RootCerts.getTrusted(pem); + var selfSigned = 0; + if (!caName) { + selfSigned = pki_data.length > 1 ? -1 : 1; + } + return { + selfSigned: selfSigned, + isChain: pki_data.length > 1, + signature: sig, + caTrusted: !!caName, + caName: caName || null + }; + } + + return sig; +}; + +PaymentProtocol.prototype.x509Verify = function(returnTrust) { + var sig = this.get('signature'); + var pki_type = this.get('pki_type'); + var pki_data = this.get('pki_data'); + pki_data = PaymentProtocol.X509Certificates.decode(pki_data); + pki_data = pki_data.certificate; + var buf = this.serializeForSig(); + var type = pki_type !== 'none' ? pki_type.split('+')[1].toUpperCase() : pki_type; + + var der; + var pem; + var verified; + + if (type !== 'none') { + var jsrsaSig = new KJUR.crypto.Signature({ + alg: type + 'withRSA', + prov: 'cryptojs/jsrsa' + }); + var signedCert = pki_data[0]; + der = signedCert.toString('hex'); + pem = KJUR.asn1.ASN1Util.getPEMStringFromHex(der, 'CERTIFICATE'); + jsrsaSig.initVerifyByCertificatePEM(pem); + jsrsaSig.updateHex(buf.toString('hex')); + verified = jsrsaSig.verify(sig.toString('hex')); + } else { + verified = true; + } + + var chain = pki_data; + + // Get the CA cert's name + + var issuer = chain[chain.length - 1]; + der = issuer.toString('hex'); + pem = KJUR.asn1.ASN1Util.getPEMStringFromHex(der, 'CERTIFICATE'); + var caName = RootCerts.getTrusted(pem); + + if (chain.length === 1 && !caName) { + if (returnTrust) { + return { + selfSigned: 1, // yes + isChain: false, + verified: verified, + caTrusted: false, + caName: null, + chainVerified: false + }; + } + return verified; + } + + // If there's no trusted root cert, don't + // bother validating the cert chain. + if (!caName) { + if (returnTrust) { + return { + selfSigned: -1, // unknown + isChain: chain.length > 1, + verified: verified, + caTrusted: false, + caName: null, + chainVerified: false + }; + } + return verified; + } + + var chainVerified = PaymentProtocol.verifyCertChain(chain, type); + + if (returnTrust) { + return { + selfSigned: 0, // no + isChain: true, + verified: verified, + caTrusted: !!caName, + caName: caName || null, + chainVerified: chainVerified + }; + } + + return verified && chainVerified; +}; + +PaymentProtocol.verifyCertChain = function(chain, sigHashAlg) { + if (sigHashAlg === 'none') { + return true; + } + return chain.every(function(cert, i) { + var der = cert.toString('hex'); + var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex(der, 'CERTIFICATE'); + var name = RootCerts.getTrusted(pem); + + var ncert = chain[i + 1]; + // The root cert, check if it's trusted: + if (!ncert || name) { + if (!name) { + return false; + } + chain.length = 0; + return true; + } + var nder = ncert.toString('hex'); + var npem = KJUR.asn1.ASN1Util.getPEMStringFromHex(nder, 'CERTIFICATE'); + + // Get Next Certificate: + var ndata = new Buffer(nder, 'hex'); + var nc = rfc3280.Certificate.decode(ndata, 'der'); + + var npubKey; + // Get Public Key from next certificate (via KJUR because it's a mess): + if (sigHashAlg !== 'none') { + var js = new KJUR.crypto.Signature({ + alg: sigHashAlg + 'withRSA', + prov: 'cryptojs/jsrsa' + }); + js.initVerifyByCertificatePEM(npem); + npubKey = js.pubKey; + } + + // Get Signature Value from current certificate: + var data = new Buffer(der, 'hex'); + var c = rfc3280.Certificate.decode(data, 'der'); + var sig = c.signature.data; + + // Check Validity of Certificates + var validityVerified = PaymentProtocol.validateCertTime(c, nc); + + // Check the Issuer matches the Subject of the next certificate: + var issuerVerified = PaymentProtocol.validateCertIssuer(c, nc); + + var sigVerified; + + // Verify current Certificate signature + if (sigHashAlg !== 'none') { + var jsrsaSig = new KJUR.crypto.Signature({ + alg: sigHashAlg + 'withRSA', + prov: 'cryptojs/jsrsa' + }); + jsrsaSig.initVerifyByPublicKey(npubKey); + + // Get the raw DER TBSCertificate + // from the DER Certificate: + var tbs = PaymentProtocol.getTBSCertificate(data); + + jsrsaSig.updateHex(tbs.toString('hex')); + + sigVerified = jsrsaSig.verify(sig.toString('hex')); + } else { + sigVerified = true; + } + + return validityVerified && issuerVerified && sigVerified; + }); +}; + +module.exports = PaymentProtocol; + +}).call(this,require("buffer").Buffer) +},{"./common":23,"./rootcerts":27,"asn1.js/rfc/3280":64,"buffer":69,"jsrsasign":232}],23:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var protobufjs = require('protobufjs/dist/ProtoBuf'); +var RootCerts = require('./rootcerts'); +var PublicKey = require('../publickey'); +var PrivateKey = require('../privatekey'); +var Signature = require('../crypto/signature'); +var ECDSA = require('../crypto/ecdsa'); +var sha256sha256 = require('../crypto/hash').sha256sha256; +var varintBufNum = require('../encoding/bufferwriter').varintBufNum; + +// BIP 70 - payment protocol +function PaymentProtocol() { + this.messageType = null; + this.message = null; +} + +PaymentProtocol.PAYMENT_REQUEST_MAX_SIZE = 50000; +PaymentProtocol.PAYMENT_MAX_SIZE = 50000; +PaymentProtocol.PAYMENT_ACK_MAX_SIZE = 60000; +PaymentProtocol.PAYMENT_REQUEST_CONTENT_TYPE = 'application/bitcoin-paymentrequest'; +PaymentProtocol.PAYMENT_CONTENT_TYPE = 'application/bitcoin-payment'; +PaymentProtocol.PAYMENT_ACK_CONTENT_TYPE = 'application/bitcoin-paymentack'; + +// https://www.google.com/search?q=signatureAlgorithm+1.2.840.113549.1.1.1 +// http://msdn.microsoft.com/en-us/library/windows/desktop/aa379057(v=vs.85).aspx +PaymentProtocol.X509_ALGORITHM = { + '1.2.840.113549.1.1.1': 'RSA', + '1.2.840.113549.1.1.2': 'RSA_MD2', + '1.2.840.113549.1.1.4': 'RSA_MD5', + '1.2.840.113549.1.1.5': 'RSA_SHA1', + '1.2.840.113549.1.1.11': 'RSA_SHA256', + '1.2.840.113549.1.1.12': 'RSA_SHA384', + '1.2.840.113549.1.1.13': 'RSA_SHA512', + + '1.2.840.10045.4.3.2': 'ECDSA_SHA256', + '1.2.840.10045.4.3.3': 'ECDSA_SHA384', + '1.2.840.10045.4.3.4': 'ECDSA_SHA512' +}; + +PaymentProtocol.getAlgorithm = function(value, index) { + if (Array.isArray(value)) { + value = value.join('.'); + } + value = PaymentProtocol.X509_ALGORITHM[value]; + if (typeof(index) !== 'undefined') { + value = value.split('_'); + if (index === true) { + return { + cipher: value[0], + hash: value[1] + }; + } + return value[index]; + } + return value; +}; + +// Grab the raw DER To-Be-Signed Certificate +// from a DER Certificate to verify +PaymentProtocol.getTBSCertificate = function(data) { + // We start by slicing off the first SEQ of the + // Certificate (TBSCertificate is its own SEQ). + + // The first 10 bytes usually look like: + // [ 48, 130, 5, 32, 48, 130, 4, 8, 160, 3 ] + var start = 0; + var starts = 0; + for (start = 0; start < data.length; start++) { + if (starts === 1 && data[start] === 48) { + break; + } + if (starts < 1 && data[start] === 48) { + starts++; + } + } + + // The bytes *after* the TBS (including the last TBS byte) will look like + // (note the 48 - the start of the sig, and the 122 - the end of the TBS): + // [ 122, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 11, 5, 0, 3, ... ] + + // The certificate in these examples has a `start` of 4, and an `end` of + // 1040. The 4 bytes is the DER SEQ of the Certificate, right before the + // SEQ of the TBSCertificate. + var end = 0; + var ends = 0; + for (end = data.length - 1; end > 0; end--) { + if (ends === 2 && data[end] === 48) { + break; + } + if (ends < 2 && data[end] === 0) { + ends++; + } + } + + // Return our raw DER TBSCertificate: + return data.slice(start, end); +}; + +// Check Validity of Certificates +PaymentProtocol.validateCertTime = function(c, nc) { + var validityVerified = true; + var now = Date.now(); + var cBefore = c.tbsCertificate.validity.notBefore.value; + var cAfter = c.tbsCertificate.validity.notAfter.value; + var nBefore = nc.tbsCertificate.validity.notBefore.value; + var nAfter = nc.tbsCertificate.validity.notAfter.value; + if (cBefore > now || cAfter < now || nBefore > now || nAfter < now) { + validityVerified = false; + } + return validityVerified; +}; + +// Check the Issuer matches the Subject of the next certificate: +PaymentProtocol.validateCertIssuer = function(c, nc) { + var issuer = c.tbsCertificate.issuer; + var subject = nc.tbsCertificate.subject; + var issuerVerified = issuer.type === subject.type && issuer.value.every(function(issuerArray, i) { + var subjectArray = subject.value[i]; + return issuerArray.every(function(issuerObject, i) { + var subjectObject = subjectArray[i]; + + var issuerObjectType = issuerObject.type.join('.'); + var subjectObjectType = subjectObject.type.join('.'); + + var issuerObjectValue = issuerObject.value.toString('hex'); + var subjectObjectValue = subjectObject.value.toString('hex'); + + return issuerObjectType === subjectObjectType && issuerObjectValue === subjectObjectValue; + }); + }); + return issuerVerified; +}; + +PaymentProtocol.RootCerts = RootCerts; + +PaymentProtocol.proto = {}; + +PaymentProtocol.proto.Output = 'message Output {\ + optional uint64 amount = 1 [default = 0];\ + optional bytes script = 2;\ +}\n'; + +PaymentProtocol.proto.PaymentDetails = 'message PaymentDetails {\ + optional string network = 1 [default = \"main\"];\ + repeated Output outputs = 2;\ + required uint64 time = 3;\ + optional uint64 expires = 4;\ + optional string memo = 5;\ + optional string payment_url = 6;\ + optional bytes merchant_data = 7;\ +}\n'; + +PaymentProtocol.proto.PaymentRequest = 'message PaymentRequest {\ + optional uint32 payment_details_version = 1 [default = 1];\ + optional string pki_type = 2 [default = \"none\"];\ + optional bytes pki_data = 3;\ + required bytes serialized_payment_details = 4;\ + optional bytes signature = 5;\ +}\n'; + +PaymentProtocol.proto.Payment = 'message Payment {\ + optional bytes merchant_data = 1;\ + repeated bytes transactions = 2;\ + repeated Output refund_to = 3;\ + optional string memo = 4;\ +}\n'; + +PaymentProtocol.proto.PaymentACK = 'message PaymentACK {\ + required Payment payment = 1;\ + optional string memo = 2;\ +}\n'; + +PaymentProtocol.proto.X509Certificates = 'message X509Certificates {\ + repeated bytes certificate = 1;\ +}\n'; + +PaymentProtocol.proto.all = ''; +PaymentProtocol.proto.all = PaymentProtocol.proto.all + PaymentProtocol.proto.Output; +PaymentProtocol.proto.all = PaymentProtocol.proto.all + PaymentProtocol.proto.PaymentDetails; +PaymentProtocol.proto.all = PaymentProtocol.proto.all + PaymentProtocol.proto.PaymentRequest; +PaymentProtocol.proto.all = PaymentProtocol.proto.all + PaymentProtocol.proto.Payment; +PaymentProtocol.proto.all = PaymentProtocol.proto.all + PaymentProtocol.proto.PaymentACK; +PaymentProtocol.proto.all = PaymentProtocol.proto.all + PaymentProtocol.proto.X509Certificates; + +PaymentProtocol.builder = protobufjs.loadProto(PaymentProtocol.proto.all); + +PaymentProtocol.Output = PaymentProtocol.builder.build('Output'); +PaymentProtocol.PaymentDetails = PaymentProtocol.builder.build('PaymentDetails'); +PaymentProtocol.PaymentRequest = PaymentProtocol.builder.build('PaymentRequest'); +PaymentProtocol.Payment = PaymentProtocol.builder.build('Payment'); +PaymentProtocol.PaymentACK = PaymentProtocol.builder.build('PaymentACK'); +PaymentProtocol.X509Certificates = PaymentProtocol.builder.build('X509Certificates'); + +PaymentProtocol.prototype.makeOutput = function(obj) { + this.messageType = 'Output'; + this.message = new PaymentProtocol.Output(); + this.setObj(obj); + return this; +}; + +PaymentProtocol.prototype.makePaymentDetails = function(obj) { + this.messageType = 'PaymentDetails'; + this.message = new PaymentProtocol.PaymentDetails(); + this.setObj(obj); + return this; +}; + +PaymentProtocol.prototype.makePaymentRequest = function(obj) { + this.messageType = 'PaymentRequest'; + this.message = new PaymentProtocol.PaymentRequest(); + this.setObj(obj); + return this; +}; + +PaymentProtocol.prototype.makePayment = function(obj) { + this.messageType = 'Payment'; + this.message = new PaymentProtocol.Payment(); + this.setObj(obj); + return this; +}; + +PaymentProtocol.prototype.makePaymentACK = function(obj) { + this.messageType = 'PaymentACK'; + this.message = new PaymentProtocol.PaymentACK(); + this.setObj(obj); + return this; +}; + +PaymentProtocol.prototype.makeX509Certificates = function(obj) { + this.messageType = 'X509Certificates'; + this.message = new PaymentProtocol.X509Certificates(); + this.setObj(obj); + return this; +}; + +PaymentProtocol.prototype.isValidSize = function() { + var s = this.serialize(); + if (this.messageType === 'PaymentRequest') { + return s.length < PaymentProtocol.PAYMENT_REQUEST_MAX_SIZE; + } + if (this.messageType === 'Payment') { + return s.length < PaymentProtocol.PAYMENT_MAX_SIZE; + } + if (this.messageType === 'PaymentACK') { + return s.length < PaymentProtocol.PAYMENT_ACK_MAX_SIZE; + } + return true; +}; + +PaymentProtocol.prototype.getContentType = function() { + if (this.messageType === 'PaymentRequest') { + return PaymentProtocol.PAYMENT_REQUEST_CONTENT_TYPE; + } + + if (this.messageType === 'Payment') { + return PaymentProtocol.PAYMENT_CONTENT_TYPE; + } + + if (this.messageType === 'PaymentACK') { + return PaymentProtocol.PAYMENT_ACK_CONTENT_TYPE; + } + + throw new Error('No known content type for this message type'); +}; + +PaymentProtocol.prototype.set = function(key, val) { + this.message.set(key, val); + return this; +}; + +PaymentProtocol.prototype.get = function(key) { + var v = this.message.get(key); + + if (v === null) { + return v; + } + + //protobuf supports longs, javascript naturally does not + //convert longs (see long.js, e.g. require('long')) to Numbers + if (typeof v.low !== 'undefined' && typeof v.high !== 'undefined') { + return v.toInt(); + } + + if (typeof v.toBuffer !== 'undefined') { + var maybebuf = v.toBuffer(); + return Buffer.isBuffer(maybebuf) ? maybebuf : new Buffer(new Uint8Array(maybebuf)); + } + + return v; +}; + +PaymentProtocol.prototype.setObj = function(obj) { + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + var val = obj[key]; + this.message.set(key, val); + } + } + return this; +}; + +PaymentProtocol.prototype.serializeForSig = function() { + if (this.messageType !== 'PaymentRequest') { + throw new Error('serializeForSig is only for PaymentRequest'); + } + + var save = this.message.get('signature'); + this.message.set('signature', new Buffer([])); + var buf = this.serialize(); + this.message.set('signature', save); + return buf; +}; + +PaymentProtocol.prototype.serialize = function() { + //protobufjs returns either a Buffer or an ArrayBuffer + //but we always want a Buffer (which browserify understands, browser or no) + var maybebuf = this.message.toBuffer(); + var buf = (Buffer.isBuffer(maybebuf)) ? maybebuf : new Buffer(new Uint8Array(maybebuf)); + return buf; +}; + +PaymentProtocol.prototype.deserialize = function(buf, messageType) { + this.messageType = messageType || this.messageType; + if (!this.messageType) { + throw new Error('Must specify messageType'); + } + this.message = PaymentProtocol[this.messageType].decode(buf); + return this; +}; + +PaymentProtocol.prototype.sign = function(key, returnTrust) { + if (this.messageType !== 'PaymentRequest') { + throw new Error('Signing can only be performed on a PaymentRequest'); + } + + var pki_type = this.get('pki_type'); + + var sig; + if (pki_type === 'SIN') { + sig = this.sinSign(key); + } else if (pki_type === 'x509+sha1' || pki_type === 'x509+sha256') { + sig = this.x509Sign(key, returnTrust); + } else if (pki_type === 'none') { + return this; + } else { + throw new Error('Unsupported pki_type'); + } + + this.set('signature', sig); + + return this; +}; + +PaymentProtocol.prototype.verify = function(returnTrust) { + if (this.messageType !== 'PaymentRequest') { + throw new Error('Verifying can only be performed on a PaymentRequest'); + } + + var pki_type = this.get('pki_type'); + + if (pki_type === 'SIN') { + return this.sinVerify(); + } else if (pki_type === 'x509+sha1' || pki_type === 'x509+sha256') { + return this.x509Verify(returnTrust); + } else if (pki_type === 'none') { + return true; + } + + throw new Error('Unsupported pki_type'); +}; + +function magicHash(str) { + var magicBytes = new Buffer('Bitcoin Signed Message:\n'); + var prefix1 = varintBufNum(magicBytes.length); + var message = new Buffer(str); + var prefix2 = varintBufNum(message.length); + var buf = Buffer.concat([prefix1, magicBytes, prefix2, message]); + var hash = sha256sha256(buf); + return hash; +} + +//default signing function for prototype.sign +PaymentProtocol.prototype.sinSign = function(privateKey) { + if ( !(privateKey instanceof PrivateKey) ) { + throw new TypeError('Expects an instance of PrivateKey'); + } + var pubkey = privateKey.toPublicKey().toBuffer(); + this.set('pki_data', pubkey); + var buf = this.serializeForSig(); + var hash = magicHash(buf); + var signature = ECDSA.sign(hash, privateKey); + return signature.toDER(); +}; + +//default verify function +PaymentProtocol.prototype.sinVerify = function() { + var sig = this.get('signature'); + var pubkey = this.get('pki_data'); + var buf = this.serializeForSig(); + var hash = magicHash(buf); + var publicKey = PublicKey.fromBuffer(pubkey); + var signature = new Signature.fromString(sig); + var verified = ECDSA.verify(hash, signature, publicKey); + return verified; +}; + +// Helpers + +PaymentProtocol.PEMtoDER = +PaymentProtocol.prototype._PEMtoDER = function(pem) { + return this._PEMtoDERParam(pem); +}; + +PaymentProtocol.PEMtoDERParam = +PaymentProtocol.prototype._PEMtoDERParam = function(pem, param) { + if (Buffer.isBuffer(pem)) { + pem = pem.toString(); + } + var start = new RegExp('(?=-----BEGIN ' + (param || '[^-]+') + '-----)', 'i'); + var end = new RegExp('^-----END ' + (param || '[^-]+') + '-----$', 'gmi'); + pem = pem.replace(end, ''); + var parts = pem.split(start); + return parts.map(function(part) { + var type = /-----BEGIN ([^-]+)-----/.exec(part)[1]; + part = part.replace(/-----BEGIN ([^-]+)-----/g, ''); + part = part.replace(/\s+/g, ''); + if (!param || type !== param) { + return; + } + return new Buffer(part, 'base64'); + }).filter(Boolean); +}; + +PaymentProtocol.DERtoPEM = +PaymentProtocol.prototype._DERtoPEM = function(der, type) { + if (typeof der === 'string') { + der = new Buffer(der, 'hex'); + } + type = type || 'PRIVACY-ENHANCED MESSAGE'; + der = der.toString('base64'); + der = der.replace(/(.{64})/g, '$1\r\n'); + der = der.replace(/\r\n$/, ''); + return '' + + '-----BEGIN ' + type + '-----\r\n' + + der + + '\r\n-----END ' + type + '-----\r\n'; +}; + +// Expose RootCerts +PaymentProtocol.getTrusted = RootCerts.getTrusted; +PaymentProtocol.getCert = RootCerts.getCert; +PaymentProtocol.parsePEM = RootCerts.parsePEM; +PaymentProtocol.certs = RootCerts.certs; +PaymentProtocol.trusted = RootCerts.trusted; + +module.exports = PaymentProtocol; + +}).call(this,require("buffer").Buffer) +},{"../crypto/ecdsa":6,"../crypto/hash":7,"../crypto/signature":10,"../encoding/bufferwriter":14,"../privatekey":28,"../publickey":29,"./rootcerts":27,"buffer":69,"protobufjs/dist/ProtoBuf":234}],24:[function(require,module,exports){ +if ( typeof(window) === 'undefined' ) { + module.exports = require('./node'); +} else { + module.exports = require('./browser'); +} + +},{"./browser":22,"./node":25}],25:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var crypto = require('crypto'); +var RootCerts = require('./rootcerts'); +var PaymentProtocol = require('./common'); +var rfc3280 = require('asn1.js/rfc/3280'); + +PaymentProtocol.prototype.x509Sign = function(key, returnTrust) { + var pki_type = this.get('pki_type'); + var pki_data = this.get('pki_data'); + pki_data = PaymentProtocol.X509Certificates.decode(pki_data); + pki_data = pki_data.certificate; + var type = pki_type !== 'none' ? pki_type.split('+')[1].toUpperCase() : pki_type; + + var sig; + if (type !== 'none') { + var signature = crypto.createSign('RSA-' + type); + var buf = this.serializeForSig(); + signature.update(buf); + sig = signature.sign(key); + } else { + sig = ''; + } + + if (returnTrust) { + var cert = pki_data[pki_data.length - 1]; + var der = cert.toString('hex'); + var pem = PaymentProtocol.DERtoPEM(der, 'CERTIFICATE'); + var caName = RootCerts.getTrusted(pem); + var selfSigned = 0; + if (!caName) { + selfSigned = pki_data.length > 1 ? -1 : 1; + } + return { + selfSigned: selfSigned, + isChain: pki_data.length > 1, + signature: sig, + caTrusted: !!caName, + caName: caName || null + }; + } + + return sig; +}; + +PaymentProtocol.prototype.x509Verify = function(returnTrust) { + var pki_type = this.get('pki_type'); + var sig = this.get('signature'); + var pki_data = this.get('pki_data'); + pki_data = PaymentProtocol.X509Certificates.decode(pki_data); + pki_data = pki_data.certificate; + var buf = this.serializeForSig(); + var type = pki_type !== 'none' ? pki_type.split('+')[1].toUpperCase() : pki_type; + + var verified; + var der; + var pem; + + if (type !== 'none') { + var verifier = crypto.createVerify('RSA-' + type); + verifier.update(buf); + var signedCert = pki_data[0]; + der = signedCert.toString('hex'); + pem = PaymentProtocol.DERtoPEM(der, 'CERTIFICATE'); + verified = verifier.verify(pem, sig); + } else { + verified = true; + } + + var chain = pki_data; + + // Get the CA cert's name + var issuer = chain[chain.length - 1]; + der = issuer.toString('hex'); + pem = PaymentProtocol.DERtoPEM(der, 'CERTIFICATE'); + var caName = RootCerts.getTrusted(pem); + + if (chain.length === 1 && !caName) { + if (returnTrust) { + return { + selfSigned: 1, // yes + isChain: false, + verified: verified, + caTrusted: false, + caName: null, + chainVerified: false + }; + } + return verified; + } + + // If there's no trusted root cert, don't + // bother validating the cert chain. + if (!caName) { + if (returnTrust) { + return { + selfSigned: -1, // unknown + isChain: chain.length > 1, + verified: verified, + caTrusted: false, + caName: null, + chainVerified: false + }; + } + return verified; + } + + var chainVerified = PaymentProtocol.verifyCertChain(chain, type); + + if (returnTrust) { + return { + selfSigned: 0, // no + isChain: true, + verified: verified, + caTrusted: !!caName, + caName: caName || null, + chainVerified: chainVerified + }; + } + + return verified && chainVerified; +}; + +PaymentProtocol.verifyCertChain = function(chain, sigHashAlg) { + if (sigHashAlg === 'none') { + return true; + } + return chain.every(function(cert, i) { + var der = cert.toString('hex'); + var pem = PaymentProtocol.DERtoPEM(der, 'CERTIFICATE'); + var name = RootCerts.getTrusted(pem); + + var ncert = chain[i + 1]; + + // The root cert, check if it's trusted: + if (!ncert || name) { + if (!name) { + return false; + } + chain.length = 0; + return true; + } + var nder = ncert.toString('hex'); + + // Get Public Key from next certificate: + var ndata = new Buffer(nder, 'hex'); + var nc = rfc3280.Certificate.decode(ndata, 'der'); + var npubKeyAlg = PaymentProtocol.getAlgorithm( + nc.tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm); + var npubKey = nc.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data; + npubKey = PaymentProtocol.DERtoPEM(npubKey, npubKeyAlg + ' PUBLIC KEY'); + + // Get Signature Value from current certificate: + var data = new Buffer(der, 'hex'); + var c = rfc3280.Certificate.decode(data, 'der'); + var sig = c.signature.data; + + // Check Validity of Certificates + var validityVerified = PaymentProtocol.validateCertTime(c, nc); + + // Check the Issuer matches the Subject of the next certificate: + var issuerVerified = PaymentProtocol.validateCertIssuer(c, nc); + + // Verify current Certificate signature: + // Get the raw DER TBSCertificate + // from the DER Certificate: + var tbs = PaymentProtocol.getTBSCertificate(data); + + var verifier = crypto.createVerify('RSA-' + sigHashAlg); + verifier.update(tbs); + var sigVerified = verifier.verify(npubKey, sig); + + return validityVerified && issuerVerified && sigVerified; + }); +}; + +module.exports = PaymentProtocol; + +}).call(this,require("buffer").Buffer) +},{"./common":23,"./rootcerts":27,"asn1.js/rfc/3280":64,"buffer":69,"crypto":76}],26:[function(require,module,exports){ +module.exports={ + "GTE CyberTrust Global Root": "-----BEGIN CERTIFICATE-----\nMIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9H\n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x75pO2mqWilMg0HZHRxdf0CiUPPXiBng+xZ8SQTGPdXqfiup/1902lMXucKS1M/mQ+\n7LZT/uqb7YLbdHVLB3luHtgZg3Pe9T7Qtd7nS2h9Qy4qIOF+oHhEngj1mPnHfxsb1gYgAlih\nw6ID\n-----END CERTIFICATE-----\n", + "Verisign Class 3 Public Primary Certification Authority": "-----BEGIN CERTIFICATE-----\nMIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkGA1UEBhMC\nVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQ\ncmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgw\nMjIzNTk1OVowXzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYD\nVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGf\nMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ\n2RHP7gJYHyX3KqhEBarsAx94f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaO\nIG+YD/isI19wKTakyYbnsZogy1Olhec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0G\nCSqGSIb3DQEBBQUAA4GBABByUqkFFBkyCEHwxWsKzH4PIRnN5GfcX6kb5sroc50i2JhucwNh\nkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWXbj9T/UWZYB2oK0z5XqcJ2HUw19JlYD1n1khV\ndWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/D/xwzoiQ\n-----END CERTIFICATE-----\n", + "Verisign Class 3 Public Primary Certification Authority - G2": "-----BEGIN CERTIFICATE-----\nMIIDAj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bGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQD\nExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl\ncnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjmFGWHOjVsQaBalfDcnWTq8+e\npvzzFlLWLU2fNUSoLgRNB0mKOCn1dzfnt6td3zZxFJmP3MKS8edgkpfs2Ejcv8ECIMYkpChM\nMFp2bbFc893enhBxoYjHW5tBbcqwuI4V7q0zK89HBFx1cQqYJJgpp0lZpd34t0NiYfPT4tBV\nPwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFa7AliEZwgs3x/be0kz9dNnnfS0ChCzycUs4pJq\ncXgn8nCDQtM+z6lU9PHYkhaM0QTLS6vJn0WuPIqpsHEzXcjFV9+vqDWzf4mH6eglkrh/hXqu\n1rweN1gqZ8mRzyqBPu3GOd/APhmcGcwTTYJBtYze4D1gCCAPRX5ron+jjBXu\n-----END CERTIFICATE-----\n", + "Verisign Class 3 Public Primary Certification Authority - G3": "-----BEGIN CERTIFICATE-----\nMIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQG\nEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0\nIE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv\ncml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1h\ncnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3\nMTYyMzU5NTlaMIHKMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAd\nBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlT\naWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWdu\nIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCC\nASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMu6nFL8eB8aHm8bN3O9+MlrlBIwT/A2\nR/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1EUGO+i2tKmFZpGcmTNDovFJbcCAEWNF6\nyaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGukxUccLwgTS8Y3pKI6GyFVxEa6X7jJhFU\nokWWVYPKMIno3Nij7SqAP395ZVc+FSBmCC+Vk7+qRy+oRpfwEuL+wgorUeZ25rdGt+INpsyo\nw0xZVYnm6FNcHOqd8GIWC6fJXwzw3sJ2zq/3avL6QaaiMxTJ5Xpj055iN9WFZZ4O5lMkdBte\nHRJTW8cs54NJOxWuimi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAERSWwauSCPc/L8my\n/uRan2Te2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5fj267Cz3qWhMe\nDGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC/Y4wjylG\nsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565pF4ErWjfJXir0xuKh\nXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGtTxzhT5yvDwyd93gN2PQ1VoDa\nt20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ==\n-----END CERTIFICATE-----\n", + "Verisign Class 4 Public Primary Certification Authority - G3": "-----BEGIN CERTIFICATE-----\nMIIEGjCCAwICEQDsoKeLbnVqAc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Fo8AasAFOq73AI25jP4BKxQft3OJvx8Fi8eNy1gTI\ndGcL+oiroQHIb/AUr9KZzVGTfu0uOMe9zkZQPXLjeSWdm4grECDdpbgyn43gKd8hdIaC2y+C\nMMbHNYaz+ZZfRtsMRf3zUMNvxsNIrUam4SdHCh0Om7bCd39j8uB9Gr784N/Xx6dssPmuujz9\ndLQR6FgNgLzTqIA6me11zEZ7\n-----END CERTIFICATE-----\n", + "America Online Root Certification Authority 2": "-----BEGIN CERTIFICATE-----\nMIIFpDCCA4ygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UE\nChMTQW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBD\nZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAyMB4XDTAyMDUyODA2MDAwMFoXDTM3MDkyOTE0MDgw\nMFowYzELMAkGA1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNV\nBAMTLUFtZXJpY2EgT25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMjCCAiIw\nDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMxBRR3pPU0Q9oyxQcngXssNt79Hc9PwVU3d\nxgz6sWYFas14tNwC206B89enfHG8dWOgXeMHDEjsJcQDIPT/DjsS/5uN4cbVG7RtIuOx238h\nZK+GvFciKtZHgVdEglZTvYYUAQv8f3SkWq7xuhG1m1hagLQ3eAkzfDJHA1zEpYNI9FdWboE2\nJxhP7JsowtS013wMPgwr38oE18aO6lhOqKSlGBxsRZijQdEt0sdtjRnxrXm3gT+9BoInLRBY\nBbV4Bbkv2wxrkJB+FFk4u5QkE+XRnRTf04JNRvCAOVIyD+OEsnpD8l7eXz8d3eOyG6ChKiMD\nbi4BFYdcpnV1x5dhvt6G3NRI270qv0pV2uh9UPu0gBe4lL8BPeraunzgWGcXuVjgiIZGZ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ddtawJXa+ZH\nfAjIgrrep4c9oW24MFbCswKBXy314powGCi4ZtPLAZZv6opFVdbgnf9nKxcCpk4aahELfrd7\n55jWjHZvwTvbUJN+5dCOHze4vbrGn2zpfDPyMjwmR/onJALJfh1biEITajV8fTXpLmaRcpPV\nMibEdPVTo7NdmvYJywIDAQABo4HIMIHFMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD\nAgHGMB8GA1UdEQQYMBaBFHBraS1vcHNAdHJ1c3Rkc3QuY29tMGIGA1UdIARbMFkwVwYKYIZI\nAWUDAgEBATBJMEcGCCsGAQUFBwIBFjtodHRwOi8vd3d3LnRydXN0ZHN0LmNvbS9jZXJ0aWZp\nY2F0ZXMvcG9saWN5L0FDRVMtaW5kZXguaHRtbDAdBgNVHQ4EFgQUCXIGThhDD+XWzMNqizF7\neI+og7gwDQYJKoZIhvcNAQEFBQADggEBAKPYjtay284F5zLNAdMEA+V25FYrnJmQ6AgwbN99\nPe7lv7UkQIRJ4dEorsTCOlMwiPH1d25Ryvr/ma8kXxug/fKshMrfqfBfBC6tFr8hlxCBPeP/\nh40y3JTlR4peahPJlJU90u7INJXQgNStMgiAVDzgvVJT11J8smk/f3rPanTK+gQqnExaBqXp\nIK1FZg9p8d2/6eMyi/rgwYZNcjwu2JN4Cir42NInPRmJX1p7ijvMDNpRrscL9yuwNwXsvFcj\n4jjSm2jzVhKIT0J8uDHEtdvkyCE06UgRNe76x5JXxZ805Mf29w4LTJxoeHtxMcfrHuBnQfO3\noKfN5XozNmr6mis=\n-----END CERTIFICATE-----\n", + "TURKTRUST Certificate Services Provider Root 1": "-----BEGIN CERTIFICATE-----\nMIID+zCCAuOgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBtzE/MD0GA1UEAww2VMOcUktUUlVT\nVCBFbGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQG\nDAJUUjEPMA0GA1UEBwwGQU5LQVJBMVYwV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JHkn2EaqbylZUohwEurdPfWbU1Rv\n4WCiqAm57OtZfMY18dwY6fFn5a+6ReAJ3spED8IXDneRRXozX1+WLGiLwUePmJs9wOzL9dWC\nkoQ10b42OFZyMVtHLaoXpGNR6woBrX/sdZ7LoR/xfxKxueRkf2fWIyr0uDldmOghp+G9PUIa\ndJpwr2hsUF1Jz//7Dl3mLEfXgTpZALVza2Mg9jFFCDkO9HB+QHBaP9BrQql0PSgvAm11cpUJ\njUhjxsYjV5KTXjXBjfkK9yydYhz2rXzdpjEetrHHfoUm+qRqtdpjMNHvkzeyZi99Bffnt0uY\nlDXA2TopwZ2yUDMdSqlapskD7+3056huirRXhOukP9DuqqqHW2Pok+JrqNS4cnhrG+055F3L\nm6qH1U9OAP7Zap88MQ8oAgF9mOinsKJknnn4SPIVqczmyETrP3iZ8ntxPjzxmKfFGBI/5rso\nM0LpRQp8bfKGeS/Fghl9CYl8slR2iK7ewfPM4W7bMdaTrpmg7yVqc5iJWzouE4gev8CSlDQb\n4ye3ix5vQv/n6TebUB0tovkC7stYWDpxvGjjqsGvHCgfotwjZT+B6q6Z09gwzxMNTxXJhLyn\nSC34MCN32EZLeW32jO06f2ARePTpm67VVMB0gNELQp/B\n-----END CERTIFICATE-----\n", + "Go Daddy Root Certificate Authority - G2": "-----BEGIN CERTIFICATE-----\nMIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMxEDAOBgNV\nBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoTEUdvRGFkZHkuY29t\nLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAt\nIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAw\nDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5\nLmNvbSwgSW5jLjExMC8GA1UEAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3Jp\ndHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3\ngElY6SKDE6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH\n/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7RnwyDfMAZiLI\njWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVhGkSBjCypQ5Yj36w6\ngZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGRtDtwKj9useiciAF9n9T521Nt\nYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO\nBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3\nDQEBCwUAA4IBAQCZ21151fmXWWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC\n2gV7+AJ1uP2lsdeu9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95\nkTXWXwTrgIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo\n2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPOLPAvTK33\nsefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI4uJEvlz36hz1\n-----END CERTIFICATE-----\n", + "Starfield Root Certificate Authority - G2": "-----BEGIN CERTIFICATE-----\nMIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBh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vE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg\n8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/KpL/QlwVK\nvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1mMpYjn0q7pBZc2T5\nNnReJaH1ZgUufzkVqSr7UIuOhWn0\n-----END CERTIFICATE-----\n", + "Starfield Services Root Certificate Authority - G2": "-----BEGIN CERTIFICATE-----\nMIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMxEDAOBgNV\nBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBU\nZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVsZCBTZXJ2aWNlcyBSb290IENl\ncnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1\nOVowgZgxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNk\nYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJT\ndGFyZmllbGQgU2VydmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p\nOsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm28xpWriu2\ndBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1KTs9DkTvnVtYAcMtS\n7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufehR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hAJO5I1KlOy/usrBdlsXebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4g\numlc7rh3zc5sH62Dlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKu\nD8z7fDvnaspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ\nYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw==\n-----END CERTIFICATE-----\n", + "Security Communication RootCA2": "-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDElMCMGA1UE\nChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMeU2VjdXJpdHkgQ29t\nbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoXDTI5MDUyOTA1MDAzOVowXTEL\nMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xJzAl\nBgNVBAsTHlNlY3VyaXR5IENvbW11bmljYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEB\nBQADggEPADCCAQoCggEBANAVOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz3\n35c9S672XewhtUGrzbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonC\nv/Q4EpVMVAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ\nhNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWOojnflLhw\nHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSwawNQwS08Ft1ENCca\ndfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXd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M3FIUPp\nqojlNcAZQmNaAl6kSBg6hW/cnbw/nZzBh7h6YQjpdwt/cKt63dmXLGQehb+8dJahw3oS7Awa\nboMMPOhyRp/7SNVel+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOS\nAgu+TGbrIP65y7WZf+a2E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xlnJ2lYJU6\nUn/10asIbvPuW/mIPX64b24D5EI=\n-----END CERTIFICATE-----\n", + "Hellenic Academic and Research Institutions RootCA 2011": "-----BEGIN CERTIFICATE-----\nMIIEMTCCAxmgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMCR1IxRDBCBgNV\nBAoTO0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4g\nQXV0aG9yaXR5MUAwPgYDVQQDEzdIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5z\ndGl0dXRpb25zIFJvb3RDQSAyMDExMB4XDTExMTIwNjEzNDk1MloXDTMxMTIwMTEzNDk1Mlow\ngZUxCzAJBgNVBAYTAkdSMUQwQgYDVQQKEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFy\nY2ggSW5zdGl0dXRpb25zIENlcnQuIEF1dGhvcml0eTFAMD4GA1UEAxM3SGVsbGVuaWMgQWNh\nZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBSb290Q0EgMjAxMTCCASIwDQYJKoZI\nhvcNAQEBBQADggEPADCCAQoCggEBAKlTAOMupvaO+mDYLZU++CwqVE7NuYRhlFhPjz2L5EPz\ndYmNUeTDN9KKiE15HrcS3UN4SoqS5tdI1Q+kOilENbgH9mgdVc04UfCMJDGFr4PJfel3r+0a\ne50X+bOdOFAPplp5kYCvN66m0zH7tSYJnTxa71HFK9+WXesyHgLacEnsbgzImjeN9/E2YEsm\nLIKe0HjzDQ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QDIIMDs4MVLqwd4lfNE7vsLDP90jmG7sWLq\nI9iroWUyeuuOF0+W2Ap7kaJjbMeMTC55v6kF/GlclY1i+blw7cNRfdCT5mzrMEvhvH2/UpvO\nbntl8jixwKIy72KyaOBhU8E2lf/slLo2rpwcpzIP5Xy0xm90/XsY6KxX7QYgSzIwWFv9zajm\nofxwvI6Sc9uXp3whrj3B9UiHbCe9nyV0gVWw93X2PaRka9ZP585ArQ/dMtO8ihJTmMmJ+xAd\nTX7Nfh9WDSFwhfYggx/2uh8Ej+p3iDXE/+pOoYtNP2MbRMNE1CV2yreN1x5KZmTNXMWcg+HC\nCIia7E6j8T4cLNlsHaFLAgMBAAGjgYowgYcwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E\nBAMCAQYwHQYDVR0OBBYEFBLyWj7qVhy/zQas8fElyalL1BSZMEUGA1UdJQQ+MDwGCCsGAQUF\nBwMCBggrBgEFBQcDAQYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEFBQcDCAYIKwYBBQUHAwkw\nDQYJKoZIhvcNAQEFBQADggEBAHv25MANqhlHt01Xo/6tu7Fq1Q+e2+RjxY6hUFaTlrg4wCQi\nZrxTFGGVv9DHKpY5P30osxBAIWrEr7BSdxjhlthWXePdNl4dp1BUoMUq5KqMlIpPnTX/dqQG\nE5Gion0ARD9V04I8GtVbvFZMIi5GQ4okQC3zErg7cBqklrkar4dBGmoYDQZPxz5uuSlNDUmJ\nEYcyW+ZLBMjkXOZ0c5RdFpgTlf7727FE5TpwrDdr5rMzcijJs1eg9gIWiAYLtqZLICjU3j2L\nrTcFU3T+bsy8QxdxXvnFzBqpYe73dgzzcvRyrc9yAjYHR8/vGVCJYMzpJJUPwssd8m92kMfM\ndcGWxZ0=\n-----END CERTIFICATE-----\n" +} +},{}],27:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var RootCerts = exports; + +var certs = require('./rootcerts.json'); + +// Use hash table for efficiency: +var trusted = Object.keys(certs).reduce(function(trusted, key) { + var pem = certs[key]; + pem = pem.replace(/-----BEGIN CERTIFICATE-----/g, ''); + pem = pem.replace(/-----END CERTIFICATE-----/g, ''); + pem = pem.replace(/\s+/g, ''); + trusted[pem] = key; + return trusted; +}, {}); + +RootCerts.getTrusted = function(pem) { + pem = RootCerts.parsePEM(pem)[0].pem; + if (!Object.prototype.hasOwnProperty.call(trusted, pem)) { + return; + } + return trusted[pem]; +}; + +RootCerts.getCert = function(name) { + name = name.replace(/^s+|s+$/g, ''); + if (!Object.prototype.hasOwnProperty.call(certs, name)) { + return; + } + return certs[name]; +}; + +RootCerts.parsePEM = function(pem) { + pem = pem + ''; + var concatted = pem.trim().split(/-----BEGIN [^\-\r\n]+-----/); + if (concatted.length > 2) { + return concatted.reduce(function(out, pem) { + if (!pem) { + return out; + } + pem = RootCerts.parsePEM(pem)[0].pem; + if (pem) { + out.push(pem); + } + return out; + }, []); + } + var type = /-----BEGIN ([^\-\r\n]+)-----/.exec(pem)[1]; + pem = pem.replace(/-----BEGIN [^\-\r\n]+-----/, ''); + pem = pem.replace(/-----END [^\-\r\n]+-----/, ''); + var parts = pem.trim().split(/(?:\r?\n){2,}/); + var headers = {}; + if (parts.length > 1) { + headers = parts[0].trim().split(/[\r\n]/).reduce(function(out, line) { + var parts = line.split(/:[ \t]+/); + var key = parts[0].trim().toLowerCase(); + var value = (parts.slice(1).join('') || '').trim(); + out[key] = value; + return out; + }, {}); + pem = parts.slice(1).join(''); + } + pem = pem.replace(/\s+/g, ''); + var der = pem ? new Buffer(pem, 'base64') : null; + return [{ + type: type, + headers: headers, + pem: pem, + der: der, + body: der || new Buffer([0]) + }]; +}; + +RootCerts.certs = certs; +RootCerts.trusted = trusted; + +}).call(this,require("buffer").Buffer) +},{"./rootcerts.json":26,"buffer":69}],28:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _ = require('lodash'); +var Address = require('./address'); +var base58check = require('./encoding/base58check'); +var BN = require('./crypto/bn'); +var JSUtil = require('./util/js'); +var Networks = require('./networks'); +var Point = require('./crypto/point'); +var PublicKey = require('./publickey'); +var Random = require('./crypto/random'); + +/** + * Instantiate a PrivateKey from a BN, Buffer and WIF. + * + * @example + * + * // generate a new random key + * var key = PrivateKey(); + * + * // get the associated address + * var address = key.toAddress(); + * + * // encode into wallet export format + * var exported = key.toWIF(); + * + * // instantiate from the exported (and saved) private key + * var imported = PrivateKey.fromWIF(exported); + * + * @param {String} data - The encoded data in various formats + * @param {String} [network] - Either "livenet" or "testnet" + * @returns {PrivateKey} A new valid instance of an PrivateKey + * @constructor + */ +var PrivateKey = function PrivateKey(data, network) { + + if (!(this instanceof PrivateKey)) { + return new PrivateKey(data, network); + } + if (data instanceof PrivateKey) { + return data; + } + + var info = { + compressed: true, + network: network ? Networks.get(network) : Networks.defaultNetwork + }; + + // detect type of data + if (_.isUndefined(data)){ + info.bn = PrivateKey._getRandomBN(); + } else if (data instanceof BN) { + info.bn = data; + } else if (data instanceof Buffer || data instanceof Uint8Array) { + info = PrivateKey._transformBuffer(data, network); + } else if (PrivateKey._isJSON(data)){ + info = PrivateKey._transformJSON(data); + } else if (typeof(data) === 'string'){ + if (JSUtil.isHexa(data)) { + info.bn = BN(new Buffer(data, 'hex')); + } else { + info = PrivateKey._transformWIF(data, network); + } + } else { + throw new TypeError('First argument is an unrecognized data type.'); + } + + // validation + if (!info.bn || info.bn.cmp(0) === 0){ + throw new TypeError('Number can not be equal to zero, undefined, null or false'); + } + if (!info.bn.lt(Point.getN())) { + throw new TypeError('Number must be less than N'); + } + if (typeof(info.network) === 'undefined') { + throw new TypeError('Must specify the network ("livenet" or "testnet")'); + } + + Object.defineProperty(this, 'bn', { + configurable: false, + value: info.bn + }); + + Object.defineProperty(this, 'compressed', { + configurable: false, + value: info.compressed + }); + + Object.defineProperty(this, 'network', { + configurable: false, + value: info.network + }); + + Object.defineProperty(this, 'publicKey', { + configurable: false, + get: this.toPublicKey.bind(this) + }); + + return this; + +}; + +/** + * Internal function to get a random BN + * + * @returns {BN} A new randomly generated BN + * @private + */ +PrivateKey._getRandomBN = function(){ + var condition; + var bn; + do { + var privbuf = Random.getRandomBuffer(32); + bn = BN().fromBuffer(privbuf); + condition = bn.lt(Point.getN()); + } while (!condition); + return bn; +}; + +/** + * Internal function to detect if a param is a JSON string or plain object + * + * @param {*} param - value to test + * @returns {boolean} + * @private + */ +PrivateKey._isJSON = function(json) { + return JSUtil.isValidJSON(json) || (json.bn && json.network && json.compressed); +}; + +/** + * Internal function to transform a WIF Buffer into a private key + * + * @param {Buffer} buf - An WIF string + * @param {String} [network] - Either "livenet" or "testnet" + * @returns {Object} An object with keys: bn, network and compressed + * @private + */ +PrivateKey._transformBuffer = function(buf, network) { + + var info = {}; + + if (buf.length === 1 + 32 + 1 && buf[1 + 32 + 1 - 1] === 1) { + info.compressed = true; + } else if (buf.length === 1 + 32) { + info.compressed = false; + } else { + throw new Error('Length of buffer must be 33 (uncompressed) or 34 (compressed)'); + } + + if (buf[0] === Networks.livenet.privatekey) { + info.network = Networks.livenet; + } else if (buf[0] === Networks.testnet.privatekey) { + info.network = Networks.testnet; + } else { + throw new Error('Invalid network'); + } + + if (network && info.network !== Networks.get(network)) { + throw new TypeError('Private key network mismatch'); + } + + info.bn = BN.fromBuffer(buf.slice(1, 32 + 1)); + + return info; + +}; + +/** + * Internal function to transform a WIF string into a private key + * + * @param {String} buf - An WIF string + * @returns {Object} An object with keys: bn, network and compressed + * @private + */ +PrivateKey._transformWIF = function(str, network) { + return PrivateKey._transformBuffer(base58check.decode(str), network); +}; + +/** + * Instantiate a PrivateKey from a JSON string + * + * @param {String} json - The JSON encoded private key string + * @returns {PrivateKey} A new valid instance of PrivateKey + */ +PrivateKey.fromJSON = function(json) { + if (!PrivateKey._isJSON(json)) { + throw new TypeError('Must be a valid JSON string or plain object'); + } + + return new PrivateKey(json); +}; + + +/** + * Internal function to transform a JSON string on plain object into a private key + * + * @param {String} json - A JSON string or plain object + * @returns {Object} An object with keys: bn, network and compressed + * @private + */ +PrivateKey._transformJSON = function(json) { + if (JSUtil.isValidJSON(json)) { + json = JSON.parse(json); + } + var bn = BN(json.bn, 'hex'); + return { + bn: bn, + network: json.network, + compressed: json.compressed + } +}; + +/** + * Instantiate a PrivateKey from a WIF string + * + * @param {String} str - The WIF encoded private key string + * @returns {PrivateKey} A new valid instance of PrivateKey + */ +PrivateKey.fromString = PrivateKey.fromWIF = function(str) { + return new PrivateKey(str); +}; + +/** + * Instantiate a PrivateKey from random bytes + * + * @param {String} [network] - Either "livenet" or "testnet" + * @returns {PrivateKey} A new valid instance of PrivateKey + */ +PrivateKey.fromRandom = function(network) { + var bn = PrivateKey._getRandomBN(); + return new PrivateKey(bn, network); +}; + +/** + * Check if there would be any errors when initializing a PrivateKey + * + * @param {String} data - The encoded data in various formats + * @param {String} [network] - Either "livenet" or "testnet" + * @returns {null|Error} An error if exists + */ + +PrivateKey.getValidationError = function(data, network) { + var error; + try { + new PrivateKey(data, network); + } catch (e) { + error = e; + } + return error; +}; + +/** + * Check if the parameters are valid + * + * @param {String} data - The encoded data in various formats + * @param {String} [network] - Either "livenet" or "testnet" + * @returns {Boolean} If the private key is would be valid + */ +PrivateKey.isValid = function(data, network){ + return !PrivateKey.getValidationError(data, network); +}; + +/** + * Will output the PrivateKey to a WIF string + * + * @returns {String} A WIP representation of the private key + */ +PrivateKey.prototype.toString = PrivateKey.prototype.toWIF = function() { + var network = this.network; + var compressed = this.compressed; + + var buf; + if (compressed) { + buf = Buffer.concat([new Buffer([network.privatekey]), + this.bn.toBuffer({size: 32}), + new Buffer([0x01])]); + } else { + buf = Buffer.concat([new Buffer([network.privatekey]), + this.bn.toBuffer({size: 32})]); + } + + return base58check.encode(buf); +}; + +/** + * Will return the private key as a BN instance + * + * @returns {BN} A BN instance of the private key + */ +PrivateKey.prototype.toBigNumber = function(){ + return this.bn; +}; + +/** + * Will return the private key as a BN buffer + * + * @returns {Buffer} A buffer of the private key + */ +PrivateKey.prototype.toBuffer = function(){ + return this.bn.toBuffer(); +}; + +/** + * Will return the corresponding public key + * + * @returns {PublicKey} A public key generated from the private key + */ +PrivateKey.prototype.toPublicKey = function(){ + if (!this._pubkey) { + this._pubkey = PublicKey.fromPrivateKey(this); + } + return this._pubkey; +}; + +/** + * Will return an address for the private key + * + * @returns {Address} An address generated from the private key + */ +PrivateKey.prototype.toAddress = function() { + var pubkey = this.toPublicKey(); + return Address.fromPublicKey(pubkey, this.network); +}; + +/** + * @returns {Object} A plain object representation + */ +PrivateKey.prototype.toObject = function toObject() { + return { + bn: this.bn.toString('hex'), + compressed: this.compressed, + network: this.network.toString() + }; +}; + +PrivateKey.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +/** + * Will return a string formatted for the console + * + * @returns {String} Private key + */ +PrivateKey.prototype.inspect = function() { + var uncompressed = !this.compressed ? ', uncompressed' : ''; + return ''; +}; + +module.exports = PrivateKey; + +}).call(this,require("buffer").Buffer) +},{"./address":2,"./crypto/bn":5,"./crypto/point":8,"./crypto/random":9,"./encoding/base58check":12,"./networks":20,"./publickey":29,"./util/js":49,"buffer":69,"lodash":233}],29:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var Address = require('./address'); +var BN = require('./crypto/bn'); +var Point = require('./crypto/point'); +var JSUtil = require('./util/js'); +var Network = require('./networks'); +var _ = require('lodash'); +var $ = require('./util/preconditions'); + +/** + * Instantiate a PublicKey from a 'PrivateKey', 'Point', 'string', 'Buffer'. + * + * @example + * + * // instantiate from a private key + * var key = PublicKey(privateKey, true); + * + * // export to as a DER hex encoded string + * var exported = key.toString(); + * + * // import the public key + * var imported = PublicKey.fromString(exported); + * + * @param {String} data - The encoded data in various formats + * @param {Object} extra - additional options + * @param {Network=} extra.network - Which network should the address for this public key be for + * @param {String=} extra.compressed - If the public key is compressed + * @returns {PublicKey} A new valid instance of an PublicKey + * @constructor + */ +var PublicKey = function PublicKey(data, extra) { + + if (!(this instanceof PublicKey)) { + return new PublicKey(data, extra); + } + + $.checkArgument(data, new TypeError('First argument is required, please include public key data.')); + + if (data instanceof PublicKey) { + // Return copy, but as it's an immutable object, return same argument + return data; + } + extra = extra || {}; + + var info = { + compressed: _.isUndefined(extra.compressed) || extra.compressed, + network: _.isUndefined(extra.network) ? undefined : Network.get(extra.network) + }; + + // detect type of data + if (data instanceof Point) { + info.point = data; + } else if (PublicKey._isJSON(data)) { + info = PublicKey._transformJSON(data); + } else if (typeof(data) === 'string') { + info = PublicKey._transformDER(new Buffer(data, 'hex')); + } else if (PublicKey._isBuffer(data)) { + info = PublicKey._transformDER(data); + } else if (PublicKey._isPrivateKey(data)) { + info = PublicKey._transformPrivateKey(data); + } else { + throw new TypeError('First argument is an unrecognized data format.'); + } + + // validation + info.point.validate(); + + Object.defineProperty(this, 'point', { + configurable: false, + value: info.point + }); + + Object.defineProperty(this, 'compressed', { + configurable: false, + value: info.compressed + }); + + Object.defineProperty(this, 'network', { + configurable: false, + value: info.network + }); + + return this; + +}; + +/** + * Internal function to detect if an object is a PrivateKey + * + * @param {*} param - object to test + * @returns {boolean} + * @private + */ +PublicKey._isPrivateKey = function(param) { + var PrivateKey = require('./privatekey'); + return param instanceof PrivateKey; +}; + +/** + * Internal function to detect if an object is a Buffer + * + * @param {*} param - object to test + * @returns {boolean} + * @private + */ +PublicKey._isBuffer = function(param) { + return (param instanceof Buffer) || (param instanceof Uint8Array); +}; + +/** + * Internal function to detect if a param is a JSON string or plain object + * + * @param {*} param - value to test + * @returns {boolean} + * @private + */ +PublicKey._isJSON = function(json) { + return JSUtil.isValidJSON(json) || (json.x && json.y); +}; + +/** + * Internal function to transform a private key into a public key point + * + * @param {PrivateKey} privkey - An instance of PrivateKey + * @returns {Object} An object with keys: point and compressed + * @private + */ +PublicKey._transformPrivateKey = function(privkey) { + $.checkArgument(PublicKey._isPrivateKey(privkey), + new TypeError('Must be an instance of PrivateKey')); + var info = {}; + info.point = Point.getG().mul(privkey.bn); + info.compressed = privkey.compressed; + info.network = privkey.network; + return info; +}; + +/** + * Internal function to transform DER into a public key point + * + * @param {Buffer} buf - An hex encoded buffer + * @param {bool} [strict] - if set to false, will loosen some conditions + * @returns {Object} An object with keys: point and compressed + * @private + */ +PublicKey._transformDER = function(buf, strict) { + $.checkArgument(PublicKey._isBuffer(buf), new TypeError('Must be a hex buffer of DER encoded public key')); + var info = {}; + + strict = _.isUndefined(strict) ? true : strict; + + var x; + var y; + var xbuf; + var ybuf; + + if (buf[0] === 0x04 || (!strict && (buf[0] === 0x06 || buf[0] === 0x07))) { + xbuf = buf.slice(1, 33); + ybuf = buf.slice(33, 65); + if (xbuf.length !== 32 || ybuf.length !== 32 || buf.length !== 65) { + throw new TypeError('Length of x and y must be 32 bytes'); + } + x = BN(xbuf); + y = BN(ybuf); + info.point = Point(x, y); + info.compressed = false; + } else if (buf[0] === 0x03) { + xbuf = buf.slice(1); + x = BN(xbuf); + info = PublicKey._transformX(true, x); + info.compressed = true; + } else if (buf[0] === 0x02) { + xbuf = buf.slice(1); + x = BN(xbuf); + info = PublicKey._transformX(false, x); + info.compressed = true; + } else { + throw new TypeError('Invalid DER format public key'); + } + return info; +}; + +/** + * Internal function to transform X into a public key point + * + * @param {Boolean} odd - If the point is above or below the x axis + * @param {Point} x - The x point + * @returns {Object} An object with keys: point and compressed + * @private + */ +PublicKey._transformX = function(odd, x) { + $.checkArgument(typeof odd === 'boolean', + new TypeError('Must specify whether y is odd or not (true or false)')); + var info = {}; + info.point = Point.fromX(odd, x); + return info; +}; + +/** + * Instantiate a PublicKey from JSON + * + * @param {String} json - A JSON string + * @returns {PublicKey} A new valid instance of PublicKey + */ +PublicKey.fromJSON = function(json) { + $.checkArgument(PublicKey._isJSON(json), + new TypeError('Must be a valid JSON string or plain object')); + return new PublicKey(json); +}; + +/** + * Internal function to transform a JSON into a public key point + * + * @param {Buffer} buf - a JSON string or plain object + * @returns {Object} An object with keys: point and compressed + * @private + */ +PublicKey._transformJSON = function(json) { + if (JSUtil.isValidJSON(json)) { + json = JSON.parse(json); + } + var x = BN(json.x, 'hex'); + var y = BN(json.y, 'hex'); + var point = new Point(x, y); + return new PublicKey(point, { + compressed: json.compressed + }); +}; + +/** + * Instantiate a PublicKey from a PrivateKey + * + * @param {PrivateKey} privkey - An instance of PrivateKey + * @returns {PublicKey} A new valid instance of PublicKey + */ +PublicKey.fromPrivateKey = function(privkey) { + $.checkArgument(PublicKey._isPrivateKey(privkey), new TypeError('Must be an instance of PrivateKey')); + var info = PublicKey._transformPrivateKey(privkey); + return new PublicKey(info.point, { + compressed: info.compressed, + network: info.network + }); +}; + +/** + * Instantiate a PublicKey from a Buffer + * @param {Buffer} buf - A DER hex buffer + * @param {bool} [strict] - if set to false, will loosen some conditions + * @returns {PublicKey} A new valid instance of PublicKey + */ +PublicKey.fromDER = PublicKey.fromBuffer = function(buf, strict) { + $.checkArgument(PublicKey._isBuffer(buf), + new TypeError('Must be a hex buffer of DER encoded public key')); + var info = PublicKey._transformDER(buf, strict); + return new PublicKey(info.point, { + compressed: info.compressed + }); +}; + +/** + * Instantiate a PublicKey from a Point + * + * @param {Point} point - A Point instance + * @param {boolean=} compressed - whether to store this public key as compressed format + * @returns {PublicKey} A new valid instance of PublicKey + */ +PublicKey.fromPoint = function(point, compressed) { + $.checkArgument(point instanceof Point, + new TypeError('First argument must be an instance of Point.')); + return new PublicKey(point, { + compressed: compressed + }); +}; + +/** + * Instantiate a PublicKey from a DER hex encoded string + * + * @param {String} str - A DER hex string + * @param {String} [encoding] - The type of string encoding + * @returns {PublicKey} A new valid instance of PublicKey + */ +PublicKey.fromString = function(str, encoding) { + var buf = new Buffer(str, encoding || 'hex'); + var info = PublicKey._transformDER(buf); + return new PublicKey(info.point, { + compressed: info.compressed + }); +}; + +/** + * Instantiate a PublicKey from an X Point + * + * @param {Boolean} odd - If the point is above or below the x axis + * @param {Point} x - The x point + * @returns {PublicKey} A new valid instance of PublicKey + */ +PublicKey.fromX = function(odd, x) { + var info = PublicKey._transformX(odd, x); + return new PublicKey(info.point, { + compressed: info.compressed + }); +}; + +/** + * Check if there would be any errors when initializing a PublicKey + * + * @param {String} data - The encoded data in various formats + * @param {String} [compressed] - If the public key is compressed + * @returns {null|Error} An error if exists + */ +PublicKey.getValidationError = function(data) { + var error; + try { + new PublicKey(data); + } catch (e) { + error = e; + } + return error; +}; + +/** + * Check if the parameters are valid + * + * @param {String} data - The encoded data in various formats + * @param {String} [compressed] - If the public key is compressed + * @returns {Boolean} If the public key would be valid + */ +PublicKey.isValid = function(data) { + return !PublicKey.getValidationError(data); +}; + +/** + * @returns {Object} A plain object of the PublicKey + */ +PublicKey.prototype.toObject = function toObject() { + return { + x: this.point.getX().toString('hex'), + y: this.point.getY().toString('hex'), + compressed: this.compressed + }; +}; + +PublicKey.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +/** + * Will output the PublicKey to a DER Buffer + * + * @returns {Buffer} A DER hex encoded buffer + */ +PublicKey.prototype.toBuffer = PublicKey.prototype.toDER = function() { + var x = this.point.getX(); + var y = this.point.getY(); + + var xbuf = x.toBuffer({ + size: 32 + }); + var ybuf = y.toBuffer({ + size: 32 + }); + + var prefix; + if (!this.compressed) { + prefix = new Buffer([0x04]); + return Buffer.concat([prefix, xbuf, ybuf]); + } else { + var odd = ybuf[ybuf.length - 1] % 2; + if (odd) { + prefix = new Buffer([0x03]); + } else { + prefix = new Buffer([0x02]); + } + return Buffer.concat([prefix, xbuf]); + } +}; + +/** + * Will return an address for the public key + * + * @returns {Address} An address generated from the public key + */ +PublicKey.prototype.toAddress = function(network) { + return Address.fromPublicKey(this, network || this.network); +}; + +/** + * Will output the PublicKey to a DER encoded hex string + * + * @returns {String} A DER hex encoded string + */ +PublicKey.prototype.toString = function() { + var compressed = _.isUndefined(this.compressed) || this.compressed; + return this.toDER(compressed).toString('hex'); +}; + +/** + * Will return a string formatted for the console + * + * @returns {String} Public key + */ +PublicKey.prototype.inspect = function() { + return ''; +}; + + +module.exports = PublicKey; + +}).call(this,require("buffer").Buffer) +},{"./address":2,"./crypto/bn":5,"./crypto/point":8,"./networks":20,"./privatekey":28,"./util/js":49,"./util/preconditions":50,"buffer":69,"lodash":233}],30:[function(require,module,exports){ +module.exports = require('./script'); + +module.exports.Interpreter = require('./interpreter'); + +},{"./interpreter":31,"./script":32}],31:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var _ = require('lodash'); + +var Script = require('./script'); +var Opcode = require('../opcode'); +var BN = require('../crypto/bn'); +var Hash = require('../crypto/hash'); +var BufferReader = require('../encoding/bufferreader'); +var BufferWriter = require('../encoding/bufferwriter'); +var Signature = require('../crypto/signature'); +var PublicKey = require('../publickey'); + +/** + * Bitcoin transactions contain scripts. Each input has a script called the + * scriptSig, and each output has a script called the scriptPubkey. To validate + * an input, the input's script is concatenated with the referenced output script, + * and the result is executed. If at the end of execution the stack contains a + * "true" value, then the transaction is valid. + * + * The primary way to use this class is via the verify function. + * e.g., Interpreter().verify( ... ); + */ +var Interpreter = function Interpreter(obj) { + if (!(this instanceof Interpreter)) { + return new Interpreter(obj); + } + if (obj) { + this.initialize(); + this.set(obj); + } else { + this.initialize(); + } +}; + +/** + * Verifies a Script by executing it and returns true if it is valid. + * This function needs to be provided with the scriptSig and the scriptPubkey + * separately. + * @param {Script} scriptSig - the script's first part (corresponding to the tx input) + * @param {Script} scriptPubkey - the script's last part (corresponding to the tx output) + * @param {Transaction} [tx] - the Transaction containing the scriptSig in one input (used + * to check signature validity for some opcodes like OP_CHECKSIG) + * @param {number} nin - index of the transaction input containing the scriptSig verified. + * @param {number} flags - evaluation flags. See Interpreter.SCRIPT_* constants + * + * Translated from bitcoind's VerifyScript + */ +Interpreter.prototype.verify = function(scriptSig, scriptPubkey, tx, nin, flags) { + var Transaction = require('../transaction'); + if (_.isUndefined(tx)) { + tx = new Transaction(); + } + if (_.isUndefined(nin)) { + nin = 0; + } + if (_.isUndefined(flags)) { + flags = 0; + } + this.set({ + script: scriptSig, + tx: tx, + nin: nin, + flags: flags + }); + var stackCopy; + + if ((flags & Interpreter.SCRIPT_VERIFY_SIGPUSHONLY) !== 0 && !scriptSig.isPushOnly()) { + this.errstr = 'SCRIPT_ERR_SIG_PUSHONLY'; + return false; + } + + // evaluate scriptSig + if (!this.evaluate()) { + return false; + } + + if (flags & Interpreter.SCRIPT_VERIFY_P2SH) { + stackCopy = this.stack.slice(); + } + + var stack = this.stack; + this.initialize(); + this.set({ + script: scriptPubkey, + stack: stack, + tx: tx, + nin: nin, + flags: flags + }); + + // evaluate scriptPubkey + if (!this.evaluate()) { + return false; + } + + if (this.stack.length === 0) { + this.errstr = 'SCRIPT_ERR_EVAL_FALSE_NO_RESULT'; + return false; + } + + var buf = this.stack[this.stack.length - 1]; + if (!Interpreter.castToBool(buf)) { + this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_STACK'; + return false; + } + + // Additional validation for spend-to-script-hash transactions: + if ((flags & Interpreter.SCRIPT_VERIFY_P2SH) && scriptPubkey.isScriptHashOut()) { + // scriptSig must be literals-only or validation fails + if (!scriptSig.isPushOnly()) { + this.errstr = 'SCRIPT_ERR_SIG_PUSHONLY'; + return false; + } + + // stackCopy cannot be empty here, because if it was the + // P2SH HASH <> EQUAL scriptPubKey would be evaluated with + // an empty stack and the EvalScript above would return false. + if (stackCopy.length === 0) { + throw new Error('internal error - stack copy empty'); + } + + var redeemScriptSerialized = stackCopy[stackCopy.length - 1]; + var redeemScript = Script.fromBuffer(redeemScriptSerialized); + stackCopy.pop(); + + this.initialize(); + this.set({ + script: redeemScript, + stack: stackCopy, + tx: tx, + nin: nin, + flags: flags + }); + + // evaluate redeemScript + if (!this.evaluate()) { + return false; + } + + if (stackCopy.length === 0) { + this.errstr = 'SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK'; + return false; + } + + if (!Interpreter.castToBool(stackCopy[stackCopy.length - 1])) { + this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK'; + return false; + } else { + return true; + } + } + + return true; +}; + +module.exports = Interpreter; + +Interpreter.prototype.initialize = function(obj) { + this.stack = []; + this.altstack = []; + this.pc = 0; + this.pbegincodehash = 0; + this.nOpCount = 0; + this.vfExec = []; + this.errstr = ''; + this.flags = 0; +}; + +Interpreter.prototype.set = function(obj) { + this.script = obj.script || this.script; + this.tx = obj.tx || this.tx; + this.nin = typeof obj.nin !== 'undefined' ? obj.nin : this.nin; + this.stack = obj.stack || this.stack; + this.altstack = obj.altack || this.altstack; + this.pc = typeof obj.pc !== 'undefined' ? obj.pc : this.pc; + this.pbegincodehash = typeof obj.pbegincodehash !== 'undefined' ? obj.pbegincodehash : this.pbegincodehash; + this.nOpCount = typeof obj.nOpCount !== 'undefined' ? obj.nOpCount : this.nOpCount; + this.vfExec = obj.vfExec || this.vfExec; + this.errstr = obj.errstr || this.errstr; + this.flags = typeof obj.flags !== 'undefined' ? obj.flags : this.flags; +}; + +Interpreter.true = new Buffer([1]); +Interpreter.false = new Buffer([]); + +Interpreter.MAX_SCRIPT_ELEMENT_SIZE = 520; + +// flags taken from bitcoind +// bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104 +Interpreter.SCRIPT_VERIFY_NONE = 0; + +// Evaluate P2SH subscripts (softfork safe, BIP16). +Interpreter.SCRIPT_VERIFY_P2SH = (1 << 0); + +// Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure. +// Passing a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) to checksig causes that pubkey to be +// skipped (not softfork safe: this flag can widen the validity of OP_CHECKSIG OP_NOT). +Interpreter.SCRIPT_VERIFY_STRICTENC = (1 << 1); + +// Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1) +Interpreter.SCRIPT_VERIFY_DERSIG = (1 << 2); + +// Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure +// (softfork safe, BIP62 rule 5). +Interpreter.SCRIPT_VERIFY_LOW_S = (1 << 3); + +// verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7). +Interpreter.SCRIPT_VERIFY_NULLDUMMY = (1 << 4); + +// Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2). +Interpreter.SCRIPT_VERIFY_SIGPUSHONLY = (1 << 5); + +// Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct +// pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating +// any other push causes the script to fail (BIP62 rule 3). +// In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4). +// (softfork safe) +Interpreter.SCRIPT_VERIFY_MINIMALDATA = (1 << 6); + +// Discourage use of NOPs reserved for upgrades (NOP1-10) +// +// Provided so that nodes can avoid accepting or mining transactions +// containing executed NOP's whose meaning may change after a soft-fork, +// thus rendering the script invalid; with this flag set executing +// discouraged NOPs fails the script. This verification flag will never be +// a mandatory flag applied to scripts in a block. NOPs that are not +// executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected. +Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1 << 7); + +Interpreter.castToBool = function(buf) { + for (var i = 0; i < buf.length; i++) { + if (buf[i] !== 0) { + // can be negative zero + if (i === buf.length - 1 && buf[i] === 0x80) { + return false; + } + return true; + } + } + return false; +}; + +/** + * Translated from bitcoind's CheckSignatureEncoding + */ +Interpreter.prototype.checkSignatureEncoding = function(buf) { + var sig; + if ((this.flags & (Interpreter.SCRIPT_VERIFY_DERSIG | Interpreter.SCRIPT_VERIFY_LOW_S | Interpreter.SCRIPT_VERIFY_STRICTENC)) !== 0 && !Signature.isTxDER(buf)) { + this.errstr = 'SCRIPT_ERR_SIG_DER_INVALID_FORMAT'; + return false; + } else if ((this.flags & Interpreter.SCRIPT_VERIFY_LOW_S) !== 0) { + sig = Signature.fromTxFormat(buf); + if (!sig.hasLowS()) { + this.errstr = 'SCRIPT_ERR_SIG_DER_HIGH_S'; + return false; + } + } else if ((this.flags & Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0) { + sig = Signature.fromTxFormat(buf); + if (!sig.hasDefinedHashtype()) { + this.errstr = 'SCRIPT_ERR_SIG_HASHTYPE'; + return false; + } + } + return true; +}; + +/** + * Translated from bitcoind's CheckPubKeyEncoding + */ +Interpreter.prototype.checkPubkeyEncoding = function(buf) { + if ((this.flags & Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0 && !PublicKey.isValid(buf)) { + this.errstr = 'SCRIPT_ERR_PUBKEYTYPE'; + return false; + } + return true; +}; + +/** + * Based on bitcoind's EvalScript function, with the inner loop moved to + * Interpreter.prototype.step() + * bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104 + */ +Interpreter.prototype.evaluate = function() { + if (this.script.toBuffer().length > 10000) { + this.errstr = 'SCRIPT_ERR_SCRIPT_SIZE'; + return false; + } + + try { + while (this.pc < this.script.chunks.length) { + var fSuccess = this.step(); + if (!fSuccess) { + return false; + } + } + + // Size limits + if (this.stack.length + this.altstack.length > 1000) { + this.errstr = 'SCRIPT_ERR_STACK_SIZE'; + return false; + } + } catch (e) { + this.errstr = 'SCRIPT_ERR_UNKNOWN_ERROR: ' + e; + return false; + } + + if (this.vfExec.length > 0) { + this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'; + return false; + } + + return true; +}; + +/** + * Based on the inner loop of bitcoind's EvalScript function + * bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104 + */ +Interpreter.prototype.step = function() { + + var fRequireMinimal = (this.flags & Interpreter.SCRIPT_VERIFY_MINIMALDATA) !== 0; + + //bool fExec = !count(vfExec.begin(), vfExec.end(), false); + var fExec = (this.vfExec.indexOf(false) === -1); + + + // Read instruction + var chunk = this.script.chunks[this.pc]; + this.pc++; + var opcodenum = chunk.opcodenum; + if (_.isUndefined(opcodenum)) { + this.errstr = 'SCRIPT_ERR_UNDEFINED_OPCODE'; + return false; + } + if (chunk.buf && chunk.buf.length > Interpreter.MAX_SCRIPT_ELEMENT_SIZE) { + this.errstr = 'SCRIPT_ERR_PUSH_SIZE'; + return false; + } + + // Note how Opcode.OP_RESERVED does not count towards the opcode limit. + if (opcodenum > Opcode.OP_16 && ++(this.nOpCount) > 201) { + this.errstr = 'SCRIPT_ERR_OP_COUNT'; + return false; + } + + + if (opcodenum === Opcode.OP_CAT || + opcodenum === Opcode.OP_SUBSTR || + opcodenum === Opcode.OP_LEFT || + opcodenum === Opcode.OP_RIGHT || + opcodenum === Opcode.OP_INVERT || + opcodenum === Opcode.OP_AND || + opcodenum === Opcode.OP_OR || + opcodenum === Opcode.OP_XOR || + opcodenum === Opcode.OP_2MUL || + opcodenum === Opcode.OP_2DIV || + opcodenum === Opcode.OP_MUL || + opcodenum === Opcode.OP_DIV || + opcodenum === Opcode.OP_MOD || + opcodenum === Opcode.OP_LSHIFT || + opcodenum === Opcode.OP_RSHIFT) { + this.errstr = 'SCRIPT_ERR_DISABLED_OPCODE'; + return false; + } + + if (fExec && 0 <= opcodenum && opcodenum <= Opcode.OP_PUSHDATA4) { + if (fRequireMinimal && !this.script.checkMinimalPush(this.pc - 1)) { + this.errstr = 'SCRIPT_ERR_MINIMALDATA'; + return false; + } + if (!chunk.buf) { + this.stack.push(Interpreter.false); + } else if (chunk.len !== chunk.buf.length) { + throw new Error('Length of push value not equal to length of data'); + } else { + this.stack.push(chunk.buf); + } + } else if (fExec || (Opcode.OP_IF <= opcodenum && opcodenum <= Opcode.OP_ENDIF)) { + switch (opcodenum) { + // Push value + case Opcode.OP_1NEGATE: + case Opcode.OP_1: + case Opcode.OP_2: + case Opcode.OP_3: + case Opcode.OP_4: + case Opcode.OP_5: + case Opcode.OP_6: + case Opcode.OP_7: + case Opcode.OP_8: + case Opcode.OP_9: + case Opcode.OP_10: + case Opcode.OP_11: + case Opcode.OP_12: + case Opcode.OP_13: + case Opcode.OP_14: + case Opcode.OP_15: + case Opcode.OP_16: + { + // ( -- value) + // ScriptNum bn((int)opcode - (int)(Opcode.OP_1 - 1)); + var n = opcodenum - (Opcode.OP_1 - 1); + var buf = BN(n).toScriptNumBuffer(); + this.stack.push(buf); + // The result of these opcodes should always be the minimal way to push the data + // they push, so no need for a CheckMinimalPush here. + } + break; + + + // + // Control + // + case Opcode.OP_NOP: + break; + + case Opcode.OP_NOP1: + case Opcode.OP_NOP2: + case Opcode.OP_NOP3: + case Opcode.OP_NOP4: + case Opcode.OP_NOP5: + case Opcode.OP_NOP6: + case Opcode.OP_NOP7: + case Opcode.OP_NOP8: + case Opcode.OP_NOP9: + case Opcode.OP_NOP10: + { + if (this.flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) { + this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS'; + return false; + } + } + break; + + case Opcode.OP_IF: + case Opcode.OP_NOTIF: + { + // if [statements] [else [statements]] endif + // bool fValue = false; + var fValue = false; + if (fExec) { + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'; + return false; + } + var buf = this.stack.pop(); + fValue = Interpreter.castToBool(buf); + if (opcodenum === Opcode.OP_NOTIF) + fValue = !fValue; + } + this.vfExec.push(fValue); + } + break; + + case Opcode.OP_ELSE: + { + if (this.vfExec.length === 0) { + this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'; + return false; + } + this.vfExec[this.vfExec.length - 1] = !this.vfExec[this.vfExec.length - 1]; + } + break; + + case Opcode.OP_ENDIF: + { + if (this.vfExec.length === 0) { + this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'; + return false; + } + this.vfExec.pop(); + } + break; + + case Opcode.OP_VERIFY: + { + // (true -- ) or + // (false -- false) and return + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf = this.stack[this.stack.length - 1]; + var fValue = Interpreter.castToBool(buf); + if (fValue) + this.stack.pop(); + else { + this.errstr = 'SCRIPT_ERR_VERIFY'; + return false; + } + } + break; + + case Opcode.OP_RETURN: + { + this.errstr = 'SCRIPT_ERR_OP_RETURN'; + return false; + } + break; + + + // + // Stack ops + // + case Opcode.OP_TOALTSTACK: + { + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + this.altstack.push(this.stack.pop()); + } + break; + + case Opcode.OP_FROMALTSTACK: + { + if (this.altstack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_ALTSTACK_OPERATION'; + return false; + } + this.stack.push(this.altstack.pop()); + } + break; + + case Opcode.OP_2DROP: + { + // (x1 x2 -- ) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + this.stack.pop(); + this.stack.pop(); + } + break; + + case Opcode.OP_2DUP: + { + // (x1 x2 -- x1 x2 x1 x2) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf1 = this.stack[this.stack.length - 2]; + var buf2 = this.stack[this.stack.length - 1]; + this.stack.push(buf1); + this.stack.push(buf2); + } + break; + + case Opcode.OP_3DUP: + { + // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3) + if (this.stack.length < 3) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf1 = this.stack[this.stack.length - 3]; + var buf2 = this.stack[this.stack.length - 2]; + var buf3 = this.stack[this.stack.length - 1]; + this.stack.push(buf1); + this.stack.push(buf2); + this.stack.push(buf3); + } + break; + + case Opcode.OP_2OVER: + { + // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2) + if (this.stack.length < 4) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf1 = this.stack[this.stack.length - 4]; + var buf2 = this.stack[this.stack.length - 3]; + this.stack.push(buf1); + this.stack.push(buf2); + } + break; + + case Opcode.OP_2ROT: + { + // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2) + if (this.stack.length < 6) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var spliced = this.stack.splice(this.stack.length - 6, 2); + this.stack.push(spliced[0]); + this.stack.push(spliced[1]); + } + break; + + case Opcode.OP_2SWAP: + { + // (x1 x2 x3 x4 -- x3 x4 x1 x2) + if (this.stack.length < 4) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var spliced = this.stack.splice(this.stack.length - 4, 2); + this.stack.push(spliced[0]); + this.stack.push(spliced[1]); + } + break; + + case Opcode.OP_IFDUP: + { + // (x - 0 | x x) + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf = this.stack[this.stack.length - 1]; + var fValue = Interpreter.castToBool(buf); + if (fValue) + this.stack.push(buf); + } + break; + + case Opcode.OP_DEPTH: + { + // -- stacksize + var buf = BN(this.stack.length).toScriptNumBuffer(); + this.stack.push(buf); + } + break; + + case Opcode.OP_DROP: + { + // (x -- ) + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + this.stack.pop(); + } + break; + + case Opcode.OP_DUP: + { + // (x -- x x) + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + this.stack.push(this.stack[this.stack.length - 1]); + } + break; + + case Opcode.OP_NIP: + { + // (x1 x2 -- x2) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + this.stack.splice(this.stack.length - 2, 1); + } + break; + + case Opcode.OP_OVER: + { + // (x1 x2 -- x1 x2 x1) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + this.stack.push(this.stack[this.stack.length - 2]); + } + break; + + case Opcode.OP_PICK: + case Opcode.OP_ROLL: + { + // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn) + // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf = this.stack[this.stack.length - 1]; + var bn = BN().fromScriptNumBuffer(buf, fRequireMinimal); + var n = bn.toNumber(); + this.stack.pop(); + if (n < 0 || n >= this.stack.length) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf = this.stack[this.stack.length - n - 1]; + if (opcodenum === Opcode.OP_ROLL) + this.stack.splice(this.stack.length - n - 1, 1); + this.stack.push(buf); + } + break; + + case Opcode.OP_ROT: + { + // (x1 x2 x3 -- x2 x3 x1) + // x2 x1 x3 after first swap + // x2 x3 x1 after second swap + if (this.stack.length < 3) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var x1 = this.stack[this.stack.length - 3]; + var x2 = this.stack[this.stack.length - 2]; + var x3 = this.stack[this.stack.length - 1]; + this.stack[this.stack.length - 3] = x2; + this.stack[this.stack.length - 2] = x3; + this.stack[this.stack.length - 1] = x1; + } + break; + + case Opcode.OP_SWAP: + { + // (x1 x2 -- x2 x1) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var x1 = this.stack[this.stack.length - 2]; + var x2 = this.stack[this.stack.length - 1]; + this.stack[this.stack.length - 2] = x2; + this.stack[this.stack.length - 1] = x1; + } + break; + + case Opcode.OP_TUCK: + { + // (x1 x2 -- x2 x1 x2) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + this.stack.splice(this.stack.length - 2, 0, this.stack[this.stack.length - 1]); + } + break; + + + case Opcode.OP_SIZE: + { + // (in -- in size) + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var bn = BN(this.stack[this.stack.length - 1].length); + this.stack.push(bn.toScriptNumBuffer()); + } + break; + + + // + // Bitwise logic + // + case Opcode.OP_EQUAL: + case Opcode.OP_EQUALVERIFY: + //case Opcode.OP_NOTEQUAL: // use Opcode.OP_NUMNOTEQUAL + { + // (x1 x2 - bool) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf1 = this.stack[this.stack.length - 2]; + var buf2 = this.stack[this.stack.length - 1]; + var fEqual = buf1.toString('hex') === buf2.toString('hex'); + // Opcode.OP_NOTEQUAL is disabled because it would be too easy to say + // something like n != 1 and have some wiseguy pass in 1 with extra + // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001) + //if (opcode == Opcode.OP_NOTEQUAL) + // fEqual = !fEqual; + this.stack.pop(); + this.stack.pop(); + this.stack.push(fEqual ? Interpreter.true : Interpreter.false); + if (opcodenum === Opcode.OP_EQUALVERIFY) { + if (fEqual) + this.stack.pop(); + else { + this.errstr = 'SCRIPT_ERR_EQUALVERIFY'; + return false; + } + } + } + break; + + + // + // Numeric + // + case Opcode.OP_1ADD: + case Opcode.OP_1SUB: + case Opcode.OP_NEGATE: + case Opcode.OP_ABS: + case Opcode.OP_NOT: + case Opcode.OP_0NOTEQUAL: + { + // (in -- out) + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf = this.stack[this.stack.length - 1]; + var bn = BN().fromScriptNumBuffer(buf, fRequireMinimal); + switch (opcodenum) { + case Opcode.OP_1ADD: + bn = bn.add(1); + break; + case Opcode.OP_1SUB: + bn = bn.sub(1); + break; + case Opcode.OP_NEGATE: + bn = bn.neg(); + break; + case Opcode.OP_ABS: + if (bn.cmp(0) < 0) bn = bn.neg(); + break; + case Opcode.OP_NOT: + bn = BN((bn.cmp(0) === 0) + 0); + break; + case Opcode.OP_0NOTEQUAL: + bn = BN((bn.cmp(0) !== 0) + 0); + break; + //default: assert(!'invalid opcode'); break; // TODO: does this ever occur? + } + this.stack.pop(); + this.stack.push(bn.toScriptNumBuffer()); + } + break; + + case Opcode.OP_ADD: + case Opcode.OP_SUB: + case Opcode.OP_BOOLAND: + case Opcode.OP_BOOLOR: + case Opcode.OP_NUMEQUAL: + case Opcode.OP_NUMEQUALVERIFY: + case Opcode.OP_NUMNOTEQUAL: + case Opcode.OP_LESSTHAN: + case Opcode.OP_GREATERTHAN: + case Opcode.OP_LESSTHANOREQUAL: + case Opcode.OP_GREATERTHANOREQUAL: + case Opcode.OP_MIN: + case Opcode.OP_MAX: + { + // (x1 x2 -- out) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var bn1 = BN().fromScriptNumBuffer(this.stack[this.stack.length - 2], fRequireMinimal); + var bn2 = BN().fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal); + var bn = BN(0); + + switch (opcodenum) { + case Opcode.OP_ADD: + bn = bn1.add(bn2); + break; + + case Opcode.OP_SUB: + bn = bn1.sub(bn2); + break; + + // case Opcode.OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break; + case Opcode.OP_BOOLAND: + bn = BN(((bn1.cmp(0) !== 0) && (bn2.cmp(0) !== 0)) + 0); + break; + // case Opcode.OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break; + case Opcode.OP_BOOLOR: + bn = BN(((bn1.cmp(0) !== 0) || (bn2.cmp(0) !== 0)) + 0); + break; + // case Opcode.OP_NUMEQUAL: bn = (bn1 == bn2); break; + case Opcode.OP_NUMEQUAL: + bn = BN((bn1.cmp(bn2) === 0) + 0); + break; + // case Opcode.OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break; + case Opcode.OP_NUMEQUALVERIFY: + bn = BN((bn1.cmp(bn2) === 0) + 0); + break; + // case Opcode.OP_NUMNOTEQUAL: bn = (bn1 != bn2); break; + case Opcode.OP_NUMNOTEQUAL: + bn = BN((bn1.cmp(bn2) !== 0) + 0); + break; + // case Opcode.OP_LESSTHAN: bn = (bn1 < bn2); break; + case Opcode.OP_LESSTHAN: + bn = BN((bn1.cmp(bn2) < 0) + 0); + break; + // case Opcode.OP_GREATERTHAN: bn = (bn1 > bn2); break; + case Opcode.OP_GREATERTHAN: + bn = BN((bn1.cmp(bn2) > 0) + 0); + break; + // case Opcode.OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break; + case Opcode.OP_LESSTHANOREQUAL: + bn = BN((bn1.cmp(bn2) <= 0) + 0); + break; + // case Opcode.OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break; + case Opcode.OP_GREATERTHANOREQUAL: + bn = BN((bn1.cmp(bn2) >= 0) + 0); + break; + case Opcode.OP_MIN: + bn = (bn1.cmp(bn2) < 0 ? bn1 : bn2); + break; + case Opcode.OP_MAX: + bn = (bn1.cmp(bn2) > 0 ? bn1 : bn2); + break; + // default: assert(!'invalid opcode'); break; //TODO: does this ever occur? + } + this.stack.pop(); + this.stack.pop(); + this.stack.push(bn.toScriptNumBuffer()); + + if (opcodenum === Opcode.OP_NUMEQUALVERIFY) { + // if (CastToBool(stacktop(-1))) + if (Interpreter.castToBool(this.stack[this.stack.length - 1])) + this.stack.pop(); + else { + this.errstr = 'SCRIPT_ERR_NUMEQUALVERIFY'; + return false; + } + } + } + break; + + case Opcode.OP_WITHIN: + { + // (x min max -- out) + if (this.stack.length < 3) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var bn1 = BN().fromScriptNumBuffer(this.stack[this.stack.length - 3], fRequireMinimal); + var bn2 = BN().fromScriptNumBuffer(this.stack[this.stack.length - 2], fRequireMinimal); + var bn3 = BN().fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal); + //bool fValue = (bn2 <= bn1 && bn1 < bn3); + var fValue = (bn2.cmp(bn1) <= 0) && (bn1.cmp(bn3) < 0); + this.stack.pop(); + this.stack.pop(); + this.stack.pop(); + this.stack.push(fValue ? Interpreter.true : Interpreter.false); + } + break; + + + // + // Crypto + // + case Opcode.OP_RIPEMD160: + case Opcode.OP_SHA1: + case Opcode.OP_SHA256: + case Opcode.OP_HASH160: + case Opcode.OP_HASH256: + { + // (in -- hash) + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + var buf = this.stack[this.stack.length - 1]; + //valtype vchHash((opcode == Opcode.OP_RIPEMD160 || opcode == Opcode.OP_SHA1 || opcode == Opcode.OP_HASH160) ? 20 : 32); + var bufHash; + if (opcodenum === Opcode.OP_RIPEMD160) + bufHash = Hash.ripemd160(buf); + else if (opcodenum === Opcode.OP_SHA1) + bufHash = Hash.sha1(buf); + else if (opcodenum === Opcode.OP_SHA256) + bufHash = Hash.sha256(buf); + else if (opcodenum === Opcode.OP_HASH160) + bufHash = Hash.sha256ripemd160(buf); + else if (opcodenum === Opcode.OP_HASH256) + bufHash = Hash.sha256sha256(buf); + this.stack.pop(); + this.stack.push(bufHash); + } + break; + + case Opcode.OP_CODESEPARATOR: + { + // Hash starts after the code separator + this.pbegincodehash = this.pc; + } + break; + + case Opcode.OP_CHECKSIG: + case Opcode.OP_CHECKSIGVERIFY: + { + // (sig pubkey -- bool) + if (this.stack.length < 2) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + + var bufSig = this.stack[this.stack.length - 2]; + var bufPubkey = this.stack[this.stack.length - 1]; + + // Subset of script starting at the most recent codeseparator + // CScript scriptCode(pbegincodehash, pend); + var subscript = Script().set({ + chunks: this.script.chunks.slice(this.pbegincodehash) + }); + + // Drop the signature, since there's no way for a signature to sign itself + var tmpScript = Script().add(bufSig); + subscript.findAndDelete(tmpScript); + + if (!this.checkSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) { + return false; + } + + var fSuccess; + try { + var sig = Signature.fromTxFormat(bufSig); + var pubkey = PublicKey.fromBuffer(bufPubkey, false); + fSuccess = this.tx.verifySignature(sig, pubkey, this.nin, subscript); + } catch (e) { + //invalid sig or pubkey + fSuccess = false; + } + + this.stack.pop(); + this.stack.pop(); + // stack.push_back(fSuccess ? vchTrue : vchFalse); + this.stack.push(fSuccess ? Interpreter.true : Interpreter.false); + if (opcodenum === Opcode.OP_CHECKSIGVERIFY) { + if (fSuccess) { + this.stack.pop(); + } else { + this.errstr = 'SCRIPT_ERR_CHECKSIGVERIFY'; + return false; + } + } + } + break; + + case Opcode.OP_CHECKMULTISIG: + case Opcode.OP_CHECKMULTISIGVERIFY: + { + // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool) + + var i = 1; + if (this.stack.length < i) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + + var nKeysCount = BN().fromScriptNumBuffer(this.stack[this.stack.length - i], fRequireMinimal).toNumber(); + if (nKeysCount < 0 || nKeysCount > 20) { + this.errstr = 'SCRIPT_ERR_PUBKEY_COUNT'; + return false; + } + this.nOpCount += nKeysCount; + if (this.nOpCount > 201) { + this.errstr = 'SCRIPT_ERR_OP_COUNT'; + return false; + } + // int ikey = ++i; + var ikey = ++i; + i += nKeysCount; + if (this.stack.length < i) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + + var nSigsCount = BN().fromScriptNumBuffer(this.stack[this.stack.length - i], fRequireMinimal).toNumber(); + if (nSigsCount < 0 || nSigsCount > nKeysCount) { + this.errstr = 'SCRIPT_ERR_SIG_COUNT'; + return false; + } + // int isig = ++i; + var isig = ++i; + i += nSigsCount; + if (this.stack.length < i) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + + // Subset of script starting at the most recent codeseparator + var subscript = Script().set({ + chunks: this.script.chunks.slice(this.pbegincodehash) + }); + + // Drop the signatures, since there's no way for a signature to sign itself + for (var k = 0; k < nSigsCount; k++) { + var bufSig = this.stack[this.stack.length - isig - k]; + subscript.findAndDelete(Script().add(bufSig)); + } + + var fSuccess = true; + while (fSuccess && nSigsCount > 0) { + // valtype& vchSig = stacktop(-isig); + var bufSig = this.stack[this.stack.length - isig]; + // valtype& vchPubKey = stacktop(-ikey); + var bufPubkey = this.stack[this.stack.length - ikey]; + + if (!this.checkSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) { + return false; + } + + var fOk; + try { + var sig = Signature.fromTxFormat(bufSig); + var pubkey = PublicKey.fromBuffer(bufPubkey, false); + fOk = this.tx.verifySignature(sig, pubkey, this.nin, subscript); + } catch (e) { + //invalid sig or pubkey + fOk = false; + } + + if (fOk) { + isig++; + nSigsCount--; + } + ikey++; + nKeysCount--; + + // If there are more signatures left than keys left, + // then too many signatures have failed + if (nSigsCount > nKeysCount) { + fSuccess = false; + } + } + + // Clean up stack of actual arguments + while (i-- > 1) { + this.stack.pop(); + } + + // A bug causes CHECKMULTISIG to consume one extra argument + // whose contents were not checked in any way. + // + // Unfortunately this is a potential source of mutability, + // so optionally verify it is exactly equal to zero prior + // to removing it from the stack. + if (this.stack.length < 1) { + this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; + return false; + } + if ((this.flags & Interpreter.SCRIPT_VERIFY_NULLDUMMY) && this.stack[this.stack.length - 1].length) { + this.errstr = 'SCRIPT_ERR_SIG_NULLDUMMY'; + return false; + } + this.stack.pop(); + + this.stack.push(fSuccess ? Interpreter.true : Interpreter.false); + + if (opcodenum === Opcode.OP_CHECKMULTISIGVERIFY) { + if (fSuccess) + this.stack.pop(); + else { + this.errstr = 'SCRIPT_ERR_CHECKMULTISIGVERIFY'; + return false; + } + } + } + break; + + default: + this.errstr = 'SCRIPT_ERR_BAD_OPCODE'; + return false; + } + } + + return true; +}; + + +}).call(this,require("buffer").Buffer) +},{"../crypto/bn":5,"../crypto/hash":7,"../crypto/signature":10,"../encoding/bufferreader":13,"../encoding/bufferwriter":14,"../opcode":21,"../publickey":29,"../transaction":33,"./script":32,"buffer":69,"lodash":233}],32:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + + +var Address = require('../address'); +var BufferReader = require('../encoding/bufferreader'); +var BufferWriter = require('../encoding/bufferwriter'); +var Hash = require('../crypto/hash'); +var Opcode = require('../opcode'); +var PublicKey = require('../publickey'); +var Signature = require('../crypto/signature'); + +var $ = require('../util/preconditions'); +var _ = require('lodash'); +var errors = require('../errors'); +var buffer = require('buffer'); +var BufferUtil = require('../util/buffer'); +var JSUtil = require('../util/js'); + +/** + * A bitcoin transaction script. Each transaction's inputs and outputs + * has a script that is evaluated to validate it's spending. + * + * See https://en.bitcoin.it/wiki/Script + * + * @constructor + * @param {Object|string|Buffer} [from] optional data to populate script + */ +var Script = function Script(from) { + if (!(this instanceof Script)) { + return new Script(from); + } + + this.chunks = []; + + if (BufferUtil.isBuffer(from)) { + return Script.fromBuffer(from); + } else if (from instanceof Address) { + return Script.fromAddress(from); + } else if (from instanceof Script) { + return Script.fromBuffer(from.toBuffer()); + } else if (typeof from === 'string') { + return Script.fromString(from); + } else if (typeof from !== 'undefined') { + this.set(from); + } +}; + +Script.prototype.set = function(obj) { + this.chunks = obj.chunks || this.chunks; + return this; +}; + +Script.fromBuffer = function(buffer) { + var script = new Script(); + script.chunks = []; + + var br = new BufferReader(buffer); + while (!br.eof()) { + var opcodenum = br.readUInt8(); + + var len, buf; + if (opcodenum > 0 && opcodenum < Opcode.OP_PUSHDATA1) { + len = opcodenum; + script.chunks.push({ + buf: br.read(len), + len: len, + opcodenum: opcodenum + }); + } else if (opcodenum === Opcode.OP_PUSHDATA1) { + len = br.readUInt8(); + buf = br.read(len); + script.chunks.push({ + buf: buf, + len: len, + opcodenum: opcodenum + }); + } else if (opcodenum === Opcode.OP_PUSHDATA2) { + len = br.readUInt16LE(); + buf = br.read(len); + script.chunks.push({ + buf: buf, + len: len, + opcodenum: opcodenum + }); + } else if (opcodenum === Opcode.OP_PUSHDATA4) { + len = br.readUInt32LE(); + buf = br.read(len); + script.chunks.push({ + buf: buf, + len: len, + opcodenum: opcodenum + }); + } else { + script.chunks.push({ + opcodenum: opcodenum + }); + } + } + + return script; +}; + +Script.prototype.toBuffer = function() { + var bw = new BufferWriter(); + + for (var i = 0; i < this.chunks.length; i++) { + var chunk = this.chunks[i]; + var opcodenum = chunk.opcodenum; + bw.writeUInt8(chunk.opcodenum); + if (chunk.buf) { + if (opcodenum < Opcode.OP_PUSHDATA1) { + bw.write(chunk.buf); + } else if (opcodenum === Opcode.OP_PUSHDATA1) { + bw.writeUInt8(chunk.len); + bw.write(chunk.buf); + } else if (opcodenum === Opcode.OP_PUSHDATA2) { + bw.writeUInt16LE(chunk.len); + bw.write(chunk.buf); + } else if (opcodenum === Opcode.OP_PUSHDATA4) { + bw.writeUInt32LE(chunk.len); + bw.write(chunk.buf); + } + } + } + + return bw.concat(); +}; + +Script.fromString = function(str) { + if (JSUtil.isHexa(str) || str.length === 0) { + return new Script(new buffer.Buffer(str, 'hex')); + } + var script = new Script(); + script.chunks = []; + + var tokens = str.split(' '); + var i = 0; + while (i < tokens.length) { + var token = tokens[i]; + var opcode = Opcode(token); + var opcodenum = opcode.toNumber(); + + if (_.isUndefined(opcodenum)) { + opcodenum = parseInt(token); + if (opcodenum > 0 && opcodenum < Opcode.OP_PUSHDATA1) { + script.chunks.push({ + buf: new Buffer(tokens[i + 1].slice(2), 'hex'), + len: opcodenum, + opcodenum: opcodenum + }); + i = i + 2; + } else { + throw new Error('Invalid script: ' + JSON.stringify(str)); + } + } else if (opcodenum === Opcode.OP_PUSHDATA1 || + opcodenum === Opcode.OP_PUSHDATA2 || + opcodenum === Opcode.OP_PUSHDATA4) { + if (tokens[i + 2].slice(0, 2) !== '0x') { + throw new Error('Pushdata data must start with 0x'); + } + script.chunks.push({ + buf: new Buffer(tokens[i + 2].slice(2), 'hex'), + len: parseInt(tokens[i + 1]), + opcodenum: opcodenum + }); + i = i + 3; + } else { + script.chunks.push({ + opcodenum: opcodenum + }); + i = i + 1; + } + } + return script; +}; + +Script.prototype.toString = function() { + var str = ''; + + for (var i = 0; i < this.chunks.length; i++) { + var chunk = this.chunks[i]; + var opcodenum = chunk.opcodenum; + if (!chunk.buf) { + if (typeof Opcode.reverseMap[opcodenum] !== 'undefined') { + str = str + ' ' + Opcode(opcodenum).toString(); + } else { + var numstr = opcodenum.toString(16); + if (numstr.length % 2 !== 0) { + numstr = '0' + numstr; + } + str = str + ' ' + '0x' + numstr; + } + } else { + if (opcodenum === Opcode.OP_PUSHDATA1 || + opcodenum === Opcode.OP_PUSHDATA2 || + opcodenum === Opcode.OP_PUSHDATA4) { + str = str + ' ' + Opcode(opcodenum).toString(); + } + str = str + ' ' + chunk.len; + if (chunk.len > 0) { + str = str + ' ' + '0x' + chunk.buf.toString('hex'); + } + } + } + + return str.substr(1); +}; + +Script.prototype.inspect = function() { + return ''; +}; + +// script classification methods + +/** + * @returns true if this is a pay to pubkey hash output script + */ +Script.prototype.isPublicKeyHashOut = function() { + return !!(this.chunks.length === 5 && + this.chunks[0].opcodenum === Opcode.OP_DUP && + this.chunks[1].opcodenum === Opcode.OP_HASH160 && + this.chunks[2].buf && + this.chunks[3].opcodenum === Opcode.OP_EQUALVERIFY && + this.chunks[4].opcodenum === Opcode.OP_CHECKSIG); +}; + +/** + * @returns true if this is a pay to public key hash input script + */ +Script.prototype.isPublicKeyHashIn = function() { + return this.chunks.length === 2 && + this.chunks[0].buf && + this.chunks[0].buf.length >= 0x47 && + this.chunks[0].buf.length <= 0x49 && + PublicKey.isValid(this.chunks[1].buf); +}; + +Script.prototype.getPublicKeyHash = function() { + $.checkState(this.isPublicKeyHashOut(), 'Can\'t retrieve PublicKeyHash from a non-PKH output'); + return this.chunks[2].buf; +}; + +/** + * @returns true if this is a public key output script + */ +Script.prototype.isPublicKeyOut = function() { + return this.chunks.length === 2 && + BufferUtil.isBuffer(this.chunks[0].buf) && + PublicKey.isValid(this.chunks[0].buf) && + this.chunks[1].opcodenum === Opcode.OP_CHECKSIG; +}; + +/** + * @returns true if this is a pay to public key input script + */ +Script.prototype.isPublicKeyIn = function() { + return this.chunks.length === 1 && + BufferUtil.isBuffer(this.chunks[0].buf) && + this.chunks[0].buf.length === 0x47; +}; + + +/** + * @returns true if this is a p2sh output script + */ +Script.prototype.isScriptHashOut = function() { + var buf = this.toBuffer(); + return (buf.length === 23 && + buf[0] === Opcode.OP_HASH160 && + buf[1] === 0x14 && + buf[buf.length - 1] === Opcode.OP_EQUAL); +}; + +/** + * @returns true if this is a p2sh input script + * Note that these are frequently indistinguishable from pubkeyhashin + */ +Script.prototype.isScriptHashIn = function() { + if (this.chunks.length === 0) { + return false; + } + var chunk = this.chunks[this.chunks.length - 1]; + if (!chunk) { + return false; + } + var scriptBuf = chunk.buf; + if (!scriptBuf) { + return false; + } + var redeemScript = new Script(scriptBuf); + var type = redeemScript.classify(); + return type !== Script.types.UNKNOWN; +}; + +/** + * @returns true if this is a mutlsig output script + */ +Script.prototype.isMultisigOut = function() { + return (this.chunks.length > 3 && + Opcode.isSmallIntOp(this.chunks[0].opcodenum) && + this.chunks.slice(1, this.chunks.length - 2).every(function(obj) { + return obj.buf && BufferUtil.isBuffer(obj.buf); + }) && + Opcode.isSmallIntOp(this.chunks[this.chunks.length - 2].opcodenum) && + this.chunks[this.chunks.length - 1].opcodenum === Opcode.OP_CHECKMULTISIG); +}; + + +/** + * @returns true if this is a multisig input script + */ +Script.prototype.isMultisigIn = function() { + return this.chunks.length >= 2 && + this.chunks[0].opcodenum === 0 && + this.chunks.slice(1, this.chunks.length).every(function(obj) { + return obj.buf && + BufferUtil.isBuffer(obj.buf) && + obj.buf.length === 0x47; + }); +}; + +/** + * @returns true if this is an OP_RETURN data script + */ +Script.prototype.isDataOut = function() { + return this.chunks.length >= 1 && + this.chunks[0].opcodenum === Opcode.OP_RETURN && + (this.chunks.length === 1 || + (this.chunks.length === 2 && + this.chunks[1].buf && + this.chunks[1].buf.length <= 40 && + this.chunks[1].length === this.chunks.len)); +}; + +/** + * @returns true if the script is only composed of data pushing + * opcodes or small int opcodes (OP_0, OP_1, ..., OP_16) + */ +Script.prototype.isPushOnly = function() { + return _.every(this.chunks, function(chunk) { + return chunk.opcodenum <= Opcode.OP_16; + }); +}; + + +Script.types = {}; +Script.types.UNKNOWN = 'Unknown'; +Script.types.PUBKEY_OUT = 'Pay to public key'; +Script.types.PUBKEY_IN = 'Spend from public key'; +Script.types.PUBKEYHASH_OUT = 'Pay to public key hash'; +Script.types.PUBKEYHASH_IN = 'Spend from public key hash'; +Script.types.SCRIPTHASH_OUT = 'Pay to script hash'; +Script.types.SCRIPTHASH_IN = 'Spend from script hash'; +Script.types.MULTISIG_OUT = 'Pay to multisig'; +Script.types.MULTISIG_IN = 'Spend from multisig'; +Script.types.DATA_OUT = 'Data push'; + +Script.identifiers = {}; +Script.identifiers.PUBKEY_OUT = Script.prototype.isPublicKeyOut; +Script.identifiers.PUBKEY_IN = Script.prototype.isPublicKeyIn; +Script.identifiers.PUBKEYHASH_OUT = Script.prototype.isPublicKeyHashOut; +Script.identifiers.PUBKEYHASH_IN = Script.prototype.isPublicKeyHashIn; +Script.identifiers.MULTISIG_OUT = Script.prototype.isMultisigOut; +Script.identifiers.MULTISIG_IN = Script.prototype.isMultisigIn; +Script.identifiers.SCRIPTHASH_OUT = Script.prototype.isScriptHashOut; +Script.identifiers.SCRIPTHASH_IN = Script.prototype.isScriptHashIn; +Script.identifiers.DATA_OUT = Script.prototype.isDataOut; + +/** + * @returns {object} The Script type if it is a known form, + * or Script.UNKNOWN if it isn't + */ +Script.prototype.classify = function() { + for (var type in Script.identifiers) { + if (Script.identifiers[type].bind(this)()) { + return Script.types[type]; + } + } + return Script.types.UNKNOWN; +}; + + +/** + * @returns true if script is one of the known types + */ +Script.prototype.isStandard = function() { + // TODO: Add BIP62 compliance + return this.classify() !== Script.types.UNKNOWN; +}; + + +// Script construction methods + +/** + * Adds a script element at the start of the script. + * @param {*} obj a string, number, Opcode, Bufer, or object to add + * @returns {Script} this script instance + */ +Script.prototype.prepend = function(obj) { + this._addByType(obj, true); + return this; +}; + +/** + * Compares a script with another script + */ +Script.prototype.equals = function(script) { + $.checkState(script instanceof Script, 'Must provide another script'); + if (this.chunks.length !== script.chunks.length) { + return false; + } + var i; + for (i = 0; i < this.chunks.length; i++) { + if (BufferUtil.isBuffer(this.chunks[i]) && !BufferUtil.isBuffer(script.chunks[i])) { + return false; + } else if (this.chunks[i] instanceof Opcode && !(script.chunks[i] instanceof Opcode)) { + return false; + } + if (BufferUtil.isBuffer(this.chunks[i]) && !BufferUtil.equals(this.chunks[i], script.chunks[i])) { + return false; + } else if (this.chunks[i].num !== script.chunks[i].num) { + return false; + } + } + return true; +}; + +/** + * Adds a script element to the end of the script. + * + * @param {*} obj a string, number, Opcode, Bufer, or object to add + * @returns {Script} this script instance + * + */ +Script.prototype.add = function(obj) { + this._addByType(obj, false); + return this; +}; + +Script.prototype._addByType = function(obj, prepend) { + if (typeof obj === 'string') { + this._addOpcode(obj, prepend); + } else if (typeof obj === 'number') { + this._addOpcode(obj, prepend); + } else if (obj.constructor && obj.constructor.name && obj.constructor.name === 'Opcode') { + this._addOpcode(obj, prepend); + } else if (BufferUtil.isBuffer(obj)) { + this._addBuffer(obj, prepend); + } else if (typeof obj === 'object') { + this._insertAtPosition(obj, prepend); + } else if (obj instanceof Script) { + this.chunks = this.chunks.concat(obj.chunks); + } else { + throw new Error('Invalid script chunk'); + } +}; + +Script.prototype._insertAtPosition = function(op, prepend) { + if (prepend) { + this.chunks.unshift(op); + } else { + this.chunks.push(op); + } +}; + +Script.prototype._addOpcode = function(opcode, prepend) { + var op; + if (typeof opcode === 'number') { + op = opcode; + } else if (opcode.constructor && opcode.constructor.name && opcode.constructor.name === 'Opcode') { + op = opcode.toNumber(); + } else { + op = Opcode(opcode).toNumber(); + } + this._insertAtPosition({ + opcodenum: op + }, prepend); + return this; +}; + +Script.prototype._addBuffer = function(buf, prepend) { + var opcodenum; + var len = buf.length; + if (len >= 0 && len < Opcode.OP_PUSHDATA1) { + opcodenum = len; + } else if (len < Math.pow(2, 8)) { + opcodenum = Opcode.OP_PUSHDATA1; + } else if (len < Math.pow(2, 16)) { + opcodenum = Opcode.OP_PUSHDATA2; + } else if (len < Math.pow(2, 32)) { + opcodenum = Opcode.OP_PUSHDATA4; + } else { + throw new Error('You can\'t push that much data'); + } + this._insertAtPosition({ + buf: buf, + len: len, + opcodenum: opcodenum + }, prepend); + return this; +}; + +Script.prototype.removeCodeseparators = function() { + var chunks = []; + for (var i = 0; i < this.chunks.length; i++) { + if (this.chunks[i].opcodenum !== Opcode.OP_CODESEPARATOR) { + chunks.push(this.chunks[i]); + } + } + this.chunks = chunks; + return this; +}; + +// high level script builder methods + +/** + * @returns a new Multisig output script for given public keys, + * requiring m of those public keys to spend + * @param {PublicKey[]} publicKeys - list of all public keys controlling the output + * @param {number} threshold - amount of required signatures to spend the output + * @param {Object} [opts] - Several options: + * - noSorting: defaults to false, if true, don't sort the given + * public keys before creating the script + */ +Script.buildMultisigOut = function(publicKeys, threshold, opts) { + opts = opts || {}; + var script = new Script(); + script.add(Opcode.smallInt(threshold)); + publicKeys = _.map(publicKeys, PublicKey); + var sorted = publicKeys; + if (!opts.noSorting) { + sorted = _.sortBy(publicKeys, function(publicKey) { + return publicKey.toString('hex'); + }); + } + for (var i = 0; i < sorted.length; i++) { + var publicKey = sorted[i]; + script.add(publicKey.toBuffer()); + } + script.add(Opcode.smallInt(publicKeys.length)); + script.add(Opcode.OP_CHECKMULTISIG); + return script; +}; + +/** + * A new P2SH Multisig input script for the given public keys, requiring m of those public keys to spend + * + * @param {PublicKey[]} pubkeys list of all public keys controlling the output + * @param {number} threshold amount of required signatures to spend the output + * @param {Array} signatures signatures to append to the script + * @param {Object=} opts + * @param {boolean=} opts.noSorting don't sort the given public keys before creating the script (false by default) + * @param {Script=} opts.cachedMultisig don't recalculate the redeemScript + * + * @returns Script + */ +Script.buildP2SHMultisigIn = function(pubkeys, threshold, signatures, opts) { + $.checkArgument(_.isArray(pubkeys)); + $.checkArgument(_.isNumber(threshold)); + $.checkArgument(_.isArray(signatures)); + opts = opts || {}; + var s = new Script(); + s.add(Opcode.OP_0); + _.each(signatures, function(signature) { + s.add(signature); + }); + s.add((opts.cachedMultisig || Script.buildMultisigOut(pubkeys, threshold, opts)).toBuffer()); + return s; +}; + +/** + * @returns a new pay to public key hash output for the given + * address or public key + * @param {(Address|PublicKey)} to - destination address or public key + */ +Script.buildPublicKeyHashOut = function(to) { + $.checkArgument(!_.isUndefined(to)); + $.checkArgument(to instanceof PublicKey || to instanceof Address || _.isString(to)); + if (to instanceof PublicKey) { + to = to.toAddress(); + } else if (_.isString(to)) { + to = new Address(to); + } + var s = new Script(); + s.add(Opcode.OP_DUP) + .add(Opcode.OP_HASH160) + .add(to.hashBuffer) + .add(Opcode.OP_EQUALVERIFY) + .add(Opcode.OP_CHECKSIG); + return s; +}; + +/** + * @returns a new pay to public key output for the given + * public key + */ +Script.buildPublicKeyOut = function(pubkey) { + $.checkArgument(pubkey instanceof PublicKey); + var s = new Script(); + s.add(pubkey.toBuffer()) + .add(Opcode.OP_CHECKSIG); + return s; +}; + +/** + * @returns a new OP_RETURN script with data + * @param {(string|Buffer)} to - the data to embed in the output + */ +Script.buildDataOut = function(data) { + $.checkArgument(_.isUndefined(data) || _.isString(data) || BufferUtil.isBuffer(data)); + if (typeof data === 'string') { + data = new Buffer(data); + } + var s = new Script(); + s.add(Opcode.OP_RETURN); + if (!_.isUndefined(data)) { + s.add(data); + } + return s; +}; + +/** + * @param {Script|Address} script - the redeemScript for the new p2sh output. + * It can also be a p2sh address + * @returns Script new pay to script hash script for given script + */ +Script.buildScriptHashOut = function(script) { + $.checkArgument(script instanceof Script || + (script instanceof Address && script.isPayToScriptHash())); + var s = new Script(); + s.add(Opcode.OP_HASH160) + .add(Hash.sha256ripemd160(script.toBuffer())) + .add(Opcode.OP_EQUAL); + return s; +}; + +/** + * Builds a scriptSig (a script for an input) that signs a public key hash + * output script. + * + * @param {Buffer|string|PublicKey} publicKey + * @param {Signature|Buffer} signature - a Signature object, or the signature in DER cannonical encoding + * @param {number=} sigtype - the type of the signature (defaults to SIGHASH_ALL) + */ +Script.buildPublicKeyHashIn = function(publicKey, signature, sigtype) { + $.checkArgument(signature instanceof Signature || BufferUtil.isBuffer(signature)); + $.checkArgument(_.isUndefined(sigtype) || _.isNumber(sigtype)); + if (signature instanceof Signature) { + signature = signature.toBuffer(); + } + var script = new Script() + .add(BufferUtil.concat([ + signature, + BufferUtil.integerAsSingleByteBuffer(sigtype || Signature.SIGHASH_ALL) + ])) + .add(new PublicKey(publicKey).toBuffer()); + return script; +}; + +/** + * @returns Script an empty script + */ +Script.empty = function() { + return new Script(); +}; + +/** + * @returns Script a new pay to script hash script that pays to this script + */ +Script.prototype.toScriptHashOut = function() { + return Script.buildScriptHashOut(this); +}; + +/** + * @return Script a script built from the address + */ +Script.fromAddress = function(address) { + address = Address(address); + if (address.isPayToScriptHash()) { + return Script.buildScriptHashOut(address); + } else if (address.isPayToPublicKeyHash()) { + return Script.buildPublicKeyHashOut(address); + } + throw new errors.Script.UnrecognizedAddress(address); +}; + +/** + * Analagous to bitcoind's FindAndDelete. Find and delete equivalent chunks, + * typically used with push data chunks. Note that this will find and delete + * not just the same data, but the same data with the same push data op as + * produced by default. i.e., if a pushdata in a tx does not use the minimal + * pushdata op, then when you try to remove the data it is pushing, it will not + * be removed, because they do not use the same pushdata op. + */ +Script.prototype.findAndDelete = function(script) { + var buf = script.toBuffer(); + var hex = buf.toString('hex'); + for (var i = 0; i < this.chunks.length; i++) { + var script2 = Script({ + chunks: [this.chunks[i]] + }); + var buf2 = script2.toBuffer(); + var hex2 = buf2.toString('hex'); + if (hex === hex2) { + this.chunks.splice(i, 1); + } + } + return this; +}; + +/** + * @returns true if the chunk {i} is the smallest way to push that particular data. + * Comes from bitcoind's script interpreter CheckMinimalPush function + */ +Script.prototype.checkMinimalPush = function(i) { + var chunk = this.chunks[i]; + var buf = chunk.buf; + var opcodenum = chunk.opcodenum; + if (!buf) { + return true; + } + if (buf.length === 0) { + // Could have used OP_0. + return opcodenum === Opcode.OP_0; + } else if (buf.length === 1 && buf[0] >= 1 && buf[0] <= 16) { + // Could have used OP_1 .. OP_16. + return opcodenum === Opcode.OP_1 + (buf[0] - 1); + } else if (buf.length === 1 && buf[0] === 0x81) { + // Could have used OP_1NEGATE + return opcodenum === Opcode.OP_1NEGATE; + } else if (buf.length <= 75) { + // Could have used a direct push (opcode indicating number of bytes pushed + those bytes). + return opcodenum === buf.length; + } else if (buf.length <= 255) { + // Could have used OP_PUSHDATA. + return opcodenum === Opcode.OP_PUSHDATA1; + } else if (buf.length <= 65535) { + // Could have used OP_PUSHDATA2. + return opcodenum === Opcode.OP_PUSHDATA2; + } + return true; +}; + +module.exports = Script; + +}).call(this,require("buffer").Buffer) +},{"../address":2,"../crypto/hash":7,"../crypto/signature":10,"../encoding/bufferreader":13,"../encoding/bufferwriter":14,"../errors":16,"../opcode":21,"../publickey":29,"../util/buffer":48,"../util/js":49,"../util/preconditions":50,"buffer":69,"lodash":233}],33:[function(require,module,exports){ +module.exports = require('./transaction'); + +module.exports.Input = require('./input'); +module.exports.Output = require('./output'); + +},{"./input":34,"./output":38,"./transaction":40}],34:[function(require,module,exports){ +module.exports = require('./input'); + +module.exports.PublicKeyHash = require('./publickeyhash'); +module.exports.MultiSigScriptHash = require('./multisigscripthash.js'); + +},{"./input":35,"./multisigscripthash.js":36,"./publickeyhash":37}],35:[function(require,module,exports){ +'use strict'; + +var _ = require('lodash'); +var errors = require('../../errors'); +var BufferWriter = require('../../encoding/bufferwriter'); +var buffer = require('buffer'); +var BufferUtil = require('../../util/buffer'); +var JSUtil = require('../../util/js'); +var Script = require('../../script'); +var Sighash = require('../sighash'); + +function Input(params) { + if (!(this instanceof Input)) { + return new Input(params); + } + if (params) { + return this._fromObject(params); + } +} + +Object.defineProperty(Input.prototype, 'script', { + configurable: false, + writeable: false, + get: function() { + if (!this._script) { + this._script = new Script(this._scriptBuffer); + } + return this._script; + } +}); + +Input.prototype._fromObject = function(params) { + if (_.isString(params.prevTxId) && JSUtil.isHexa(params.prevTxId)) { + params.prevTxId = new buffer.Buffer(params.prevTxId, 'hex'); + } + this.output = params.output; + this.prevTxId = params.prevTxId; + this.outputIndex = params.outputIndex; + this.sequenceNumber = params.sequenceNumber; + if (params.script || params.scriptBuffer) { + this.setScript(params.script || params.scriptBuffer); + } + return this; +}; + +Input.prototype.toObject = function toObject() { + return { + prevTxId: this.prevTxId.toString('hex'), + outputIndex: this.outputIndex, + sequenceNumber: this.sequenceNumber, + script: this._script.toString() + }; +}; + +Input.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +Input.fromJSON = function(json) { + if (JSUtil.isValidJSON(json)) { + json = JSON.parse(json); + } + return new Input({ + prevTxId: json.prevTxId || json.txidbuf, + outputIndex: _.isUndefined(json.outputIndex) ? json.txoutnum : json.outputIndex, + sequenceNumber: json.sequenceNumber || json.seqnum, + scriptBuffer: new Script(json.script, 'hex') + }); +}; + +Input.fromBufferReader = function(br) { + var input = new Input(); + input.prevTxId = br.readReverse(32); + input.outputIndex = br.readUInt32LE(); + var scriptSize = br.readVarintNum(); + if (scriptSize) { + input._scriptBuffer = br.read(scriptSize); + } else { + input._scriptBuffer = new buffer.Buffer([]); + } + input.sequenceNumber = br.readUInt32LE(); + return input; +}; + +Input.prototype.toBufferWriter = function(writer) { + if (!writer) { + writer = new BufferWriter(); + } + writer.writeReverse(this.prevTxId); + writer.writeUInt32LE(this.outputIndex); + var script = this._scriptBuffer; + writer.writeVarintNum(script.length); + writer.write(script); + writer.writeUInt32LE(this.sequenceNumber); + return writer; +}; + +Input.prototype.setScript = function(script) { + if (script instanceof Script) { + this._script = script; + this._scriptBuffer = script.toBuffer(); + } else if (BufferUtil.isBuffer(script)) { + this._script = null; + this._scriptBuffer = new buffer.Buffer(script); + } else { + console.log(script); + throw new TypeError('Invalid Argument'); + } + return this; +}; + +/** + * Retrieve signatures for the provided PrivateKey. + * + * @param {Transaction} transaction - the transaction to be signed + * @param {PrivateKey} privateKey - the private key to use when signing + * @param {number} inputIndex - the index of this input in the provided transaction + * @param {number} sigType - defaults to Signature.SIGHASH_ALL + * @param {Buffer} addressHash - if provided, don't calculate the hash of the + * public key associated with the private key provided + * @abstract + */ +Input.prototype.getSignatures = function() { + throw new errors.AbstractMethodInvoked('Input#getSignatures'); +}; + +Input.prototype.isFullySigned = function() { + throw new errors.AbstractMethodInvoked('Input#isFullySigned'); +}; + +Input.prototype.addSignature = function() { + throw new errors.AbstractMethodInvoked('Input#addSignature'); +}; + +Input.prototype.clearSignatures = function() { + throw new errors.AbstractMethodInvoked('Input#clearSignatures'); +}; + +Input.prototype.isValidSignature = function(transaction, signature) { + // FIXME: Refactor signature so this is not necessary + signature.signature.nhashtype = signature.sigtype; + return Sighash.verify( + transaction, + signature.signature, + signature.publicKey, + signature.inputIndex, + this.output.script + ); +}; + +/** + * @returns true if this is a coinbase input (represents no input) + */ +Input.prototype.isNull = function() { + return this.prevTxId.toString('hex') === '0000000000000000000000000000000000000000000000000000000000000000' && + this.outputIndex === 0xffffffff; +}; + +module.exports = Input; + +},{"../../encoding/bufferwriter":14,"../../errors":16,"../../script":30,"../../util/buffer":48,"../../util/js":49,"../sighash":39,"buffer":69,"lodash":233}],36:[function(require,module,exports){ +'use strict'; + +var _ = require('lodash'); +var JSUtil = require('../../util/js'); +var inherits = require('inherits'); +var Input = require('./input'); +var Output = require('../output'); +var $ = require('../../util/preconditions'); + +var Script = require('../../script'); +var Signature = require('../../crypto/signature'); +var Sighash = require('../sighash'); +var BufferUtil = require('../../util/buffer'); + +/** + * @constructor + */ +function MultiSigScriptHashInput(input, pubkeys, threshold) { + Input.apply(this, arguments); + var self = this; + this.publicKeys = _.sortBy(pubkeys, function(publicKey) { return publicKey.toString('hex'); }); + this.redeemScript = Script.buildMultisigOut(this.publicKeys, threshold); + $.checkState(Script.buildScriptHashOut(this.redeemScript).equals(this.output.script), + 'Provided public keys don\'t hash to the provided output'); + this.publicKeyIndex = {}; + _.each(this.publicKeys, function(publicKey, index) { + self.publicKeyIndex[publicKey.toString()] = index; + }); + this.threshold = threshold; + // Empty array of signatures + this.signatures = new Array(this.publicKeys.length); +} +inherits(MultiSigScriptHashInput, Input); + +MultiSigScriptHashInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype) { + $.checkState(this.output instanceof Output); + sigtype = sigtype || Signature.SIGHASH_ALL; + + var self = this; + var results = []; + _.each(this.publicKeys, function(publicKey) { + if (publicKey.toString() === privateKey.publicKey.toString()) { + results.push({ + publicKey: privateKey.publicKey, + prevTxId: self.txId, + outputIndex: self.outputIndex, + inputIndex: index, + signature: Sighash.sign(transaction, privateKey, sigtype, index, self.redeemScript), + sigtype: sigtype + }); + } + }); + return results; +}; + +MultiSigScriptHashInput.prototype.addSignature = function(transaction, signature) { + $.checkState(!this.isFullySigned(), 'All needed signatures have already been added'); + $.checkArgument(!_.isUndefined(this.publicKeyIndex[signature.publicKey.toString()]), + 'Signature has no matching public key'); + $.checkState(this.isValidSignature(transaction, signature)); + this.signatures[this.publicKeyIndex[signature.publicKey.toString()]] = signature; + this._updateScript(); + return this; +}; + +MultiSigScriptHashInput.prototype._updateScript = function() { + this.setScript(Script.buildP2SHMultisigIn( + this.publicKeys, + this.threshold, + this._createSignatures(), + { cachedMultisig: this.redeemScript } + )); + return this; +}; + +MultiSigScriptHashInput.prototype._createSignatures = function() { + var reverseOrder = JSUtil.cloneArray(this.signatures).reverse(); + return _.map( + _.filter(reverseOrder, function(signature) { return !_.isUndefined(signature); }), + function(signature) { + return BufferUtil.concat([ + signature.signature.toDER(), + BufferUtil.integerAsSingleByteBuffer(signature.sigtype) + ]); + } + ); +}; + +MultiSigScriptHashInput.prototype.clearSignatures = function() { + this.signatures = new Array(this.publicKeys.length); + this._updateScript(); +}; + +MultiSigScriptHashInput.prototype.isFullySigned = function() { + return this.countSignatures() === this.threshold; +}; + +MultiSigScriptHashInput.prototype.countMissingSignatures = function() { + return this.threshold - this.countSignatures(); +}; + +MultiSigScriptHashInput.prototype.countSignatures = function() { + return _.reduce(this.signatures, function(sum, signature) { + return sum + (!!signature); + }, 0); +}; + +MultiSigScriptHashInput.prototype.publicKeysWithoutSignature = function() { + var self = this; + return _.filter(this.publicKeys, function(publicKey) { + return !(self.signatures[self.publicKeyIndex[publicKey.toString()]]); + }); +}; + +MultiSigScriptHashInput.prototype.isValidSignature = function(transaction, signature) { + // FIXME: Refactor signature so this is not necessary + signature.signature.nhashtype = signature.sigtype; + return Sighash.verify( + transaction, + signature.signature, + signature.publicKey, + signature.inputIndex, + this.redeemScript + ); +}; + +MultiSigScriptHashInput.OPCODES_SIZE = 10; +MultiSigScriptHashInput.SIGNATURE_SIZE = 36; + +MultiSigScriptHashInput.prototype._estimateSize = function() { + return MultiSigScriptHashInput.OPCODES_SIZE + this.threshold * MultiSigScriptHashInput.SIGNATURE_SIZE; +}; + +module.exports = MultiSigScriptHashInput; + +},{"../../crypto/signature":10,"../../script":30,"../../util/buffer":48,"../../util/js":49,"../../util/preconditions":50,"../output":38,"../sighash":39,"./input":35,"inherits":231,"lodash":233}],37:[function(require,module,exports){ +'use strict'; + +var inherits = require('inherits'); + +var $ = require('../../util/preconditions'); +var BufferUtil = require('../../util/buffer'); + +var Hash = require('../../crypto/hash'); +var Input = require('./input'); +var Output = require('../output'); +var Sighash = require('../sighash'); +var Script = require('../../script'); +var Signature = require('../../crypto/signature'); + +/** + * Represents a special kind of input of PayToPublicKeyHash kind. + * @constructor + */ +function PublicKeyHashInput() { + Input.apply(this, arguments); +} +inherits(PublicKeyHashInput, Input); + +/* jshint maxparams: 5 */ +/** + * @param {Transaction} transaction - the transaction to be signed + * @param {PrivateKey} privateKey - the private key with which to sign the transaction + * @param {number} index - the index of the input in the transaction input vector + * @param {number=} sigtype - the type of signature, defaults to Signature.SIGHASH_ALL + * @param {Buffer=} hashData - the precalculated hash of the public key associated with the privateKey provided + * @return {Array} of objects that can be + */ +PublicKeyHashInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype, hashData) { + $.checkState(this.output instanceof Output); + hashData = hashData || Hash.sha256ripemd160(privateKey.publicKey.toBuffer()); + sigtype = sigtype || Signature.SIGHASH_ALL; + + if (BufferUtil.equals(hashData, this.output.script.getPublicKeyHash())) { + return [{ + publicKey: privateKey.publicKey, + prevTxId: this.txId, + outputIndex: this.outputIndex, + inputIndex: index, + signature: Sighash.sign(transaction, privateKey, sigtype, index, this.output.script), + sigtype: sigtype + }]; + } + return []; +}; +/* jshint maxparams: 3 */ + +/** + * Add the provided signature + * + * @param {Object} signature + * @param {PublicKey} signature.publicKey + * @param {Signature} signature.signature + * @param {number=} signature.sigtype + * @return {PublicKeyHashInput} this, for chaining + */ +PublicKeyHashInput.prototype.addSignature = function(transaction, signature) { + $.checkState(this.isValidSignature(transaction, signature), 'Signature is invalid'); + this.setScript(Script.buildPublicKeyHashIn( + signature.publicKey, + signature.signature.toDER(), + signature.sigtype + )); + return this; +}; + +/** + * Clear the input's signature + * @return {PublicKeyHashInput} this, for chaining + */ +PublicKeyHashInput.prototype.clearSignatures = function() { + this.setScript(Script.empty()); + return this; +}; + +/** + * Query whether the input is signed + * @return {boolean} + */ +PublicKeyHashInput.prototype.isFullySigned = function() { + return this.script.isPublicKeyHashIn(); +}; + +PublicKeyHashInput.FIXED_SIZE = 32 + 4 + 2; +PublicKeyHashInput.SCRIPT_MAX_SIZE = 34 + 20; +PublicKeyHashInput.prototype._estimateSize = function() { + return PublicKeyHashInput.FIXED_SIZE + PublicKeyHashInput.SCRIPT_MAX_SIZE; +}; + +module.exports = PublicKeyHashInput; + +},{"../../crypto/hash":7,"../../crypto/signature":10,"../../script":30,"../../util/buffer":48,"../../util/preconditions":50,"../output":38,"../sighash":39,"./input":35,"inherits":231}],38:[function(require,module,exports){ +'use strict'; + +var _ = require('lodash'); +var BN = require('../crypto/bn'); +var buffer = require('buffer'); +var bufferUtil = require('../util/buffer'); +var JSUtil = require('../util/js'); +var BufferWriter = require('../encoding/bufferwriter'); +var Script = require('../script'); + +function Output(params) { + if (!(this instanceof Output)) { + return new Output(params); + } + if (params) { + return this._fromObject(params); + } +} + +Object.defineProperty(Output.prototype, 'script', { + configurable: false, + writeable: false, + get: function() { + if (!this._script) { + this._script = new Script(this._scriptBuffer); + } + return this._script; + } +}); + +Object.defineProperty(Output.prototype, 'satoshis', { + configurable: false, + writeable: true, + get: function() { + return this._satoshis.toNumber(); + }, + set: function(num) { + if (num instanceof BN) { + this._satoshis = num; + } else { + this._satoshis = BN().fromNumber(num); + } + } +}); + +Output.prototype._fromObject = function(param) { + this.satoshis = param.satoshis; + if (param.script || param.scriptBuffer) { + this.setScript(param.script || param.scriptBuffer); + } + return this; +}; + +Output.prototype.toObject = function toObject() { + return { + satoshis: this.satoshis, + script: this._script.toString() + }; +}; + +Output.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +Output.fromJSON = function(json) { + if (JSUtil.isValidJSON(json)) { + json = JSON.parse(json); + } + return new Output({ + satoshis: json.satoshis || -(-json.valuebn), + script: new Script(json.script) + }); +}; + +Output.prototype.setScript = function(script) { + if (script instanceof Script) { + this._scriptBuffer = script.toBuffer(); + this._script = script; + } else if (bufferUtil.isBuffer(script)) { + this._scriptBuffer = script; + this._script = null; + } else { + throw new TypeError('Unrecognized Argument'); + } + return this; +}; + +Output.fromBufferReader = function(br) { + var output = new Output(); + output._satoshis = br.readUInt64LEBN(); + var size = br.readVarintNum(); + if (size !== 0) { + output._scriptBuffer = br.read(size); + } else { + output._scriptBuffer = new buffer.Buffer([]); + } + return output; +}; + +Output.prototype.toBufferWriter = function(writer) { + if (!writer) { + writer = new BufferWriter(); + } + writer.writeUInt64LEBN(this._satoshis); + var script = this._scriptBuffer; + writer.writeVarintNum(script.length); + writer.write(script); + return writer; +}; + +module.exports = Output; + +},{"../crypto/bn":5,"../encoding/bufferwriter":14,"../script":30,"../util/buffer":48,"../util/js":49,"buffer":69,"lodash":233}],39:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var buffer = require('buffer'); + +var Signature = require('../crypto/signature'); +var Script = require('../script'); +var Output = require('./output'); +var BufferReader = require('../encoding/bufferreader'); +var BufferWriter = require('../encoding/bufferwriter'); +var BN = require('../crypto/bn'); +var Hash = require('../crypto/hash'); +var ECDSA = require('../crypto/ecdsa'); +var $ = require('../util/preconditions'); +var _ = require('lodash'); + +var SIGHASH_SINGLE_BUG = '0000000000000000000000000000000000000000000000000000000000000001'; +var BITS_64_ON = 'ffffffffffffffff'; + +/** + * Returns a buffer of length 32 bytes with the hash that needs to be signed + * for OP_CHECKSIG. + * + * @name Signing.sighash + * @param {Transaction} transaction the transaction to sign + * @param {number} sighashType the type of the hash + * @param {number} inputNumber the input index for the signature + * @param {Script} subscript the script that will be signed + */ +var sighash = function sighash(transaction, sighashType, inputNumber, subscript) { + var Transaction = require('./transaction'); + var Input = require('./input'); + + var i; + // Copy transaction + var txcopy = Transaction.shallowCopy(transaction); + + // Copy script + subscript = new Script(subscript); + subscript.removeCodeseparators(); + + for (i = 0; i < txcopy.inputs.length; i++) { + // Blank signatures for other inputs + txcopy.inputs[i] = new Input(txcopy.inputs[i]).setScript(Script.empty()); + } + + txcopy.inputs[inputNumber] = new Input(txcopy.inputs[inputNumber]).setScript(subscript); + + if ((sighashType & 31) === Signature.SIGHASH_NONE || + (sighashType & 31) === Signature.SIGHASH_SINGLE) { + + // clear all sequenceNumbers + for (i = 0; i < txcopy.inputs.length; i++) { + if (i !== inputNumber) { + txcopy.inputs[i].sequenceNumber = 0; + } + } + } + + if ((sighashType & 31) === Signature.SIGHASH_NONE) { + txcopy.outputs = []; + + } else if ((sighashType & 31) === Signature.SIGHASH_SINGLE) { + // The SIGHASH_SINGLE bug. + // https://bitcointalk.org/index.php?topic=260595.0 + if (inputNumber > txcopy.outputs.length - 1) { + return new Buffer(SIGHASH_SINGLE_BUG, 'hex'); + } + if (txcopy.outputs.length <= inputNumber) { + throw new Error('Missing output to sign'); + } + + txcopy.outputs.length = inputNumber + 1; + + for (i = 0; i < inputNumber; i++) { + txcopy.outputs[i] = new Output({ + satoshis: BN().fromBuffer(new buffer.Buffer(BITS_64_ON, 'hex')), + script: Script.empty() + }); + } + } + + if (sighashType & Signature.SIGHASH_ANYONECANPAY) { + txcopy.inputs = [txcopy.inputs[inputNumber]]; + } + + var buf = BufferWriter() + .write(txcopy.toBuffer()) + .writeInt32LE(sighashType) + .toBuffer(); + var ret = Hash.sha256sha256(buf); + ret = new BufferReader(ret).readReverse(); + return ret; +}; + +/** + * Create a signature + * + * @name Signing.sign + * @param {Transaction} transaction + * @param {PrivateKey} privateKey + * @param {number} sighash + * @param {number} inputIndex + * @param {Script} subscript + * @return {Signature} + */ +function sign(transaction, privateKey, sighashType, inputIndex, subscript) { + var hashbuf = sighash(transaction, sighashType, inputIndex, subscript); + var sig = ECDSA.sign(hashbuf, privateKey, 'little').set({ + nhashtype: sighashType + }); + return sig; +} + +/** + * Verify a signature + * + * @name Signing.verify + * @param {Transaction} transaction + * @param {Signature} signature + * @param {PublicKey} publicKey + * @param {number} inputIndex + * @param {Script} subscript + * @return {boolean} + */ +function verify(transaction, signature, publicKey, inputIndex, subscript) { + $.checkArgument(!_.isUndefined(transaction)); + $.checkArgument(!_.isUndefined(signature) && !_.isUndefined(signature.nhashtype)); + var hashbuf = sighash(transaction, signature.nhashtype, inputIndex, subscript); + return ECDSA.verify(hashbuf, signature, publicKey, 'little'); +} + +/** + * @namespace Signing + */ +module.exports = { + sighash: sighash, + sign: sign, + verify: verify +}; + +}).call(this,require("buffer").Buffer) +},{"../crypto/bn":5,"../crypto/ecdsa":6,"../crypto/hash":7,"../crypto/signature":10,"../encoding/bufferreader":13,"../encoding/bufferwriter":14,"../script":30,"../util/preconditions":50,"./input":34,"./output":38,"./transaction":40,"buffer":69,"lodash":233}],40:[function(require,module,exports){ +'use strict'; + +var _ = require('lodash'); +var $ = require('../util/preconditions'); +var buffer = require('buffer'); +var assert = require('assert'); + +var util = require('../util/js'); +var bufferUtil = require('../util/buffer'); +var JSUtil = require('../util/js'); +var BufferReader = require('../encoding/bufferreader'); +var BufferWriter = require('../encoding/bufferwriter'); +var Hash = require('../crypto/hash'); +var Signature = require('../crypto/signature'); +var Sighash = require('./sighash'); + +var Address = require('../address'); +var Unit = require('../unit'); +var Input = require('./input'); +var PublicKeyHashInput = Input.PublicKeyHash; +var MultiSigScriptHashInput = Input.MultiSigScriptHash; +var Output = require('./output'); +var Script = require('../script'); +var PrivateKey = require('../privatekey'); +var Block = require('../block'); +var BN = require('../crypto/bn'); + +var CURRENT_VERSION = 1; +var DEFAULT_NLOCKTIME = 0; +var DEFAULT_SEQNUMBER = 0xFFFFFFFF; + +/** + * Represents a transaction, a set of inputs and outputs to change ownership of tokens + * + * @param {*} serialized + * @constructor + */ +function Transaction(serialized) { + if (!(this instanceof Transaction)) { + return new Transaction(serialized); + } + this.inputs = []; + this.outputs = []; + this._inputAmount = 0; + this._outputAmount = 0; + + if (serialized) { + if (serialized instanceof Transaction) { + return Transaction.shallowCopy(serialized); + } else if (util.isHexa(serialized)) { + this.fromString(serialized); + } else if (bufferUtil.isBuffer(serialized)) { + this.fromBuffer(serialized); + } else if (_.isObject(serialized)) { + this.fromObject(serialized); + } + } else { + this._newTransaction(); + } +} + +// max amount of satoshis in circulation +Transaction.MAX_MONEY = 21000000 * 1e8; + +/* Constructors and Serialization */ + +/** + * Create a 'shallow' copy of the transaction, by serializing and deserializing + * it dropping any additional information that inputs and outputs may have hold + * + * @param {Transaction} transaction + * @return {Transaction} + */ +Transaction.shallowCopy = function(transaction) { + var copy = new Transaction(transaction.toBuffer()); + return copy; +}; + +var hashProperty = { + configurable: false, + writeable: false, + get: function() { + return new BufferReader(this._getHash()).readReverse().toString('hex'); + } +}; +Object.defineProperty(Transaction.prototype, 'hash', hashProperty); +Object.defineProperty(Transaction.prototype, 'id', hashProperty); + +/** + * Retrieve the little endian hash of the transaction (used for serialization) + * @return {Buffer} + */ +Transaction.prototype._getHash = function() { + return Hash.sha256sha256(this.toBuffer()); +}; + +/** + * Retrieve a hexa string that can be used with bitcoind's CLI interface + * (decoderawtransaction, sendrawtransaction) + * + * @return {string} + */ +Transaction.prototype.serialize = Transaction.prototype.toString = function() { + return this.toBuffer().toString('hex'); +}; + +Transaction.prototype.inspect = function() { + return ''; +}; + +Transaction.prototype.toBuffer = function() { + var writer = new BufferWriter(); + return this.toBufferWriter(writer).toBuffer(); +}; + +Transaction.prototype.toBufferWriter = function(writer) { + writer.writeUInt32LE(this.version); + writer.writeVarintNum(this.inputs.length); + _.each(this.inputs, function(input) { + input.toBufferWriter(writer); + }); + writer.writeVarintNum(this.outputs.length); + _.each(this.outputs, function(output) { + output.toBufferWriter(writer); + }); + writer.writeUInt32LE(this.nLockTime); + return writer; +}; + +Transaction.prototype.fromBuffer = function(buffer) { + var reader = new BufferReader(buffer); + return this.fromBufferReader(reader); +}; + +Transaction.prototype.fromBufferReader = function(reader) { + var i, sizeTxIns, sizeTxOuts; + + this.version = reader.readUInt32LE(); + sizeTxIns = reader.readVarintNum(); + for (i = 0; i < sizeTxIns; i++) { + var input = Input.fromBufferReader(reader); + this.inputs.push(input); + } + sizeTxOuts = reader.readVarintNum(); + for (i = 0; i < sizeTxOuts; i++) { + this.outputs.push(Output.fromBufferReader(reader)); + } + this.nLockTime = reader.readUInt32LE(); + return this; +}; + +Transaction.prototype.fromJSON = function(json) { + if (JSUtil.isValidJSON(json)) { + json = JSON.parse(json); + } + var self = this; + this.inputs = []; + var inputs = json.inputs || json.txins; + inputs.forEach(function(input) { + self.inputs.push(Input.fromJSON(input)); + }); + this.outputs = []; + var outputs = json.outputs || json.txouts; + outputs.forEach(function(output) { + self.outputs.push(Output.fromJSON(output)); + }); + this.version = json.version; + this.nLockTime = json.nLockTime; + return this; +}; + +Transaction.prototype.toObject = function toObject() { + var inputs = []; + this.inputs.forEach(function(input) { + inputs.push(input.toObject()); + }); + var outputs = []; + this.outputs.forEach(function(output) { + outputs.push(output.toObject()); + }); + return { + version: this.version, + inputs: inputs, + outputs: outputs, + nLockTime: this.nLockTime + }; +}; + +Transaction.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +Transaction.prototype.fromString = function(string) { + this.fromBuffer(new buffer.Buffer(string, 'hex')); +}; + +Transaction.prototype._newTransaction = function() { + this.version = CURRENT_VERSION; + this.nLockTime = DEFAULT_NLOCKTIME; +}; + +/* Transaction creation interface */ + +/** + * Add an input to this transaction. This is a high level interface + * to add an input, for more control, use @{link Transaction#addInput}. + * + * Can receive, as output information, the output of bitcoind's `listunspent` command, + * and a slightly fancier format recognized by bitcore: + * + * ``` + * { + * address: 'mszYqVnqKoQx4jcTdJXxwKAissE3Jbrrc1', + * txId: 'a477af6b2667c29670467e4e0728b685ee07b240235771862318e29ddbe58458', + * outputIndex: 0, + * script: Script.empty(), + * satoshis: 1020000 + * } + * ``` + * Where `address` can be either a string or a bitcore Address object. The + * same is true for `script`, which can be a string or a bitcore Script. + * + * Beware that this resets all the signatures for inputs (in further versions, + * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset). + * + * @example + * var transaction = new Transaction(); + * + * // From a pay to public key hash output from bitcoind's listunspent + * transaction.from({'txid': '0000...', vout: 0, amount: 0.1, scriptPubKey: 'OP_DUP ...'}); + * + * // From a pay to public key hash output + * transaction.from({'txId': '0000...', outputIndex: 0, satoshis: 1000, script: 'OP_DUP ...'}); + * + * // From a multisig P2SH output + * transaction.from({'txId': '0000...', inputIndex: 0, satoshis: 1000, script: '... OP_HASH'}, + * ['03000...', '02000...'], 2); + * + * @param {Object} utxo + * @param {Array=} pubkeys + * @param {number=} threshold + */ +Transaction.prototype.from = function(utxo, pubkeys, threshold) { + if (pubkeys && threshold) { + this._fromMultiSigP2SH(utxo, pubkeys, threshold); + } else { + this._fromNonP2SH(utxo); + } + return this; +}; + +Transaction.prototype._fromMultiSigP2SH = function(utxo, pubkeys, threshold) { + if (Transaction._isNewUtxo(utxo)) { + this._fromMultisigNewUtxo(utxo, pubkeys, threshold); + } else if (Transaction._isOldUtxo(utxo)) { + this._fromMultisigOldUtxo(utxo, pubkeys, threshold); + } else { + throw new Transaction.Errors.UnrecognizedUtxoFormat(utxo); + } +}; + +Transaction.prototype._fromNonP2SH = function(utxo) { + var self = this; + if (_.isArray(utxo)) { + _.each(utxo, function(single) { + self._fromNonP2SH(single); + }); + return; + } + if (Transaction._isNewUtxo(utxo)) { + this._fromNewUtxo(utxo); + } else if (Transaction._isOldUtxo(utxo)) { + this._fromOldUtxo(utxo); + } else { + throw new Transaction.Errors.UnrecognizedUtxoFormat(utxo); + } +}; + +Transaction._isNewUtxo = function(utxo) { + var isDefined = function(param) { + return !_.isUndefined(param); + }; + return _.all(_.map([utxo.txId, utxo.outputIndex, utxo.satoshis, utxo.script], isDefined)); +}; + +Transaction._isOldUtxo = function(utxo) { + var isDefined = function(param) { + return !_.isUndefined(param); + }; + return _.all(_.map([utxo.txid, utxo.vout, utxo.scriptPubKey, utxo.amount], isDefined)); +}; + +Transaction.prototype._fromOldUtxo = function(utxo) { + return this._fromNewUtxo({ + address: utxo.address && new Address(utxo.address), + txId: utxo.txid, + outputIndex: utxo.vout, + script: util.isHexa(utxo.script) ? new buffer.Buffer(utxo.scriptPubKey, 'hex') : utxo.scriptPubKey, + satoshis: Unit.fromBTC(utxo.amount).satoshis + }); +}; + +Transaction.prototype._fromNewUtxo = function(utxo) { + utxo.address = utxo.address && new Address(utxo.address); + utxo.script = new Script(util.isHexa(utxo.script) ? new buffer.Buffer(utxo.script, 'hex') : utxo.script); + this.inputs.push(new PublicKeyHashInput({ + output: new Output({ + script: utxo.script, + satoshis: utxo.satoshis + }), + prevTxId: utxo.txId, + outputIndex: utxo.outputIndex, + sequenceNumber: DEFAULT_SEQNUMBER, + script: Script.empty() + })); + this._inputAmount += utxo.satoshis; +}; + +Transaction.prototype._fromMultisigOldUtxo = function(utxo, pubkeys, threshold) { + return this._fromMultisigNewUtxo({ + address: utxo.address && new Address(utxo.address), + txId: utxo.txid, + outputIndex: utxo.vout, + script: new buffer.Buffer(utxo.scriptPubKey, 'hex'), + satoshis: Unit.fromBTC(utxo.amount).satoshis + }, pubkeys, threshold); +}; + +Transaction.prototype._fromMultisigNewUtxo = function(utxo, pubkeys, threshold) { + this._changeSetup = false; + utxo.address = utxo.address && new Address(utxo.address); + utxo.script = new Script(util.isHexa(utxo.script) ? new buffer.Buffer(utxo.script, 'hex') : utxo.script); + this.inputs.push(new MultiSigScriptHashInput({ + output: new Output({ + script: utxo.script, + satoshis: utxo.satoshis + }), + prevTxId: utxo.txId, + outputIndex: utxo.outputIndex, + sequenceNumber: DEFAULT_SEQNUMBER, + script: Script.empty() + }, pubkeys, threshold)); + this._inputAmount += utxo.satoshis; +}; + +/** + * Returns true if the transaction has enough info on all inputs to be correctly validated + * + * @return {boolean} + */ +Transaction.prototype.hasAllUtxoInfo = function() { + return _.all(this.inputs.map(function(input) { + return !!input.output; + })); +}; + +/** + * Manually set the fee for this transaction. Beware that this resets all the signatures + * for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not + * be reset). + * + * @param {number} amount satoshis to be sent + * @return {Transaction} this, for chaining + */ +Transaction.prototype.fee = function(amount) { + this._fee = amount; + this._changeSetup = false; + return this; +}; + +/* Output management */ + +/** + * Set the change address for this transaction + * + * Beware that this resets all the signatures for inputs (in further versions, + * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset). + * + * @param {number} amount satoshis to be sent + * @return {Transaction} this, for chaining + */ +Transaction.prototype.change = function(address) { + this._change = new Address(address); + this._changeSetup = false; + return this; +}; + +/** + * Add an output to the transaction. + * + * Beware that this resets all the signatures for inputs (in further versions, + * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset). + * + * @param {string|Address} address + * @param {number} amount in satoshis + * @return {Transaction} this, for chaining + */ +Transaction.prototype.to = function(address, amount) { + this._addOutput(new Output({ + script: Script(new Address(address)), + satoshis: amount + })); + return this; +}; + +/** + * Add an OP_RETURN output to the transaction. + * + * Beware that this resets all the signatures for inputs (in further versions, + * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset). + * + * @param {Buffer|string} value the data to be stored in the OP_RETURN output. + * In case of a string, the UTF-8 representation will be stored + * @return {Transaction} this, for chaining + */ +Transaction.prototype.addData = function(value) { + this._addOutput(new Output({ + script: Script.buildDataOut(value), + satoshis: 0 + })); + return this; +}; + +Transaction.prototype._addOutput = function(output) { + this.outputs.push(output); + this._changeSetup = false; + this._outputAmount += output.satoshis; +}; + +Transaction.prototype._updateChangeOutput = function() { + if (!this._change) { + return; + } + if (this._changeSetup) { + return; + } + if (!_.isUndefined(this._changeSetup)) { + this._clearSignatures(); + } + if (!_.isUndefined(this._changeOutput)) { + this.removeOutput(this._changeOutput); + } + var estimatedSize = this._estimateSize(); + var available = this._inputAmount - this._outputAmount; + var fee = this._fee || Transaction._estimateFee(estimatedSize, available); + if (available - fee > 0) { + this._changeOutput = this.outputs.length; + this._addOutput(new Output({ + script: Script.fromAddress(this._change), + satoshis: available - fee + })); + } else { + this._changeOutput = undefined; + } + this._changeSetup = true; +}; + +Transaction.prototype._clearSignatures = function() { + _.each(this.inputs, function(input) { + input.clearSignatures(); + }); +}; + +Transaction.FEE_PER_KB = 10000; +Transaction.CHANGE_OUTPUT_MAX_SIZE = 20 + 4 + 34 + 4; + +Transaction._estimateFee = function(size, amountAvailable) { + var fee = Math.ceil(size / Transaction.FEE_PER_KB); + if (amountAvailable > fee) { + // Safe upper bound for change address script + size += Transaction.CHANGE_OUTPUT_MAX_SIZE; + } + return Math.ceil(size / 1000 / Transaction.FEE_PER_KB) * 1000; +}; + +Transaction.MAXIMUM_EXTRA_SIZE = 4 + 9 + 9 + 4; + +Transaction.prototype._estimateSize = function() { + var result = Transaction.MAXIMUM_EXTRA_SIZE; + _.each(this.inputs, function(input) { + result += input._estimateSize(); + }); + _.each(this.outputs, function(output) { + result += output.script.toBuffer().length + 9; + }); + return result; +}; + +Transaction.prototype.removeOutput = function(index) { + var output = this.outputs[index]; + this._outputAmount -= output.satoshis; + this.outputs = _.without(this.outputs, this.outputs[this._changeOutput]); +}; + +/* Signature handling */ + +/** + * Sign the transaction using one or more private keys. + * + * It tries to sign each input, verifying that the signature will be valid + * (matches a public key). + * + * @param {Array|String|PrivateKey} privateKey + * @param {number} sigtype + * @return {Transaction} this, for chaining + */ +Transaction.prototype.sign = function(privateKey, sigtype) { + $.checkState(this.hasAllUtxoInfo()); + this._updateChangeOutput(); + var self = this; + if (_.isArray(privateKey)) { + _.each(privateKey, function(privateKey) { + self.sign(privateKey); + }); + return this; + } + _.each(this.getSignatures(privateKey, sigtype), function(signature) { + self.applySignature(signature); + }); + return this; +}; + +Transaction.prototype.getSignatures = function(privKey, sigtype) { + privKey = new PrivateKey(privKey); + sigtype = sigtype || Signature.SIGHASH_ALL; + var transaction = this; + var results = []; + var hashData = Hash.sha256ripemd160(privKey.publicKey.toBuffer()); + _.each(this.inputs, function forEachInput(input, index) { + _.each(input.getSignatures(transaction, privKey, index, sigtype, hashData), function(signature) { + results.push(signature); + }); + }); + return results; +}; + +/** + * Add a signature to the transaction + * + * @param {Object} signature + * @param {number} signature.inputIndex + * @param {number} signature.sighash + * @param {PublicKey} signature.publicKey + * @param {Signature} signature.signature + * @return {Transaction} this, for chaining + */ +Transaction.prototype.applySignature = function(signature) { + this.inputs[signature.inputIndex].addSignature(this, signature); + return this; +}; + +Transaction.prototype.isFullySigned = function() { + return _.all(_.map(this.inputs, function(input) { + return input.isFullySigned(); + })); +}; + +Transaction.prototype.isValidSignature = function(signature) { + var self = this; + return this.inputs[signature.inputIndex].isValidSignature(self, signature); +}; + +/** + * @returns {bool} whether the signature is valid for this transaction input + */ +Transaction.prototype.verifySignature = function(sig, pubkey, nin, subscript) { + return Sighash.verify(this, sig, pubkey, nin, subscript); +}; + +/** + * Check that a transaction passes basic sanity tests. If not, return a string + * describing the error. This function contains the same logic as + * CheckTransaction in bitcoin core. + */ +Transaction.prototype.verify = function() { + // Basic checks that don't depend on any context + if (this.inputs.length === 0) { + return 'transaction txins empty'; + } + + if (this.outputs.length === 0) { + return 'transaction txouts empty'; + } + + // Size limits + if (this.toBuffer().length > Block.MAX_BLOCK_SIZE) { + return 'transaction over the maximum block size'; + } + + // Check for negative or overflow output values + var valueoutbn = BN(0); + for (var i = 0; i < this.outputs.length; i++) { + var txout = this.outputs[i]; + var valuebn = BN(txout.satoshis.toString(16)); + if (valuebn.lt(0)) { + return 'transaction txout ' + i + ' negative'; + } + if (valuebn.gt(Transaction.MAX_MONEY)) { + return 'transaction txout ' + i + ' greater than MAX_MONEY'; + } + valueoutbn = valueoutbn.add(valuebn); + if (valueoutbn.gt(Transaction.MAX_MONEY)) { + return 'transaction txout ' + i + ' total output greater than MAX_MONEY'; + } + } + + // Check for duplicate inputs + var txinmap = {}; + for (i = 0; i < this.inputs.length; i++) { + var txin = this.inputs[i]; + + var inputid = txin.prevTxId + ':' + txin.outputIndex; + if (!_.isUndefined(txinmap[inputid])) { + return 'transaction input ' + i + ' duplicate input'; + } + txinmap[inputid] = true; + } + + var isCoinbase = this.isCoinbase(); + if (isCoinbase) { + var buf = this.inputs[0]._script.toBuffer(); + if (buf.length < 2 || buf.length > 100) { + return 'coinbase trasaction script size invalid'; + } + } else { + for (i = 0; i < this.inputs.length; i++) { + if (this.inputs[i].isNull()) { + return 'tranasction input ' + i + ' has null input'; + } + } + } + return true; +}; + +/** + * Analagous to bitcoind's IsCoinBase function in transaction.h + */ +Transaction.prototype.isCoinbase = function() { + return (this.inputs.length === 1 && this.inputs[0].isNull()); +}; + + +module.exports = Transaction; + +},{"../address":2,"../block":3,"../crypto/bn":5,"../crypto/hash":7,"../crypto/signature":10,"../encoding/bufferreader":13,"../encoding/bufferwriter":14,"../privatekey":28,"../script":30,"../unit":46,"../util/buffer":48,"../util/js":49,"../util/preconditions":50,"./input":34,"./output":38,"./sighash":39,"assert":67,"buffer":69,"lodash":233}],41:[function(require,module,exports){ +/** + * @namespace Transport + */ +module.exports = { + Messages: require('./messages'), + Peer: require('./peer'), + Pool: require('./pool'), + RPC: require('./rpc') +}; + +},{"./messages":42,"./peer":43,"./pool":44,"./rpc":45}],42:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +/** + * @namespace Transport.Message + */ +/* jshint curly: false */ + +var Buffers = require('buffers'); +var Put = require('bufferput'); +var util = require('util'); + +var BlockHeaderModel = require('../blockheader'); +var BlockModel = require('../block'); +var BufferReader = require('../encoding/bufferreader'); +var BufferUtil = require('../util/buffer'); +var Hash = require('../crypto/hash'); +var Random = require('../crypto/random'); +var TransactionModel = require('../transaction'); + +var CONNECTION_NONCE = Random.getPseudoRandomBuffer(8); +var PROTOCOL_VERSION = 70000; + +/** + * Static helper for consuming a data buffer until the next message. + * + * @name Transport.Message#parseMessage + * @param{Network} network - the network object + * @param{Buffer} dataBuffer - the buffer to read from + * @returns{Message|undefined} A message or undefined if there is nothing to read. + */ +var parseMessage = function(network, dataBuffer) { + if (dataBuffer.length < 20) return; + + // Search the next magic number + if (!discardUntilNextMessage(network, dataBuffer)) return; + + var PAYLOAD_START = 16; + var payloadLen = (dataBuffer.get(PAYLOAD_START)) + + (dataBuffer.get(PAYLOAD_START + 1) << 8) + + (dataBuffer.get(PAYLOAD_START + 2) << 16) + + (dataBuffer.get(PAYLOAD_START + 3) << 24); + + var messageLength = 24 + payloadLen; + if (dataBuffer.length < messageLength) return; + + var command = dataBuffer.slice(4, 16).toString('ascii').replace(/\0+$/, ''); + var payload = dataBuffer.slice(24, messageLength); + var checksum = dataBuffer.slice(20, 24); + + var checksumConfirm = Hash.sha256sha256(payload).slice(0, 4); + if (!BufferUtil.equals(checksumConfirm, checksum)) { + dataBuffer.skip(messageLength); + return; + } + + dataBuffer.skip(messageLength); + return Message.buildMessage(command, payload); +}; + +module.exports.parseMessage = parseMessage; + +/** + * @desc Internal function that discards data until founds the next message. + * @name Transport.Message#discardUntilNextMessage + */ +function discardUntilNextMessage(network, dataBuffer) { + var magicNumber = network.networkMagic; + + var i = 0; + for (;;) { + // check if it's the beginning of a new message + var packageNumber = dataBuffer.slice(0, 4); + if (BufferUtil.equals(packageNumber, magicNumber)) { + dataBuffer.skip(i); + return true; + } + + // did we reach the end of the buffer? + if (i > (dataBuffer.length - 4)) { + dataBuffer.skip(i); + return false; + } + + i++; // continue scanning + } +} + +/** + * Abstract Message that knows how to parse and serialize itself. + * Concret subclases should implement {fromBuffer} and {getPayload} methods. + * @name Transport.Message + */ +function Message() {} + +/** + * @value + * @name Transport.Message.COMMANDS + */ +Message.COMMANDS = {}; + +/** + * Look up a message type by command name and instantiate the correct Message + * @name Transport.Message#buildMessage + */ +Message.buildMessage = function(command, payload) { + try { + var CommandClass = Message.COMMANDS[command]; + return new CommandClass().fromBuffer(payload); + } catch (err) { + console.log('Error while parsing message', err); + } +}; + +/** + * Parse instance state from buffer. + * + * @param{Buffer} payload - the buffer to read from + * @returns{Message} The same message instance + */ +Message.prototype.fromBuffer = function(payload) { + /* jshint unused: false */ + return this; +}; + +/** + * Serialize the payload into a buffer. + * + * @returns{Buffer} the serialized payload + */ +Message.prototype.getPayload = function() { + return BufferUtil.EMPTY_BUFFER; +}; + +/** + * Serialize the message into a buffer. + * + * @returns{Buffer} the serialized message + */ +Message.prototype.serialize = function(network) { + var magic = network.networkMagic; + var commandBuf = new Buffer(this.command, 'ascii'); + if (commandBuf.length > 12) throw 'Command name too long'; + + var payload = this.getPayload(); + var checksum = Hash.sha256sha256(payload).slice(0, 4); + + // -- HEADER -- + var message = new Put(); + message.put(magic); + message.put(commandBuf); + message.pad(12 - commandBuf.length); // zero-padded + message.word32le(payload.length); + message.put(checksum); + + // -- BODY -- + message.put(payload); + + return message.buffer(); +} + +/** + * Version Message + * + * @name Transport.Message.Version + * @param{string} subversion - version of the client + * @param{Buffer} nonce - a random 8 bytes buffer + */ +function Version(subversion, nonce) { + this.command = 'version'; + this.version = PROTOCOL_VERSION; + this.subversion = subversion || '/BitcoinX:0.1/'; + this.nonce = nonce || CONNECTION_NONCE; +} +util.inherits(Version, Message); + +Version.prototype.fromBuffer = function(payload) { + var parser = new BufferReader(payload); + this.version = parser.readUInt32LE(); + this.services = parser.readUInt64LEBN(); + this.timestamp = parser.readUInt64LEBN(); + this.addr_me = parser.read(26); + this.addr_you = parser.read(26); + this.nonce = parser.read(8); + this.subversion = parser.readVarintBuf().toString(); + this.start_height = parser.readUInt32LE(); + + return this; +}; + +Version.prototype.getPayload = function() { + var put = new Put(); + put.word32le(this.version); // version + put.word64le(1); // services + put.word64le(Math.round(new Date().getTime() / 1000)); // timestamp + put.pad(26); // addr_me + put.pad(26); // addr_you + put.put(this.nonce); + put.varint(this.subversion.length); + put.put(new Buffer(this.subversion, 'ascii')); + put.word32le(0); + + return put.buffer(); +}; + +module.exports.Version = Message.COMMANDS.version = Version; + +/** + * Inv Message + * + * @name Transport.Message.Inventory + * @param{Array} inventory - reported elements + */ +function Inventory(inventory) { + this.command = 'inv'; + this.inventory = inventory || []; +} +util.inherits(Inventory, Message); + +Inventory.prototype.fromBuffer = function(payload) { + var parser = new BufferReader(payload); + var count = parser.readVarintNum(); + for (var i = 0; i < count; i++) { + this.inventory.push({ + type: parser.readUInt32LE(), + hash: parser.read(32) + }); + } + + return this; +}; + +Inventory.prototype.getPayload = function() { + var put = new Put(); + + put.varint(this.inventory.length); + this.inventory.forEach(function(value) { + put.word32le(value.type); + put.put(value.hash); + }); + + return put.buffer(); +}; + +module.exports.Inventory = Message.COMMANDS.inv = Inventory; + +/** + * Getdata Message + * + * @name Transport.Message.GetData + * @param{Array} inventory - requested elements + */ +function GetData(inventory) { + this.command = 'getdata'; + this.inventory = inventory || []; +} + +util.inherits(GetData, Inventory); +module.exports.GetData = GetData; + +/** + * Ping Message + * + * @name Transport.Message.Ping + * @param{Buffer} nonce - a random 8 bytes buffer + */ +function Ping(nonce) { + this.command = 'ping'; + this.nonce = nonce || CONNECTION_NONCE; +} +util.inherits(Ping, Message); + +Ping.prototype.fromBuffer = function(payload) { + this.nonce = new BufferReader(payload).read(8); + return this; +}; + +Ping.prototype.getPayload = function() { + return this.nonce; +}; + +module.exports.Ping = Message.COMMANDS.ping = Ping; + +/** + * Pong Message + * + * @name Transport.Message.Pong + * @param{Buffer} nonce - a random 8 bytes buffer + */ +function Pong(nonce) { + this.command = 'pong'; + this.nonce = nonce || CONNECTION_NONCE; +} + +util.inherits(Pong, Ping); +module.exports.Pong = Message.COMMANDS.pong = Pong; + +/** + * Addr Message + * + * @name Transport.Message.Addressess + * @param{Array} addresses - array of know addresses + */ +function Addresses(addresses) { + this.command = 'addr'; + this.addresses = addresses || []; +} +util.inherits(Addresses, Message); + +Addresses.prototype.fromBuffer = function(payload) { + var parser = new BufferReader(payload); + var addrCount = Math.min(parser.readVarintNum(), 1000); + + this.addresses = []; + for (var i = 0; i < addrCount; i++) { + // TODO: Time actually depends on the version of the other peer (>=31402) + + var time = parser.readUInt32LE(); + var services = parser.readUInt64LEBN(); + + // parse the ipv6 to a string + var ipv6 = []; + for (var a = 0; a < 6; a++) { + ipv6.push(parser.read(2).toString('hex')); + } + ipv6 = ipv6.join(':'); + + // parse the ipv4 to a string + var ipv4 = []; + for (var b = 0; b < 4; b++) { + ipv4.push(parser.read(1)[0]); + } + ipv4 = ipv4.join('.'); + + var port = parser.readUInt16BE(); + + this.addresses.push({ + time: time, + services: services, + ip: { v6: ipv6, v4: ipv4 }, + port: port + }); + } + + return this; +}; + +Addresses.prototype.getPayload = function() { + var put = new Put(); + put.varint(this.addresses.length); + + for (var i = 0; i < this.addresses.length; i++) { + put.word32le(this.addresses[i].time); + put.word64le(this.addresses[i].services); + put.put(this.addresses[i].ip); + put.word16be(this.addresses[i].port); + } + + return put.buffer(); +}; + +module.exports.Addresses = Message.COMMANDS.addr = Addresses; + +/** + * GetAddr Message + * + * @name Transport.Message.GetAddresses + */ +function GetAddresses() { + this.command = 'getaddr'; +} + +util.inherits(GetAddresses, Message); +module.exports.GetAddresses = Message.COMMANDS.getaddr = GetAddresses; + +/** + * Verack Message + * + * @name Transport.Message.VerAck + */ +function VerAck() { + this.command = 'verack'; +} + +util.inherits(VerAck, Message); +module.exports.VerAck = Message.COMMANDS.verack = VerAck; + +/** + * Reject Message + * + * @name Transport.Message.Reject + */ +function Reject() { + this.command = 'reject'; +} +util.inherits(Reject, Message); + +// TODO: Parse REJECT message + +module.exports.Reject = Message.COMMANDS.reject = Reject; + +/** + * Alert Message + * + * @name Transport.Message.Alert + */ +function Alert(payload, signature) { + this.command = 'alert'; + this.payload = payload || new Buffer(32); + this.signature = signature || new Buffer(32); +} +util.inherits(Alert, Message); + +Alert.prototype.fromBuffer = function(payload) { + var parser = new BufferReader(payload); + this.payload = parser.readVarintBuf(); // TODO: Use current format + this.signature = parser.readVarintBuf(); + return this; +}; + +Alert.prototype.getPayload = function() { + var put = new Put(); + put.varint(this.payload.length); + put.put(this.payload); + + put.varint(this.signature.length); + put.put(this.signature); + + return put.buffer(); +}; + +module.exports.Alert = Message.COMMANDS.alert = Alert; + +/** + * Headers Message + * + * @name Transport.Message.Headers + * @param{Array} blockheaders - array of block headers + */ +function Headers(blockheaders) { + this.command = 'headers'; + this.headers = blockheaders || []; +} +util.inherits(Headers, Message); + +Headers.prototype.fromBuffer = function(payload) { + var parser = new BufferReader(payload); + var count = parser.readVarintNum(); + + this.headers = []; + for (var i = 0; i < count; i++) { + var header = BlockHeaderModel._fromBufferReader(parser); + this.headers.push(header); + } + + return this; +}; + +Headers.prototype.getPayload = function() { + var put = new Put(); + put.varint(this.headers.length); + + for (var i = 0; i < this.headers.length; i++) { + var buffer = this.headers[i].toBuffer(); + put.put(buffer); + } + + return put.buffer(); +}; + +module.exports.Headers = Message.COMMANDS.headers = Headers; + +/** + * Block Message + * + * @name Transport.Message.Block + * @param{Block} block + */ +function Block(block) { + this.command = 'block'; + this.block = block; +} +util.inherits(Block, Message); + +Block.prototype.fromBuffer = function(payload) { + this.block = BlockModel(payload); + return this; +}; + +Block.prototype.getPayload = function() { + return this.block.toBuffer(); +}; + +module.exports.Block = Message.COMMANDS.block = Block; + +/** + * Tx Message + * + * @name Transport.Message.Transaction + * @param{Transaction} transaction + */ +function Transaction(transaction) { + this.command = 'tx'; + this.transaction = transaction; +} +util.inherits(Transaction, Message); + +Transaction.prototype.fromBuffer = function(payload) { + this.transaction = TransactionModel(payload); + return this; +}; + +Transaction.prototype.getPayload = function() { + return this.transaction.toBuffer(); +}; + +module.exports.Transaction = Message.COMMANDS.tx = Transaction; + +/** + * Getblocks Message + * + * @name Transport.Message.GetBlocks + * @param{Array} starts - array of buffers with the starting block hashes + * @param{Buffer} [stop] - hash of the last block + */ +function GetBlocks(starts, stop) { + this.command = 'getblocks'; + this.version = PROTOCOL_VERSION; + this.starts = starts || []; + this.stop = stop || BufferUtil.NULL_HASH; +} +util.inherits(GetBlocks, Message); + +GetBlocks.prototype.fromBuffer = function(payload) { + var parser = new BufferReader(payload); + this.version = parser.readUInt32LE(); + + var startCount = Math.min(parser.readVarintNum(), 500); + this.starts = []; + for (var i = 0; i < startCount; i++) { + this.starts.push(parser.read(32)); + } + this.stop = parser.read(32); + + return this; +}; + +GetBlocks.prototype.getPayload = function() { + var put = new Put(); + put.word32le(this.version); + put.varint(this.starts.length); + + for (var i = 0; i < this.starts.length; i++) { + if (this.starts[i].length !== 32) { + throw new Error('Invalid hash length'); + } + put.put(this.starts[i]); + } + + if (this.stop.length !== 32) { + throw new Error('Invalid hash length'); + } + put.put(this.stop); + + return put.buffer(); +}; + +module.exports.GetBlocks = Message.COMMANDS.getblocks = GetBlocks; + +/** + * Getheaders Message + * + * @name Transport.Message.GetHeaders + * @param{Array} starts - array of buffers with the starting block hashes + * @param{Buffer} [stop] - hash of the last block + */ +function GetHeaders(starts, stop) { + this.command = 'getheaders'; + this.version = PROTOCOL_VERSION; + this.starts = starts || []; + this.stop = stop || BufferUtil.NULL_HASH; +} + +util.inherits(GetHeaders, GetBlocks); +module.exports.GetHeaders = Message.COMMANDS.getheaders = GetHeaders; + + +// TODO: Remove this PATCH (yemel) +Buffers.prototype.skip = function (i) { + if (i === 0) return; + + if (i === this.length) { + this.buffers = []; + this.length = 0; + return; + } + + var pos = this.pos(i); + this.buffers = this.buffers.slice(pos.buf); + this.buffers[0] = new Buffer(this.buffers[0].slice(pos.offset)); + this.length -= i; +}; + +}).call(this,require("buffer").Buffer) +},{"../block":3,"../blockheader":4,"../crypto/hash":7,"../crypto/random":9,"../encoding/bufferreader":13,"../transaction":33,"../util/buffer":48,"buffer":69,"bufferput":209,"buffers":210,"util":205}],43:[function(require,module,exports){ +'use strict'; + +var Buffers = require('buffers'); +var EventEmitter = require('events').EventEmitter; +var Net = require('net'); +var Socks5Client = require('socks5-client'); +var util = require('util'); + +var Networks = require('../networks'); +var Messages = require('./messages'); + +var MAX_RECEIVE_BUFFER = 10000000; + +/** + * A Peer instance represents a remote bitcoin node and allows to communicate + * with it using the standar messages of the bitcoin p2p protocol. + * + * @example + * + * var peer = new Peer('127.0.0.1').setProxy('127.0.0.1', 9050); + * peer.on('tx', function(tx) { + * console.log('New transaction: ', tx.id); + * }); + * peer.connect(); + * + * @param {String} host - IP address of the remote host + * @param {Number} [port] - Port number of the remote host + * @param {Network} [network] - The context for this communication + * @returns {Peer} A new instance of Peer. + * @constructor + */ +function Peer(host, port, network) { + if (!(this instanceof Peer)) { + return new Peer(host, port, network); + } + + // overloading stuff + if (port instanceof Object && !network) { + network = port; + port = undefined; + } + + this.host = host; + this.status = Peer.STATUS.DISCONNECTED; + this.network = network || Networks.livenet; + this.port = port || this.network.port; + + this.dataBuffer = new Buffers(); + + this.version = 0; + this.bestHeight = 0; + this.subversion = null; + + // set message handlers + var self = this; + this.on('verack', function() { + self.status = Peer.STATUS.READY; + self.emit('ready'); + }); + + this.on('version', function(message) { + self.version = message.version; + self.subversion = message.subversion; + self.bestHeight = message.start_height + }); + + this.on('ping', function(message) { + self._sendPong(message.nonce); + }); + +} +util.inherits(Peer, EventEmitter); + +Peer.STATUS = { + DISCONNECTED: 'disconnected', + CONNECTING: 'connecting', + CONNECTED: 'connected', + READY: 'ready' +}; + +/** + * Set a socks5 proxy for the connection. Enables the use of the TOR network. + * + * @param {String} host - IP address of the proxy + * @param {Number} port - Port number of the proxy + * @returns {Peer} The same Peer instance. + */ +Peer.prototype.setProxy = function(host, port) { + if (this.status != Peer.STATUS.DISCONNECTED) { + throw Error('Invalid State'); + } + + this.proxy = { + host: host, + port: port + }; + return this; +}; + +/** + * Init the connection with the remote peer. + * + * @returns {Socket} The same peer instance. + */ +Peer.prototype.connect = function() { + this.socket = this._getSocket(); + this.status = Peer.STATUS.CONNECTING; + + var self = this; + this.socket.on('connect', function(ev) { + self.status = Peer.STATUS.CONNECTED; + self.emit('connect'); + self._sendVersion(); + }); + + this.socket.on('error', self.disconnect.bind(this)); + this.socket.on('end', self.disconnect.bind(this)); + + this.socket.on('data', function(data) { + self.dataBuffer.push(data); + + if (self.dataBuffer.length > MAX_RECEIVE_BUFFER) return self.disconnect(); + self._readMessage(); + }); + + this.socket.connect(this.port, this.host); + return this; +}; + +/** + * Disconnects the remote connection. + * + * @returns {Socket} The same peer instance. + */ +Peer.prototype.disconnect = function() { + this.status = Peer.STATUS.DISCONNECTED; + this.socket.destroy(); + this.emit('disconnect'); + return this; +}; + +/** + * Send a Message to the remote peer. + * + * @param {Message} message - A message instance + */ +Peer.prototype.sendMessage = function(message) { + this.socket.write(message.serialize(this.network)); +}; + +/** + * Internal function that sends VERSION message to the remote peer. + */ +Peer.prototype._sendVersion = function() { + var message = new Messages.Version(); + this.sendMessage(message); +}; + +/** + * Send a PONG message to the remote peer. + */ +Peer.prototype._sendPong = function(nonce) { + var message = new Messages.Pong(nonce); + this.sendMessage(message); +}; + +/** + * Internal function that tries to read a message from the data buffer + */ +Peer.prototype._readMessage = function() { + var message = Messages.parseMessage(this.network, this.dataBuffer); + + if (message) { + this.emit(message.command, message); + this._readMessage(); + } +}; + +/** + * Internal function that creates a socket using a proxy if neccesary. + * + * @returns {Socket} A Socket instance not yet connected. + */ +Peer.prototype._getSocket = function() { + if (this.proxy) { + return new Socks5Client(this.proxy.host, this.proxy.port); + } + + return new Net.Socket(); +}; + +module.exports = Peer; + +},{"../networks":20,"./messages":42,"buffers":210,"events":177,"net":66,"socks5-client":244,"util":205}],44:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var dns = require('dns'); +var EventEmitter = require('events').EventEmitter; +var Networks = require('../networks'); +var sha256 = require('../crypto/hash').sha256; +var Peer = require('./peer'); +var util = require('util'); + +function now() { + return Math.floor(new Date().getTime() / 1000); +} + +/** + * A pool is a collection of Peers. A pool will discover peers from DNS seeds, and + * collect information about new peers in the network. When a peer disconnects the pool + * will connect to others that are available to maintain a max number of + * ongoing peer connections. Peer events are relayed to the pool. + * + * @example + * + * var pool = new Pool(Networks.livenet); + * pool.on('peerinv', function(peer, message) { + * // do something with the inventory announcement + * }); + * pool.connect(); + * + * @param {Network|String} network - The network to connect + * @returns {Pool} + * @constructor + */ +function Pool(network) { + + var self = this; + + this.network = Networks.get(network) || Networks.defaultNetwork; + this.keepalive = false; + this._connectedPeers = {}; + this._addrs = []; + + this.on('peeraddr', function peerAddrEvent(peer, message) { + var addrs = message.addresses; + var length = addrs.length; + for (var i = 0; i < length; i++) { + var addr = addrs[i]; + // In case of an invalid time, assume "5 days ago" + if (addr.time <= 100000000 || addr.time > (now() + 10 * 60)) { + addr.time = now() - 5 * 24 * 60 * 60; + } + this._addAddr(addr); + } + }); + + this.on('seed', function seedEvent(ips) { + ips.forEach(function(ip) { + self._addAddr({ + ip: { + v4: ip + } + }); + }); + if (self.keepalive) { + self._fillConnections(); + } + }); + + this.on('peerdisconnect', function peerDisconnectEvent(peer, addr) { + self._deprioritizeAddr(addr); + self._removeConnectedPeer(addr); + if (self.keepalive) { + self._fillConnections(); + } + }); + + return this; + +} + +util.inherits(Pool, EventEmitter); + +Pool.MaxConnectedPeers = 8; +Pool.RetrySeconds = 30; +Pool.PeerEvents = ['version', 'inv', 'getdata', 'ping', 'ping', 'addr', + 'getaddr', 'verack', 'reject', 'alert', 'headers', 'block', + 'tx', 'getblocks', 'getheaders' +]; + + +/** + * Will initiatiate connection to peers, if available peers have been added to + * the pool, it will connect to those, otherwise will use DNS seeds to find + * peers to connect. When a peer disconnects it will add another. + */ +Pool.prototype.connect = function connect() { + this.keepalive = true; + var self = this; + if (self._addrs.length === 0) { + self._addAddrsFromSeeds(); + } else { + self._fillConnections(); + } + return this; +}; + + +/** + * Will disconnect all peers that are connected. + */ +Pool.prototype.disconnect = function disconnect() { + this.keepalive = false; + for (var i in this._connectedPeers) { + this._connectedPeers[i].disconnect(); + } + return this; +}; + +/** + * @returns {Number} The number of peers currently connected. + */ +Pool.prototype.numberConnected = function numberConnected() { + return Object.keys(this._connectedPeers).length; +}; + +/** + * Will fill the conneted peers to the maximum amount. + */ +Pool.prototype._fillConnections = function _fillConnections() { + var length = this._addrs.length; + for (var i = 0; i < length; i++) { + if (this.numberConnected() >= Pool.MaxConnectedPeers) { + break; + } + var addr = this._addrs[i]; + if (!addr.retryTime || now() > addr.retryTime) { + this._connectPeer(addr); + } + } + return this; +}; + +/** + * Will remove a peer from the list of connected peers. + * @param {Object} addr - An addr from the list of addrs + */ +Pool.prototype._removeConnectedPeer = function _removeConnectedPeer(addr) { + if (this._connectedPeers[addr.hash].status !== Peer.STATUS.DISCONNECTED) { + this._connectedPeers[addr.hash].disconnect(); + } else { + delete this._connectedPeers[addr.hash]; + } + return this; +}; + +/** + * Will connect a peer and add to the list of connected peers. + * @param {Object} addr - An addr from the list of addrs + */ +Pool.prototype._connectPeer = function _connectPeer(addr) { + var self = this; + + function addConnectedPeer(addr) { + var port = addr.port || self.network.port; + var ip = addr.ip.v4 || addr.ip.v6; + var peer = new Peer(ip, port, self.network); + peer.on('disconnect', function peerDisconnect() { + self.emit('peerdisconnect', peer, addr); + }); + peer.on('ready', function peerReady() { + self.emit('peerready', peer, addr); + }); + Pool.PeerEvents.forEach(function addPeerEvents(event) { + peer.on(event, function peerEvent(message) { + self.emit('peer' + event, peer, message); + }); + }); + peer.connect(); + self._connectedPeers[addr.hash] = peer; + } + + if (!this._connectedPeers[addr.hash]) { + addConnectedPeer(addr); + } + + return this; +}; + +/** + * Will deprioritize an addr in the list of addrs by moving it to the end + * of the array, and setting a retryTime + * @param {Object} addr - An addr from the list of addrs + */ +Pool.prototype._deprioritizeAddr = function _deprioritizeAddr(addr) { + for (var i = 0; i < this._addrs.length; i++) { + if (this._addrs[i].hash === addr.hash) { + var middle = this._addrs[i]; + middle.retryTime = now() + Pool.RetrySeconds; + var beginning = this._addrs.splice(0, i); + var end = this._addrs.splice(i + 1, this._addrs.length); + var combined = beginning.concat(end); + this._addrs = combined.concat([middle]); + } + } + return this; +}; + +/** + * Will add an addr to the beginning of the addrs array + * @param {Object} + */ +Pool.prototype._addAddr = function _addAddr(addr) { + + // make a unique key + addr.hash = sha256(new Buffer(addr.ip.v6 + addr.ip.v4 + addr.port)).toString('hex'); + + var length = this._addrs.length; + var exists = false; + for (var i = 0; i < length; i++) { + if (this._addrs[i].hash === addr.hash) { + exists = true; + } + } + if (!exists) { + this._addrs.unshift(addr); + } + return this; +}; + +/** + * Will add addrs to the list of addrs from a DNS seed + * @param {String} seed - A domain name to resolve known peers + * @param {Function} done + */ +Pool.prototype._addAddrsFromSeed = function _addAddrsFromSeed(seed) { + var self = this; + dns.resolve(seed, function(err, ips) { + if (err) { + self.emit('seederror', err); + return; + } + if (!ips || !ips.length) { + self.emit('seederror', new Error('No IPs found from seed lookup.')); + return; + } + // announce to pool + self.emit('seed', ips); + }); + return this; +}; + +/** + * Will add addrs to the list of addrs from network DNS seeds + * @param {Function} done + */ +Pool.prototype._addAddrsFromSeeds = function _addAddrsFromSeeds() { + var self = this; + var seeds = this.network.dnsSeeds; + seeds.forEach(function(seed) { + self._addAddrsFromSeed(seed); + }); + return this; +}; + +/** + * @returns {String} A string formatted for the console + */ +Pool.prototype.inspect = function inspect() { + return ''; +}; + +module.exports = Pool; + +}).call(this,require("buffer").Buffer) +},{"../crypto/hash":7,"../networks":20,"./peer":43,"buffer":69,"dns":66,"events":177,"util":205}],45:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var http = require('http'); +var https = require('https'); + +/** + * A JSON RPC client for bitcoind. An instances of RPC connects to a bitcoind + * server and enables simple and batch RPC calls. + * + * @example + * + * var client = new RPC('user', 'pass'); + * client.getInfo(function(err, info) { + * // do something with the info + * }); + * + * @param {String} user - username used to connect bitcoind + * @param {String} password - password used to connect bitcoind + * @param {Object} opts - Connection options: host, port, secure, disableAgent, rejectUnauthorized + * @returns {RPC} + * @constructor + */ +function RPC(user, password, opts) { + if (!(this instanceof RPC)) { + return new RPC(user, password, opts); + } + + this.user = user; + this.pass = password; + + opts = opts || {}; + this.host = opts.host || '127.0.0.1'; + this.port = opts.port || 8332; + + this.secure = typeof opts.secure === 'undefined' ? true : opts.secure; + this._client = opts.secure ? https : http; + + this.batchedCalls = null; + this.disableAgent = opts.disableAgent || false; + this.rejectUnauthorized = opts.rejectUnauthorized || false; +} + +/** + * Allows to excecute RPC calls in batch. + * + * @param {Function} batchCallback - Function that makes all calls to be excecuted in bach + * @param {Function} resultCallbak - Function to be called on result + */ +RPC.prototype.batch = function(batchCallback, resultCallback) { + this.batchedCalls = []; + batchCallback(); + this._request(this.batchedCalls, resultCallback); + this.batchedCalls = null; +} + +/** + * Internal function to make an RPC call + * + * @param {Object} request - Object to be serialized and sent to bitcoind + * @param {Function} callbak - Function to be called on result + */ +RPC.prototype._request = function(request, callback) { + var self = this; + + var request = JSON.stringify(request); + var auth = Buffer(self.user + ':' + self.pass).toString('base64'); + + var options = { + host: self.host, + path: '/', + method: 'POST', + port: self.port, + rejectUnauthorized: self.rejectUnauthorized, + agent: self.disableAgent ? false : undefined + }; + + var req = this._client.request(options, function(res) { + var buf = ''; + res.on('data', function(data) { + buf += data; + }); + + res.on('end', function() { + if (res.statusCode == 401) { + var error = new Error('bitcoin JSON-RPC connection rejected: 401 unauthorized'); + return callback(error); + } + + if (res.statusCode == 403) { + var error = new Error('bitcoin JSON-RPC connection rejected: 403 forbidden'); + return callback(error); + } + + try { + var parsedBuf = JSON.parse(buf); + } catch (e) { + return callback(e); + } + + callback(parsedBuf.error, parsedBuf); + }); + }); + + req.on('error', function(e) { + var err = new Error('Could not connect to bitcoin via RPC at host: ' + self.host + ' port: ' + self.port + ' Error: ' + e.message); + callback(err); + }); + + req.setHeader('Content-Length', request.length); + req.setHeader('Content-Type', 'application/json'); + req.setHeader('Authorization', 'Basic ' + auth); + req.write(request); + req.end(); +}; + +var callspec = { + addMultiSigAddress: '', + addNode: '', + backupWallet: '', + createMultiSig: '', + createRawTransaction: '', + decodeRawTransaction: '', + dumpPrivKey: '', + encryptWallet: '', + getAccount: '', + getAccountAddress: 'str', + getAddedNodeInfo: '', + getAddressesByAccount: '', + getBalance: 'str int', + getBestBlockHash: '', + getBlock: '', + getBlockCount: '', + getBlockHash: 'int', + getBlockNumber: '', + getBlockTemplate: '', + getConnectionCount: '', + getDifficulty: '', + getGenerate: '', + getHashesPerSec: '', + getInfo: '', + getMemoryPool: '', + getMiningInfo: '', + getNewAddress: '', + getPeerInfo: '', + getRawMemPool: '', + getRawTransaction: 'str int', + getReceivedByAccount: 'str int', + getReceivedByAddress: 'str int', + getTransaction: '', + getTxOut: 'str int bool', + getTxOutSetInfo: '', + getWork: '', + help: '', + importAddress: 'str str bool', + importPrivKey: 'str str bool', + keyPoolRefill: '', + listAccounts: 'int', + listAddressGroupings: '', + listReceivedByAccount: 'int bool', + listReceivedByAddress: 'int bool', + listSinceBlock: 'str int', + listTransactions: 'str int int', + listUnspent: 'int int', + listLockUnspent: 'bool', + lockUnspent: '', + move: 'str str float int str', + sendFrom: 'str str float int str str', + sendMany: 'str str int str', //not sure this is will work + sendRawTransaction: '', + sendToAddress: 'str float str str', + setAccount: '', + setGenerate: 'bool int', + setTxFee: 'float', + signMessage: '', + signRawTransaction: '', + stop: '', + submitBlock: '', + validateAddress: '', + verifyMessage: '', + walletLock: '', + walletPassPhrase: 'string int', + walletPassphraseChange: '', +}; + + +var slice = function(arr, start, end) { + return Array.prototype.slice.call(arr, start, end); +}; + +function generateRPCMethods(constructor, apiCalls) { + function createRPCMethod(methodName, argMap) { + return function() { + var limit = arguments.length - 1; + if (this.batchedCalls) var limit = arguments.length; + for (var i = 0; i < limit; i++) { + if (argMap[i]) arguments[i] = argMap[i](arguments[i]); + }; + if (this.batchedCalls) { + this.batchedCalls.push({ + jsonrpc: '2.0', + method: methodName, + params: slice(arguments) + }); + } else { + this._request({ + method: methodName, + params: slice(arguments, 0, arguments.length - 1) + }, arguments[arguments.length - 1]); + } + }; + }; + + var types = { + str: function(arg) { + return arg.toString(); + }, + int: function(arg) { + return parseFloat(arg); + }, + float: function(arg) { + return parseFloat(arg); + }, + bool: function(arg) { + return (arg === true || arg == '1' || arg == 'true' || arg.toString().toLowerCase() == 'true'); + }, + }; + + for (var k in apiCalls) { + if (apiCalls.hasOwnProperty(k)) { + var spec = apiCalls[k].split(' '); + for (var i = 0; i < spec.length; i++) { + if (types[spec[i]]) { + spec[i] = types[spec[i]]; + } else { + spec[i] = types.string; + } + } + var methodName = k.toLowerCase(); + constructor.prototype[k] = createRPCMethod(methodName, spec); + constructor.prototype[methodName] = constructor.prototype[k]; + } + } +} + +generateRPCMethods(RPC, callspec); + +module.exports = RPC; + +}).call(this,require("buffer").Buffer) +},{"buffer":69,"http":178,"https":182}],46:[function(require,module,exports){ +'use strict'; + +var JSUtil = require('./util/js'); + +/** + * + * Bitcore Unit + * + * Utility for handling and converting bitcoins units. The supported units are + * BTC, mBTC, bits and satoshis. A unit instance can be created with an + * amount and a unit code, or alternatively using static methods like {fromBTC}. + * You can consult for different representation of a unit instance using it's + * {to} method, the fixed unit methods like {toSatoshis} or alternatively using + * the unit accessors. + * + * @example + * + * var sats = Unit.fromBTC(1.3).toSatoshis(); + * var mili = Unit.fromBits(1.3).to(Unit.mBTC); + * var btc = new Unit(1.3, Unit.bits).BTC; + * + * @param {Number} amount - The amount to be represented + * @param {String} code - The unit of the amount + * @returns {Unit} A new instance of an Unit + * @constructor + */ +function Unit(amount, code) { + if (!(this instanceof Unit)) { + return new Unit(amount, code); + } + + this._amount = amount; + this._code = code; + + this._value = this._from(amount, code); + + var self = this; + var defineAccesor = function(key) { + Object.defineProperty(self, key, { + get: function() { return self.to(key); }, + enumerable: true, + }); + }; + + Object.keys(UNITS).forEach(defineAccesor); +}; + +var UNITS = { + 'BTC' : [1e8, 8], + 'mBTC' : [1e5, 5], + 'uBTC' : [1e2, 2], + 'bits' : [1e2, 2], + 'satoshis' : [1, 0] +}; + +Object.keys(UNITS).forEach(function(key) { + Unit[key] = key; +}); + +/** + * Will return a Unit instance created from JSON string or object + * + * @param {String|Object} json - JSON with keys: amount and code + * @returns {Unit} A Unit instance + */ +Unit.fromJSON = function fromJSON(json){ + if (JSUtil.isValidJSON(json)) { + json = JSON.parse(json); + } + return new Unit(json.amount, json.code); +}; + +/** + * Will return a Unit instance created from an amount in BTC + * + * @param {Number} amount - The amount in BTC + * @returns {Unit} A Unit instance + */ +Unit.fromBTC = function(amount) { + return new Unit(amount, Unit.BTC); +}; + +/** + * Will return a Unit instance created from an amount in mBTC + * + * @param {Number} amount - The amount in mBTC + * @returns {Unit} A Unit instance + */ +Unit.fromMilis = function(amount) { + return new Unit(amount, Unit.mBTC); +}; + +/** + * Will return a Unit instance created from an amount in bits + * + * @param {Number} amount - The amount in bits + * @returns {Unit} A Unit instance + */ +Unit.fromMicros = Unit.fromBits = function(amount) { + return new Unit(amount, Unit.bits); +}; + +/** + * Will return a Unit instance created from an amount in satoshis + * + * @param {Number} amount - The amount in satoshis + * @returns {Unit} A Unit instance + */ +Unit.fromSatoshis = function(amount) { + return new Unit(amount, Unit.satoshis); +}; + +Unit.prototype._from = function(amount, code) { + if (!UNITS[code]) throw Error('Unknown unit code'); + + return parseInt((amount * UNITS[code][0]).toFixed()); +}; + +/** + * Will return the value represented in the specified unit + * + * @param {string} code - The unit code + * @returns {Number} The converted value + */ +Unit.prototype.to = function(code) { + if (!UNITS[code]) throw Error('Unknown unit code'); + + var value = this._value / UNITS[code][0]; + return parseFloat(value.toFixed(UNITS[code][1])); +}; + +/** + * Will return the value represented in BTC + * + * @returns {Number} The value converted to BTC + */ +Unit.prototype.toBTC = function() { + return this.to(Unit.BTC); +}; + +/** + * + * Will return the value represented in mBTC + * + * @returns {Number} The value converted to mBTC + */ +Unit.prototype.toMilis = function(code) { + return this.to(Unit.mBTC); +}; + +/** + * Will return the value represented in bits + * + * @returns {Number} The value converted to bits + */ +Unit.prototype.toMicros = Unit.prototype.toBits = function(code) { + return this.to(Unit.bits); +}; + +/** + * Will return the value represented in satoshis + * + * @returns {Number} The value converted to satoshis + */ +Unit.prototype.toSatoshis = function() { + return this.to(Unit.satoshis); +}; + +/** + * Will return a the string representation of the value in satoshis + * + * @returns {String} the value in satoshis + */ +Unit.prototype.toString = function() { + return this.satoshis + ' satoshis'; +}; + +/** + * Will return a plain object representation of the Unit + * + * @returns {Object} An object with the keys: amount and code + */ +Unit.prototype.toObject = function toObject() { + return { + amount: this._amount, + code: this._code + }; +}; + +Unit.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +/** + * Will return a string formatted for the console + * + * @returns {String} the value in satoshis + */ +Unit.prototype.inspect = function() { + return ''; +}; + +module.exports = Unit; + +},{"./util/js":49}],47:[function(require,module,exports){ +'use strict'; + +var _ = require('lodash'); +var URL = require('url'); + +var Address = require('./address'); +var Unit = require('./unit'); +var JSUtil = require('./util/js'); + +/** + * Bitcore URI + * + * Instantiate an URI from a bitcoin URI String or an Object. An URI instance + * can be created with a bitcoin uri string or an object. All instances of + * URI are valid, the static method isValid allows checking before instanciation. + * + * All standard parameters can be found as members of the class, the address + * is represented using an {Address} instance and the amount is represented in + * satoshis. Any other non-standard parameters can be found under the extra member. + * + * @example + * + * var uri = new URI('bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2'); + * console.log(uri.address, uri.amount); + * + * @param {string|Object} data - A bitcoin URI string or an Object + * @param {Array.} [knownParams] - Required non-standard params + * @throws {TypeError} Invalid bitcoin address + * @throws {TypeError} Invalid amount + * @throws {Error} Unknown required argument + * @returns {URI} A new valid and frozen instance of URI + * @constructor + */ +var URI = function(data, knownParams) { + this.extras = {}; + this.knownParams = knownParams || []; + this.address = this.network = this.amount = this.message = null; + + if (typeof(data) === 'string') { + var params = URI.parse(data); + if (params.amount) { + params.amount = this._parseAmount(params.amount); + } + this._fromObject(params); + } else if (typeof(data) === 'object') { + this._fromObject(data); + } else { + throw new TypeError('Unrecognized data format.'); + } +}; + +/** + * Instantiate a URI from a String + * + * @param {String} str - JSON string or object of the URI + * @returns {URI} A new instance of a URI + */ +URI.fromString = function fromString(str) { + if (typeof(str) !== 'string') { + throw TypeError('Expected a string'); + } + return new URI(str); +}; + +/** + * Instantiate a URI from JSON + * + * @param {String|Object} json - JSON string or object of the URI + * @returns {URI} A new instance of a URI + */ +URI.fromJSON = function fromJSON(json) { + if (JSUtil.isValidJSON(json)) { + json = JSON.parse(json); + } + return new URI(json); +}; + +/** + * Check if an bitcoin URI string is valid + * + * @example + * + * var valid = URI.isValid('bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu'); + * // true + * + * @param {string|Object} data - A bitcoin URI string or an Object + * @param {Array.} [knownParams] - Required non-standard params + * @returns {boolean} Result of uri validation + */ +URI.isValid = function(arg, knownParams) { + try { + var uri = new URI(arg, knownParams); + return true; + } catch (err) { + return false; + } +}; + +/** + * Convert a bitcoin URI string into a simple object. + * + * @param {string} uri - A bitcoin URI string + * @throws {TypeError} Invalid bitcoin URI + * @returns {Object} An object with the parsed params + */ +URI.parse = function(uri) { + var info = URL.parse(uri, true); + + if (info.protocol != 'bitcoin:') { + throw new TypeError('Invalid bitcoin URI'); + } + + // workaround to host insensitiveness + var group = /[^:]*:\/?\/?([^?]*)/.exec(uri); + info.query.address = group && group[1] || undefined; + + return info.query; +}; + +URI.Members = ['address', 'amount', 'message', 'label', 'r']; + +/** + * Internal function to load the URI instance with an object. + * + * @param {Object} obj - Object with the information + * @throws {TypeError} Invalid bitcoin address + * @throws {TypeError} Invalid amount + * @throws {Error} Unknown required argument + */ +URI.prototype._fromObject = function(obj) { + + if (!Address.isValid(obj.address)) { + throw new TypeError('Invalid bitcoin address'); + } + + this.address = new Address(obj.address); + this.network = this.address.network; + this.amount = obj.amount; + + for (var key in obj) { + if (key === 'address' || key === 'amount') continue; + + if (/^req-/.exec(key) && this.knownParams.indexOf(key) === -1) { + throw Error('Unknown required argument ' + key); + } + + var destination = URI.Members.indexOf(key) > -1 ? this : this.extras; + destination[key] = obj[key]; + } +}; + +/** + * Internal function to transform a BTC string amount into satoshis + * + * @param {String} amount - Amount BTC string + * @throws {TypeError} Invalid amount + * @returns {Object} Amount represented in satoshis + */ +URI.prototype._parseAmount = function(amount) { + amount = Number(amount); + if (isNaN(amount)) { + throw new TypeError('Invalid amount'); + } + return Unit.fromBTC(amount).toSatoshis(); +}; + +URI.prototype.toObject = function toObject() { + var json = {}; + for (var i = 0; i < URI.Members.length; i++) { + var m = URI.Members[i]; + if (this.hasOwnProperty(m) && typeof(this[m]) !== 'undefined') { + if (typeof(this[m].toString) === 'function') { + json[m] = this[m].toString(); + } else { + json[m] = this[m]; + } + } + } + _.extend(json, this.extras); + return json; +}; + +URI.prototype.toJSON = function toJSON() { + return JSON.stringify(this.toObject()); +}; + +/** + * Will return a the string representation of the URI + * + * @returns {String} Bitcoin URI string + */ +URI.prototype.toString = function() { + var query = {}; + if (this.amount) { + query.amount = Unit.fromSatoshis(this.amount).toBTC(); + } + if (this.message) { + query.message = this.message; + } + if (this.label) { + query.label = this.label; + } + if (this.r) { + query.r = this.r; + } + _.extend(query, this.extras); + + return URL.format({ + protocol: 'bitcoin:', + host: this.address, + query: query + }); +}; + +/** + * Will return a string formatted for the console + * + * @returns {String} Bitcoin URI + */ +URI.prototype.inspect = function() { + return ''; +}; + +module.exports = URI; + +},{"./address":2,"./unit":46,"./util/js":49,"lodash":233,"url":203}],48:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var buffer = require('buffer'); +var assert = require('assert'); + +var js = require('./js'); +var $ = require('./preconditions'); + +function equals(a, b) { + if (a.length !== b.length) { + return false; + } + var length = a.length; + for (var i = 0; i < length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} + +module.exports = { + /** + * Fill a buffer with a value. + * + * @param {Buffer} buffer + * @param {number} value + * @return {Buffer} + */ + fill: function fill(buffer, value) { + $.checkArgumentType(buffer, 'Buffer', 'buffer'); + $.checkArgumentType(value, 'number', 'value'); + var length = buffer.length; + for (var i = 0; i < length; i++) { + buffer[i] = value; + } + return buffer; + }, + + /** + * Returns true if the given argument is an instance of a buffer. Tests for + * both node's Buffer and Uint8Array + * + * @param {*} arg + * @return {boolean} + */ + isBuffer: function isBuffer(arg) { + return buffer.Buffer.isBuffer(arg) || arg instanceof Uint8Array; + }, + + /** + * Returns a zero-filled byte array + * + * @param {number} bytes + * @return {Buffer} + */ + emptyBuffer: function emptyBuffer(bytes) { + $.checkArgumentType(bytes, 'number', 'bytes'); + var result = new buffer.Buffer(bytes); + for (var i = 0; i < bytes; i++) { + result.write('\0', i); + } + return result; + }, + + /** + * Concatenates a buffer + * + * Shortcut for buffer.Buffer.concat + */ + concat: buffer.Buffer.concat, + + equals: equals, + equal: equals, + + /** + * Transforms a number from 0 to 255 into a Buffer of size 1 with that value + * + * @param {number} integer + * @return {Buffer} + */ + integerAsSingleByteBuffer: function integerAsSingleByteBuffer(integer) { + $.checkArgumentType(integer, 'number', 'integer'); + return new buffer.Buffer([integer & 0xff]); + }, + + /** + * Transform a 4-byte integer into a Buffer of length 4. + * + * @param {number} integer + * @return {Buffer} + */ + integerAsBuffer: function integerAsBuffer(integer) { + $.checkArgumentType(integer, 'number', 'integer'); + var bytes = []; + bytes.push((integer >> 24) & 0xff); + bytes.push((integer >> 16) & 0xff); + bytes.push((integer >> 8) & 0xff); + bytes.push(integer & 0xff); + return new Buffer(bytes); + }, + + /** + * Transform the first 4 values of a Buffer into a number, in little endian encoding + * + * @param {Buffer} buffer + * @return {number} + */ + integerFromBuffer: function integerFromBuffer(buffer) { + $.checkArgumentType(buffer, 'Buffer', 'buffer'); + return buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3]; + }, + + /** + * Transforms the first byte of an array into a number ranging from -128 to 127 + * @param {Buffer} buffer + * @return {number} + */ + integerFromSingleByteBuffer: function integerFromBuffer(buffer) { + $.checkArgumentType(buffer, 'Buffer', 'buffer'); + return buffer[0]; + }, + + /** + * Transforms a buffer into a string with a number in hexa representation + * + * Shorthand for buffer.toString('hex') + * + * @param {Buffer} buffer + * @return {string} + */ + bufferToHex: function bufferToHex(buffer) { + $.checkArgumentType(buffer, 'Buffer', 'buffer'); + return buffer.toString('hex'); + }, + + /** + * Reverse a buffer + * @param {Buffer} param + * @return {Buffer} + */ + reverse: function reverse(param) { + $.checkArgumentType(param, 'Buffer', 'param'); + var ret = new buffer.Buffer(param.length); + for (var i = 0; i < param.length; i++) { + ret[i] = param[param.length - i - 1]; + } + return ret; + }, + + /** + * Transforms an hexa encoded string into a Buffer with binary values + * + * Shorthand for Buffer(string, 'hex') + * + * @param {string} string + * @return {Buffer} + */ + hexToBuffer: function hexToBuffer(string) { + assert(js.isHexa(string)); + return new buffer.Buffer(string, 'hex'); + } +}; + +module.exports.NULL_HASH = module.exports.fill(new Buffer(32), 0); +module.exports.EMPTY_BUFFER = new Buffer(0); + +}).call(this,require("buffer").Buffer) +},{"./js":49,"./preconditions":50,"assert":67,"buffer":69}],49:[function(require,module,exports){ +'use strict'; + +var _ = require('lodash'); + +/** + * Determines whether a string contains only hexadecimal values + * + * @name JSUtil.isHexa + * @param {string} value + * @return {boolean} true if the string is the hexa representation of a number + */ +var isHexa = function isHexa(value) { + if (!_.isString(value)) { + return false; + } + return /^[0-9a-fA-F]+$/.test(value); +}; + +/** + * @namespace JSUtil + */ +module.exports = { + /** + * Test if an argument is a valid JSON object. If it is, returns a truthy + * value (the json object decoded), so no double JSON.parse call is necessary + * + * @param {string} arg + * @return {Object|boolean} false if the argument is not a JSON string. + */ + isValidJSON: function isValidJSON(arg) { + try { + return JSON.parse(arg); + } catch (e) { + return false; + } + }, + isHexa: isHexa, + isHexaString: isHexa, + + /** + * Clone an array + */ + cloneArray: function(array) { + return [].concat(array); + }, + + /** + * Define immutable properties on a target object + * + * @param {Object} target - An object to be extended + * @param {Object} values - An object of properties + * @return {Object} The target object + */ + defineImmutable: function defineImmutable(target, values){ + Object.keys(values).forEach(function(key){ + Object.defineProperty(target, key, { + configurable: false, + value: values[key] + }); + }); + return target; + } +}; + +},{"lodash":233}],50:[function(require,module,exports){ +'use strict'; + +var errors = require('../errors'); +var _ = require('lodash'); + +module.exports = { + checkState: function(condition, message) { + if (!condition) { + throw new errors.InvalidState(message); + } + }, + checkArgument: function(condition, argumentName, message) { + if (!condition) { + throw new errors.InvalidArgument(argumentName, message); + } + }, + checkArgumentType: function(argument, type, argumentName) { + argumentName = argumentName || '(unknown name)'; + if (_.isString(type)) { + if (type === 'Buffer') { + var BufferUtil = require('./buffer'); + if (!BufferUtil.isBuffer(argument)) { + throw new errors.InvalidArgumentType(argument, type, argumentName); + } + } else if (typeof argument !== type) { + throw new errors.InvalidArgumentType(argument, type, argumentName); + } + } else { + if (!(argument instanceof type)) { + throw new errors.InvalidArgumentType(argument, type.name, argumentName); + } + } + } +}; + +},{"../errors":16,"./buffer":48,"lodash":233}],51:[function(require,module,exports){ +var asn1 = exports; + +asn1.bignum = require('bn.js'); + +asn1.define = require('./asn1/api').define; +asn1.base = require('./asn1/base'); +asn1.constants = require('./asn1/constants'); +asn1.decoders = require('./asn1/decoders'); +asn1.encoders = require('./asn1/encoders'); + +},{"./asn1/api":52,"./asn1/base":54,"./asn1/constants":58,"./asn1/decoders":60,"./asn1/encoders":62,"bn.js":63}],52:[function(require,module,exports){ +var asn1 = require('../asn1'); +var util = require('util'); +var vm = require('vm'); + +var api = exports; + +api.define = function define(name, body) { + return new Entity(name, body); +}; + +function Entity(name, body) { + this.name = name; + this.body = body; + + this.decoders = {}; + this.encoders = {}; +}; + +Entity.prototype._createNamed = function createNamed(base) { + var named = vm.runInThisContext('(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})'); + util.inherits(named, base); + named.prototype._initNamed = function initnamed(entity) { + base.call(this, entity); + }; + + return new named(this); +}; + +Entity.prototype._getDecoder = function _getDecoder(enc) { + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(asn1.decoders[enc]); + return this.decoders[enc]; +}; + +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; + +Entity.prototype._getEncoder = function _getEncoder(enc) { + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(asn1.encoders[enc]); + return this.encoders[enc]; +}; + +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; + +},{"../asn1":51,"util":205,"vm":206}],53:[function(require,module,exports){ +var assert = require('assert'); +var util = require('util'); +var Reporter = require('../base').Reporter; +var Buffer = require('buffer').Buffer; + +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } + + this.base = base; + this.offset = 0; + this.length = base.length; +} +util.inherits(DecoderBuffer, Reporter); +exports.DecoderBuffer = DecoderBuffer; + +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset }; +}; + +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + + this.offset = save.offset; + + return res; +}; + +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; + +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +} + +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + + var res = new DecoderBuffer(this.base); + + // Share reporter state + res._reporterState = this._reporterState; + + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +} + +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupporter type: ' + typeof value); + } +} +exports.EncoderBuffer = EncoderBuffer; + +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; + + if (this.length === 0) + return out; + + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } + + return out; +}; + +},{"../base":54,"assert":67,"buffer":69,"util":205}],54:[function(require,module,exports){ +var base = exports; + +base.Reporter = require('./reporter').Reporter; +base.DecoderBuffer = require('./buffer').DecoderBuffer; +base.EncoderBuffer = require('./buffer').EncoderBuffer; +base.Node = require('./node'); + +},{"./buffer":53,"./node":55,"./reporter":56}],55:[function(require,module,exports){ +var assert = require('assert'); +var Reporter = require('../base').Reporter; +var EncoderBuffer = require('../base').EncoderBuffer; + +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'octstr', 'bitstr', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int' +]; + +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any' +].concat(tags); + +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + var state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + var state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(key) { + var state = this._baseState; + + assert(state.key === null); + state.key = key; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input)); + + var result = state['default']; + var present = true; + + var prevKey; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + present = this._peekTag( + input, + state.explicit !== null ? state.explicit : + state.implicit !== null ? state.implicit : + state.tag || 0 + ); + if (input.isError(present)) + return present; + } + + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input); + else + result = this._decodeChoice(input); + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + var fail = state.children.some(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input); + }); + if (fail) + return err; + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input) { + var state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0]); + else if (tag === 'octstr' || tag === 'bitstr') + return this._decodeStr(input, tag); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1]); + else if (tag === 'objid') + return this._decodeObjid(input, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag); + else if (tag === 'null_') + return this._decodeNull(input); + else if (tag === 'bool') + return this._decodeBool(input); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0]); + else if (state.use !== null) + return this._getUse(state.use)._decode(input); + else + return input.error('unknown tag: ' + tag); + + return null; +}; + +Node.prototype._getUse = function _getUse(entity) { + var state = this._baseState; + if (!state.useDecoder) { + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== null) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + var result = null; + var present = true; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; + } + + // For error reporting + var prevKey; + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + content = this._createEncoderBuffer(data.map(function(item) { + return this._getUse(state.args[0])._encode(item, reporter); + }, this)); + } else if (state.use !== null) { + result = this._getUse(state.use)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be ommited only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (tag === 'octstr' || tag === 'bitstr') + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else + throw new Error('Unsupported tag: ' + tag); +}; + +},{"../base":54,"assert":67}],56:[function(require,module,exports){ +var util = require('util'); + +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.Reporter = Reporter; + +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; + +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; + +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; + + state.path = state.path.slice(0, index - 1); + if (state.obj !== null) + state.obj[key] = value; +}; + +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + + var prev = state.obj; + state.obj = {}; + return prev; +}; + +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; + + var now = state.obj; + state.obj = prev; + return now; +}; + +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } + + if (!state.options.partial) + throw err; + + if (!inherited) + state.errors.push(err); + + return err; +}; + +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; + + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; + +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +util.inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + Error.captureStackTrace(this, ReporterError); + + return this; +}; + +},{"util":205}],57:[function(require,module,exports){ +var constants = require('../constants'); + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); + +},{"../constants":58}],58:[function(require,module,exports){ +var constants = exports; + +// Helper +constants._reverse = function reverse(map) { + var res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + var value = map[key]; + res[value] = key; + }); + + return res; +}; + +constants.der = require('./der'); + +},{"./der":57}],59:[function(require,module,exports){ +var util = require('util'); + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +util.inherits(DERNode, base.Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag) { + if (buffer.isEmpty()) + return false; + + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + var state = buffer.start(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + return buffer.cut(state); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + var res = decoder.decode(buffer, 'der'); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + + return { unused: unused, data: buffer.raw() }; + } else { + return this.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) + result = values[result.join(' ')]; + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return this.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + var res = 0; + + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + if (raw.length > 3) + return new bignum(raw); + + while (!buffer.isEmpty()) { + res <<= 8; + var i = buffer.readUInt8(); + if (buffer.isError(i)) + return i; + res |= i; + } + + if (values) + res = values[res] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity) { + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + var num = len & 0x7f; + if (num >= 4) + return buf.error('length octect is too long'); + + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} + +},{"../../asn1":51,"util":205}],60:[function(require,module,exports){ +var decoders = exports; + +decoders.der = require('./der'); + +},{"./der":59}],61:[function(require,module,exports){ +var util = require('util'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +util.inherits(DERNode, base.Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'octstr') + return this._createEncoderBuffer(str); + else if (tag === 'bitstr') + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/\s+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num <= 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + date.getFullYear(), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + date.getFullYear() % 100, + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (bignum !== null && num instanceof bignum) + num = new Buffer(num.toArray()); + + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x100) + return this._createEncoderBuffer(num); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Buffer(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + + return this._createEncoderBuffer(out); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity) { + return entity._getEncoder('der').tree; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} + +},{"../../asn1":51,"buffer":69,"util":205}],62:[function(require,module,exports){ +var encoders = exports; + +encoders.der = require('./der'); + +},{"./der":61}],63:[function(require,module,exports){ +// Utils + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +} + +// Could use `inherits` module, but don't want to move from single file +// architecture yet. +function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor +} + +// BN + +function BN(number, base) { + // May be `new BN(bn)` ? + if (number !== null && + typeof number === 'object' && + Array.isArray(number.words)) { + return number; + } + + this.sign = false; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) + this._init(number || 0, base || 10); +} +if (typeof module === 'object') + module.exports = BN; + +BN.BN = BN; +BN.wordSize = 26; + +BN.prototype._init = function init(number, base) { + if (typeof number === 'number') { + if (number < 0) { + this.sign = true; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } + return; + } else if (typeof number === 'object') { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + // Assume big-endian + var off = 0; + for (var i = number.length - 1, j = 0; i >= 0; i -= 3) { + var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + + return this.strip(); + } + if (base === 'hex') + base = 16; + assert(base <= 16); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') + start++; + + if (base === 16) + this._parseHex(number, start); + else + this._parseBase(number, base, start); + + if (number[0] === '-') + this.sign = true; + + this.strip(); +}; + +BN.prototype._parseHex = function parseHex(number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + // Scan 24-bit chunks and add them to the number + var off = 0; + for (var i = number.length - 6, j = 0; i >= start; i -= 6) { + var w = parseInt(number.slice(i, i + 6), 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + var w = parseInt(number.slice(start, i + 6), 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); +}; + +BN.prototype._parseBase = function parseBase(number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + var word = 0; + var q = 1; + var p = 0; + var bigQ = null; + for (var i = start; i < number.length; i++) { + var digit; + var ch = number[i]; + if (base === 10 || ch <= '9') + digit = ch | 0; + else if (ch >= 'a') + digit = ch.charCodeAt(0) - 97 + 10; + else + digit = ch.charCodeAt(0) - 65 + 10; + word *= base; + word += digit; + q *= base; + p++; + + if (q > 0xfffff) { + assert(q <= 0x3ffffff); + if (!bigQ) + bigQ = new BN(q); + this.mul(bigQ).copy(this); + this.iadd(new BN(word)); + word = 0; + q = 1; + p = 0; + } + } + if (p !== 0) { + this.mul(new BN(q)).copy(this); + this.iadd(new BN(word)); + } +}; + +BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + dest.words[i] = this.words[i]; + dest.length = this.length; + dest.sign = this.sign; + dest.red = this.red; +}; + +BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; +}; + +// Remove leading `0` from `this` +BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) + this.length--; + return this._normSign(); +}; + +BN.prototype._normSign = function _normSign() { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) + this.sign = false; + return this; +}; + +BN.prototype.inspect = function inspect() { + return (this.red ? ''; +}; + +/* +function _zero(n) { + var code = ''; + for (var i = n - 1; i > 0; i--) { + var pad = ''; + for (var j = 0; j < n - i; j++) + pad += '0'; + code += 'if (w.length === ' + i + ') return \'' + pad + '\' + w;\n'; + } + code += 'return w'; + + return new Function('w', code); +} + +var zero6 = _zero(6); +var zero14 = _zero(14); +*/ + +// Sadly chrome apps could not contain `new Function()` calls +function zero6(w) { + if (w.length === 5) return '0' + w; + if (w.length === 4) return '00' + w; + if (w.length === 3) return '000' + w; + if (w.length === 2) return '0000' + w; + if (w.length === 1) return '00000' + w; + return w; +} + +function zero14(w) { + if (w.length === 13) return '0' + w; + if (w.length === 12) return '00' + w; + if (w.length === 11) return '000' + w; + if (w.length === 10) return '0000' + w; + if (w.length === 9) return '00000' + w; + if (w.length === 8) return '000000' + w; + if (w.length === 7) return '0000000' + w; + if (w.length === 6) return '00000000' + w; + if (w.length === 5) return '000000000' + w; + if (w.length === 4) return '0000000000' + w; + if (w.length === 3) return '00000000000' + w; + if (w.length === 2) return '000000000000' + w; + if (w.length === 1) return '0000000000000' + w; + return w; +} + +// Precomputed divisor for `.toString(10)` = 10 ^ 14 +var div10 = new BN(null); +div10.words = [ 0x7a4000, 0x16bcc4 ]; +div10.length = 2; + +BN.prototype.toString = function toString(base) { + base = base || 10; + if (base === 16 || base === 'hex') { + var out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) + out = zero6(word) + out; + else + out = word + out; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) + out = carry.toString(16) + out; + if (this.sign) + out = '-' + out; + return out; + } else if (base === 10) { + var out = ''; + var c = this.clone(); + c.sign = false; + while (c.cmpn(0) !== 0) { + var r = c.modn(1000000); + c = c.idivn(1000000); + + if (c.cmpn(0) !== 0) + out = zero6(r + '') + out; + else + out = r + out; + } + if (this.cmpn(0) === 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else { + assert(false, 'Only 16 and 10 base are supported'); + } +}; + +BN.prototype.toJSON = function toJSON() { + return this.toString(16); +}; + +BN.prototype.toArray = function toArray() { + this.strip(); + var res = new Array(this.byteLength()); + res[0] = 0; + + var q = this.clone(); + for (var i = 0; q.cmpn(0) !== 0; i++) { + var b = q.andln(0xff); + q.ishrn(8); + + // Assume big-endian + res[res.length - i - 1] = b; + } + + return res; +}; + +/* +function genCountBits(bits) { + var arr = []; + + for (var i = bits - 1; i >= 0; i--) { + var bit = '0x' + (1 << i).toString(16); + arr.push('w >= ' + bit + ' ? ' + (i + 1)); + } + + return new Function('w', 'return ' + arr.join(' :\n') + ' :\n0;'); +}; + +BN.prototype._countBits = genCountBits(26); +*/ + +// Sadly chrome apps could not contain `new Function()` calls +BN.prototype._countBits = function _countBits(w) { + return w >= 0x2000000 ? 26 : + w >= 0x1000000 ? 25 : + w >= 0x800000 ? 24 : + w >= 0x400000 ? 23 : + w >= 0x200000 ? 22 : + w >= 0x100000 ? 21 : + w >= 0x80000 ? 20 : + w >= 0x40000 ? 19 : + w >= 0x20000 ? 18 : + w >= 0x10000 ? 17 : + w >= 0x8000 ? 16 : + w >= 0x4000 ? 15 : + w >= 0x2000 ? 14 : + w >= 0x1000 ? 13 : + w >= 0x800 ? 12 : + w >= 0x400 ? 11 : + w >= 0x200 ? 10 : + w >= 0x100 ? 9 : + w >= 0x80 ? 8 : + w >= 0x40 ? 7 : + w >= 0x20 ? 6 : + w >= 0x10 ? 5 : + w >= 0x8 ? 4 : + w >= 0x4 ? 3 : + w >= 0x2 ? 2 : + w >= 0x1 ? 1 : + 0; +}; + +// Return number of used bits in a BN +BN.prototype.bitLength = function bitLength() { + var hi = 0; + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; +}; + +BN.prototype.byteLength = function byteLength() { + var hi = 0; + var w = this.words[this.length - 1]; + return Math.ceil(this.bitLength() / 8); +}; + +// Return negative clone of `this` +BN.prototype.neg = function neg() { + if (this.cmpn(0) === 0) + return this.clone(); + + var r = this.clone(); + r.sign = !this.sign; + return r; +}; + +// Add `num` to `this` in-place +BN.prototype.iadd = function iadd(num) { + // negative + positive + if (this.sign && !num.sign) { + this.sign = false; + var r = this.isub(num); + this.sign = !this.sign; + return this._normSign(); + + // positive + negative + } else if (!this.sign && num.sign) { + num.sign = false; + var r = this.isub(num); + num.sign = true; + return r._normSign(); + } + + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] + b.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) + this.words[i] = a.words[i]; + } + + return this; +}; + +// Add `num` to `this` +BN.prototype.add = function add(num) { + if (num.sign && !this.sign) { + num.sign = false; + var res = this.sub(num); + num.sign = true; + return res; + } else if (!num.sign && this.sign) { + this.sign = false; + var res = num.sub(this); + this.sign = true; + return res; + } + + if (this.length > num.length) + return this.clone().iadd(num); + else + return num.clone().iadd(this); +}; + +// Subtract `num` from `this` in-place +BN.prototype.isub = function isub(num) { + // this - (-num) = this + num + if (num.sign) { + num.sign = false; + var r = this.iadd(num); + num.sign = true; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.sign) { + this.sign = false; + this.iadd(num); + this.sign = true; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.sign = false; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + if (cmp > 0) { + var a = this; + var b = num; + } else { + var a = num; + var b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] - b.words[i] - carry; + if (r < 0) { + r += 0x4000000; + carry = 1; + } else { + carry = 0; + } + this.words[i] = r; + } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] - carry; + if (r < 0) { + r += 0x4000000; + carry = 1; + } else { + carry = 0; + } + this.words[i] = r; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) + for (; i < a.length; i++) + this.words[i] = a.words[i]; + this.length = Math.max(this.length, i); + + if (a !== this) + this.sign = true; + + return this.strip(); +}; + +// Subtract `num` from `this` +BN.prototype.sub = function sub(num) { + return this.clone().isub(num); +}; + +/* +// NOTE: This could be potentionally used to generate loop-less multiplications +function _genCombMulTo(alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + + 'mask = 0x3ffffff, shift = 0x4000000;', + 'out.length = ' + len + ';' + ]; + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + for (var j = minJ; j <= maxJ; j++) { + var i = k - j; + var mul = 'a[' + i + '] * b[' + j + ']'; + + if (j === minJ) { + src.push('w = ' + mul + ' + c;'); + src.push('c = (w / shift) | 0;'); + } else { + src.push('w += ' + mul + ';'); + src.push('c += (w / shift) | 0;'); + } + src.push('w &= mask;'); + } + src.push('o[' + k + '] = w;'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} +*/ + +// Multiply `this` by `num` and store data in out +BN.prototype.mulTo = function mulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; + + var carry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i]; + var b = num.words[j]; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry += (r / 0x4000000) | 0; + lo += rword; + rword = lo & 0x3ffffff; + ncarry += lo >>> 26; + } + out.words[k] = rword; + carry = ncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); +}; + +// Multiply `this` by `num` +BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); +}; + +// In-place Multiplication +BN.prototype.imul = function imul(num) { + if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { + this.words[0] = 0; + this.length = 1; + return this; + } + + var tlen = this.length; + var nlen = num.length; + + this.sign = num.sign !== this.sign; + this.length = this.length + num.length; + this.words[this.length - 1] = 0; + + var lastCarry = 0; + for (var k = this.length - 2; k >= 0; k--) { + // Sum all words with the same `i + j = k` and accumulate `carry`, + // note that carry could be >= 0x3ffffff + var carry = 0; + var rword = 0; + var maxJ = Math.min(k, nlen - 1); + for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i]; + var b = num.words[j]; + var r = a * b; + + var lo = r & 0x3ffffff; + carry += (r / 0x4000000) | 0; + lo += rword; + rword = lo & 0x3ffffff; + carry += lo >>> 26; + } + this.words[k] = rword; + this.words[k + 1] += carry; + carry = 0; + } + + // Propagate overflows + var carry = 0; + for (var i = 1; i < this.length; i++) { + var w = this.words[i] + carry; + this.words[i] = w & 0x3ffffff; + carry = w >>> 26; + } + + return this.strip(); +}; + +// `this` * `this` +BN.prototype.sqr = function sqr() { + return this.mul(this); +}; + +// `this` * `this` in-place +BN.prototype.isqr = function isqr() { + return this.mul(this); +}; + +// Shift-left in-place +BN.prototype.ishln = function ishln(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + + var o = this.clone(); + if (r !== 0) { + var carry = 0; + for (var i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (var i = this.length - 1; i >= 0; i--) + this.words[i + s] = this.words[i]; + for (var i = 0; i < s; i++) + this.words[i] = 0; + this.length += s; + } + + return this.strip(); +}; + +// Shift-right in-place +// NOTE: `hint` is a lowest bit before trailing zeroes +// NOTE: if `extended` is true - { lo: ..., hi: } object will be returned +BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + if (hint) + hint = (hint - (hint % 26)) / 26; + else + hint = 0; + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + hint -= s; + hint = Math.max(0, hint); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) + maskedWords.words[i] = this.words[i]; + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (var i = 0; i < this.length; i++) + this.words[i] = this.words[i + s]; + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= hint); i--) { + var word = this.words[i]; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) + maskedWords.words[maskedWords.length++] = carry; + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + this.strip(); + if (extended) + return { hi: this, lo: maskedWords }; + + return this; +}; + +// Shift-left +BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); +}; + +// Shift-right +BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); +}; + +// Test if n bit is set +BN.prototype.testn = function testn(bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + return false; + } + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); +}; + +// Return only lowers bits of number (in-place) +BN.prototype.imaskn = function imaskn(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(!this.sign, 'imaskn works only with positive numbers'); + + if (r !== 0) + s++; + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); +}; + +// Return only lowers bits of number +BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); +}; + +// Add plain number `num` to `this` +BN.prototype.iaddn = function iaddn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.isubn(num); + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) + this.words[i + 1] = 1; + else + this.words[i + 1]++; + } + this.length = Math.max(this.length, i + 1); + + return this; +}; + +// Subtract plain number `num` from `this` +BN.prototype.isubn = function isubn(num) { + assert(typeof num === 'number'); + assert(this.cmpn(num) >= 0, 'Sign change is not supported in isubn'); + if (num < 0) + return this.iaddn(-num); + this.words[0] -= num; + + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + + return this.strip(); +}; + +BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); +}; + +BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); +}; + +BN.prototype.iabs = function iabs() { + this.sign = false; + + return this +}; + +BN.prototype.abs = function abs() { + return this.clone().iabs(); +}; + +BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + var q = mode !== 'mod' && new BN(0); + var sign = false; + + // Approximate quotient at each step + while (a.length > b.length) { + // NOTE: a.length is always >= 2, because of the condition .div() + var hi = a.words[a.length - 1] * 0x4000000 + a.words[a.length - 2]; + var sq = (hi / b.words[b.length - 1]); + var sqhi = (sq / 0x4000000) | 0; + var sqlo = sq & 0x3ffffff; + sq = new BN(null); + sq.words = [ sqlo, sqhi ]; + sq.length = 2; + + // Collect quotient + var shift = (a.length - b.length - 1) * 26; + if (q) { + var t = sq.shln(shift); + if (a.sign) + q.isub(t); + else + q.iadd(t); + } + + sq = sq.mul(b).ishln(shift); + if (a.sign) + a.iadd(sq) + else + a.isub(sq); + } + // At this point a.length <= b.length + while (a.ucmp(b) >= 0) { + // NOTE: a.length is always >= 2, because of the condition above + var hi = a.words[a.length - 1]; + var sq = new BN((hi / b.words[b.length - 1]) | 0); + var shift = (a.length - b.length) * 26; + + if (q) { + var t = sq.shln(shift); + if (a.sign) + q.isub(t); + else + q.iadd(t); + } + + sq = sq.mul(b).ishln(shift); + + if (a.sign) + a.iadd(sq); + else + a.isub(sq); + } + + if (a.sign) { + if (q) + q.isubn(1); + a.iadd(b); + } + return { div: q ? q : null, mod: a }; +}; + +BN.prototype.divmod = function divmod(num, mode) { + assert(num.cmpn(0) !== 0); + + if (this.sign && !num.sign) { + var res = this.neg().divmod(num, mode); + var div; + var mod; + if (mode !== 'mod') + div = res.div.neg(); + if (mode !== 'div') + mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); + return { + div: div, + mod: mod + }; + } else if (!this.sign && num.sign) { + var res = this.divmod(num.neg(), mode); + var div; + if (mode !== 'mod') + div = res.div.neg(); + return { div: div, mod: res.mod }; + } else if (this.sign && num.sign) { + return this.neg().divmod(num.neg(), mode); + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) + return { div: new BN(0), mod: this }; + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') + return { div: this.divn(num.words[0]), mod: null }; + else if (mode === 'mod') + return { div: null, mod: new BN(this.modn(num.words[0])) }; + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); +}; + +// Find `this` / `num` +BN.prototype.div = function div(num) { + return this.divmod(num, 'div').div; +}; + +// Find `this` % `num` +BN.prototype.mod = function mod(num) { + return this.divmod(num, 'mod').mod; +}; + +// Find Round(`this` / `num`) +BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.cmpn(0) === 0) + return dm.div; + + var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod; + + var half = num.shrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) + return dm.div; + + // Round up + return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1); +}; + +BN.prototype.modn = function modn(num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) + acc = (p * acc + this.words[i]) % num; + + return acc; +}; + +// In-place division by number +BN.prototype.idivn = function idivn(num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = this.words[i] + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); +}; + +BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); +}; + +BN.prototype._egcd = function _egcd(x1, p) { + assert(!p.sign); + assert(p.cmpn(0) !== 0); + + var a = this; + var b = p.clone(); + + if (a.sign) + a = a.mod(p); + else + a = a.clone(); + + var x2 = new BN(0); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + while (a.isEven()) { + a.ishrn(1); + if (x1.isEven()) + x1.ishrn(1); + else + x1.iadd(p).ishrn(1); + } + while (b.isEven()) { + b.ishrn(1); + if (x2.isEven()) + x2.ishrn(1); + else + x2.iadd(p).ishrn(1); + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + if (a.cmpn(1) === 0) + return x1; + else + return x2; +}; + +BN.prototype.gcd = function gcd(num) { + if (this.cmpn(0) === 0) + return num.clone(); + if (num.cmpn(0) === 0) + return this.clone(); + + var a = this.clone(); + var b = num.clone(); + a.sign = false; + b.sign = false; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.ishrn(1); + b.ishrn(1); + } + + while (a.isEven()) + a.ishrn(1); + + do { + while (b.isEven()) + b.ishrn(1); + + // Swap `a` and `b` to make `a` always bigger than `b` + if (a.cmp(b) < 0) { + var t = a; + a = b; + b = t; + } + a.isub(a.div(b).mul(b)); + } while (a.cmpn(0) !== 0 && b.cmpn(0) !== 0); + if (a.cmpn(0) === 0) + return b.ishln(shift); + else + return a.ishln(shift); +}; + +// Invert number in the field F(num) +BN.prototype.invm = function invm(num) { + return this._egcd(new BN(1), num).mod(num); +}; + +BN.prototype.isEven = function isEven(num) { + return (this.words[0] & 1) === 0; +}; + +BN.prototype.isOdd = function isOdd(num) { + return (this.words[0] & 1) === 1; +}; + +// And first word and num +BN.prototype.andln = function andln(num) { + return this.words[0] & num; +}; + +// Increment at the bit position in-line +BN.prototype.bincn = function bincn(bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + for (var i = this.length; i < s + 1; i++) + this.words[i] = 0; + this.words[s] |= q; + this.length = s + 1; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i]; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; +}; + +BN.prototype.cmpn = function cmpn(num) { + var sign = num < 0; + if (sign) + num = -num; + + if (this.sign && !sign) + return -1; + else if (!this.sign && sign) + return 1; + + num &= 0x3ffffff; + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + var w = this.words[0]; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.sign) + res = -res; + return res; +}; + +// Compare two numbers and return: +// 1 - if `this` > `num` +// 0 - if `this` == `num` +// -1 - if `this` < `num` +BN.prototype.cmp = function cmp(num) { + if (this.sign && !num.sign) + return -1; + else if (!this.sign && num.sign) + return 1; + + var res = this.ucmp(num); + if (this.sign) + return -res; + else + return res; +}; + +// Unsigned comparison +BN.prototype.ucmp = function ucmp(num) { + // At this point both numbers have the same sign + if (this.length > num.length) + return 1; + else if (this.length < num.length) + return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i]; + var b = num.words[i]; + + if (a === b) + continue; + if (a < b) + res = -1; + else if (a > b) + res = 1; + break; + } + return res; +}; + +// +// A reduce context, could be using montgomery or something better, depending +// on the `m` itself. +// +BN.red = function red(num) { + return new Red(num); +}; + +BN.prototype.toRed = function toRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(!this.sign, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); +}; + +BN.prototype.fromRed = function fromRed() { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); +}; + +BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; +}; + +BN.prototype.forceRed = function forceRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); +}; + +BN.prototype.redAdd = function redAdd(num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); +}; + +BN.prototype.redIAdd = function redIAdd(num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); +}; + +BN.prototype.redSub = function redSub(num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); +}; + +BN.prototype.redISub = function redISub(num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); +}; + +BN.prototype.redShl = function redShl(num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); +}; + +BN.prototype.redMul = function redMul(num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); +}; + +BN.prototype.redIMul = function redIMul(num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); +}; + +BN.prototype.redSqr = function redSqr() { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); +}; + +BN.prototype.redISqr = function redISqr() { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); +}; + +// Square root over p +BN.prototype.redSqrt = function redSqrt() { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); +}; + +BN.prototype.redInvm = function redInvm() { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); +}; + +// Return negative clone of `this` % `red modulo` +BN.prototype.redNeg = function redNeg() { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); +}; + +BN.prototype.redPow = function redPow(num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); +}; + +// Prime numbers with efficient reduction +var primes = { + k256: null, + p224: null, + p192: null, + p25519: null +}; + +// Pseudo-Mersenne prime +function MPrime(name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).ishln(this.n).isub(this.p); + + this.tmp = this._tmp(); +} + +MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; +}; + +MPrime.prototype.ireduce = function ireduce(num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + var pair = r.ishrn(this.n, 0, this.tmp); + r = this.imulK(pair.hi); + r = r.iadd(pair.lo); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.cmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; +}; + +MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); +}; + +function K256() { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); +} +inherits(K256, MPrime); + +K256.prototype.imulK = function imulK(num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + for (var i = num.length - 3; i >= 0; i--) { + var w = num.words[i]; + var hi = w * 0x40; + var lo = w * 0x3d1; + hi += (lo / 0x4000000) | 0; + var uhi = (hi / 0x4000000) | 0; + hi &= 0x3ffffff; + lo &= 0x3ffffff; + + num.words[i + 2] += uhi; + num.words[i + 1] += hi; + num.words[i] = lo; + } + var w = num.words[num.length - 2]; + if (w >= 0x4000000) { + num.words[num.length - 1] += w >>> 26; + num.words[num.length - 2] = w & 0x3ffffff; + } + if (num.words[num.length - 1] === 0) + num.length--; + if (num.words[num.length - 1] === 0) + num.length--; + return num; +}; + +function P224() { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); +} +inherits(P224, MPrime); + +function P192() { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); +} +inherits(P192, MPrime); + +function P25519() { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); +} +inherits(P25519, MPrime); + +P25519.prototype.imulK = function imulK(num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = num.words[i] * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) + num.words[num.length++] = carry; + return num; +}; + +// Exported mostly for testing purposes, use plain name instead +BN._prime = function prime(name) { + // Cached version of prime + if (primes[name]) + return primes[name]; + + var prime; + if (name === 'k256') + prime = new K256(); + else if (name === 'p224') + prime = new P224(); + else if (name === 'p192') + prime = new P192(); + else if (name === 'p25519') + prime = new P25519(); + else + throw new Error('Unknown prime ' + name); + primes[name] = prime; + + return prime; +} + +// +// Base reduction engine +// +function Red(m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; + } +} + +Red.prototype._verify1 = function _verify1(a) { + assert(!a.sign, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); +}; + +Red.prototype._verify2 = function _verify2(a, b) { + assert(!a.sign && !b.sign, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); +}; + +Red.prototype.imod = function imod(a) { + if (this.prime) + return this.prime.ireduce(a)._forceRed(this); + return a.mod(this.m)._forceRed(this); +}; + +Red.prototype.neg = function neg(a) { + var r = a.clone(); + r.sign = !r.sign; + return r.iadd(this.m)._forceRed(this); +}; + +Red.prototype.add = function add(a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res._forceRed(this); +}; + +Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res; +}; + +Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res._forceRed(this); +}; + +Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res; +}; + +Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.shln(num)); +}; + +Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); +}; + +Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); +}; + +Red.prototype.isqr = function isqr(a) { + return this.imul(a, a); +}; + +Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); +}; + +Red.prototype.sqrt = function sqrt(a) { + if (a.cmpn(0) === 0) + return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).ishrn(2); + var r = this.pow(a, pow); + return r; + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (q.cmpn(0) !== 0 && q.andln(1) === 0) { + s++; + q.ishrn(1); + } + assert(q.cmpn(0) !== 0); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).ishrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) + z.redIAdd(nOne); + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).ishrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) + tmp = tmp.redSqr(); + assert(i < m); + var b = this.pow(c, new BN(1).ishln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; +}; + +Red.prototype.invm = function invm(a) { + var inv = a._egcd(new BN(1), this.m); + if (inv.sign) { + inv.sign = false; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } +}; + +Red.prototype.pow = function pow(a, num) { + var w = []; + var q = num.clone(); + while (q.cmpn(0) !== 0) { + w.push(q.andln(1)); + q.ishrn(1); + } + + // Skip leading zeroes + var res = a; + for (var i = 0; i < w.length; i++, res = this.sqr(res)) + if (w[i] !== 0) + break; + + if (++i < w.length) { + for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { + if (w[i] === 0) + continue; + res = this.mul(res, q); + } + } + + return res; +}; + +Red.prototype.convertTo = function convertTo(num) { + return num.clone(); +}; + +Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; +}; + +// +// Montgomery method engine +// + +BN.mont = function mont(num) { + return new Mont(num); +}; + +function Mont(m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) + this.shift += 26 - (this.shift % 26); + this.r = new BN(1).ishln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r.invm(this.m); + + // TODO(indutny): simplify it + this.minv = this.rinv.mul(this.r) + .sub(new BN(1)) + .div(this.m) + .neg() + .mod(this.r); +} +inherits(Mont, Red); + +Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.shln(this.shift)); +}; + +Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; +}; + +Mont.prototype.imul = function imul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); + + return res._forceRed(this); +}; + +Mont.prototype.mul = function mul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) + return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); + + return res._forceRed(this); +}; + +Mont.prototype.invm = function invm(a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a.invm(this.m).mul(this.r2)); + return res._forceRed(this); +}; + +},{}],64:[function(require,module,exports){ +try { + var asn1 = require('asn1.js'); +} catch (e) { + var asn1 = require('../..'); +} + +var CRLReason = asn1.define('CRLReason', function() { + this.enum({ + 0: 'unspecified', + 1: 'keyCompromise', + 2: 'CACompromise', + 3: 'affiliationChanged', + 4: 'superseded', + 5: 'cessationOfOperation', + 6: 'certificateHold', + 8: 'removeFromCRL', + 9: 'privilegeWithdrawn', + 10: 'AACompromise' + }); +}); +exports.CRLReason = CRLReason; + +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function() { + this.seq().obj( + this.key('algorithm').objid(), + this.key('parameters').optional().any() + ); +}); +exports.AlgorithmIdentifier = AlgorithmIdentifier; + +var Certificate = asn1.define('Certificate', function() { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signature').bitstr() + ); +}); +exports.Certificate = Certificate; + +var TBSCertificate = asn1.define('TBSCertificate', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).use(Version), + this.key('serialNumber').use(CertificateSerialNumber), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + + // TODO(indutny): validate that version is v2 or v3 + this.key('issuerUniqueID').optional().explicit(1).use(UniqueIdentifier), + this.key('subjectUniqueID').optional().explicit(2).use(UniqueIdentifier), + + // TODO(indutny): validate that version is v3 + this.key('extensions').optional().explicit(3).use(Extensions) + ); +}); +exports.TBSCertificate = TBSCertificate; + +var Version = asn1.define('Version', function() { + this.int({ + 0: 'v1', + 1: 'v2', + 2: 'v3' + }); +}); +exports.Version = Version; + +var CertificateSerialNumber = asn1.define('CertificateSerialNumber', + function() { + this.int(); +}); +exports.CertificateSerialNumber = CertificateSerialNumber; + +var Validity = asn1.define('Validity', function() { + this.seq().obj( + this.key('notBefore').use(Time), + this.key('notAfter').use(Time) + ); +}); +exports.Validity = Validity; + +var Time = asn1.define('Time', function() { + this.choice({ + utcTime: this.utctime(), + genTime: this.gentime() + }); +}); +exports.Time = Time; + +var UniqueIdentifier = asn1.define('UniqueIdentifier', function() { + this.bitstr(); +}); +exports.UniqueIdentifier = UniqueIdentifier; + +var SubjectPublicKeyInfo = asn1.define('SubjectPublicKeyInfo', function() { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); +exports.SubjectPublicKeyInfo = SubjectPublicKeyInfo; + +var Extensions = asn1.define('Extensions', function() { + this.seqof(Extension); +}); +exports.Extensions = Extensions; + +var Extension = asn1.define('Extension', function() { + this.seq().obj( + this.key('extnID').objid(), + this.key('critical').bool().def(false), + this.key('extnValue').octstr() + ); +}); +exports.Extension = Extension; + +var Name = asn1.define('Name', function() { + this.choice({ + rdn: this.use(RDNSequence) + }); +}); +exports.Name = Name; + +var RDNSequence = asn1.define('RDNSequence', function() { + this.seqof(RelativeDistinguishedName); +}); +exports.RDNSequence = RDNSequence; + +var RelativeDistinguishedName = asn1.define('RelativeDistinguishedName', + function() { + this.setof(AttributeTypeAndValue); +}); +exports.RelativeDistinguishedName = RelativeDistinguishedName; + +var AttributeTypeAndValue = asn1.define('AttributeTypeAndValue', function() { + this.seq().obj( + this.key('type').use(AttributeType), + this.key('value').use(AttributeValue) + ); +}); +exports.AttributeTypeAndValue = AttributeTypeAndValue; + +var AttributeType = asn1.define('AttributeType', function() { + this.objid(); +}); +exports.AttributeType = AttributeType; + +var AttributeValue = asn1.define('AttributeValue', function() { + this.any(); +}); +exports.AttributeValue = AttributeValue; + +},{"../..":51,"asn1.js":51}],65:[function(require,module,exports){ +// Utils + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +} + +// Could use `inherits` module, but don't want to move from single file +// architecture yet. +function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor +} + +// BN + +function BN(number, base) { + // May be `new BN(bn)` ? + if (number !== null && + typeof number === 'object' && + Array.isArray(number.words)) { + return number; + } + + this.sign = false; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) + this._init(number || 0, base || 10); +} +if (typeof module === 'object') + module.exports = BN; + +BN.BN = BN; +BN.wordSize = 26; + +BN.prototype._init = function init(number, base) { + if (typeof number === 'number') { + if (number < 0) { + this.sign = true; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } + return; + } else if (typeof number === 'object') { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + // Assume big-endian + var off = 0; + for (var i = number.length - 1, j = 0; i >= 0; i -= 3) { + var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + + return this.strip(); + } + if (base === 'hex') + base = 16; + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') + start++; + + if (base === 16) + this._parseHex(number, start); + else + this._parseBase(number, base, start); + + if (number[0] === '-') + this.sign = true; + + this.strip(); +}; + +BN.prototype._parseHex = function parseHex(number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + // Scan 24-bit chunks and add them to the number + var off = 0; + for (var i = number.length - 6, j = 0; i >= start; i -= 6) { + var w = parseInt(number.slice(i, i + 6), 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + var w = parseInt(number.slice(start, i + 6), 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); +}; + +BN.prototype._parseBase = function parseBase(number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + var word = 0; + var q = 1; + var p = 0; + var bigQ = null; + for (var i = start; i < number.length; i++) { + var digit; + var ch = number[i]; + if (base === 10 || ch <= '9') + digit = ch | 0; + else if (ch >= 'a') + digit = ch.charCodeAt(0) - 97 + 10; + else + digit = ch.charCodeAt(0) - 65 + 10; + word *= base; + word += digit; + q *= base; + p++; + + if (q > 0xfffff) { + assert(q <= 0x3ffffff); + if (!bigQ) + bigQ = new BN(q); + this.mul(bigQ).copy(this); + this.iadd(new BN(word)); + word = 0; + q = 1; + p = 0; + } + } + if (p !== 0) { + this.mul(new BN(q)).copy(this); + this.iadd(new BN(word)); + } +}; + +BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + dest.words[i] = this.words[i]; + dest.length = this.length; + dest.sign = this.sign; + dest.red = this.red; +}; + +BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; +}; + +// Remove leading `0` from `this` +BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) + this.length--; + return this._normSign(); +}; + +BN.prototype._normSign = function _normSign() { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) + this.sign = false; + return this; +}; + +BN.prototype.inspect = function inspect() { + return (this.red ? ''; +}; + +/* + +var zeros = []; +var groupSizes = []; +var groupBases = []; + +var s = ''; +var i = -1; +while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; +} +groupSizes[0] = 0; +groupSizes[1] = 0; +groupBases[0] = 0; +groupBases[1] = 0; +var base = 2 - 1; +while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + // TODO: <= + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; +} + +*/ + +var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' +]; + +var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 +]; + +var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 +]; + +BN.prototype.toString = function toString(base, padding) { + base = base || 10; + if (base === 16 || base === 'hex') { + var out = ''; + var off = 0; + var padding = padding | 0 || 1; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) + out = zeros[6 - word.length] + word + out; + else + out = word + out; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) + out = carry.toString(16) + out; + while (out.length % padding !== 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + var out = ''; + var c = this.clone(); + c.sign = false; + while (c.cmpn(0) !== 0) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (c.cmpn(0) !== 0) + out = zeros[groupSize - r.length] + r + out; + else + out = r + out; + } + if (this.cmpn(0) === 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else { + assert(false, 'Base should be between 2 and 36'); + } +}; + +BN.prototype.toJSON = function toJSON() { + return this.toString(16); +}; + +BN.prototype.toArray = function toArray() { + this.strip(); + var res = new Array(this.byteLength()); + res[0] = 0; + + var q = this.clone(); + for (var i = 0; q.cmpn(0) !== 0; i++) { + var b = q.andln(0xff); + q.ishrn(8); + + // Assume big-endian + res[res.length - i - 1] = b; + } + + return res; +}; + +/* +function genCountBits(bits) { + var arr = []; + + for (var i = bits - 1; i >= 0; i--) { + var bit = '0x' + (1 << i).toString(16); + arr.push('w >= ' + bit + ' ? ' + (i + 1)); + } + + return new Function('w', 'return ' + arr.join(' :\n') + ' :\n0;'); +}; + +BN.prototype._countBits = genCountBits(26); +*/ + +// Sadly chrome apps could not contain `new Function()` calls +BN.prototype._countBits = function _countBits(w) { + return w >= 0x2000000 ? 26 : + w >= 0x1000000 ? 25 : + w >= 0x800000 ? 24 : + w >= 0x400000 ? 23 : + w >= 0x200000 ? 22 : + w >= 0x100000 ? 21 : + w >= 0x80000 ? 20 : + w >= 0x40000 ? 19 : + w >= 0x20000 ? 18 : + w >= 0x10000 ? 17 : + w >= 0x8000 ? 16 : + w >= 0x4000 ? 15 : + w >= 0x2000 ? 14 : + w >= 0x1000 ? 13 : + w >= 0x800 ? 12 : + w >= 0x400 ? 11 : + w >= 0x200 ? 10 : + w >= 0x100 ? 9 : + w >= 0x80 ? 8 : + w >= 0x40 ? 7 : + w >= 0x20 ? 6 : + w >= 0x10 ? 5 : + w >= 0x8 ? 4 : + w >= 0x4 ? 3 : + w >= 0x2 ? 2 : + w >= 0x1 ? 1 : + 0; +}; + +// Return number of used bits in a BN +BN.prototype.bitLength = function bitLength() { + var hi = 0; + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; +}; + +BN.prototype.byteLength = function byteLength() { + var hi = 0; + var w = this.words[this.length - 1]; + return Math.ceil(this.bitLength() / 8); +}; + +// Return negative clone of `this` +BN.prototype.neg = function neg() { + if (this.cmpn(0) === 0) + return this.clone(); + + var r = this.clone(); + r.sign = !this.sign; + return r; +}; + +// Add `num` to `this` in-place +BN.prototype.iadd = function iadd(num) { + // negative + positive + if (this.sign && !num.sign) { + this.sign = false; + var r = this.isub(num); + this.sign = !this.sign; + return this._normSign(); + + // positive + negative + } else if (!this.sign && num.sign) { + num.sign = false; + var r = this.isub(num); + num.sign = true; + return r._normSign(); + } + + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] + b.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) + this.words[i] = a.words[i]; + } + + return this; +}; + +// Add `num` to `this` +BN.prototype.add = function add(num) { + if (num.sign && !this.sign) { + num.sign = false; + var res = this.sub(num); + num.sign = true; + return res; + } else if (!num.sign && this.sign) { + this.sign = false; + var res = num.sub(this); + this.sign = true; + return res; + } + + if (this.length > num.length) + return this.clone().iadd(num); + else + return num.clone().iadd(this); +}; + +// Subtract `num` from `this` in-place +BN.prototype.isub = function isub(num) { + // this - (-num) = this + num + if (num.sign) { + num.sign = false; + var r = this.iadd(num); + num.sign = true; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.sign) { + this.sign = false; + this.iadd(num); + this.sign = true; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.sign = false; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + if (cmp > 0) { + var a = this; + var b = num; + } else { + var a = num; + var b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] - b.words[i] - carry; + if (r < 0) { + r += 0x4000000; + carry = 1; + } else { + carry = 0; + } + this.words[i] = r; + } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] - carry; + if (r < 0) { + r += 0x4000000; + carry = 1; + } else { + carry = 0; + } + this.words[i] = r; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) + for (; i < a.length; i++) + this.words[i] = a.words[i]; + this.length = Math.max(this.length, i); + + if (a !== this) + this.sign = true; + + return this.strip(); +}; + +// Subtract `num` from `this` +BN.prototype.sub = function sub(num) { + return this.clone().isub(num); +}; + +/* +// NOTE: This could be potentionally used to generate loop-less multiplications +function _genCombMulTo(alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + + 'mask = 0x3ffffff, shift = 0x4000000;', + 'out.length = ' + len + ';' + ]; + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + for (var j = minJ; j <= maxJ; j++) { + var i = k - j; + var mul = 'a[' + i + '] * b[' + j + ']'; + + if (j === minJ) { + src.push('w = ' + mul + ' + c;'); + src.push('c = (w / shift) | 0;'); + } else { + src.push('w += ' + mul + ';'); + src.push('c += (w / shift) | 0;'); + } + src.push('w &= mask;'); + } + src.push('o[' + k + '] = w;'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} +*/ + +BN.prototype._smallMulTo = function _smallMulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; + + var carry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + } + out.words[k] = rword; + carry = ncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); +}; + +BN.prototype._bigMulTo = function _bigMulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); +}; + +BN.prototype.mulTo = function mulTo(num, out) { + var res; + if (this.length + num.length < 63) + res = this._smallMulTo(num, out); + else + res = this._bigMulTo(num, out); + return res; +}; + +// Multiply `this` by `num` +BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); +}; + +// In-place Multiplication +BN.prototype.imul = function imul(num) { + if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { + this.words[0] = 0; + this.length = 1; + return this; + } + + var tlen = this.length; + var nlen = num.length; + + this.sign = num.sign !== this.sign; + this.length = this.length + num.length; + this.words[this.length - 1] = 0; + + var lastCarry = 0; + for (var k = this.length - 2; k >= 0; k--) { + // Sum all words with the same `i + j = k` and accumulate `carry`, + // note that carry could be >= 0x3ffffff + var carry = 0; + var rword = 0; + var maxJ = Math.min(k, nlen - 1); + for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i]; + var b = num.words[j]; + var r = a * b; + + var lo = r & 0x3ffffff; + carry += (r / 0x4000000) | 0; + lo += rword; + rword = lo & 0x3ffffff; + carry += lo >>> 26; + } + this.words[k] = rword; + this.words[k + 1] += carry; + carry = 0; + } + + // Propagate overflows + var carry = 0; + for (var i = 1; i < this.length; i++) { + var w = this.words[i] + carry; + this.words[i] = w & 0x3ffffff; + carry = w >>> 26; + } + + return this.strip(); +}; + +// `this` * `this` +BN.prototype.sqr = function sqr() { + return this.mul(this); +}; + +// `this` * `this` in-place +BN.prototype.isqr = function isqr() { + return this.mul(this); +}; + +// Shift-left in-place +BN.prototype.ishln = function ishln(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + + var o = this.clone(); + if (r !== 0) { + var carry = 0; + for (var i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (var i = this.length - 1; i >= 0; i--) + this.words[i + s] = this.words[i]; + for (var i = 0; i < s; i++) + this.words[i] = 0; + this.length += s; + } + + return this.strip(); +}; + +// Shift-right in-place +// NOTE: `hint` is a lowest bit before trailing zeroes +// NOTE: if `extended` is true - { lo: ..., hi: } object will be returned +BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + if (hint) + hint = (hint - (hint % 26)) / 26; + else + hint = 0; + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + hint -= s; + hint = Math.max(0, hint); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) + maskedWords.words[i] = this.words[i]; + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (var i = 0; i < this.length; i++) + this.words[i] = this.words[i + s]; + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= hint); i--) { + var word = this.words[i]; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) + maskedWords.words[maskedWords.length++] = carry; + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + this.strip(); + if (extended) + return { hi: this, lo: maskedWords }; + + return this; +}; + +// Shift-left +BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); +}; + +// Shift-right +BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); +}; + +// Test if n bit is set +BN.prototype.testn = function testn(bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + return false; + } + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); +}; + +// Return only lowers bits of number (in-place) +BN.prototype.imaskn = function imaskn(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(!this.sign, 'imaskn works only with positive numbers'); + + if (r !== 0) + s++; + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); +}; + +// Return only lowers bits of number +BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); +}; + +// Add plain number `num` to `this` +BN.prototype.iaddn = function iaddn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.isubn(-num); + + // Possible sign change + if (this.sign) { + if (this.length === 1 && this.words[0] < num) { + this.words[0] = num - this.words[0]; + this.sign = false; + return this; + } + + this.sign = false; + this.isubn(num); + this.sign = true; + return this; + } + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) + this.words[i + 1] = 1; + else + this.words[i + 1]++; + } + this.length = Math.max(this.length, i + 1); + + return this; +}; + +// Subtract plain number `num` from `this` +BN.prototype.isubn = function isubn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.iaddn(-num); + + if (this.sign) { + this.sign = false; + this.iaddn(num); + this.sign = true; + return this; + } + + this.words[0] -= num; + + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + + return this.strip(); +}; + +BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); +}; + +BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); +}; + +BN.prototype.iabs = function iabs() { + this.sign = false; + + return this +}; + +BN.prototype.abs = function abs() { + return this.clone().iabs(); +}; + +BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + var q = mode !== 'mod' && new BN(0); + var sign = false; + + // Approximate quotient at each step + while (a.length > b.length) { + // NOTE: a.length is always >= 2, because of the condition .div() + var hi = a.words[a.length - 1] * 0x4000000 + a.words[a.length - 2]; + var sq = (hi / b.words[b.length - 1]); + var sqhi = (sq / 0x4000000) | 0; + var sqlo = sq & 0x3ffffff; + sq = new BN(null); + sq.words = [ sqlo, sqhi ]; + sq.length = 2; + + // Collect quotient + var shift = (a.length - b.length - 1) * 26; + if (q) { + var t = sq.shln(shift); + if (a.sign) + q.isub(t); + else + q.iadd(t); + } + + sq = sq.mul(b).ishln(shift); + if (a.sign) + a.iadd(sq) + else + a.isub(sq); + } + // At this point a.length <= b.length + while (a.ucmp(b) >= 0) { + // NOTE: a.length is always >= 2, because of the condition above + var hi = a.words[a.length - 1]; + var sq = new BN((hi / b.words[b.length - 1]) | 0); + var shift = (a.length - b.length) * 26; + + if (q) { + var t = sq.shln(shift); + if (a.sign) + q.isub(t); + else + q.iadd(t); + } + + sq = sq.mul(b).ishln(shift); + + if (a.sign) + a.iadd(sq); + else + a.isub(sq); + } + + if (a.sign) { + if (q) + q.isubn(1); + a.iadd(b); + } + return { div: q ? q : null, mod: a }; +}; + +BN.prototype.divmod = function divmod(num, mode) { + assert(num.cmpn(0) !== 0); + + if (this.sign && !num.sign) { + var res = this.neg().divmod(num, mode); + var div; + var mod; + if (mode !== 'mod') + div = res.div.neg(); + if (mode !== 'div') + mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); + return { + div: div, + mod: mod + }; + } else if (!this.sign && num.sign) { + var res = this.divmod(num.neg(), mode); + var div; + if (mode !== 'mod') + div = res.div.neg(); + return { div: div, mod: res.mod }; + } else if (this.sign && num.sign) { + return this.neg().divmod(num.neg(), mode); + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) + return { div: new BN(0), mod: this }; + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') + return { div: this.divn(num.words[0]), mod: null }; + else if (mode === 'mod') + return { div: null, mod: new BN(this.modn(num.words[0])) }; + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); +}; + +// Find `this` / `num` +BN.prototype.div = function div(num) { + return this.divmod(num, 'div').div; +}; + +// Find `this` % `num` +BN.prototype.mod = function mod(num) { + return this.divmod(num, 'mod').mod; +}; + +// Find Round(`this` / `num`) +BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.cmpn(0) === 0) + return dm.div; + + var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod; + + var half = num.shrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) + return dm.div; + + // Round up + return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1); +}; + +BN.prototype.modn = function modn(num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) + acc = (p * acc + this.words[i]) % num; + + return acc; +}; + +// In-place division by number +BN.prototype.idivn = function idivn(num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = this.words[i] + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); +}; + +BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); +}; + +BN.prototype._egcd = function _egcd(x1, p) { + assert(!p.sign); + assert(p.cmpn(0) !== 0); + + var a = this; + var b = p.clone(); + + if (a.sign) + a = a.mod(p); + else + a = a.clone(); + + var x2 = new BN(0); + while (b.isEven()) + b.ishrn(1); + var delta = b.clone(); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + while (a.isEven()) { + a.ishrn(1); + if (x1.isEven()) + x1.ishrn(1); + else + x1.iadd(delta).ishrn(1); + } + while (b.isEven()) { + b.ishrn(1); + if (x2.isEven()) + x2.ishrn(1); + else + x2.iadd(delta).ishrn(1); + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + if (a.cmpn(1) === 0) + return x1; + else + return x2; +}; + +BN.prototype.gcd = function gcd(num) { + if (this.cmpn(0) === 0) + return num.clone(); + if (num.cmpn(0) === 0) + return this.clone(); + + var a = this.clone(); + var b = num.clone(); + a.sign = false; + b.sign = false; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.ishrn(1); + b.ishrn(1); + } + + while (a.isEven()) + a.ishrn(1); + + do { + while (b.isEven()) + b.ishrn(1); + + // Swap `a` and `b` to make `a` always bigger than `b` + if (a.cmp(b) < 0) { + var t = a; + a = b; + b = t; + } + a.isub(a.div(b).mul(b)); + } while (a.cmpn(0) !== 0 && b.cmpn(0) !== 0); + if (a.cmpn(0) === 0) + return b.ishln(shift); + else + return a.ishln(shift); +}; + +// Invert number in the field F(num) +BN.prototype.invm = function invm(num) { + return this._egcd(new BN(1), num).mod(num); +}; + +BN.prototype.isEven = function isEven(num) { + return (this.words[0] & 1) === 0; +}; + +BN.prototype.isOdd = function isOdd(num) { + return (this.words[0] & 1) === 1; +}; + +// And first word and num +BN.prototype.andln = function andln(num) { + return this.words[0] & num; +}; + +// Increment at the bit position in-line +BN.prototype.bincn = function bincn(bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + for (var i = this.length; i < s + 1; i++) + this.words[i] = 0; + this.words[s] |= q; + this.length = s + 1; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i]; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; +}; + +BN.prototype.cmpn = function cmpn(num) { + var sign = num < 0; + if (sign) + num = -num; + + if (this.sign && !sign) + return -1; + else if (!this.sign && sign) + return 1; + + num &= 0x3ffffff; + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + var w = this.words[0]; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.sign) + res = -res; + return res; +}; + +// Compare two numbers and return: +// 1 - if `this` > `num` +// 0 - if `this` == `num` +// -1 - if `this` < `num` +BN.prototype.cmp = function cmp(num) { + if (this.sign && !num.sign) + return -1; + else if (!this.sign && num.sign) + return 1; + + var res = this.ucmp(num); + if (this.sign) + return -res; + else + return res; +}; + +// Unsigned comparison +BN.prototype.ucmp = function ucmp(num) { + // At this point both numbers have the same sign + if (this.length > num.length) + return 1; + else if (this.length < num.length) + return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i]; + var b = num.words[i]; + + if (a === b) + continue; + if (a < b) + res = -1; + else if (a > b) + res = 1; + break; + } + return res; +}; + +// +// A reduce context, could be using montgomery or something better, depending +// on the `m` itself. +// +BN.red = function red(num) { + return new Red(num); +}; + +BN.prototype.toRed = function toRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(!this.sign, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); +}; + +BN.prototype.fromRed = function fromRed() { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); +}; + +BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; +}; + +BN.prototype.forceRed = function forceRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); +}; + +BN.prototype.redAdd = function redAdd(num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); +}; + +BN.prototype.redIAdd = function redIAdd(num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); +}; + +BN.prototype.redSub = function redSub(num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); +}; + +BN.prototype.redISub = function redISub(num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); +}; + +BN.prototype.redShl = function redShl(num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); +}; + +BN.prototype.redMul = function redMul(num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); +}; + +BN.prototype.redIMul = function redIMul(num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); +}; + +BN.prototype.redSqr = function redSqr() { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); +}; + +BN.prototype.redISqr = function redISqr() { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); +}; + +// Square root over p +BN.prototype.redSqrt = function redSqrt() { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); +}; + +BN.prototype.redInvm = function redInvm() { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); +}; + +// Return negative clone of `this` % `red modulo` +BN.prototype.redNeg = function redNeg() { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); +}; + +BN.prototype.redPow = function redPow(num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); +}; + +// Prime numbers with efficient reduction +var primes = { + k256: null, + p224: null, + p192: null, + p25519: null +}; + +// Pseudo-Mersenne prime +function MPrime(name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).ishln(this.n).isub(this.p); + + this.tmp = this._tmp(); +} + +MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; +}; + +MPrime.prototype.ireduce = function ireduce(num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + var pair = r.ishrn(this.n, 0, this.tmp); + r = this.imulK(pair.hi); + r = r.iadd(pair.lo); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.cmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; +}; + +MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); +}; + +function K256() { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); +} +inherits(K256, MPrime); + +K256.prototype.imulK = function imulK(num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + for (var i = num.length - 3; i >= 0; i--) { + var w = num.words[i]; + var hi = w * 0x40; + var lo = w * 0x3d1; + hi += (lo / 0x4000000) | 0; + var uhi = (hi / 0x4000000) | 0; + hi &= 0x3ffffff; + lo &= 0x3ffffff; + + num.words[i + 2] += uhi; + num.words[i + 1] += hi; + num.words[i] = lo; + } + var w = num.words[num.length - 2]; + if (w >= 0x4000000) { + num.words[num.length - 1] += w >>> 26; + num.words[num.length - 2] = w & 0x3ffffff; + } + if (num.words[num.length - 1] === 0) + num.length--; + if (num.words[num.length - 1] === 0) + num.length--; + return num; +}; + +function P224() { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); +} +inherits(P224, MPrime); + +function P192() { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); +} +inherits(P192, MPrime); + +function P25519() { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); +} +inherits(P25519, MPrime); + +P25519.prototype.imulK = function imulK(num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = num.words[i] * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) + num.words[num.length++] = carry; + return num; +}; + +// Exported mostly for testing purposes, use plain name instead +BN._prime = function prime(name) { + // Cached version of prime + if (primes[name]) + return primes[name]; + + var prime; + if (name === 'k256') + prime = new K256(); + else if (name === 'p224') + prime = new P224(); + else if (name === 'p192') + prime = new P192(); + else if (name === 'p25519') + prime = new P25519(); + else + throw new Error('Unknown prime ' + name); + primes[name] = prime; + + return prime; +} + +// +// Base reduction engine +// +function Red(m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; + } +} + +Red.prototype._verify1 = function _verify1(a) { + assert(!a.sign, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); +}; + +Red.prototype._verify2 = function _verify2(a, b) { + assert(!a.sign && !b.sign, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); +}; + +Red.prototype.imod = function imod(a) { + if (this.prime) + return this.prime.ireduce(a)._forceRed(this); + return a.mod(this.m)._forceRed(this); +}; + +Red.prototype.neg = function neg(a) { + var r = a.clone(); + r.sign = !r.sign; + return r.iadd(this.m)._forceRed(this); +}; + +Red.prototype.add = function add(a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res._forceRed(this); +}; + +Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res; +}; + +Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res._forceRed(this); +}; + +Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res; +}; + +Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.shln(num)); +}; + +Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); +}; + +Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); +}; + +Red.prototype.isqr = function isqr(a) { + return this.imul(a, a); +}; + +Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); +}; + +Red.prototype.sqrt = function sqrt(a) { + if (a.cmpn(0) === 0) + return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).ishrn(2); + var r = this.pow(a, pow); + return r; + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (q.cmpn(0) !== 0 && q.andln(1) === 0) { + s++; + q.ishrn(1); + } + assert(q.cmpn(0) !== 0); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).ishrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) + z.redIAdd(nOne); + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).ishrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) + tmp = tmp.redSqr(); + assert(i < m); + var b = this.pow(c, new BN(1).ishln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; +}; + +Red.prototype.invm = function invm(a) { + var inv = a._egcd(new BN(1), this.m); + if (inv.sign) { + inv.sign = false; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } +}; + +Red.prototype.pow = function pow(a, num) { + var w = []; + var q = num.clone(); + while (q.cmpn(0) !== 0) { + w.push(q.andln(1)); + q.ishrn(1); + } + + // Skip leading zeroes + var res = a; + for (var i = 0; i < w.length; i++, res = this.sqr(res)) + if (w[i] !== 0) + break; + + if (++i < w.length) { + for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { + if (w[i] === 0) + continue; + res = this.mul(res, q); + } + } + + return res; +}; + +Red.prototype.convertTo = function convertTo(num) { + return num.clone(); +}; + +Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; +}; + +// +// Montgomery method engine +// + +BN.mont = function mont(num) { + return new Mont(num); +}; + +function Mont(m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) + this.shift += 26 - (this.shift % 26); + this.r = new BN(1).ishln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r.invm(this.m); + + // TODO(indutny): simplify it + this.minv = this.rinv.mul(this.r) + .sub(new BN(1)) + .div(this.m) + .neg() + .mod(this.r); +} +inherits(Mont, Red); + +Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.shln(this.shift)); +}; + +Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; +}; + +Mont.prototype.imul = function imul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); + + return res._forceRed(this); +}; + +Mont.prototype.mul = function mul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) + return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); + + return res._forceRed(this); +}; + +Mont.prototype.invm = function invm(a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a.invm(this.m).mul(this.r2)); + return res._forceRed(this); +}; + +},{}],66:[function(require,module,exports){ + +},{}],67:[function(require,module,exports){ +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// when used in node, this will actually load the util module we depend on +// versus loading the builtin util module as happens otherwise +// this is a bug in node module loading as far as I am concerned +var util = require('util/'); + +var pSlice = Array.prototype.slice; +var hasOwn = Object.prototype.hasOwnProperty; + +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } + else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = stackStartFunction.name; + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); + } + return value; +} + +function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} + +function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +function _deepEqual(actual, expected) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; + + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } + + return true; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + //~~~I've managed to break Object.keys through screwy arguments passing. + // Converting to array solves the problem. + if (isArguments(a)) { + if (!isArguments(b)) { + return false; + } + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b); + } + try { + var ka = objectKeys(a), + kb = objectKeys(b), + key, i; + } catch (e) {//happens when one is a string literal and the other isn't + return false; + } + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key])) return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (util.isString(expected)) { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws.apply(this, [true].concat(pSlice.call(arguments))); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); +}; + +assert.ifError = function(err) { if (err) {throw err;}}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +},{"util/":205}],68:[function(require,module,exports){ +module.exports=require(66) +},{"/Users/yemeljardi/code/bitcore/node_modules/browserify/lib/_empty.js":66}],69:[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('is-array') + +exports.Buffer = Buffer +exports.SlowBuffer = Buffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 // not used by this implementation + +var kMaxLength = 0x3fffffff + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Note: + * + * - Implementation must support adding new properties to `Uint8Array` instances. + * Firefox 4-29 lacked support, fixed in Firefox 30+. + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + * + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will + * get the Object implementation, which is slower but will work correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = (function () { + try { + var buf = new ArrayBuffer(0) + var arr = new Uint8Array(buf) + arr.foo = function () { return 42 } + return 42 === arr.foo() && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +})() + +/** + * Class: Buffer + * ============= + * + * The Buffer constructor returns instances of `Uint8Array` that are augmented + * with function properties for all the node `Buffer` API functions. We use + * `Uint8Array` so that square bracket notation works as expected -- it returns + * a single octet. + * + * By augmenting the instances, we can avoid modifying the `Uint8Array` + * prototype. + */ +function Buffer (subject, encoding, noZero) { + if (!(this instanceof Buffer)) + return new Buffer(subject, encoding, noZero) + + var type = typeof subject + + // Find the length + var length + if (type === 'number') + length = subject > 0 ? subject >>> 0 : 0 + else if (type === 'string') { + if (encoding === 'base64') + subject = base64clean(subject) + length = Buffer.byteLength(subject, encoding) + } else if (type === 'object' && subject !== null) { // assume object is array-like + if (subject.type === 'Buffer' && isArray(subject.data)) + subject = subject.data + length = +subject.length > 0 ? Math.floor(+subject.length) : 0 + } else + throw new TypeError('must start with number, buffer, array or string') + + if (this.length > kMaxLength) + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength.toString(16) + ' bytes') + + var buf + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Preferred: Return an augmented `Uint8Array` instance for best performance + buf = Buffer._augment(new Uint8Array(length)) + } else { + // Fallback: Return THIS instance of Buffer (created by `new`) + buf = this + buf.length = length + buf._isBuffer = true + } + + var i + if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { + // Speed optimization -- use set if we're copying from a typed array + buf._set(subject) + } else if (isArrayish(subject)) { + // Treat array-ish objects as a byte array + if (Buffer.isBuffer(subject)) { + for (i = 0; i < length; i++) + buf[i] = subject.readUInt8(i) + } else { + for (i = 0; i < length; i++) + buf[i] = ((subject[i] % 256) + 256) % 256 + } + } else if (type === 'string') { + buf.write(subject, 0, encoding) + } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) { + for (i = 0; i < length; i++) { + buf[i] = 0 + } + } + + return buf +} + +Buffer.isBuffer = function (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) + throw new TypeError('Arguments must be Buffers') + + var x = a.length + var y = b.length + for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} + if (i !== len) { + x = a[i] + y = b[i] + } + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function (list, totalLength) { + if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])') + + if (list.length === 0) { + return new Buffer(0) + } else if (list.length === 1) { + return list[0] + } + + var i + if (totalLength === undefined) { + totalLength = 0 + for (i = 0; i < list.length; i++) { + totalLength += list[i].length + } + } + + var buf = new Buffer(totalLength) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} + +Buffer.byteLength = function (str, encoding) { + var ret + str = str + '' + switch (encoding || 'utf8') { + case 'ascii': + case 'binary': + case 'raw': + ret = str.length + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = str.length * 2 + break + case 'hex': + ret = str.length >>> 1 + break + case 'utf8': + case 'utf-8': + ret = utf8ToBytes(str).length + break + case 'base64': + ret = base64ToBytes(str).length + break + default: + ret = str.length + } + return ret +} + +// pre-set for values that may exist in the future +Buffer.prototype.length = undefined +Buffer.prototype.parent = undefined + +// toString(encoding, start=0, end=buffer.length) +Buffer.prototype.toString = function (encoding, start, end) { + var loweredCase = false + + start = start >>> 0 + end = end === undefined || end === Infinity ? this.length : end >>> 0 + + if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'binary': + return binarySlice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) + throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.equals = function (b) { + if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) + str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + return Buffer.compare(this, b) +} + +// `get` will be removed in Node 0.13+ +Buffer.prototype.get = function (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} + +// `set` will be removed in Node 0.13+ +Buffer.prototype.set = function (v, offset) { + console.log('.set() is deprecated. Access using array indexes instead.') + return this.writeUInt8(v, offset) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var byte = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(byte)) throw new Error('Invalid hex string') + buf[offset + i] = byte + } + return i +} + +function utf8Write (buf, string, offset, length) { + var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) + return charsWritten +} + +function asciiWrite (buf, string, offset, length) { + var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) + return charsWritten +} + +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) + return charsWritten +} + +function utf16leWrite (buf, string, offset, length) { + var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length, 2) + return charsWritten +} + +Buffer.prototype.write = function (string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length + length = undefined + } + } else { // legacy + var swap = encoding + encoding = offset + offset = length + length = swap + } + + offset = Number(offset) || 0 + var remaining = this.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + encoding = String(encoding || 'utf8').toLowerCase() + + var ret + switch (encoding) { + case 'hex': + ret = hexWrite(this, string, offset, length) + break + case 'utf8': + case 'utf-8': + ret = utf8Write(this, string, offset, length) + break + case 'ascii': + ret = asciiWrite(this, string, offset, length) + break + case 'binary': + ret = binaryWrite(this, string, offset, length) + break + case 'base64': + ret = base64Write(this, string, offset, length) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = utf16leWrite(this, string, offset, length) + break + default: + throw new TypeError('Unknown encoding: ' + encoding) + } + return ret +} + +Buffer.prototype.toJSON = function () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + var res = '' + var tmp = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + if (buf[i] <= 0x7F) { + res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) + tmp = '' + } else { + tmp += '%' + buf[i].toString(16) + } + } + + return res + decodeUtf8Char(tmp) +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function binarySlice (buf, start, end) { + return asciiSlice(buf, start, end) +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len; + if (start < 0) + start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) + end = 0 + } else if (end > len) { + end = len + } + + if (end < start) + end = start + + if (Buffer.TYPED_ARRAY_SUPPORT) { + return Buffer._augment(this.subarray(start, end)) + } else { + var sliceLen = end - start + var newBuf = new Buffer(sliceLen, undefined, true) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + return newBuf + } +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) + throw new RangeError('offset is not uint') + if (offset + ext > length) + throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUInt8 = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readInt8 = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) + return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') + if (value > max || value < min) throw new TypeError('value is out of bounds') + if (offset + ext > buf.length) throw new TypeError('index out of range') +} + +Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = value + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + } else objectWriteUInt16(this, value, offset, true) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = value + } else objectWriteUInt16(this, value, offset, false) + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = value + } else objectWriteUInt32(this, value, offset, true) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = value + } else objectWriteUInt32(this, value, offset, false) + return offset + 4 +} + +Buffer.prototype.writeInt8 = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = value + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + } else objectWriteUInt16(this, value, offset, true) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = value + } else objectWriteUInt16(this, value, offset, false) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else objectWriteUInt32(this, value, offset, true) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = value + } else objectWriteUInt32(this, value, offset, false) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (value > max || value < min) throw new TypeError('value is out of bounds') + if (offset + ext > buf.length) throw new TypeError('index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function (target, target_start, start, end) { + var source = this + + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (!target_start) target_start = 0 + + // Copy 0 bytes; we're done + if (end === start) return + if (target.length === 0 || source.length === 0) return + + // Fatal error conditions + if (end < start) throw new TypeError('sourceEnd < sourceStart') + if (target_start < 0 || target_start >= target.length) + throw new TypeError('targetStart out of bounds') + if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds') + if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) + end = this.length + if (target.length - target_start < end - start) + end = target.length - target_start + start + + var len = end - start + + if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < len; i++) { + target[i + target_start] = this[i + start] + } + } else { + target._set(this.subarray(start, start + len), target_start) + } +} + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length + + if (end < start) throw new TypeError('end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + if (start < 0 || start >= this.length) throw new TypeError('start out of bounds') + if (end < 0 || end > this.length) throw new TypeError('end out of bounds') + + var i + if (typeof value === 'number') { + for (i = start; i < end; i++) { + this[i] = value + } + } else { + var bytes = utf8ToBytes(value.toString()) + var len = bytes.length + for (i = start; i < end; i++) { + this[i] = bytes[i % len] + } + } + + return this +} + +/** + * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. + * Added in Node 0.12. Only available in browsers that support ArrayBuffer. + */ +Buffer.prototype.toArrayBuffer = function () { + if (typeof Uint8Array !== 'undefined') { + if (Buffer.TYPED_ARRAY_SUPPORT) { + return (new Buffer(this)).buffer + } else { + var buf = new Uint8Array(this.length) + for (var i = 0, len = buf.length; i < len; i += 1) { + buf[i] = this[i] + } + return buf.buffer + } + } else { + throw new TypeError('Buffer.toArrayBuffer not supported in this browser') + } +} + +// HELPER FUNCTIONS +// ================ + +var BP = Buffer.prototype + +/** + * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods + */ +Buffer._augment = function (arr) { + arr.constructor = Buffer + arr._isBuffer = true + + // save reference to original Uint8Array get/set methods before overwriting + arr._get = arr.get + arr._set = arr.set + + // deprecated, will be removed in node 0.13+ + arr.get = BP.get + arr.set = BP.set + + arr.write = BP.write + arr.toString = BP.toString + arr.toLocaleString = BP.toString + arr.toJSON = BP.toJSON + arr.equals = BP.equals + arr.compare = BP.compare + arr.copy = BP.copy + arr.slice = BP.slice + arr.readUInt8 = BP.readUInt8 + arr.readUInt16LE = BP.readUInt16LE + arr.readUInt16BE = BP.readUInt16BE + arr.readUInt32LE = BP.readUInt32LE + arr.readUInt32BE = BP.readUInt32BE + arr.readInt8 = BP.readInt8 + arr.readInt16LE = BP.readInt16LE + arr.readInt16BE = BP.readInt16BE + arr.readInt32LE = BP.readInt32LE + arr.readInt32BE = BP.readInt32BE + arr.readFloatLE = BP.readFloatLE + arr.readFloatBE = BP.readFloatBE + arr.readDoubleLE = BP.readDoubleLE + arr.readDoubleBE = BP.readDoubleBE + arr.writeUInt8 = BP.writeUInt8 + arr.writeUInt16LE = BP.writeUInt16LE + arr.writeUInt16BE = BP.writeUInt16BE + arr.writeUInt32LE = BP.writeUInt32LE + arr.writeUInt32BE = BP.writeUInt32BE + arr.writeInt8 = BP.writeInt8 + arr.writeInt16LE = BP.writeInt16LE + arr.writeInt16BE = BP.writeInt16BE + arr.writeInt32LE = BP.writeInt32LE + arr.writeInt32BE = BP.writeInt32BE + arr.writeFloatLE = BP.writeFloatLE + arr.writeFloatBE = BP.writeFloatBE + arr.writeDoubleLE = BP.writeDoubleLE + arr.writeDoubleBE = BP.writeDoubleBE + arr.fill = BP.fill + arr.inspect = BP.inspect + arr.toArrayBuffer = BP.toArrayBuffer + + return arr +} + +var INVALID_BASE64_RE = /[^+\/0-9A-z]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function isArrayish (subject) { + return isArray(subject) || Buffer.isBuffer(subject) || + subject && typeof subject === 'object' && + typeof subject.length === 'number' +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + var b = str.charCodeAt(i) + if (b <= 0x7F) { + byteArray.push(b) + } else { + var start = i + if (b >= 0xD800 && b <= 0xDFFF) i++ + var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') + for (var j = 0; j < h.length; j++) { + byteArray.push(parseInt(h[j], 16)) + } + } + } + return byteArray +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(str) +} + +function blitBuffer (src, dst, offset, length, unitSize) { + if (unitSize) length -= length % unitSize; + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) + break + dst[i + offset] = src[i] + } + return i +} + +function decodeUtf8Char (str) { + try { + return decodeURIComponent(str) + } catch (err) { + return String.fromCharCode(0xFFFD) // UTF 8 invalid char + } +} + +},{"base64-js":70,"ieee754":71,"is-array":72}],70:[function(require,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +;(function (exports) { + 'use strict'; + + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array + + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS) + return 62 // '+' + if (code === SLASH) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } + + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length + + var L = 0 + + function push (v) { + arr[L++] = v + } + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } + + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } + + return arr + } + + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length + + function encode (num) { + return lookup.charAt(num) + } + + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } + + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } + + return output + } + + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + +},{}],71:[function(require,module,exports){ +exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = isLE ? (nBytes - 1) : 0, + d = isLE ? -1 : 1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = isLE ? 0 : (nBytes - 1), + d = isLE ? 1 : -1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +},{}],72:[function(require,module,exports){ + +/** + * isArray + */ + +var isArray = Array.isArray; + +/** + * toString + */ + +var str = Object.prototype.toString; + +/** + * Whether or not the given `val` + * is an array. + * + * example: + * + * isArray([]); + * // > true + * isArray(arguments); + * // > false + * isArray(''); + * // > false + * + * @param {mixed} val + * @return {bool} + */ + +module.exports = isArray || function (val) { + return !! val && '[object Array]' == str.call(val); +}; + +},{}],73:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var createHash = require('sha.js') + +var md5 = require('./md5') +var rmd160 = require('ripemd160') +var Transform = require('stream').Transform; +var inherits = require('util').inherits + +module.exports = function (alg) { + if('md5' === alg) return new HashNoConstructor(md5) + if('rmd160' === alg) return new HashNoConstructor(rmd160) + return new Hash(createHash(alg)) +} +inherits(HashNoConstructor, Transform) + +function HashNoConstructor(hash) { + Transform.call(this); + this._hash = hash + this.buffers = [] +} + +HashNoConstructor.prototype._transform = function (data, _, done) { + this.buffers.push(data) + done() +} +HashNoConstructor.prototype._flush = function (done) { + var buf = Buffer.concat(this.buffers) + var r = this._hash(buf) + this.buffers = null + this.push(r) + done() +} +HashNoConstructor.prototype.update = function (data, enc) { + this.write(data, enc) + return this +} + +HashNoConstructor.prototype.digest = function (enc) { + this.end() + var outData = new Buffer('') + var chunk + while ((chunk = this.read())) { + outData = Buffer.concat([outData, chunk]) + } + if (enc) { + outData = outData.toString(enc) + } + return outData +} + +inherits(Hash, Transform) + +function Hash(hash) { + Transform.call(this); + this._hash = hash +} + +Hash.prototype._transform = function (data, _, done) { + this._hash.update(data) + done() +} +Hash.prototype._flush = function (done) { + this.push(this._hash.digest()) + this._hash = null + done() +} +Hash.prototype.update = function (data, enc) { + this.write(data, enc) + return this +} + +Hash.prototype.digest = function (enc) { + this.end() + var outData = new Buffer('') + var chunk + while ((chunk = this.read())) { + outData = Buffer.concat([outData, chunk]) + } + if (enc) { + outData = outData.toString(enc) + } + return outData +} + +}).call(this,require("buffer").Buffer) +},{"./md5":77,"buffer":69,"ripemd160":167,"sha.js":169,"stream":201,"util":205}],74:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var createHash = require('./create-hash') +var Transform = require('stream').Transform; +var inherits = require('util').inherits +var zeroBuffer = new Buffer(128) +zeroBuffer.fill(0) + +module.exports = Hmac +inherits(Hmac, Transform) +function Hmac (alg, key) { + if(!(this instanceof Hmac)) return new Hmac(alg, key) + + Transform.call(this) + this._opad = opad + this._alg = alg + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key + + if(key.length > blocksize) { + key = createHash(alg).update(key).digest() + } else if(key.length < blocksize) { + key = Buffer.concat([key, zeroBuffer], blocksize) + } + + var ipad = this._ipad = new Buffer(blocksize) + var opad = this._opad = new Buffer(blocksize) + + for(var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + this._hash = createHash(alg).update(ipad) +} + +Hmac.prototype.update = function (data, enc) { + this.write(data, enc) + return this +} + +Hmac.prototype._transform = function (data, _, next) { + this._hash.update(data) + next() +} + +Hmac.prototype._flush = function (next) { + var h = this._hash.digest() + this.push(createHash(this._alg).update(this._opad).update(h).digest()) + next() +} + +Hmac.prototype.digest = function (enc) { + this.end() + var outData = new Buffer('') + var chunk + while ((chunk = this.read())) { + outData = Buffer.concat([outData, chunk]) + } + if (enc) { + outData = outData.toString(enc) + } + return outData +} + + +}).call(this,require("buffer").Buffer) +},{"./create-hash":73,"buffer":69,"stream":201,"util":205}],75:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; + +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } + + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; +} + +function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); + } + return buf; +} + +function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); +} + +module.exports = { hash: hash }; + +}).call(this,require("buffer").Buffer) +},{"buffer":69}],76:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var rng = require('./rng') + +function error () { + var m = [].slice.call(arguments).join(' ') + throw new Error([ + m, + 'we accept pull requests', + 'http://github.com/dominictarr/crypto-browserify' + ].join('\n')) +} + +exports.createHash = require('./create-hash') + +exports.createHmac = require('./create-hmac') + +exports.randomBytes = function(size, callback) { + if (callback && callback.call) { + try { + callback.call(this, undefined, new Buffer(rng(size))) + } catch (err) { callback(err) } + } else { + return new Buffer(rng(size)) + } +} + +function each(a, f) { + for(var i in a) + f(a[i], i) +} +var hashes = ['sha1', 'sha256', 'sha512', 'md5', 'rmd160'].concat(Object.keys(require('browserify-sign/algos'))) +exports.getHashes = function () { + return hashes; +} + +var p = require('./pbkdf2')(exports) +exports.pbkdf2 = p.pbkdf2 +exports.pbkdf2Sync = p.pbkdf2Sync +require('browserify-aes/inject')(exports, module.exports); +require('browserify-sign/inject')(module.exports, exports); +require('diffie-hellman/inject')(exports, module.exports); +require('create-ecdh/inject')(module.exports, exports); + +// the least I can do is make error messages for the rest of the node.js/crypto api. +each([ + 'createCredentials', 'publicEncrypt', 'privateDecrypt' +], function (name) { + exports[name] = function () { + error('sorry,', name, 'is not implemented yet') + } +}) + +}).call(this,require("buffer").Buffer) +},{"./create-hash":73,"./create-hmac":74,"./pbkdf2":175,"./rng":176,"browserify-aes/inject":85,"browserify-sign/algos":97,"browserify-sign/inject":100,"buffer":69,"create-ecdh/inject":139,"diffie-hellman/inject":162}],77:[function(require,module,exports){ +'use strict'; +/* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +var helpers = require('./helpers'); + +/* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ +function core_md5(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << ((len) % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); + d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); + d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); + d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i+10], 17, -42063); + b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); + d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); + d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); + c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); + d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); + c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); + d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); + c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); + d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); + c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); + d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); + d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); + d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); + d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); + d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); + d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); + d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); + d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + +} + +/* + * These functions implement the four basic operations the algorithm uses. + */ +function md5_cmn(q, a, b, x, s, t) +{ + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); +} +function md5_ff(a, b, c, d, x, s, t) +{ + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5_gg(a, b, c, d, x, s, t) +{ + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5_hh(a, b, c, d, x, s, t) +{ + return md5_cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5_ii(a, b, c, d, x, s, t) +{ + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function bit_rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); +}; + +},{"./helpers":75}],78:[function(require,module,exports){ +(function (Buffer){ + +module.exports = function (crypto, password, keyLen, ivLen) { + keyLen = keyLen/8; + ivLen = ivLen || 0; + var ki = 0; + var ii = 0; + var key = new Buffer(keyLen); + var iv = new Buffer(ivLen); + var addmd = 0; + var md, md_buf; + var i; + while (true) { + md = crypto.createHash('md5'); + if(addmd++ > 0) { + md.update(md_buf); + } + md.update(password); + md_buf = md.digest(); + i = 0; + if(keyLen > 0) { + while(true) { + if(keyLen === 0) { + break; + } + if(i === md_buf.length) { + break; + } + key[ki++] = md_buf[i]; + keyLen--; + i++; + } + } + if(ivLen > 0 && i !== md_buf.length) { + while(true) { + if(ivLen === 0) { + break; + } + if(i === md_buf.length) { + break; + } + iv[ii++] = md_buf[i]; + ivLen--; + i++; + } + } + if(keyLen === 0 && ivLen === 0) { + break; + } + } + for(i=0;i uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x; + return ret; +} +function scrub_vec(v) { + var i, _i, _ref; + for (i = _i = 0, _ref = v.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + v[i] = 0; + } + return false; +} + +function Global() { + var i; + this.SBOX = []; + this.INV_SBOX = []; + this.SUB_MIX = (function() { + var _i, _results; + _results = []; + for (i = _i = 0; _i < 4; i = ++_i) { + _results.push([]); + } + return _results; + })(); + this.INV_SUB_MIX = (function() { + var _i, _results; + _results = []; + for (i = _i = 0; _i < 4; i = ++_i) { + _results.push([]); + } + return _results; + })(); + this.init(); + this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; +} + +Global.prototype.init = function() { + var d, i, sx, t, x, x2, x4, x8, xi, _i; + d = (function() { + var _i, _results; + _results = []; + for (i = _i = 0; _i < 256; i = ++_i) { + if (i < 128) { + _results.push(i << 1); + } else { + _results.push((i << 1) ^ 0x11b); + } + } + return _results; + })(); + x = 0; + xi = 0; + for (i = _i = 0; _i < 256; i = ++_i) { + sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + this.SBOX[x] = sx; + this.INV_SBOX[sx] = x; + x2 = d[x]; + x4 = d[x2]; + x8 = d[x4]; + t = (d[sx] * 0x101) ^ (sx * 0x1010100); + this.SUB_MIX[0][x] = (t << 24) | (t >>> 8); + this.SUB_MIX[1][x] = (t << 16) | (t >>> 16); + this.SUB_MIX[2][x] = (t << 8) | (t >>> 24); + this.SUB_MIX[3][x] = t; + t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8); + this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16); + this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24); + this.INV_SUB_MIX[3][sx] = t; + if (x === 0) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + return true; +}; + +var G = new Global(); + + +AES.blockSize = 4 * 4; + +AES.prototype.blockSize = AES.blockSize; + +AES.keySize = 256 / 8; + +AES.prototype.keySize = AES.keySize; + +AES.ivSize = AES.blockSize; + +AES.prototype.ivSize = AES.ivSize; + + function bufferToArray(buf) { + var len = buf.length/4; + var out = new Array(len); + var i = -1; + while (++i < len) { + out[i] = buf.readUInt32BE(i * 4); + } + return out; + } +function AES(key) { + this._key = bufferToArray(key); + this._doReset(); +} + +AES.prototype._doReset = function() { + var invKsRow, keySize, keyWords, ksRow, ksRows, t, _i, _j; + keyWords = this._key; + keySize = keyWords.length; + this._nRounds = keySize + 6; + ksRows = (this._nRounds + 1) * 4; + this._keySchedule = []; + for (ksRow = _i = 0; 0 <= ksRows ? _i < ksRows : _i > ksRows; ksRow = 0 <= ksRows ? ++_i : --_i) { + this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t); + } + this._invKeySchedule = []; + for (invKsRow = _j = 0; 0 <= ksRows ? _j < ksRows : _j > ksRows; invKsRow = 0 <= ksRows ? ++_j : --_j) { + ksRow = ksRows - invKsRow; + t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)]; + this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]]; + } + return true; +}; + +AES.prototype.encryptBlock = function(M) { + M = bufferToArray(new Buffer(M)); + var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX); + var buf = new Buffer(16); + buf.writeUInt32BE(out[0], 0); + buf.writeUInt32BE(out[1], 4); + buf.writeUInt32BE(out[2], 8); + buf.writeUInt32BE(out[3], 12); + return buf; +}; + +AES.prototype.decryptBlock = function(M) { + M = bufferToArray(new Buffer(M)); + var temp = [M[3], M[1]]; + M[1] = temp[0]; + M[3] = temp[1]; + var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX); + var buf = new Buffer(16); + buf.writeUInt32BE(out[0], 0); + buf.writeUInt32BE(out[3], 4); + buf.writeUInt32BE(out[2], 8); + buf.writeUInt32BE(out[1], 12); + return buf; +}; + +AES.prototype.scrub = function() { + scrub_vec(this._keySchedule); + scrub_vec(this._invKeySchedule); + scrub_vec(this._key); +}; + +AES.prototype._doCryptBlock = function(M, keySchedule, SUB_MIX, SBOX) { + var ksRow, round, s0, s1, s2, s3, t0, t1, t2, t3, _i, _ref; + + s0 = M[0] ^ keySchedule[0]; + s1 = M[1] ^ keySchedule[1]; + s2 = M[2] ^ keySchedule[2]; + s3 = M[3] ^ keySchedule[3]; + ksRow = 4; + for (round = _i = 1, _ref = this._nRounds; 1 <= _ref ? _i < _ref : _i > _ref; round = 1 <= _ref ? ++_i : --_i) { + 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++]; + 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++]; + 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++]; + 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++]; + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + return [ + fixup_uint32(t0), + fixup_uint32(t1), + fixup_uint32(t2), + fixup_uint32(t3) + ]; + +}; + + + + + exports.AES = AES; +}).call(this,require("buffer").Buffer) +},{"buffer":69}],80:[function(require,module,exports){ +(function (Buffer){ +var aes = require('./aes'); +var Transform = require('./cipherBase'); +var inherits = require('inherits'); +var GHASH = require('./ghash'); +var xor = require('./xor'); +inherits(StreamCipher, Transform); +module.exports = StreamCipher; + +function StreamCipher(mode, key, iv, decrypt) { + if (!(this instanceof StreamCipher)) { + return new StreamCipher(mode, key, iv); + } + Transform.call(this); + this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])]); + iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])]); + this._cipher = new aes.AES(key); + this._prev = new Buffer(iv.length); + this._cache = new Buffer(''); + this._secCache = new Buffer(''); + this._decrypt = decrypt; + this._alen = 0; + this._len = 0; + iv.copy(this._prev); + this._mode = mode; + var h = new Buffer(4); + h.fill(0); + this._ghash = new GHASH(this._cipher.encryptBlock(h)); + this._authTag = null; + this._called = false; +} +StreamCipher.prototype._transform = function (chunk, _, next) { + if (!this._called && this._alen) { + var rump = 16 - (this._alen % 16); + if (rump <16) { + rump = new Buffer(rump); + rump.fill(0); + this._ghash.update(rump); + } + } + this._called = true; + var out = this._mode.encrypt(this, chunk); + if (this._decrypt) { + this._ghash.update(chunk); + } else { + this._ghash.update(out); + } + this._len += chunk.length; + next(null, out); +}; +StreamCipher.prototype._flush = function (next) { + if (this._decrypt && !this._authTag) { + throw new Error('Unsupported state or unable to authenticate data'); + } + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)); + if (this._decrypt) { + if (xorTest(tag, this._authTag)) { + throw new Error('Unsupported state or unable to authenticate data'); + } + } else { + this._authTag = tag; + } + this._cipher.scrub(); + next(); +}; +StreamCipher.prototype.getAuthTag = function getAuthTag () { + if (!this._decrypt && Buffer.isBuffer(this._authTag)) { + return this._authTag; + } else { + throw new Error('Attempting to get auth tag in unsupported state'); + } +}; +StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { + if (this._decrypt) { + this._authTag = tag; + } else { + throw new Error('Attempting to set auth tag in unsupported state'); + } +}; +StreamCipher.prototype.setAAD = function setAAD (buf) { + if (!this._called) { + this._ghash.update(buf); + this._alen += buf.length; + } else { + throw new Error('Attempting to set AAD in unsupported state'); + } +}; +function xorTest(a, b) { + var out = 0; + if (a.length !== b.length) { + out++; + } + var len = Math.min(a.length, b.length); + var i = -1; + while (++i < len) { + out += (a[i] ^ b[i]); + } + return out; +} + + + +}).call(this,require("buffer").Buffer) +},{"./aes":79,"./cipherBase":81,"./ghash":84,"./xor":95,"buffer":69,"inherits":231}],81:[function(require,module,exports){ +(function (Buffer){ +var Transform = require('stream').Transform; +var inherits = require('inherits'); + +module.exports = CipherBase; +inherits(CipherBase, Transform); +function CipherBase() { + Transform.call(this); +} +CipherBase.prototype.update = function (data, inputEnd, outputEnc) { + this.write(data, inputEnd); + var outData = new Buffer(''); + var chunk; + while ((chunk = this.read())) { + outData = Buffer.concat([outData, chunk]); + } + if (outputEnc) { + outData = outData.toString(outputEnc); + } + return outData; +}; +CipherBase.prototype.final = function (outputEnc) { + this.end(); + var outData = new Buffer(''); + var chunk; + while ((chunk = this.read())) { + outData = Buffer.concat([outData, chunk]); + } + if (outputEnc) { + outData = outData.toString(outputEnc); + } + return outData; +}; +}).call(this,require("buffer").Buffer) +},{"buffer":69,"inherits":231,"stream":201}],82:[function(require,module,exports){ +(function (Buffer){ +var aes = require('./aes'); +var Transform = require('./cipherBase'); +var inherits = require('inherits'); +var modes = require('./modes'); +var StreamCipher = require('./streamCipher'); +var AuthCipher = require('./authCipher'); +var ebtk = require('./EVP_BytesToKey'); + +inherits(Decipher, Transform); +function Decipher(mode, key, iv) { + if (!(this instanceof Decipher)) { + return new Decipher(mode, key, iv); + } + Transform.call(this); + this._cache = new Splitter(); + this._last = void 0; + this._cipher = new aes.AES(key); + this._prev = new Buffer(iv.length); + iv.copy(this._prev); + this._mode = mode; +} +Decipher.prototype._transform = function (data, _, next) { + this._cache.add(data); + var chunk; + var thing; + while ((chunk = this._cache.get())) { + thing = this._mode.decrypt(this, chunk); + this.push(thing); + } + next(); +}; +Decipher.prototype._flush = function (next) { + var chunk = this._cache.flush(); + if (!chunk) { + return next; + } + + this.push(unpad(this._mode.decrypt(this, chunk))); + + next(); +}; + +function Splitter() { + if (!(this instanceof Splitter)) { + return new Splitter(); + } + this.cache = new Buffer(''); +} +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]); +}; + +Splitter.prototype.get = function () { + if (this.cache.length > 16) { + var out = this.cache.slice(0, 16); + this.cache = this.cache.slice(16); + return out; + } + return null; +}; +Splitter.prototype.flush = function () { + if (this.cache.length) { + return this.cache; + } +}; +function unpad(last) { + var padded = last[15]; + if (padded === 16) { + return; + } + return last.slice(0, 16 - padded); +} + +var modelist = { + ECB: require('./modes/ecb'), + CBC: require('./modes/cbc'), + CFB: require('./modes/cfb'), + CFB8: require('./modes/cfb8'), + CFB1: require('./modes/cfb1'), + OFB: require('./modes/ofb'), + CTR: require('./modes/ctr'), + GCM: require('./modes/ctr') +}; + +module.exports = function (crypto) { + function createDecipheriv(suite, password, iv) { + var config = modes[suite]; + if (!config) { + throw new TypeError('invalid suite type'); + } + if (typeof iv === 'string') { + iv = new Buffer(iv); + } + if (typeof password === 'string') { + password = new Buffer(password); + } + if (password.length !== config.key/8) { + throw new TypeError('invalid key length ' + password.length); + } + if (iv.length !== config.iv) { + throw new TypeError('invalid iv length ' + iv.length); + } + if (config.type === 'stream') { + return new StreamCipher(modelist[config.mode], password, iv, true); + } else if (config.type === 'auth') { + return new AuthCipher(modelist[config.mode], password, iv, true); + } + return new Decipher(modelist[config.mode], password, iv); + } + + function createDecipher (suite, password) { + var config = modes[suite]; + if (!config) { + throw new TypeError('invalid suite type'); + } + var keys = ebtk(crypto, password, config.key, config.iv); + return createDecipheriv(suite, keys.key, keys.iv); + } + return { + createDecipher: createDecipher, + createDecipheriv: createDecipheriv + }; +}; + +}).call(this,require("buffer").Buffer) +},{"./EVP_BytesToKey":78,"./aes":79,"./authCipher":80,"./cipherBase":81,"./modes":86,"./modes/cbc":87,"./modes/cfb":88,"./modes/cfb1":89,"./modes/cfb8":90,"./modes/ctr":91,"./modes/ecb":92,"./modes/ofb":93,"./streamCipher":94,"buffer":69,"inherits":231}],83:[function(require,module,exports){ +(function (Buffer){ +var aes = require('./aes'); +var Transform = require('./cipherBase'); +var inherits = require('inherits'); +var modes = require('./modes'); +var ebtk = require('./EVP_BytesToKey'); +var StreamCipher = require('./streamCipher'); +var AuthCipher = require('./authCipher'); +inherits(Cipher, Transform); +function Cipher(mode, key, iv) { + if (!(this instanceof Cipher)) { + return new Cipher(mode, key, iv); + } + Transform.call(this); + this._cache = new Splitter(); + this._cipher = new aes.AES(key); + this._prev = new Buffer(iv.length); + iv.copy(this._prev); + this._mode = mode; +} +Cipher.prototype._transform = function (data, _, next) { + this._cache.add(data); + var chunk; + var thing; + while ((chunk = this._cache.get())) { + thing = this._mode.encrypt(this, chunk); + this.push(thing); + } + next(); +}; +Cipher.prototype._flush = function (next) { + var chunk = this._cache.flush(); + this.push(this._mode.encrypt(this, chunk)); + this._cipher.scrub(); + next(); +}; + + +function Splitter() { + if (!(this instanceof Splitter)) { + return new Splitter(); + } + this.cache = new Buffer(''); +} +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]); +}; + +Splitter.prototype.get = function () { + if (this.cache.length > 15) { + var out = this.cache.slice(0, 16); + this.cache = this.cache.slice(16); + return out; + } + return null; +}; +Splitter.prototype.flush = function () { + var len = 16 - this.cache.length; + var padBuff = new Buffer(len); + + var i = -1; + while (++i < len) { + padBuff.writeUInt8(len, i); + } + var out = Buffer.concat([this.cache, padBuff]); + return out; +}; +var modelist = { + ECB: require('./modes/ecb'), + CBC: require('./modes/cbc'), + CFB: require('./modes/cfb'), + CFB8: require('./modes/cfb8'), + CFB1: require('./modes/cfb1'), + OFB: require('./modes/ofb'), + CTR: require('./modes/ctr'), + GCM: require('./modes/ctr') +}; +module.exports = function (crypto) { + function createCipheriv(suite, password, iv) { + var config = modes[suite]; + if (!config) { + throw new TypeError('invalid suite type'); + } + if (typeof iv === 'string') { + iv = new Buffer(iv); + } + if (typeof password === 'string') { + password = new Buffer(password); + } + if (password.length !== config.key/8) { + throw new TypeError('invalid key length ' + password.length); + } + if (iv.length !== config.iv) { + throw new TypeError('invalid iv length ' + iv.length); + } + if (config.type === 'stream') { + return new StreamCipher(modelist[config.mode], password, iv); + } else if (config.type === 'auth') { + return new AuthCipher(modelist[config.mode], password, iv); + } + return new Cipher(modelist[config.mode], password, iv); + } + function createCipher (suite, password) { + var config = modes[suite]; + if (!config) { + throw new TypeError('invalid suite type'); + } + var keys = ebtk(crypto, password, config.key, config.iv); + return createCipheriv(suite, keys.key, keys.iv); + } + return { + createCipher: createCipher, + createCipheriv: createCipheriv + }; +}; + +}).call(this,require("buffer").Buffer) +},{"./EVP_BytesToKey":78,"./aes":79,"./authCipher":80,"./cipherBase":81,"./modes":86,"./modes/cbc":87,"./modes/cfb":88,"./modes/cfb1":89,"./modes/cfb8":90,"./modes/ctr":91,"./modes/ecb":92,"./modes/ofb":93,"./streamCipher":94,"buffer":69,"inherits":231}],84:[function(require,module,exports){ +(function (Buffer){ +var zeros = new Buffer(16); +zeros.fill(0); +module.exports = GHASH; +function GHASH(key){ + this.h = key; + this.state = new Buffer(16); + this.state.fill(0); + this.cache = new Buffer(''); +} +// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html +// by Juho Vähä-Herttua +GHASH.prototype.ghash = function (block) { + var i = -1; + while (++i < block.length) { + this.state[i] ^= 0xff & block[i]; + } + this._multiply(); +}; + +GHASH.prototype._multiply = function () { + var Vi = toArray(this.h); + var Zi = [0, 0, 0, 0]; + var j, xi, lsb_Vi; + var i = -1; + while (++i < 128) { + xi = (this.state[~~(i/8)] & (1 << (7-i%8))) !== 0; + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi = xor(Zi, Vi); + } + + // Store the value of LSB(V_i) + lsb_Vi = (Vi[3] & 1) !== 0; + + // V_i+1 = V_i >> 1 + for (j=3; j>0; j--) { + Vi[j] = (Vi[j] >>> 1) | ((Vi[j-1]&1) << 31); + } + Vi[0] = Vi[0] >>> 1; + + // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R + if (lsb_Vi) { + Vi[0] = Vi[0] ^ (0xe1 << 24); + } + } + this.state = fromArray(Zi); +}; +GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]); + var chunk; + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16); + this.cache = this.cache.slice(16); + this.ghash(chunk); + } +}; +GHASH.prototype.final = function (abl, bl) { + if (this.cache.length) { + this.ghash(Buffer.concat([this.cache, zeros], 16)); + } + this.ghash(fromArray([ + 0, abl, + 0, bl + ])); + return this.state; +}; + +function toArray(buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ]; +} +function fromArray(out) { + out = out.map(fixup_uint32); + var buf = new Buffer(16); + buf.writeUInt32BE(out[0], 0); + buf.writeUInt32BE(out[1], 4); + buf.writeUInt32BE(out[2], 8); + buf.writeUInt32BE(out[3], 12); + return buf; +} +var uint_max = Math.pow(2, 32); +function fixup_uint32(x) { + var ret, x_pos; + ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x; + return ret; +} +function xor(a, b) { + return [ + a[0] ^ b[0], + a[1] ^ b[1], + a[2] ^ b[2], + a[3] ^ b[3], + ]; +} +}).call(this,require("buffer").Buffer) +},{"buffer":69}],85:[function(require,module,exports){ +module.exports = function (crypto, exports) { + exports = exports || {}; + var ciphers = require('./encrypter')(crypto); + exports.createCipher = ciphers.createCipher; + exports.createCipheriv = ciphers.createCipheriv; + var deciphers = require('./decrypter')(crypto); + exports.createDecipher = deciphers.createDecipher; + exports.createDecipheriv = deciphers.createDecipheriv; + var modes = require('./modes'); + function listCiphers () { + return Object.keys(modes); + } + exports.listCiphers = listCiphers; +}; + + +},{"./decrypter":82,"./encrypter":83,"./modes":86}],86:[function(require,module,exports){ +exports['aes-128-ecb'] = { + cipher: 'AES', + key: 128, + iv: 0, + mode: 'ECB', + type: 'block' +}; +exports['aes-192-ecb'] = { + cipher: 'AES', + key: 192, + iv: 0, + mode: 'ECB', + type: 'block' +}; +exports['aes-256-ecb'] = { + cipher: 'AES', + key: 256, + iv: 0, + mode: 'ECB', + type: 'block' +}; +exports['aes-128-cbc'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CBC', + type: 'block' +}; +exports['aes-192-cbc'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CBC', + type: 'block' +}; +exports['aes-256-cbc'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CBC', + type: 'block' +}; +exports['aes128'] = exports['aes-128-cbc']; +exports['aes192'] = exports['aes-192-cbc']; +exports['aes256'] = exports['aes-256-cbc']; +exports['aes-128-cfb'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB', + type: 'stream' +}; +exports['aes-192-cfb'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB', + type: 'stream' +}; +exports['aes-256-cfb'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB', + type: 'stream' +}; +exports['aes-128-cfb8'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB8', + type: 'stream' +}; +exports['aes-192-cfb8'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB8', + type: 'stream' +}; +exports['aes-256-cfb8'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB8', + type: 'stream' +}; +exports['aes-128-cfb1'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB1', + type: 'stream' +}; +exports['aes-192-cfb1'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB1', + type: 'stream' +}; +exports['aes-256-cfb1'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB1', + type: 'stream' +}; +exports['aes-128-ofb'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'OFB', + type: 'stream' +}; +exports['aes-192-ofb'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'OFB', + type: 'stream' +}; +exports['aes-256-ofb'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'OFB', + type: 'stream' +}; +exports['aes-128-ctr'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CTR', + type: 'stream' +}; +exports['aes-192-ctr'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CTR', + type: 'stream' +}; +exports['aes-256-ctr'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CTR', + type: 'stream' +}; +exports['aes-128-gcm'] = { + cipher: 'AES', + key: 128, + iv: 12, + mode: 'GCM', + type: 'auth' +}; +exports['aes-192-gcm'] = { + cipher: 'AES', + key: 192, + iv: 12, + mode: 'GCM', + type: 'auth' +}; +exports['aes-256-gcm'] = { + cipher: 'AES', + key: 256, + iv: 12, + mode: 'GCM', + type: 'auth' +}; +},{}],87:[function(require,module,exports){ +var xor = require('../xor'); +exports.encrypt = function (self, block) { + var data = xor(block, self._prev); + self._prev = self._cipher.encryptBlock(data); + return self._prev; +}; +exports.decrypt = function (self, block) { + var pad = self._prev; + self._prev = block; + var out = self._cipher.decryptBlock(block); + return xor(out, pad); +}; +},{"../xor":95}],88:[function(require,module,exports){ +(function (Buffer){ +var xor = require('../xor'); +exports.encrypt = function (self, data, decrypt) { + var out = new Buffer(''); + var len; + while (data.length) { + if (self._cache.length === 0) { + self._cache = self._cipher.encryptBlock(self._prev); + self._prev = new Buffer(''); + } + if (self._cache.length <= data.length) { + len = self._cache.length; + out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]); + data = data.slice(len); + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]); + break; + } + } + return out; +}; +function encryptStart(self, data, decrypt) { + var len = data.length; + var out = xor(data, self._cache); + self._cache = self._cache.slice(len); + self._prev = Buffer.concat([self._prev, decrypt?data:out]); + return out; +} +}).call(this,require("buffer").Buffer) +},{"../xor":95,"buffer":69}],89:[function(require,module,exports){ +(function (Buffer){ + +function encryptByte(self, byte, decrypt) { + var pad; + var i = -1; + var len = 8; + var out = 0; + var bit, value; + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev); + bit = (byte & (1 << (7-i))) ? 0x80:0; + value = pad[0] ^ bit; + out += ((value&0x80) >> (i%8)); + self._prev = shiftIn(self._prev, decrypt?bit:value); + } + return out; +} +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length; + var out = new Buffer(len); + var i = -1; + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt); + } + return out; +}; +function shiftIn(buffer, value) { + var len = buffer.length; + var i = -1; + var out = new Buffer(buffer.length); + buffer = Buffer.concat([buffer, new Buffer([value])]); + while(++i < len) { + out[i] = buffer[i]<<1 | buffer[i+1]>>(7); + } + return out; +} +}).call(this,require("buffer").Buffer) +},{"buffer":69}],90:[function(require,module,exports){ +(function (Buffer){ +function encryptByte(self, byte, decrypt) { + var pad = self._cipher.encryptBlock(self._prev); + var out = pad[0] ^ byte; + self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt?byte:out])]); + return out; +} +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length; + var out = new Buffer(len); + var i = -1; + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt); + } + return out; +}; +}).call(this,require("buffer").Buffer) +},{"buffer":69}],91:[function(require,module,exports){ +(function (Buffer){ +var xor = require('../xor'); +function getBlock(self) { + var out = self._cipher.encryptBlock(self._prev); + incr32(self._prev); + return out; +} +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]); + } + var pad = self._cache.slice(0, chunk.length); + self._cache = self._cache.slice(chunk.length); + return xor(chunk, pad); +}; +function incr32(iv) { + var len = iv.length; + var item; + while (len--) { + item = iv.readUInt8(len); + if (item === 255) { + iv.writeUInt8(0, len); + } else { + item++; + iv.writeUInt8(item, len); + break; + } + } +} +}).call(this,require("buffer").Buffer) +},{"../xor":95,"buffer":69}],92:[function(require,module,exports){ +exports.encrypt = function (self, block) { + return self._cipher.encryptBlock(block); +}; +exports.decrypt = function (self, block) { + return self._cipher.decryptBlock(block); +}; +},{}],93:[function(require,module,exports){ +(function (Buffer){ +var xor = require('../xor'); +function getBlock(self) { + self._prev = self._cipher.encryptBlock(self._prev); + return self._prev; +} +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]); + } + var pad = self._cache.slice(0, chunk.length); + self._cache = self._cache.slice(chunk.length); + return xor(chunk, pad); +}; +}).call(this,require("buffer").Buffer) +},{"../xor":95,"buffer":69}],94:[function(require,module,exports){ +(function (Buffer){ +var aes = require('./aes'); +var Transform = require('./cipherBase'); +var inherits = require('inherits'); + +inherits(StreamCipher, Transform); +module.exports = StreamCipher; +function StreamCipher(mode, key, iv, decrypt) { + if (!(this instanceof StreamCipher)) { + return new StreamCipher(mode, key, iv); + } + Transform.call(this); + this._cipher = new aes.AES(key); + this._prev = new Buffer(iv.length); + this._cache = new Buffer(''); + this._secCache = new Buffer(''); + this._decrypt = decrypt; + iv.copy(this._prev); + this._mode = mode; +} +StreamCipher.prototype._transform = function (chunk, _, next) { + next(null, this._mode.encrypt(this, chunk, this._decrypt)); +}; +StreamCipher.prototype._flush = function (next) { + this._cipher.scrub(); + next(); +}; +}).call(this,require("buffer").Buffer) +},{"./aes":79,"./cipherBase":81,"buffer":69,"inherits":231}],95:[function(require,module,exports){ +(function (Buffer){ +module.exports = xor; +function xor(a, b) { + var len = Math.min(a.length, b.length); + var out = new Buffer(len); + var i = -1; + while (++i < len) { + out.writeUInt8(a[i] ^ b[i], i); + } + return out; +} +}).call(this,require("buffer").Buffer) +},{"buffer":69}],96:[function(require,module,exports){ +module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", +"2.16.840.1.101.3.4.1.2": "aes-128-cbc", +"2.16.840.1.101.3.4.1.3": "aes-128-ofb", +"2.16.840.1.101.3.4.1.4": "aes-128-cfb", +"2.16.840.1.101.3.4.1.21": "aes-192-ecb", +"2.16.840.1.101.3.4.1.22": "aes-192-cbc", +"2.16.840.1.101.3.4.1.23": "aes-192-ofb", +"2.16.840.1.101.3.4.1.24": "aes-192-cfb", +"2.16.840.1.101.3.4.1.41": "aes-256-ecb", +"2.16.840.1.101.3.4.1.42": "aes-256-cbc", +"2.16.840.1.101.3.4.1.43": "aes-256-ofb", +"2.16.840.1.101.3.4.1.44": "aes-256-cfb" +} +},{}],97:[function(require,module,exports){ +(function (Buffer){ +exports['RSA-SHA224'] = exports.sha224WithRSAEncryption = { + sign: 'rsa', + hash: 'sha224', + id: new Buffer('302d300d06096086480165030402040500041c', 'hex') +}; +exports['RSA-SHA256'] = exports.sha256WithRSAEncryption = { + sign: 'rsa', + hash: 'sha256', + id: new Buffer('3031300d060960864801650304020105000420', 'hex') +}; +exports['RSA-SHA384'] = exports.sha384WithRSAEncryption = { + sign: 'rsa', + hash: 'sha384', + id: new Buffer('3041300d060960864801650304020205000430', 'hex') +}; +exports['RSA-SHA512'] = exports.sha512WithRSAEncryption = { + sign: 'rsa', + hash: 'sha512', + id: new Buffer('3051300d060960864801650304020305000440', 'hex') +}; +exports['RSA-SHA1'] = { + sign: 'rsa', + hash: 'sha1', + id: new Buffer('3021300906052b0e03021a05000414', 'hex') +} +exports['ecdsa-with-SHA1'] = { + sign: 'ecdsa', + hash: 'sha1', + id: new Buffer(/*'3021300906052b0e03021a05000414'*/'', 'hex') +} +}).call(this,require("buffer").Buffer) +},{"buffer":69}],98:[function(require,module,exports){ +// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js +// Fedor, you are amazing. + +var asn1 = require('asn1.js'); +var rfc3280 = require('asn1.js-rfc3280'); + +var RSAPrivateKey = asn1.define('RSAPrivateKey', function() { + this.seq().obj( + this.key('version').int(), + this.key('modulus').int(), + this.key('publicExponent').int(), + this.key('privateExponent').int(), + this.key('prime1').int(), + this.key('prime2').int(), + this.key('exponent1').int(), + this.key('exponent2').int(), + this.key('coefficient').int() + ); +}); +exports.RSAPrivateKey = RSAPrivateKey; + +var RSAPublicKey = asn1.define('RSAPublicKey', function() { + this.seq().obj( + this.key('modulus').int(), + this.key('publicExponent').int() + ); +}); +exports.RSAPublicKey = RSAPublicKey; + +var PublicKey = rfc3280.SubjectPublicKeyInfo; +exports.PublicKey = PublicKey; +var ECPublicKey = asn1.define('ECPublicKey', function() { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('curve').objid() + ), + this.key('subjectPrivateKey').bitstr() + ); +}); +exports.ECPublicKey = ECPublicKey; +var ECPrivateWrap = asn1.define('ECPrivateWrap', function() { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('curve').objid() + ), + this.key('subjectPrivateKey').octstr() + ); +}); +exports.ECPrivateWrap = ECPrivateWrap; +var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function() { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').use(rfc3280.AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ); +}); +exports.PrivateKey = PrivateKeyInfo; +var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function() { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters').int() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ); +}); +exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo; + + + +var ECPrivateKey = asn1.define('ECPrivateKey', function() { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ); +}); +exports.ECPrivateKey = ECPrivateKey; +var ECParameters = asn1.define('ECParameters', function() { + this.choice({ + namedCurve: this.objid() + }); +}); + +var ECPrivateKey2 = asn1.define('ECPrivateKey2', function() { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('publicKey').seq().obj( + this.key('key').bitstr() + ) + ); +}); +exports.ECPrivateKey2 = ECPrivateKey2; +},{"asn1.js":102,"asn1.js-rfc3280":101}],99:[function(require,module,exports){ +require('./inject')(module.exports, require('crypto')); +},{"./inject":100,"crypto":76}],100:[function(require,module,exports){ +(function (Buffer){ +var sign = require('./sign'); +var verify = require('./verify'); +var Writable = require('readable-stream').Writable; +var inherits = require('inherits'); +var algos = require('./algos'); +'use strict'; +module.exports = function (exports, crypto) { + exports.createSign = createSign; + function createSign(algorithm) { + + return new Sign(algorithm, crypto); + } + exports.createVerify = createVerify; + function createVerify(algorithm) { + return new Verify(algorithm, crypto); + } +}; +inherits(Sign, Writable); +function Sign(algorithm, crypto) { + Writable.call(this); + var data = algos[algorithm]; + if (!data) { + throw new Error('Unknown message digest'); + } + this._hash = crypto.createHash(data.hash); + this._tag = data.id; + this._crypto = crypto; +}; +Sign.prototype._write = function _write(data, _, done) { + this._hash.update(data); + done(); +}; +Sign.prototype.update = function update(data) { + this.write(data); + return this; +}; + +Sign.prototype.sign = function signMethod(key, enc) { + this.end(); + var hash = this._hash.digest(); + var sig = sign(Buffer.concat([this._tag, hash]), key, this._crypto); + if (enc) { + sig = sig.toString(enc); + } + return sig; +}; + +inherits(Verify, Writable); +function Verify(algorithm, crypto) { + Writable.call(this); + var data = algos[algorithm]; + if (!data) { + throw new Error('Unknown message digest'); + } + this._hash = crypto.createHash(data.hash); + this._tag = data.id; +}; +Verify.prototype._write = function _write(data, _, done) { + this._hash.update(data); + done(); +}; +Verify.prototype.update = function update(data) { + this.write(data); + return this; +}; + +Verify.prototype.verify = function verifyMethod(key, sig, enc) { + this.end(); + var hash = this._hash.digest(); + if (!Buffer.isBuffer(sig)) { + sig = new Buffer(sig, enc); + } + return verify(sig, Buffer.concat([this._tag, hash]), key); +}; +}).call(this,require("buffer").Buffer) +},{"./algos":97,"./sign":136,"./verify":137,"buffer":69,"inherits":231,"readable-stream":198}],101:[function(require,module,exports){ +arguments[4][64][0].apply(exports,arguments) +},{"../..":99,"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/rfc/3280/index.js":64,"asn1.js":102}],102:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"./asn1/api":103,"./asn1/base":105,"./asn1/constants":109,"./asn1/decoders":111,"./asn1/encoders":113,"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/lib/asn1.js":51,"bn.js":65}],103:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"../asn1":102,"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/lib/asn1/api.js":52,"util":205,"vm":206}],104:[function(require,module,exports){ +var assert = require('assert'); +var util = require('util'); +var Reporter = require('../base').Reporter; +var Buffer = require('buffer').Buffer; + +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } + + this.base = base; + this.offset = 0; + this.length = base.length; +} +util.inherits(DecoderBuffer, Reporter); +exports.DecoderBuffer = DecoderBuffer; + +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset }; +}; + +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + + this.offset = save.offset; + + return res; +}; + +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; + +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +} + +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + + var res = new DecoderBuffer(this.base); + + // Share reporter state + res._reporterState = this._reporterState; + + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +} + +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } +} +exports.EncoderBuffer = EncoderBuffer; + +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; + + if (this.length === 0) + return out; + + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } + + return out; +}; + +},{"../base":105,"assert":67,"buffer":69,"util":205}],105:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"./buffer":104,"./node":106,"./reporter":107,"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/lib/asn1/base/index.js":54}],106:[function(require,module,exports){ +var assert = require('assert'); +var Reporter = require('../base').Reporter; +var EncoderBuffer = require('../base').EncoderBuffer; + +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'octstr', 'bitstr', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'ia5str' +]; + +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any' +].concat(tags); + +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + var state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + var state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(key) { + var state = this._baseState; + + assert(state.key === null); + state.key = key; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input)); + + var result = state['default']; + var present = true; + + var prevKey; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + present = this._peekTag( + input, + state.explicit !== null ? state.explicit : + state.implicit !== null ? state.implicit : + state.tag || 0 + ); + if (input.isError(present)) + return present; + } + + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input); + else + result = this._decodeChoice(input); + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + var fail = state.children.some(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input); + }); + if (fail) + return err; + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input) { + var state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0]); + else if (tag === 'octstr' || tag === 'bitstr' || tag === 'ia5str') + return this._decodeStr(input, tag); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1]); + else if (tag === 'objid') + return this._decodeObjid(input, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag); + else if (tag === 'null_') + return this._decodeNull(input); + else if (tag === 'bool') + return this._decodeBool(input); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0]); + else if (state.use !== null) + return this._getUse(state.use, input._reporterState.obj)._decode(input); + else + return input.error('unknown tag: ' + tag); + + return null; +}; + +Node.prototype._getUse = function _getUse(entity, obj) { + + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; + + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; + + if (this._skipDefault(result, reporter, parent)) + return; + + return result; +}; + +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + var result = null; + var present = true; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; + } + + // For error reporting + var prevKey; + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be ommited only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (tag === 'octstr' || tag === 'bitstr' || tag === 'ia5str') + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else + throw new Error('Unsupported tag: ' + tag); +}; + +},{"../base":105,"assert":67}],107:[function(require,module,exports){ +module.exports=require(56) +},{"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/lib/asn1/base/reporter.js":56,"util":205}],108:[function(require,module,exports){ +module.exports=require(57) +},{"../constants":109,"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/lib/asn1/constants/der.js":57}],109:[function(require,module,exports){ +module.exports=require(58) +},{"./der":108,"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/lib/asn1/constants/index.js":58}],110:[function(require,module,exports){ +var util = require('util'); + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +util.inherits(DERNode, base.Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag) { + if (buffer.isEmpty()) + return false; + + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + var state = buffer.start(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + return buffer.cut(state); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + var res = decoder.decode(buffer, 'der'); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'ia5str') { + return buffer.raw().toString(); + } else { + return this.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) + result = values[result.join(' ')]; + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return this.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + var res = 0; + + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + if (raw.length > 3) + return new bignum(raw); + + while (!buffer.isEmpty()) { + res <<= 8; + var i = buffer.readUInt8(); + if (buffer.isError(i)) + return i; + res |= i; + } + + if (values) + res = values[res] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + var num = len & 0x7f; + if (num >= 4) + return buf.error('length octect is too long'); + + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} + +},{"../../asn1":102,"util":205}],111:[function(require,module,exports){ +arguments[4][60][0].apply(exports,arguments) +},{"./der":110,"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/lib/asn1/decoders/index.js":60}],112:[function(require,module,exports){ +var util = require('util'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +util.inherits(DERNode, base.Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'octstr') + return this._createEncoderBuffer(str); + else if (tag === 'bitstr') + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + else if (tag === 'ia5str') + return this._createEncoderBuffer(str); + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/\s+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num <= 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + date.getFullYear(), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + date.getFullYear() % 100, + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (bignum !== null && num instanceof bignum) { + var numArray = num.toArray(); + if(num.sign === false && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = new Buffer(numArray); + } + + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(new Buffer(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; + + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} + +},{"../../asn1":102,"buffer":69,"util":205}],113:[function(require,module,exports){ +arguments[4][62][0].apply(exports,arguments) +},{"./der":112,"/Users/yemeljardi/code/bitcore/node_modules/asn1.js/lib/asn1/encoders/index.js":62}],114:[function(require,module,exports){ +var elliptic = exports; + +elliptic.version = require('../package.json').version; +elliptic.utils = require('./elliptic/utils'); +elliptic.rand = require('brorand'); +elliptic.hmacDRBG = require('./elliptic/hmac-drbg'); +elliptic.curve = require('./elliptic/curve'); +elliptic.curves = require('./elliptic/curves'); + +// Protocols +elliptic.ec = require('./elliptic/ec'); + +},{"../package.json":133,"./elliptic/curve":117,"./elliptic/curves":120,"./elliptic/ec":121,"./elliptic/hmac-drbg":124,"./elliptic/utils":125,"brorand":126}],115:[function(require,module,exports){ +var assert = require('assert'); +var bn = require('bn.js'); +var elliptic = require('../../elliptic'); + +var getNAF = elliptic.utils.getNAF; +var getJSF = elliptic.utils.getJSF; + +function BaseCurve(type, conf) { + this.type = type; + this.p = new bn(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); + + // Useful for many curves + this.zero = new bn(0).toRed(this.red); + this.one = new bn(1).toRed(this.red); + this.two = new bn(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new bn(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); +} +module.exports = BaseCurve; + +BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype.validate = function validate(point) { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + for (var j = 0; j < naf.length; j += doubles.step) { + var nafW = 0; + for (var k = j + doubles.step - 1; k >= j; k--) + nafW = (nafW << 1) + naf[k]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (var j = 0; j < repr.length; j++) { + var nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; + +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var k = 0; i >= 0 && naf[i] === 0; i--) + k++; + if (i >= 0) + k++; + acc = acc.dblp(k); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; +}; + +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + for (var i = 0; i < len; i++) { + var p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (var i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a]); + naf[b] = getNAF(coeffs[b], wndWidth[b]); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b] /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3 /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (var j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (var i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (var j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (var j = 0; j < len; j++) { + var z = tmp[j]; + var p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (var i = 0; i < len; i++) + wnd[i] = null; + return acc.toP(); +}; + +BaseCurve.BasePoint = BasePoint; + +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} + +BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); +}; + +BasePoint.prototype.precompute = function precompute(power, _beta) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; +}; + +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles + }; +}; + +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res + }; +}; + +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; + +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; +}; + +},{"../../elliptic":114,"assert":67,"bn.js":65}],116:[function(require,module,exports){ +var assert = require('assert'); +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var bn = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var getNAF = elliptic.utils.getNAF; + +function EdwardsCurve(conf) { + // NOTE: Important as we are creating point in Base.call() + this.twisted = conf.a != 1; + this.mOneA = this.twisted && conf.a == -1; + this.extended = this.mOneA; + + Base.call(this, 'mont', conf); + + this.a = new bn(conf.a, 16).mod(this.red.m).toRed(this.red); + this.c = new bn(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new bn(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = conf.c == 1; +} +inherits(EdwardsCurve, Base); +module.exports = EdwardsCurve; + +EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); +}; + +EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); +}; + +EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); +}; + +// Just for compatibility with Short curve +EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); +}; + +EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +EdwardsCurve.prototype.pointFromX = function pointFromX(odd, x) { + x = new bn(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + + var y = rhs.redMul(lhs.redInvm()).redSqrt(); + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y, curve.one); +}; + +EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); + + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + + return lhs.cmp(rhs) === 0; +}; + +function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new bn(x, 16); + this.y = new bn(y, 16); + this.z = z ? new bn(z, 16) : this.curve.one; + this.t = t && new bn(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } +} +inherits(Point, Base.BasePoint); + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + this.y.cmp(this.z) === 0; +}; + +Point.prototype._extDbl = function _extDbl() { + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projDbl = function _projDbl() { + // http://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp + // http://hyperelliptic.org/EFD/g1p/auto-edwards-projective.html#doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + if (this.curve.twisted) { + // E = a * C + var e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + var nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + var ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + var nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + var h = this.z.redSqr(); + // J = F - 2 * H + var j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + var nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + var ny = f.redMul(e.redSub(d)); + // Z3 = F * J + var nz = f.redMul(j); + } + } else { + // E = C + D + var e = c.redAdd(d); + // H = (c * Z1)^2 + var h = this.curve._mulC(redMul(this.z)).redSqr(); + // J = E - 2 * H + var j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + var nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + var ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + var nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); +}; + +Point.prototype._extAdd = function _extAdd(p) { + // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projAdd = function _projAdd(p) { + // http://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#addition-add-2008-bbjlp + // http://hyperelliptic.org/EFD/g1p/auto-edwards-projective.html#addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + var ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + var nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + var ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + var nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); +}; + +Point.prototype.mul = function mul(k) { + if (this.precomputed && this.precomputed.doubles) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2); +}; + +Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; +}; + +Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); +}; + +Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); +}; + +// Compatibility with BaseCurve +Point.prototype.toP = Point.prototype.normalize; +Point.prototype.mixedAdd = Point.prototype.add; + +},{"../../elliptic":114,"../curve":117,"assert":67,"bn.js":65,"inherits":231}],117:[function(require,module,exports){ +var curve = exports; + +curve.base = require('./base'); +curve.short = require('./short'); +curve.mont = require('./mont'); +curve.edwards = require('./edwards'); + +},{"./base":115,"./edwards":116,"./mont":118,"./short":119}],118:[function(require,module,exports){ +var assert = require('assert'); +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var bn = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var getNAF = elliptic.utils.getNAF; + +function MontCurve(conf) { + Base.call(this, 'mont', conf); + + this.a = new bn(conf.a, 16).toRed(this.red); + this.b = new bn(conf.b, 16).toRed(this.red); + this.i4 = new bn(4).toRed(this.red).redInvm(); + this.two = new bn(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); +} +inherits(MontCurve, Base); +module.exports = MontCurve; + +MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); +}; + +MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +} + +MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; +}; + +function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new bn(x, 16); + this.z = new bn(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } +} +inherits(Point, Base.BasePoint); + +Point.prototype.precompute = function precompute() { + // No-op +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); +}; + +Point.prototype.add = function add(p) { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); +}; + +Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.ishrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; +}; + +Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; +}; + +Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); +}; + +},{"../../elliptic":114,"../curve":117,"assert":67,"bn.js":65,"inherits":231}],119:[function(require,module,exports){ +var assert = require('assert'); +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var bn = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var getNAF = elliptic.utils.getNAF; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new bn(conf.a, 16).toRed(this.red); + this.b = new bn(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new bn(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new bn(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new bn(vec.a, 16), + b: new bn(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : bn.mont(num); + var tinv = new bn(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + var one = new bn(1).toRed(red); + + var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.shrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new bn(1); + var y1 = new bn(0); + var x2 = new bn(0); + var y2 = new bn(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + var r = v.sub(q.mul(u)); + var x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.sign) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.sign) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromX = function pointFromX(odd, x) { + x = new bn(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.sign) { + split.k1.sign = !split.k1.sign; + p = p.neg(true); + } + if (split.k2.sign) { + split.k2.sign = !split.k2.sign; + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; +}; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new bn(x, 16); + this.y = new bn(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + function endoMul(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + } + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + }]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new bn(k, 16); + + if (this.precomputed && this.precomputed.doubles) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + function negate(p) { + return p.neg(); + } + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new bn(0); + } else { + this.x = new bn(x, 16); + this.y = new bn(y, 16); + this.z = new bn(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + // Z = 1 + if (this.zOne) { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + var nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + var nz = this.y.redAdd(this.y); + } else { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + var nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + var ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + var nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + // Z = 1 + if (this.zOne) { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + var nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + var ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + var nz = this.y.redAdd(this.y); + } else { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + var nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + var nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + var ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + var tinv = this.curve.tinv; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new bn(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +},{"../../elliptic":114,"../curve":117,"assert":67,"bn.js":65,"inherits":231}],120:[function(require,module,exports){ +var curves = exports; + +var assert = require('assert'); +var hash = require('hash.js'); +var bn = require('bn.js'); +var elliptic = require('../elliptic'); + +function PresetCurve(options) { + if (options.type === 'short') + this.curve = new elliptic.curve.short(options); + else if (options.type === 'edwards') + this.curve = new elliptic.curve.edwards(options); + else + this.curve = new elliptic.curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); +} +curves.PresetCurve = PresetCurve; + +function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); +} + +defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' + ], +}); + +defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' + ], +}); + +defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' + ], +}); + +defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '0', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9' + ] +}); + +defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658' + ] +}); + +defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3' + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15' + } + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + { + 'doubles': { + 'step': 4, + 'points': [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' + ] + ] + }, + 'naf': { + 'wnd': 7, + 'points': [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] + } + } + ] +}); + +},{"../elliptic":114,"assert":67,"bn.js":65,"hash.js":127}],121:[function(require,module,exports){ +var assert = require('assert'); +var bn = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; + +var KeyPair = require('./key'); +var Signature = require('./signature'); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); + + options = elliptic.curves[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof elliptic.curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.shrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash for function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(priv, pub) { + return new KeyPair(this, priv, pub); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new elliptic.hmacDRBG({ + hash: this.hash, + pers: options.pers, + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + nonce: this.n.toArray() + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new bn(2)); + do { + var priv = new bn(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyPair(priv); + } while (true); +}; + +EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.shrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, options) { + key = this.keyPair(key, 'hex'); + msg = this._truncateToN(new bn(msg, 16)); + if (!options) + options = {}; + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray(); + for (var i = bkey.length; i < 21; i++) + bkey.unshift(0); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray(); + for (var i = nonce.length; i < bytes; i++) + nonce.unshift(0); + + // Instantiate Hmac_DRBG + var drbg = new elliptic.hmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new bn(1)); + do { + var k = new bn(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var r = kp.getX().mod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)).mod(this.n); + if (s.cmpn(0) === 0) + continue; + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) + s = this.n.sub(s); + + return new Signature(r, s); + } while (true); +}; + +EC.prototype.verify = function verify(msg, signature, key) { + msg = this._truncateToN(new bn(msg, 16)); + key = this.keyPair(key, 'hex'); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).mod(this.n); + var u2 = sinv.mul(r).mod(this.n); + + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().mod(this.n).cmp(r) === 0; +}; + +},{"../../elliptic":114,"./key":122,"./signature":123,"assert":67,"bn.js":65}],122:[function(require,module,exports){ +var assert = require('assert'); +var bn = require('bn.js'); + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; + +function KeyPair(ec, priv, pub) { + if (priv instanceof KeyPair) + return priv; + if (pub instanceof KeyPair) + return pub; + + if (!priv) { + priv = pub; + pub = null; + } + if (priv !== null && typeof priv === 'object') { + if (priv.x) { + // KeyPair(public) + pub = priv; + priv = null; + } else if (priv.priv || priv.pub) { + // KeyPair({ priv: ..., pub: ... }) + pub = priv.pub; + priv = priv.priv; + } + } + + this.ec = ec; + this.priv = null; + this.pub = null; + + // KeyPair(public, 'hex') + if (this._importPublicHex(priv, pub)) + return; + + if (pub === 'hex') + pub = null; + + // KeyPair(priv, pub) + if (priv) + this._importPrivate(priv); + if (pub) + this._importPublic(pub); +} +module.exports = KeyPair; + +KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; +}; + +KeyPair.prototype.getPublic = function getPublic(compact, enc) { + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!enc) + return this.pub; + + var len = this.ec.curve.p.byteLength(); + var x = this.pub.getX().toArray(); + + for (var i = x.length; i < len; i++) + x.unshift(0); + + if (compact) { + var res = [ this.pub.getY().isEven() ? 0x02 : 0x03 ].concat(x); + } else { + var y = this.pub.getY().toArray(); + for (var i = y.length; i < len; i++) + y.unshift(0); + var res = [ 0x04 ].concat(x, y); + } + return utils.encode(res, enc); +}; + +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; +}; + +KeyPair.prototype._importPrivate = function _importPrivate(key) { + this.priv = new bn(key, 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.mod(this.ec.curve.n); +}; + +KeyPair.prototype._importPublic = function _importPublic(key) { + this.pub = this.ec.curve.point(key.x, key.y); +}; + +KeyPair.prototype._importPublicHex = function _importPublic(key, enc) { + key = utils.toArray(key, enc); + var len = this.ec.curve.p.byteLength(); + if (key[0] === 0x04 && key.length - 1 === 2 * len) { + this.pub = this.ec.curve.point( + key.slice(1, 1 + len), + key.slice(1 + len, 1 + 2 * len)); + } else if ((key[0] === 0x02 || key[0] === 0x03) && key.length - 1 === len) { + this.pub = this.ec.curve.pointFromX(key[0] === 0x03, + key.slice(1, 1 +len)); + } else { + return false; + } + + return true; +}; + +// ECDH +KeyPair.prototype.derive = function derive(pub) { + return pub.mul(this.priv).getX(); +}; + +// ECDSA +KeyPair.prototype.sign = function sign(msg) { + return this.ec.sign(msg, this); +}; + +KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); +}; + +KeyPair.prototype.inspect = function inspect() { + return ''; +}; + +},{"../../elliptic":114,"assert":67,"bn.js":65}],123:[function(require,module,exports){ +var assert = require('assert'); +var bn = require('bn.js'); + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; + +function Signature(r, s) { + if (r instanceof Signature) + return r; + + if (this._importDER(r, s)) + return; + + assert(r && s, 'Signature without r or s'); + this.r = new bn(r, 16); + this.s = new bn(s, 16); +} +module.exports = Signature; + +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + if (data.length < 6 || data[0] !== 0x30 || data[2] !== 0x02) + return false; + var total = data[1]; + if (1 + total > data.length) + return false; + var rlen = data[3]; + // Short length notation + if (rlen >= 0x80) + return false; + if (4 + rlen + 2 >= data.length) + return false; + if (data[4 + rlen] !== 0x02) + return false; + var slen = data[5 + rlen]; + // Short length notation + if (slen >= 0x80) + return false; + if (4 + rlen + 2 + slen > data.length) + return false; + + this.r = new bn(data.slice(4, 4 + rlen)); + this.s = new bn(data.slice(4 + rlen + 2, 4 + rlen + 2 + slen)); + + return true; +}; + +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + var total = r.length + s.length + 4; + var res = [ 0x30, total, 0x02, r.length ]; + res = res.concat(r, [ 0x02, s.length ], s); + return utils.encode(res, enc); +}; + +},{"../../elliptic":114,"assert":67,"bn.js":65}],124:[function(require,module,exports){ +var assert = require('assert'); + +var hash = require('hash.js'); +var elliptic = require('../elliptic'); +var utils = elliptic.utils; + +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + + this.reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + + var entropy = utils.toArray(options.entropy, options.entropyEnc); + var nonce = utils.toArray(options.nonce, options.nonceEnc); + var pers = utils.toArray(options.pers, options.persEnc); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); +} +module.exports = HmacDRBG; + +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this.reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 +}; + +HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); +}; + +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); +}; + +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toBuffer(entropy, entropyEnc); + add = utils.toBuffer(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this.reseed = 1; +}; + +HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this.reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this.reseed++; + return utils.encode(res, enc); +}; + +},{"../elliptic":114,"assert":67,"hash.js":127}],125:[function(require,module,exports){ +var assert = require('assert'); +var bn = require('bn.js'); + +var utils = exports; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +utils.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +// Represent num in a w-NAF form +function getNAF(num, w) { + var naf = []; + var ws = 1 << (w + 1); + var k = num.clone(); + while (k.cmpn(1) >= 0) { + var z; + if (k.isOdd()) { + var mod = k.andln(ws - 1); + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + naf.push(z); + + // Optimization, shift by word if possible + var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; + for (var i = 1; i < shift; i++) + naf.push(0); + k.ishrn(shift); + } + + return naf; +} +utils.getNAF = getNAF; + +// Represent k1, k2 in a Joint Sparse Form +function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + var m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + var m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.ishrn(1); + k2.ishrn(1); + } + + return jsf; +} +utils.getJSF = getJSF; + +},{"assert":67,"bn.js":65}],126:[function(require,module,exports){ +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +if (typeof window === 'object') { + if (window.crypto && window.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.crypto.getRandomValues(arr); + return arr; + }; + } else if (window.msCrypto && window.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.msCrypto.getRandomValues(arr); + return arr; + }; + } else { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker + try { + var crypto = require('cry' + 'pto'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + // Emulate crypto API using randy + Rand.prototype._rand = function _rand(n) { + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; + }; + } +} + +},{}],127:[function(require,module,exports){ +var hash = exports; + +hash.utils = require('./hash/utils'); +hash.common = require('./hash/common'); +hash.sha = require('./hash/sha'); +hash.ripemd = require('./hash/ripemd'); +hash.hmac = require('./hash/hmac'); + +// Proxy hash functions to the main object +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.ripemd160 = hash.ripemd.ripemd160; + +},{"./hash/common":128,"./hash/hmac":129,"./hash/ripemd":130,"./hash/sha":131,"./hash/utils":132}],128:[function(require,module,exports){ +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.endian = 'big'; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this.blockSize / 8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % (this.blockSize / 8); + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg.slice(0, msg.length - r), this.endian); + for (var i = 0; i < msg.length; i += this.blockSize / 32) + this._update(msg.slice(i, i + this.blockSize / 32)); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this.blockSize / 8; + var k = bytes - ((len + 8) % bytes); + var res = new Array(k + 8); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + } + + return res; +} + +},{"../hash":127}],129:[function(require,module,exports){ +var hmac = exports; + +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + var okey = key.slice(); + for (var i = 0; i < key.length; i++) { + key[i] ^= 0x36; + okey[i] ^= 0x5c; + } + + this.hash = { + inner: new this.Hash().update(key), + outer: new this.Hash().update(okey) + }; +}; + +Hmac.prototype.update = function update(msg, enc) { + this.hash.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.hash.outer.update(this.hash.inner.digest()); + return this.hash.outer.digest(enc); +}; + +},{"../hash":127}],130:[function(require,module,exports){ +var hash = require('../hash'); +var utils = hash.utils; + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = hash.common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; + +RIPEMD160.prototype._update = function update(msg) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j]], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j]], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; + +},{"../hash":127}],131:[function(require,module,exports){ +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +var rotr32 = utils.rotr32; +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var BlockHash = hash.common.BlockHash; + +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; + this.k = sha256_K; +} +utils.inherits(SHA256, BlockHash); +exports.sha256 = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; + +SHA256.prototype._update = function _update(msg) { + var W = new Array(64); + for (var i = 0; i < 16; i++) + W[i] = msg[i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +exports.sha224 = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} + +},{"../hash":127}],132:[function(require,module,exports){ +var utils = exports; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 != 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +utils.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') { + w = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + if (w < 0) + w += 0x100000000; + } + res += zero8(w.toString(16)); + } + return res; +} +utils.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +utils.zero8 = zero8; + +function join32(msg, endian) { + assert(msg.length % 4 === 0); + var res = new Array(msg.length / 4); + for (var i = 0, k = 0; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + if (w < 0) + w += 0x100000000; + res[i] = w; + } + return res; +} +utils.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +utils.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +utils.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +utils.rotl32 = rotl32; + +function sum32(a, b) { + var r = (a + b) & 0xffffffff; + if (r < 0) + r += 0x100000000; + return r; +} +utils.sum32 = sum32; + +function sum32_3(a, b, c) { + var r = (a + b + c) & 0xffffffff; + if (r < 0) + r += 0x100000000; + return r; +} +utils.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + var r = (a + b + c + d) & 0xffffffff; + if (r < 0) + r += 0x100000000; + return r; +} +utils.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + var r = (a + b + c + d + e) & 0xffffffff; + if (r < 0) + r += 0x100000000; + return r; +} +utils.sum32_5 = sum32_5; + +function assert(cond, msg) { + if (!cond) + throw new Error(msg || 'Assertion failed'); +} +utils.assert = assert; + +// Shamelessly copied from browserify +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + utils.inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + utils.inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],133:[function(require,module,exports){ +module.exports={ + "name": "elliptic", + "version": "0.15.15", + "description": "EC cryptography", + "main": "lib/elliptic.js", + "scripts": { + "test": "mocha --reporter=spec test/*-test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:indutny/elliptic" + }, + "keywords": [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/elliptic/issues" + }, + "homepage": "https://github.com/indutny/elliptic", + "devDependencies": { + "browserify": "^3.44.2", + "mocha": "^1.18.2", + "uglify-js": "^2.4.13" + }, + "dependencies": { + "bn.js": "^0.15.0", + "brorand": "^1.0.1", + "hash.js": "^0.2.0", + "inherits": "^2.0.1" + }, + "readme": "# Elliptic [![Build Status](https://secure.travis-ci.org/indutny/elliptic.png)](http://travis-ci.org/indutny/elliptic)\n\nFast elliptic-curve cryptography in a plain javascript implementation.\n\nNOTE: Please take a look at http://safecurves.cr.yp.to/ before choosing a curve\nfor your cryptography operations.\n\n## Incentive\n\nECC is much slower than regular RSA cryptography, the JS implementations are\neven more slower.\n\n## Benchmarks\n\n```bash\n$ node benchmarks/index.js\nBenchmarking: sign\nelliptic#sign x 262 ops/sec ±0.51% (177 runs sampled)\neccjs#sign x 55.91 ops/sec ±0.90% (144 runs sampled)\n------------------------\nFastest is elliptic#sign\n========================\nBenchmarking: verify\nelliptic#verify x 113 ops/sec ±0.50% (166 runs sampled)\neccjs#verify x 48.56 ops/sec ±0.36% (125 runs sampled)\n------------------------\nFastest is elliptic#verify\n========================\nBenchmarking: gen\nelliptic#gen x 294 ops/sec ±0.43% (176 runs sampled)\neccjs#gen x 62.25 ops/sec ±0.63% (129 runs sampled)\n------------------------\nFastest is elliptic#gen\n========================\nBenchmarking: ecdh\nelliptic#ecdh x 136 ops/sec ±0.85% (156 runs sampled)\n------------------------\nFastest is elliptic#ecdh\n========================\n```\n\n## API\n\n### ECDSA\n\n```javascript\nvar EC = require('elliptic').ec;\n\n// Create and initialize EC context\n// (better do it once and reuse it)\nvar ec = new EC('secp256k1');\n\n// Generate keys\nvar key = ec.genKeyPair();\n\n// Sign message (must be an array, or it'll be treated as a hex sequence)\nvar msg = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];\nvar signature = key.sign(msg);\n\n// Export DER encoded signature in Array\nvar derSign = signature.toDER();\n\n// Verify signature\nconsole.log(key.verify(msg, derSign));\n```\n\n### ECDH\n\n```javascript\n// Generate keys\nvar key1 = ec.genKeyPair();\nvar key2 = ec.genKeyPair();\n\nvar shared1 = key1.derive(key2.getPublic());\nvar shared2 = key2.derive(key1.getPublic());\n\nconsole.log('Both shared secrets are BN instances');\nconsole.log(shared1.toString(16));\nconsole.log(shared2.toString(16));\n```\n\nNOTE: `.derive()` returns a [BN][1] instance.\n\n## Supported curves\n\nElliptic.js support following curve types:\n\n* Short Weierstrass\n* Montgomery\n* Edwards\n* Twisted Edwards\n\nFollowing curve 'presets' are embedded into the library:\n\n* `secp256k1`\n* `p192`\n* `p224`\n* `p256`\n* `curve25519`\n* `ed25519`\n\nNOTE: That `curve25519` could not be used for ECDSA, use `ed25519` instead.\n\n### Implementation details\n\nECDSA is using deterministic `k` value generation as per [RFC6979][0]. Most of\nthe curve operations are performed on non-affine coordinates (either projective\nor extended), various windowing techniques are used for different cases.\n\nAll operations are performed in reduction context using [bn.js][1], hashing is\nprovided by [hash.js][2]\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[0]: http://tools.ietf.org/html/rfc6979\n[1]: https://github.com/indutny/bn.js\n[2]: https://github.com/indutny/hash.js\n", + "readmeFilename": "README.md", + "_id": "elliptic@0.15.15", + "_shasum": "63269184a856d6e00871e84f37a8401ff84e4aea", + "_from": "elliptic@^0.15.14", + "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-0.15.15.tgz" +} + +},{}],134:[function(require,module,exports){ +exports.strip = function strip(artifact) { + artifact = artifact.toString() + var startRegex = /^-----BEGIN (.*)-----\n/; + var match = startRegex.exec(artifact); + var tag = match[1]; + var endRegex = new RegExp("\n-----END " + tag + "-----(\n*)$"); + var base64 = artifact.slice(match[0].length).replace(endRegex, "").replace(/\n/g, ""); + return {tag: tag, base64: base64}; +}; + +// http://stackoverflow.com/a/7033705 +var wrap = function wrap(str, l) { + var chunks = []; + while (str) { + if (str.length < l) { + chunks.push(str); + break; + } + else { + chunks.push(str.substr(0, l)); + str = str.substr(l); + } + } + return chunks.join("\n"); +} + +exports.assemble = function assemble(info) { + var tag = info.tag; + var base64 = info.base64; + var startLine = "-----BEGIN " + tag + "-----"; + var endLine = "-----END " + tag + "-----"; + return startLine + "\n" + wrap(base64, 64) + "\n" + endLine + "\n"; +} +},{}],135:[function(require,module,exports){ +(function (Buffer){ +var pemstrip = require('pemstrip'); +var asn1 = require('./asn1'); +var aesid = require('./aesid.json'); +module.exports = parseKeys; + +function parseKeys(buffer, crypto) { + var password; + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase; + buffer = buffer.key; + } + var stripped = pemstrip.strip(buffer); + var type = stripped.tag; + var data = new Buffer(stripped.base64, 'base64'); + var subtype,ndata; + switch (type) { + case 'PUBLIC KEY': + ndata = asn1.PublicKey.decode(data, 'der'); + subtype = ndata.algorithm.algorithm.join('.'); + switch(subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der'); + case '1.2.840.10045.2.1': + return { + type: 'ec', + data: asn1.ECPublicKey.decode(data, 'der') + }; + default: throw new Error('unknown key id ' + subtype); + } + throw new Error('unknown key type ' + type); + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der'); + data = decrypt(crypto, data, password); + //falling through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der'); + subtype = ndata.algorithm.algorithm.join('.'); + switch(subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der'); + case '1.2.840.10045.2.1': + ndata = asn1.ECPrivateWrap.decode(data, 'der'); + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + }; + default: throw new Error('unknown key id ' + subtype); + } + throw new Error('unknown key type ' + type); + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der'); + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der'); + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der'); + return { + curve: data.parameters.value, + privateKey: data.privateKey + } + default: throw new Error('unknown key type ' + type); + } +} +function decrypt(crypto, data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt; + var iters = data.algorithm.decrypt.kde.kdeparams.iters; + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]; + var iv = data.algorithm.decrypt.cipher.iv; + var cipherText = data.subjectPrivateKey; + var keylen = parseInt(algo.split('-')[1], 10)/8; + var key = crypto.pbkdf2Sync(password, salt, iters, keylen); + var cipher = crypto.createDecipheriv(algo, key, iv); + var out = []; + out.push(cipher.update(cipherText)); + out.push(cipher.final()); + return Buffer.concat(out); +} +}).call(this,require("buffer").Buffer) +},{"./aesid.json":96,"./asn1":98,"buffer":69,"pemstrip":134}],136:[function(require,module,exports){ +(function (Buffer){ +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var parseKeys = require('./parseKeys'); +var bn = require('bn.js'); +var elliptic = require('elliptic'); +module.exports = sign; +function sign(hash, key, crypto) { + var priv = parseKeys(key, crypto); + if (priv.curve) { + return ecSign(hash, priv, crypto); + } + var len = priv.modulus.byteLength(); + var pad = [ 0, 1 ]; + while (hash.length + pad.length + 1 < len) { + pad.push(0xff); + } + pad.push(0x00); + var i = -1; + while (++i < hash.length) { + pad.push(hash[i]); + } + + var out = crt(pad, priv); + if (out.length < len) { + var prefix = new Buffer(len - out.length); + prefix.fill(0); + out = Buffer.concat([prefix, out], len); + } + return out; +} +function crt(msg, priv) { + var c1 = new bn(msg).toRed(bn.mont(priv.prime1)); + var c2 = new bn(msg).toRed(bn.mont(priv.prime2)); + var qinv = new bn(priv.coefficient); + var p = new bn(priv.prime1); + var q = new bn(priv.prime2); + var m1 = c1.redPow(priv.exponent1) + var m2 = c2.redPow(priv.exponent2); + m1 = m1.fromRed(); + m2 = m2.fromRed(); + var h = m1.isub(m2).imul(qinv).mod(p); + h.imul(q); + m2.iadd(h); + return new Buffer(m2.toArray()); +} +function ecSign(hash, priv, crypto) { + elliptic.rand = crypto.randomBytes; + var curve; + if (priv.curve.join('.') === '1.3.132.0.10') { + curve = new elliptic.ec('secp256k1'); + } + var key = curve.genKeyPair(); + key._importPrivate(priv.privateKey); + var out = key.sign(hash); + return new Buffer(out.toDER()); +} +}).call(this,require("buffer").Buffer) +},{"./parseKeys":135,"bn.js":65,"buffer":69,"elliptic":114}],137:[function(require,module,exports){ +(function (Buffer){ +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var parseKeys = require('./parseKeys'); +var elliptic = require('elliptic'); +var bn = require('bn.js'); +module.exports = verify; +function verify(sig, hash, key) { + var pub = parseKeys(key); + if (pub.type === 'ec') { + return ecVerify(sig, hash, pub); + } + var red = bn.mont(pub.modulus); + sig = new bn(sig).toRed(red); + + sig = sig.redPow(new bn(pub.publicExponent)); + + sig = new Buffer(sig.fromRed().toArray()); + sig = sig.slice(sig.length - hash.length); + var out = 0; + var len = sig.length; + var i = -1; + while (++i < len) { + out += (sig[i] ^ hash[i]); + } + return !out; +} +function ecVerify(sig, hash, pub) { + var curve; + if (pub.data.algorithm.curve.join('.') === '1.3.132.0.10') { + curve = new elliptic.ec('secp256k1'); + } + var pubkey = pub.data.subjectPrivateKey.data; + return curve.verify(hash.toString('hex'), sig.toString('hex'), pubkey.toString('hex')); +} + +}).call(this,require("buffer").Buffer) +},{"./parseKeys":135,"bn.js":65,"buffer":69,"elliptic":114}],138:[function(require,module,exports){ +(function (Buffer){ +var elliptic = require('elliptic'); +var BN = require('bn.js'); +module.exports = ECDH; + +function ECDH(curve, crypto) { + elliptic.rand = crypto.randomBytes; + this.curve = new elliptic.ec(curve); + this.keys = void 0; +} +ECDH.prototype.generateKeys = function (enc, format) { + this.keys = this.curve.genKeyPair(); + return this.getPublicKey(enc, format); +}; + +ECDH.prototype.computeSecret = function (other, inenc, enc) { + inenc = inenc || 'utf8'; + if (!Buffer.isBuffer(other)) { + other = new Buffer(other, inenc); + } + other = new BN(other); + other = other.toString(16); + var otherPub = this.curve.keyPair(other, 'hex').getPublic(); + var out = otherPub.mul(this.keys.getPrivate()).getX(); + return returnValue(out, enc); +}; +ECDH.prototype.getPublicKey = function (enc, format) { + var key = this.keys.getPublic(format === 'compressed', true); + if (format === 'hybrid') { + if (key[key.length - 1] % 2) { + key[0] = 7; + } else { + key [0] = 6; + } + } + return returnValue(key, enc); +}; +ECDH.prototype.getPrivateKey = function (enc) { + return returnValue(this.keys.getPrivate(), enc); +}; + +ECDH.prototype.setPublicKey = function (pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + var pkey = new BN(pub); + pkey = pkey.toArray(); + this.keys._importPublicHex(pkey); +}; +ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + var _priv = new BN(priv); + _priv = _priv.toString(16); + this.keys._importPrivate(_priv); +}; +function returnValue(bn, enc) { + if (!Array.isArray(bn)) { + bn = bn.toArray(); + } + var buf = new Buffer(bn); + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } +} +}).call(this,require("buffer").Buffer) +},{"bn.js":65,"buffer":69,"elliptic":140}],139:[function(require,module,exports){ +var ECDH = require('./ecdh'); +module.exports = function (crypto, exports) { + exports.createECDH = function (curve) { + return new ECDH(curve, crypto); + }; +}; +},{"./ecdh":138}],140:[function(require,module,exports){ +module.exports=require(114) +},{"../package.json":159,"./elliptic/curve":143,"./elliptic/curves":146,"./elliptic/ec":147,"./elliptic/hmac-drbg":150,"./elliptic/utils":151,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js":114,"brorand":152}],141:[function(require,module,exports){ +module.exports=require(115) +},{"../../elliptic":140,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js":115,"assert":67,"bn.js":65}],142:[function(require,module,exports){ +module.exports=require(116) +},{"../../elliptic":140,"../curve":143,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js":116,"assert":67,"bn.js":65,"inherits":231}],143:[function(require,module,exports){ +module.exports=require(117) +},{"./base":141,"./edwards":142,"./mont":144,"./short":145,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js":117}],144:[function(require,module,exports){ +module.exports=require(118) +},{"../../elliptic":140,"../curve":143,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js":118,"assert":67,"bn.js":65,"inherits":231}],145:[function(require,module,exports){ +module.exports=require(119) +},{"../../elliptic":140,"../curve":143,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/short.js":119,"assert":67,"bn.js":65,"inherits":231}],146:[function(require,module,exports){ +module.exports=require(120) +},{"../elliptic":140,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js":120,"assert":67,"bn.js":65,"hash.js":153}],147:[function(require,module,exports){ +module.exports=require(121) +},{"../../elliptic":140,"./key":148,"./signature":149,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/index.js":121,"assert":67,"bn.js":65}],148:[function(require,module,exports){ +module.exports=require(122) +},{"../../elliptic":140,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js":122,"assert":67,"bn.js":65}],149:[function(require,module,exports){ +module.exports=require(123) +},{"../../elliptic":140,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js":123,"assert":67,"bn.js":65}],150:[function(require,module,exports){ +module.exports=require(124) +},{"../elliptic":140,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/hmac-drbg.js":124,"assert":67,"hash.js":153}],151:[function(require,module,exports){ +module.exports=require(125) +},{"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js":125,"assert":67,"bn.js":65}],152:[function(require,module,exports){ +module.exports=require(126) +},{"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/index.js":126}],153:[function(require,module,exports){ +module.exports=require(127) +},{"./hash/common":154,"./hash/hmac":155,"./hash/ripemd":156,"./hash/sha":157,"./hash/utils":158,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash.js":127}],154:[function(require,module,exports){ +module.exports=require(128) +},{"../hash":153,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/common.js":128}],155:[function(require,module,exports){ +module.exports=require(129) +},{"../hash":153,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/hmac.js":129}],156:[function(require,module,exports){ +module.exports=require(130) +},{"../hash":153,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/ripemd.js":130}],157:[function(require,module,exports){ +module.exports=require(131) +},{"../hash":153,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/sha.js":131}],158:[function(require,module,exports){ +module.exports=require(132) +},{"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/utils.js":132}],159:[function(require,module,exports){ +module.exports=require(133) +},{"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/package.json":133}],160:[function(require,module,exports){ +(function (Buffer){ +var BN = require('bn.js'); +var MillerRabin = require('miller-rabin'); +var millerRabin = new MillerRabin(); +var TWENTYFOUR = new BN(24); +var ELEVEN = new BN(11); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var primes = require('./generatePrime'); +module.exports = DH; +function setPublicKey(pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this._pub = new BN(pub); +} +function setPrivateKey(priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + this._priv = new BN(priv); +} +var primeCache = {}; +function checkPrime(prime, generator) { + var gen = generator.toString('hex'); + var hex = [gen, prime.toString(16)].join('_'); + if (hex in primeCache) { + return primeCache[hex]; + } + var error = 0; + + if (prime.isEven() || + !primes.simpleSieve || + !primes.fermatTest(prime) || + !millerRabin.test(prime)) { + //not a prime so +1 + error += 1; + + if (gen === '02' || gen === '05') { + // we'd be able to check the generator + // it would fail so +8 + error += 8; + } else { + //we wouldn't be able to test the generator + // so +4 + error += 4; + } + primeCache[hex] = error; + return error; + } + if (!millerRabin.test(prime.shrn(1))) { + //not a safe prime + error += 2; + } + var gen = generator.toString('hex'); + var rem; + switch (gen) { + case '02': + if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { + // unsuidable generator + error += 8; + } + break; + case '05': + rem = prime.mod(TEN); + if (rem.cmp(THREE) && rem.cmp(SEVEN)) { + // prime mod 10 needs to equal 3 or 7 + error += 8; + } + break; + default: + error += 4; + } + primeCache[hex] = error; + return error; +} +function defineError (self, error) { + try { + Object.defineProperty(self, 'verifyError', { + enumerable: true, + value: error, + writable: false + }); + } catch(e) { + self.verifyError = error; + } +} +function DH(prime, generator,crypto, malleable) { + this.setGenerator(generator); + this.__prime = new BN(prime); + this._prime = BN.mont(this.__prime); + this._pub = void 0; + this._priv = void 0; + + if (malleable) { + this.setPublicKey = setPublicKey; + this.setPrivateKey = setPrivateKey; + defineError(this, checkPrime(this.__prime, generator)); + } else { + defineError(this, 8); + } + this._makeNum = function makeNum() { + return crypto.randomBytes(192); + }; +} +DH.prototype.generateKeys = function () { + if (!this._priv) { + this._priv = new BN(this._makeNum()); + } + this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); + return this.getPublicKey(); +}; + +DH.prototype.computeSecret = function (other) { + other = new BN(other); + other = other.toRed(this._prime); + var secret = other.redPow(this._priv).fromRed(); + var out = new Buffer(secret.toArray()); + var prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0); + out = Buffer.concat([front, out]); + } + return out; +}; +DH.prototype.getPublicKey = function getPublicKey(enc) { + return returnValue(this._pub, enc); +}; +DH.prototype.getPrivateKey = function getPrivateKey(enc) { + return returnValue(this._priv, enc); +}; + +DH.prototype.getPrime = function (enc) { + return returnValue(this.__prime, enc); +}; +DH.prototype.getGenerator = function (enc) { + return returnValue(this._gen, enc); +}; +DH.prototype.setGenerator = function (gen, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(gen)) { + gen = new Buffer(gen, enc); + } + this._gen = new BN(gen); +}; + +function returnValue(bn, enc) { + var buf = new Buffer(bn.toArray()); + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } +} +}).call(this,require("buffer").Buffer) +},{"./generatePrime":161,"bn.js":65,"buffer":69,"miller-rabin":163}],161:[function(require,module,exports){ + +module.exports = findPrime; +findPrime.simpleSieve = simpleSieve; +findPrime.fermatTest = fermatTest; +var BN = require('bn.js'); +var TWENTYFOUR = new BN(24); +var MillerRabin = require('miller-rabin'); +var millerRabin = new MillerRabin(); +var ONE = new BN(1); +var TWO = new BN(2); +var FIVE = new BN(5); +var SIXTEEN = new BN(16); +var EIGHT = new BN(8); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var ELEVEN = new BN(11); +var FOUR = new BN(4); +var TWELVE = new BN(12); +var primes = null; + +function _getPrimes() { + if (primes !== null) + return primes; + + var limit = 0x100000; + var res = []; + res[0] = 2; + for (var i = 1, k = 3; k < limit; k += 2) { + var sqrt = Math.ceil(Math.sqrt(k)); + for (var j = 0; j < i && res[j] <= sqrt; j++) + if (k % res[j] === 0) + break; + + if (i !== j && res[j] <= sqrt) + continue; + + res[i++] = k; + } + primes = res; + return res; +} +function simpleSieve(p) { + var primes = _getPrimes(); + + for (var i = 0; i < primes.length; i++) + if (p.modn(primes[i]) === 0) + return false; + + return true; +} +function fermatTest(p) { + var red = BN.mont(p); + return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; +} +function findPrime(bits, gen ,crypto) { + gen = new BN(gen); + var runs, comp; + function generateRandom(bits) { + runs = -1; + var r = crypto.randomBytes(Math.ceil(bits / 8)); + r[0] |= 0xc0; + r[r.length - 1] |= 3; + var rem; + var out = new BN(r); + if (!gen.cmp(TWO)) { + while (out.mod(TWENTYFOUR).cmp(ELEVEN)) { + out.iadd(FOUR); + } + comp = { + major: [TWENTYFOUR], + minor: [TWELVE] + }; + } else if (!gen.cmp(FIVE)) { + rem = out.mod(TEN); + while (rem.cmp(THREE)) { + out.iadd(FOUR); + rem = out.mod(TEN); + } + comp = { + major: [FOUR, SIXTEEN], + minor: [TWO, EIGHT] + }; + } else { + comp = { + major: [FOUR], + minor: [TWO] + } + } + return out; + } + var num = generateRandom(bits); + + + + var n2 = num.shrn(1); + + while (true) { + if (num.bitLength() > bits) { + num = generateRandom(bits); + n2 = num.shrn(1); + } + runs++; + if (simpleSieve(n2) && + fermatTest(n2) && + millerRabin.test(n2) && + simpleSieve(num) && + fermatTest(num) && + millerRabin.test(num)) { + return num; + } + num.iadd(comp.major[runs%comp.major.length]); + n2.iadd(comp.minor[runs%comp.minor.length]); + } + +} +},{"bn.js":65,"miller-rabin":163}],162:[function(require,module,exports){ +(function (Buffer){ +var primes = require('./primes.json'); +var DH = require('./dh'); +var generatePrime = require('./generatePrime'); +module.exports = function (crypto, exports) { + exports.DiffieHellmanGroup = + exports.createDiffieHellmanGroup = + exports.getDiffieHellman = DiffieHellmanGroup; + function DiffieHellmanGroup(mod) { + return new DH(new Buffer(primes[mod].prime, 'hex'), + new Buffer(primes[mod].gen, 'hex'), crypto); + } + exports.createDiffieHellman = exports.DiffieHellman = DiffieHellman; + function DiffieHellman(prime, enc, generator, genc) { + + if (Buffer.isBuffer(enc) || + (typeof enc === 'string' && ['hex', 'binary', 'base64'].indexOf(enc) === -1)) { + genc = generator; + generator = enc + enc = void 0; + } + enc = enc || 'binary'; + genc = genc || 'binary'; + generator = generator || new Buffer([2]); + if (!Buffer.isBuffer(generator)) { + generator = new Buffer(generator, genc); + } + if (typeof prime === 'number') { + return new DH(generatePrime(prime, generator, crypto), generator, crypto, true); + } + if (!Buffer.isBuffer(prime)) { + prime = new Buffer(prime, enc); + } + + return new DH(prime, generator, crypto, true); + }; +} +}).call(this,require("buffer").Buffer) +},{"./dh":160,"./generatePrime":161,"./primes.json":165,"buffer":69}],163:[function(require,module,exports){ +var bn = require('bn.js'); +var brorand = require('brorand'); + +function MillerRabin(rand) { + this.rand = rand || new brorand.Rand(); +} +module.exports = MillerRabin; + +MillerRabin.create = function create(rand) { + return new MillerRabin(rand); +}; + +MillerRabin.prototype._rand = function _rand(n) { + var len = n.bitLength(); + var buf = this.rand.generate(Math.ceil(len / 8)); + + // Set low bits + buf[0] |= 3; + + // Mask high bits + var mask = len & 0x7; + if (mask !== 0) + buf[buf.length - 1] >>= 7 - mask; + + return new bn(buf); +} + +MillerRabin.prototype.test = function test(n, k, cb) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + var n2 = n1.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + var prime = true; + for (; k > 0; k--) { + var a = this._rand(n2); + if (cb) + cb(a); + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return false; + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) + return false; + } + + return prime; +}; + +MillerRabin.prototype.getDivisor = function getDivisor(n, k) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + var n2 = n1.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + var prime = true; + for (; k > 0; k--) { + var a = this._rand(n2); + + var g = n.gcd(a); + if (g.cmpn(1) !== 0) + return g; + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return x.fromRed().subn(1).gcd(n); + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) { + x = x.redSqr(); + return x.fromRed().subn(1).gcd(n); + } + } + + return prime; +}; + +},{"bn.js":65,"brorand":164}],164:[function(require,module,exports){ +module.exports=require(126) +},{"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/index.js":126}],165:[function(require,module,exports){ +module.exports={ + "modp1": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" + }, + "modp2": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" + }, + "modp5": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" + }, + "modp14": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" + }, + "modp15": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" + }, + "modp16": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" + }, + "modp17": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" + }, + "modp18": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" + } +} +},{}],166:[function(require,module,exports){ +(function (Buffer){ +module.exports = function(crypto) { + function pbkdf2(password, salt, iterations, keylen, digest, callback) { + if ('function' === typeof digest) { + callback = digest + digest = undefined + } + + if ('function' !== typeof callback) + throw new Error('No callback provided to pbkdf2') + + setTimeout(function() { + var result + + try { + result = pbkdf2Sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + + callback(undefined, result) + }) + } + + function pbkdf2Sync(password, salt, iterations, keylen, digest) { + if ('number' !== typeof iterations) + throw new TypeError('Iterations not a number') + + if (iterations < 0) + throw new TypeError('Bad iterations') + + if ('number' !== typeof keylen) + throw new TypeError('Key length not a number') + + if (keylen < 0) + throw new TypeError('Bad key length') + + digest = digest || 'sha1' + + if (!Buffer.isBuffer(password)) password = new Buffer(password) + if (!Buffer.isBuffer(salt)) salt = new Buffer(salt) + + var hLen, l = 1, r, T + var DK = new Buffer(keylen) + var block1 = new Buffer(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + + var U = crypto.createHmac(digest, password).update(block1).digest() + + if (!hLen) { + hLen = U.length + T = new Buffer(hLen) + l = Math.ceil(keylen / hLen) + r = keylen - (l - 1) * hLen + + if (keylen > (Math.pow(2, 32) - 1) * hLen) + throw new TypeError('keylen exceeds maximum length') + } + + U.copy(T, 0, 0, hLen) + + for (var j = 1; j < iterations; j++) { + U = crypto.createHmac(digest, password).update(U).digest() + + for (var k = 0; k < hLen; k++) { + T[k] ^= U[k] + } + } + + var destPos = (i - 1) * hLen + var len = (i == l ? r : hLen) + T.copy(DK, destPos, 0, len) + } + + return DK + } + + return { + pbkdf2: pbkdf2, + pbkdf2Sync: pbkdf2Sync + } +} + +}).call(this,require("buffer").Buffer) +},{"buffer":69}],167:[function(require,module,exports){ +(function (Buffer){ + +module.exports = ripemd160 + + + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/** @preserve +(c) 2012 by Cédric Mesnil. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - 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. + +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. +*/ + +// Constants table +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]; +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]; +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]; +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]; + +var hl = [ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]; +var hr = [ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]; + +var bytesToWords = function (bytes) { + var words = []; + for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { + words[b >>> 5] |= bytes[i] << (24 - b % 32); + } + return words; +}; + +var wordsToBytes = function (words) { + var bytes = []; + for (var b = 0; b < words.length * 32; b += 8) { + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); + } + return bytes; +}; + +var processBlock = function (H, M, offset) { + + // Swap endian + for (var i = 0; i < 16; i++) { + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + // Computation + var t; + for (var i = 0; i < 80; i += 1) { + t = (al + M[offset+zl[i]])|0; + if (i<16){ + t += f1(bl,cl,dl) + hl[0]; + } else if (i<32) { + t += f2(bl,cl,dl) + hl[1]; + } else if (i<48) { + t += f3(bl,cl,dl) + hl[2]; + } else if (i<64) { + t += f4(bl,cl,dl) + hl[3]; + } else {// if (i<80) { + t += f5(bl,cl,dl) + hl[4]; + } + t = t|0; + t = rotl(t,sl[i]); + t = (t+el)|0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset+zr[i]])|0; + if (i<16){ + t += f5(br,cr,dr) + hr[0]; + } else if (i<32) { + t += f4(br,cr,dr) + hr[1]; + } else if (i<48) { + t += f3(br,cr,dr) + hr[2]; + } else if (i<64) { + t += f2(br,cr,dr) + hr[3]; + } else {// if (i<80) { + t += f1(br,cr,dr) + hr[4]; + } + t = t|0; + t = rotl(t,sr[i]) ; + t = (t+er)|0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + // Intermediate hash value + t = (H[1] + cl + dr)|0; + H[1] = (H[2] + dl + er)|0; + H[2] = (H[3] + el + ar)|0; + H[3] = (H[4] + al + br)|0; + H[4] = (H[0] + bl + cr)|0; + H[0] = t; +}; + +function f1(x, y, z) { + return ((x) ^ (y) ^ (z)); +} + +function f2(x, y, z) { + return (((x)&(y)) | ((~x)&(z))); +} + +function f3(x, y, z) { + return (((x) | (~(y))) ^ (z)); +} + +function f4(x, y, z) { + return (((x) & (z)) | ((y)&(~(z)))); +} + +function f5(x, y, z) { + return ((x) ^ ((y) |(~(z)))); +} + +function rotl(x,n) { + return (x<>>(32-n)); +} + +function ripemd160(message) { + var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; + + if (typeof message == 'string') + message = new Buffer(message, 'utf8'); + + var m = bytesToWords(message); + + var nBitsLeft = message.length * 8; + var nBitsTotal = message.length * 8; + + // Add padding + m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ); + + for (var i=0 ; i>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + var digestbytes = wordsToBytes(H); + return new Buffer(digestbytes); +} + + + +}).call(this,require("buffer").Buffer) +},{"buffer":69}],168:[function(require,module,exports){ +(function (Buffer){ + + +//prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = new Buffer(blockSize) //new Uint32Array(blockSize/4) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 + this._s = 0 +} + +Hash.prototype.init = function () { + this._s = 0 + this._len = 0 +} + +Hash.prototype.update = function (data, enc) { + if ("string" === typeof data) { + enc = enc || "utf8" + data = new Buffer(data, enc) + } + + var l = this._len += data.length + var s = this._s = (this._s || 0) + var f = 0 + var buffer = this._block + + while (s < l) { + var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize)) + var ch = (t - f) + + for (var i = 0; i < ch; i++) { + buffer[(s % this._blockSize) + i] = data[i + f] + } + + s += ch + f += ch + + if ((s % this._blockSize) === 0) { + this._update(buffer) + } + } + this._s = s + + return this +} + +Hash.prototype.digest = function (enc) { + // Suppose the length of the message M, in bits, is l + var l = this._len * 8 + + // Append the bit 1 to the end of the message + this._block[this._len % this._blockSize] = 0x80 + + // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize + this._block.fill(0, this._len % this._blockSize + 1) + + if (l % (this._blockSize * 8) >= this._finalSize * 8) { + this._update(this._block) + this._block.fill(0) + } + + // to this append the block which is equal to the number l written in binary + // TODO: handle case where l is > Math.pow(2, 29) + this._block.writeInt32BE(l, this._blockSize - 4) + + var hash = this._update(this._block) || this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash + +}).call(this,require("buffer").Buffer) +},{"buffer":69}],169:[function(require,module,exports){ +var exports = module.exports = function (alg) { + var Alg = exports[alg.toLowerCase()] + if(!Alg) throw new Error(alg + ' is not supported (we accept pull requests)') + return new Alg() +} + + +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') + +},{"./sha1":170,"./sha224":171,"./sha256":172,"./sha384":173,"./sha512":174}],170:[function(require,module,exports){ +(function (Buffer){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = require('util').inherits + +var Hash = require('./hash') + +var A = 0|0 +var B = 4|0 +var C = 8|0 +var D = 12|0 +var E = 16|0 + +var W = new (typeof Int32Array === 'undefined' ? Array : Int32Array)(80) + +var POOL = [] + +function Sha1 () { + if(POOL.length) + return POOL.pop().init() + + if(!(this instanceof Sha1)) return new Sha1() + this._w = W + Hash.call(this, 16*4, 14*4) + + this._h = null + this.init() +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + Hash.prototype.init.call(this) + return this +} + +Sha1.prototype._POOL = POOL +Sha1.prototype._update = function (X) { + + var a, b, c, d, e, _a, _b, _c, _d, _e + + a = _a = this._a + b = _b = this._b + c = _c = this._c + d = _d = this._d + e = _e = this._e + + var w = this._w + + for(var j = 0; j < 80; j++) { + var W = w[j] = j < 16 ? X.readInt32BE(j*4) + : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1) + + var t = add( + add(rol(a, 5), sha1_ft(j, b, c, d)), + add(add(e, W), sha1_kt(j)) + ) + + e = d + d = c + c = rol(b, 30) + b = a + a = t + } + + this._a = add(a, _a) + this._b = add(b, _b) + this._c = add(c, _c) + this._d = add(d, _d) + this._e = add(e, _e) +} + +Sha1.prototype._hash = function () { + if(POOL.length < 100) POOL.push(this) + var H = new Buffer(20) + //console.log(this._a|0, this._b|0, this._c|0, this._d|0, this._e|0) + H.writeInt32BE(this._a|0, A) + H.writeInt32BE(this._b|0, B) + H.writeInt32BE(this._c|0, C) + H.writeInt32BE(this._d|0, D) + H.writeInt32BE(this._e|0, E) + return H +} + +/* + * Perform the appropriate triplet combination function for the current + * iteration + */ +function sha1_ft(t, b, c, d) { + if(t < 20) return (b & c) | ((~b) & d); + if(t < 40) return b ^ c ^ d; + if(t < 60) return (b & c) | (b & d) | (c & d); + return b ^ c ^ d; +} + +/* + * Determine the appropriate additive constant for the current iteration + */ +function sha1_kt(t) { + return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : + (t < 60) ? -1894007588 : -899497514; +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + * //dominictarr: this is 10 years old, so maybe this can be dropped?) + * + */ +function add(x, y) { + return (x + y ) | 0 +//lets see how this goes on testling. +// var lsw = (x & 0xFFFF) + (y & 0xFFFF); +// var msw = (x >> 16) + (y >> 16) + (lsw >> 16); +// return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function rol(num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = Sha1 + + +}).call(this,require("buffer").Buffer) +},{"./hash":168,"buffer":69,"util":205}],171:[function(require,module,exports){ +(function (Buffer){ + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('util').inherits +var SHA256 = require('./sha256') +var Hash = require('./hash') + +var W = new Array(64) + +function Sha224() { + this.init() + + this._w = W //new Array(64) + + Hash.call(this, 16*4, 14*4) +} + +inherits(Sha224, SHA256) + +Sha224.prototype.init = function () { + + this._a = 0xc1059ed8|0 + this._b = 0x367cd507|0 + this._c = 0x3070dd17|0 + this._d = 0xf70e5939|0 + this._e = 0xffc00b31|0 + this._f = 0x68581511|0 + this._g = 0x64f98fa7|0 + this._h = 0xbefa4fa4|0 + + this._len = this._s = 0 + + return this +} + + +Sha224.prototype._hash = function () { + var H = new Buffer(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 + +}).call(this,require("buffer").Buffer) +},{"./hash":168,"./sha256":172,"buffer":69,"util":205}],172:[function(require,module,exports){ +(function (Buffer){ + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('util').inherits + +var Hash = require('./hash') + +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 + ] + +var W = new Array(64) + +function Sha256() { + this.init() + + this._w = W //new Array(64) + + Hash.call(this, 16*4, 14*4) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + + this._a = 0x6a09e667|0 + this._b = 0xbb67ae85|0 + this._c = 0x3c6ef372|0 + this._d = 0xa54ff53a|0 + this._e = 0x510e527f|0 + this._f = 0x9b05688c|0 + this._g = 0x1f83d9ab|0 + this._h = 0x5be0cd19|0 + + this._len = this._s = 0 + + return this +} + +function S (X, n) { + return (X >>> n) | (X << (32 - n)); +} + +function R (X, n) { + return (X >>> n); +} + +function Ch (x, y, z) { + return ((x & y) ^ ((~x) & z)); +} + +function Maj (x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)); +} + +function Sigma0256 (x) { + return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); +} + +function Sigma1256 (x) { + return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); +} + +function Gamma0256 (x) { + return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); +} + +function Gamma1256 (x) { + return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); +} + +Sha256.prototype._update = function(M) { + + var W = this._w + var a, b, c, d, e, f, g, h + var T1, T2 + + a = this._a | 0 + b = this._b | 0 + c = this._c | 0 + d = this._d | 0 + e = this._e | 0 + f = this._f | 0 + g = this._g | 0 + h = this._h | 0 + + for (var j = 0; j < 64; j++) { + var w = W[j] = j < 16 + ? M.readInt32BE(j * 4) + : Gamma1256(W[j - 2]) + W[j - 7] + Gamma0256(W[j - 15]) + W[j - 16] + + T1 = h + Sigma1256(e) + Ch(e, f, g) + K[j] + w + + T2 = Sigma0256(a) + Maj(a, b, c); + h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 + +}; + +Sha256.prototype._hash = function () { + var H = new Buffer(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 + +}).call(this,require("buffer").Buffer) +},{"./hash":168,"buffer":69,"util":205}],173:[function(require,module,exports){ +(function (Buffer){ +var inherits = require('util').inherits +var SHA512 = require('./sha512'); +var Hash = require('./hash') + +var W = new Array(160) + +function Sha384() { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + + this._a = 0xcbbb9d5d|0 + this._b = 0x629a292a|0 + this._c = 0x9159015a|0 + this._d = 0x152fecd8|0 + this._e = 0x67332667|0 + this._f = 0x8eb44a87|0 + this._g = 0xdb0c2e0d|0 + this._h = 0x47b5481d|0 + + this._al = 0xc1059ed8|0 + this._bl = 0x367cd507|0 + this._cl = 0x3070dd17|0 + this._dl = 0xf70e5939|0 + this._el = 0xffc00b31|0 + this._fl = 0x68581511|0 + this._gl = 0x64f98fa7|0 + this._hl = 0xbefa4fa4|0 + + this._len = this._s = 0 + + return this +} + + + +Sha384.prototype._hash = function () { + var H = new Buffer(48) + + function writeInt64BE(h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._a, this._al, 0) + writeInt64BE(this._b, this._bl, 8) + writeInt64BE(this._c, this._cl, 16) + writeInt64BE(this._d, this._dl, 24) + writeInt64BE(this._e, this._el, 32) + writeInt64BE(this._f, this._fl, 40) + + return H +} + +module.exports = Sha384 + +}).call(this,require("buffer").Buffer) +},{"./hash":168,"./sha512":174,"buffer":69,"util":205}],174:[function(require,module,exports){ +(function (Buffer){ +var inherits = require('util').inherits + +var Hash = require('./hash') + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512() { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + + this._a = 0x6a09e667|0 + this._b = 0xbb67ae85|0 + this._c = 0x3c6ef372|0 + this._d = 0xa54ff53a|0 + this._e = 0x510e527f|0 + this._f = 0x9b05688c|0 + this._g = 0x1f83d9ab|0 + this._h = 0x5be0cd19|0 + + this._al = 0xf3bcc908|0 + this._bl = 0x84caa73b|0 + this._cl = 0xfe94f82b|0 + this._dl = 0x5f1d36f1|0 + this._el = 0xade682d1|0 + this._fl = 0x2b3e6c1f|0 + this._gl = 0xfb41bd6b|0 + this._hl = 0x137e2179|0 + + this._len = this._s = 0 + + return this +} + +function S (X, Xl, n) { + return (X >>> n) | (Xl << (32 - n)) +} + +function Ch (x, y, z) { + return ((x & y) ^ ((~x) & z)); +} + +function Maj (x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)); +} + +Sha512.prototype._update = function(M) { + + var W = this._w + var a, b, c, d, e, f, g, h + var al, bl, cl, dl, el, fl, gl, hl + + a = this._a | 0 + b = this._b | 0 + c = this._c | 0 + d = this._d | 0 + e = this._e | 0 + f = this._f | 0 + g = this._g | 0 + h = this._h | 0 + + al = this._al | 0 + bl = this._bl | 0 + cl = this._cl | 0 + dl = this._dl | 0 + el = this._el | 0 + fl = this._fl | 0 + gl = this._gl | 0 + hl = this._hl | 0 + + for (var i = 0; i < 80; i++) { + var j = i * 2 + + var Wi, Wil + + if (i < 16) { + Wi = W[j] = M.readInt32BE(j * 4) + Wil = W[j + 1] = M.readInt32BE(j * 4 + 4) + + } else { + var x = W[j - 15*2] + var xl = W[j - 15*2 + 1] + var gamma0 = S(x, xl, 1) ^ S(x, xl, 8) ^ (x >>> 7) + var gamma0l = S(xl, x, 1) ^ S(xl, x, 8) ^ S(xl, x, 7) + + x = W[j - 2*2] + xl = W[j - 2*2 + 1] + var gamma1 = S(x, xl, 19) ^ S(xl, x, 29) ^ (x >>> 6) + var gamma1l = S(xl, x, 19) ^ S(x, xl, 29) ^ S(xl, x, 6) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7 = W[j - 7*2] + var Wi7l = W[j - 7*2 + 1] + + var Wi16 = W[j - 16*2] + var Wi16l = W[j - 16*2 + 1] + + Wil = gamma0l + Wi7l + Wi = gamma0 + Wi7 + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0) + Wil = Wil + gamma1l + Wi = Wi + gamma1 + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0) + Wil = Wil + Wi16l + Wi = Wi + Wi16 + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0) + + W[j] = Wi + W[j + 1] = Wil + } + + var maj = Maj(a, b, c) + var majl = Maj(al, bl, cl) + + var sigma0h = S(a, al, 28) ^ S(al, a, 2) ^ S(al, a, 7) + var sigma0l = S(al, a, 28) ^ S(a, al, 2) ^ S(a, al, 7) + var sigma1h = S(e, el, 14) ^ S(e, el, 18) ^ S(el, e, 9) + var sigma1l = S(el, e, 14) ^ S(el, e, 18) ^ S(e, el, 9) + + // t1 = h + sigma1 + ch + K[i] + W[i] + var Ki = K[j] + var Kil = K[j + 1] + + var ch = Ch(e, f, g) + var chl = Ch(el, fl, gl) + + var t1l = hl + sigma1l + var t1 = h + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0) + t1l = t1l + chl + t1 = t1 + ch + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0) + t1l = t1l + Kil + t1 = t1 + Ki + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0) + t1l = t1l + Wil + t1 = t1 + Wi + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0) + + // t2 = sigma0 + maj + var t2l = sigma0l + majl + var t2 = sigma0h + maj + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0) + + h = g + hl = gl + g = f + gl = fl + f = e + fl = el + el = (dl + t1l) | 0 + e = (d + t1 + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0 + d = c + dl = cl + c = b + cl = bl + b = a + bl = al + al = (t1l + t2l) | 0 + a = (t1 + t2 + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._a = (this._a + a + ((this._al >>> 0) < (al >>> 0) ? 1 : 0)) | 0 + this._b = (this._b + b + ((this._bl >>> 0) < (bl >>> 0) ? 1 : 0)) | 0 + this._c = (this._c + c + ((this._cl >>> 0) < (cl >>> 0) ? 1 : 0)) | 0 + this._d = (this._d + d + ((this._dl >>> 0) < (dl >>> 0) ? 1 : 0)) | 0 + this._e = (this._e + e + ((this._el >>> 0) < (el >>> 0) ? 1 : 0)) | 0 + this._f = (this._f + f + ((this._fl >>> 0) < (fl >>> 0) ? 1 : 0)) | 0 + this._g = (this._g + g + ((this._gl >>> 0) < (gl >>> 0) ? 1 : 0)) | 0 + this._h = (this._h + h + ((this._hl >>> 0) < (hl >>> 0) ? 1 : 0)) | 0 +} + +Sha512.prototype._hash = function () { + var H = new Buffer(64) + + function writeInt64BE(h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._a, this._al, 0) + writeInt64BE(this._b, this._bl, 8) + writeInt64BE(this._c, this._cl, 16) + writeInt64BE(this._d, this._dl, 24) + writeInt64BE(this._e, this._el, 32) + writeInt64BE(this._f, this._fl, 40) + writeInt64BE(this._g, this._gl, 48) + writeInt64BE(this._h, this._hl, 56) + + return H +} + +module.exports = Sha512 + +}).call(this,require("buffer").Buffer) +},{"./hash":168,"buffer":69,"util":205}],175:[function(require,module,exports){ +'use strict'; +var pbkdf2Export = require('pbkdf2-compat/pbkdf2') + +module.exports = function (crypto, exports) { + exports = exports || {} + + var exported = pbkdf2Export(crypto) + + exports.pbkdf2 = exported.pbkdf2 + exports.pbkdf2Sync = exported.pbkdf2Sync + + return exports +} + +},{"pbkdf2-compat/pbkdf2":166}],176:[function(require,module,exports){ +(function (global,Buffer){ +'use strict'; +(function() { + var g = ('undefined' === typeof window ? global : window) || {} + var _crypto = ( + g.crypto || g.msCrypto || require('crypto') + ) + module.exports = function(size) { + // Modern Browsers + if(_crypto.getRandomValues) { + var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array + /* This will not work in older browsers. + * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + */ + + _crypto.getRandomValues(bytes); + return bytes; + } + else if (_crypto.randomBytes) { + return _crypto.randomBytes(size) + } + else + throw new Error( + 'secure random number generation not supported by this browser\n'+ + 'use chrome, FireFox or Internet Explorer 11' + ) + } +}()) + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"buffer":69,"crypto":68}],177:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + handler.apply(this, args); + } + } else if (isObject(handler)) { + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + var m; + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + var ret; + if (!emitter._events || !emitter._events[type]) + ret = 0; + else if (isFunction(emitter._events[type])) + ret = 1; + else + ret = emitter._events[type].length; + return ret; +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],178:[function(require,module,exports){ +var http = module.exports; +var EventEmitter = require('events').EventEmitter; +var Request = require('./lib/request'); +var url = require('url') + +http.request = function (params, cb) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params) params = {}; + if (!params.host && !params.port) { + params.port = parseInt(window.location.port, 10); + } + if (!params.host && params.hostname) { + params.host = params.hostname; + } + + if (!params.protocol) { + if (params.scheme) { + params.protocol = params.scheme + ':'; + } else { + params.protocol = window.location.protocol; + } + } + + if (!params.host) { + params.host = window.location.hostname || window.location.host; + } + if (/:/.test(params.host)) { + if (!params.port) { + params.port = params.host.split(':')[1]; + } + params.host = params.host.split(':')[0]; + } + if (!params.port) params.port = params.protocol == 'https:' ? 443 : 80; + + var req = new Request(new xhrHttp, params); + if (cb) req.on('response', cb); + return req; +}; + +http.get = function (params, cb) { + params.method = 'GET'; + var req = http.request(params, cb); + req.end(); + return req; +}; + +http.Agent = function () {}; +http.Agent.defaultMaxSockets = 4; + +var xhrHttp = (function () { + if (typeof window === 'undefined') { + throw new Error('no window object present'); + } + else if (window.XMLHttpRequest) { + return window.XMLHttpRequest; + } + else if (window.ActiveXObject) { + var axs = [ + 'Msxml2.XMLHTTP.6.0', + 'Msxml2.XMLHTTP.3.0', + 'Microsoft.XMLHTTP' + ]; + for (var i = 0; i < axs.length; i++) { + try { + var ax = new(window.ActiveXObject)(axs[i]); + return function () { + if (ax) { + var ax_ = ax; + ax = null; + return ax_; + } + else { + return new(window.ActiveXObject)(axs[i]); + } + }; + } + catch (e) {} + } + throw new Error('ajax not supported in this browser') + } + else { + throw new Error('ajax not supported in this browser'); + } +})(); + +http.STATUS_CODES = { + 100 : 'Continue', + 101 : 'Switching Protocols', + 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918 + 200 : 'OK', + 201 : 'Created', + 202 : 'Accepted', + 203 : 'Non-Authoritative Information', + 204 : 'No Content', + 205 : 'Reset Content', + 206 : 'Partial Content', + 207 : 'Multi-Status', // RFC 4918 + 300 : 'Multiple Choices', + 301 : 'Moved Permanently', + 302 : 'Moved Temporarily', + 303 : 'See Other', + 304 : 'Not Modified', + 305 : 'Use Proxy', + 307 : 'Temporary Redirect', + 400 : 'Bad Request', + 401 : 'Unauthorized', + 402 : 'Payment Required', + 403 : 'Forbidden', + 404 : 'Not Found', + 405 : 'Method Not Allowed', + 406 : 'Not Acceptable', + 407 : 'Proxy Authentication Required', + 408 : 'Request Time-out', + 409 : 'Conflict', + 410 : 'Gone', + 411 : 'Length Required', + 412 : 'Precondition Failed', + 413 : 'Request Entity Too Large', + 414 : 'Request-URI Too Large', + 415 : 'Unsupported Media Type', + 416 : 'Requested Range Not Satisfiable', + 417 : 'Expectation Failed', + 418 : 'I\'m a teapot', // RFC 2324 + 422 : 'Unprocessable Entity', // RFC 4918 + 423 : 'Locked', // RFC 4918 + 424 : 'Failed Dependency', // RFC 4918 + 425 : 'Unordered Collection', // RFC 4918 + 426 : 'Upgrade Required', // RFC 2817 + 428 : 'Precondition Required', // RFC 6585 + 429 : 'Too Many Requests', // RFC 6585 + 431 : 'Request Header Fields Too Large',// RFC 6585 + 500 : 'Internal Server Error', + 501 : 'Not Implemented', + 502 : 'Bad Gateway', + 503 : 'Service Unavailable', + 504 : 'Gateway Time-out', + 505 : 'HTTP Version Not Supported', + 506 : 'Variant Also Negotiates', // RFC 2295 + 507 : 'Insufficient Storage', // RFC 4918 + 509 : 'Bandwidth Limit Exceeded', + 510 : 'Not Extended', // RFC 2774 + 511 : 'Network Authentication Required' // RFC 6585 +}; +},{"./lib/request":179,"events":177,"url":203}],179:[function(require,module,exports){ +var Stream = require('stream'); +var Response = require('./response'); +var Base64 = require('Base64'); +var inherits = require('inherits'); + +var Request = module.exports = function (xhr, params) { + var self = this; + self.writable = true; + self.xhr = xhr; + self.body = []; + + self.uri = (params.protocol || 'http:') + '//' + + params.host + + (params.port ? ':' + params.port : '') + + (params.path || '/') + ; + + if (typeof params.withCredentials === 'undefined') { + params.withCredentials = true; + } + + try { xhr.withCredentials = params.withCredentials } + catch (e) {} + + if (params.responseType) try { xhr.responseType = params.responseType } + catch (e) {} + + xhr.open( + params.method || 'GET', + self.uri, + true + ); + + xhr.onerror = function(event) { + self.emit('error', new Error('Network error')); + }; + + self._headers = {}; + + if (params.headers) { + var keys = objectKeys(params.headers); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (!self.isSafeRequestHeader(key)) continue; + var value = params.headers[key]; + self.setHeader(key, value); + } + } + + if (params.auth) { + //basic auth + this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth)); + } + + var res = new Response; + res.on('close', function () { + self.emit('close'); + }); + + res.on('ready', function () { + self.emit('response', res); + }); + + res.on('error', function (err) { + self.emit('error', err); + }); + + xhr.onreadystatechange = function () { + // Fix for IE9 bug + // SCRIPT575: Could not complete the operation due to error c00c023f + // It happens when a request is aborted, calling the success callback anyway with readyState === 4 + if (xhr.__aborted) return; + res.handle(xhr); + }; +}; + +inherits(Request, Stream); + +Request.prototype.setHeader = function (key, value) { + this._headers[key.toLowerCase()] = value +}; + +Request.prototype.getHeader = function (key) { + return this._headers[key.toLowerCase()] +}; + +Request.prototype.removeHeader = function (key) { + delete this._headers[key.toLowerCase()] +}; + +Request.prototype.write = function (s) { + this.body.push(s); +}; + +Request.prototype.destroy = function (s) { + this.xhr.__aborted = true; + this.xhr.abort(); + this.emit('close'); +}; + +Request.prototype.end = function (s) { + if (s !== undefined) this.body.push(s); + + var keys = objectKeys(this._headers); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = this._headers[key]; + if (isArray(value)) { + for (var j = 0; j < value.length; j++) { + this.xhr.setRequestHeader(key, value[j]); + } + } + else this.xhr.setRequestHeader(key, value) + } + + if (this.body.length === 0) { + this.xhr.send(''); + } + else if (typeof this.body[0] === 'string') { + this.xhr.send(this.body.join('')); + } + else if (isArray(this.body[0])) { + var body = []; + for (var i = 0; i < this.body.length; i++) { + body.push.apply(body, this.body[i]); + } + this.xhr.send(body); + } + else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) { + var len = 0; + for (var i = 0; i < this.body.length; i++) { + len += this.body[i].length; + } + var body = new(this.body[0].constructor)(len); + var k = 0; + + for (var i = 0; i < this.body.length; i++) { + var b = this.body[i]; + for (var j = 0; j < b.length; j++) { + body[k++] = b[j]; + } + } + this.xhr.send(body); + } + else if (isXHR2Compatible(this.body[0])) { + this.xhr.send(this.body[0]); + } + else { + var body = ''; + for (var i = 0; i < this.body.length; i++) { + body += this.body[i].toString(); + } + this.xhr.send(body); + } +}; + +// Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html +Request.unsafeHeaders = [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "cookie2", + "content-transfer-encoding", + "date", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "user-agent", + "via" +]; + +Request.prototype.isSafeRequestHeader = function (headerName) { + if (!headerName) return false; + return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1; +}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +var indexOf = function (xs, x) { + if (xs.indexOf) return xs.indexOf(x); + for (var i = 0; i < xs.length; i++) { + if (xs[i] === x) return i; + } + return -1; +}; + +var isXHR2Compatible = function (obj) { + if (typeof Blob !== 'undefined' && obj instanceof Blob) return true; + if (typeof ArrayBuffer !== 'undefined' && obj instanceof ArrayBuffer) return true; + if (typeof FormData !== 'undefined' && obj instanceof FormData) return true; +}; + +},{"./response":180,"Base64":181,"inherits":231,"stream":201}],180:[function(require,module,exports){ +var Stream = require('stream'); +var util = require('util'); + +var Response = module.exports = function (res) { + this.offset = 0; + this.readable = true; +}; + +util.inherits(Response, Stream); + +var capable = { + streaming : true, + status2 : true +}; + +function parseHeaders (res) { + var lines = res.getAllResponseHeaders().split(/\r?\n/); + var headers = {}; + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (line === '') continue; + + var m = line.match(/^([^:]+):\s*(.*)/); + if (m) { + var key = m[1].toLowerCase(), value = m[2]; + + if (headers[key] !== undefined) { + + if (isArray(headers[key])) { + headers[key].push(value); + } + else { + headers[key] = [ headers[key], value ]; + } + } + else { + headers[key] = value; + } + } + else { + headers[line] = true; + } + } + return headers; +} + +Response.prototype.getResponse = function (xhr) { + var respType = String(xhr.responseType).toLowerCase(); + if (respType === 'blob') return xhr.responseBlob || xhr.response; + if (respType === 'arraybuffer') return xhr.response; + return xhr.responseText; +} + +Response.prototype.getHeader = function (key) { + return this.headers[key.toLowerCase()]; +}; + +Response.prototype.handle = function (res) { + if (res.readyState === 2 && capable.status2) { + try { + this.statusCode = res.status; + this.headers = parseHeaders(res); + } + catch (err) { + capable.status2 = false; + } + + if (capable.status2) { + this.emit('ready'); + } + } + else if (capable.streaming && res.readyState === 3) { + try { + if (!this.statusCode) { + this.statusCode = res.status; + this.headers = parseHeaders(res); + this.emit('ready'); + } + } + catch (err) {} + + try { + this._emitData(res); + } + catch (err) { + capable.streaming = false; + } + } + else if (res.readyState === 4) { + if (!this.statusCode) { + this.statusCode = res.status; + this.emit('ready'); + } + this._emitData(res); + + if (res.error) { + this.emit('error', this.getResponse(res)); + } + else this.emit('end'); + + this.emit('close'); + } +}; + +Response.prototype._emitData = function (res) { + var respBody = this.getResponse(res); + if (respBody.toString().match(/ArrayBuffer/)) { + this.emit('data', new Uint8Array(respBody, this.offset)); + this.offset = respBody.byteLength; + return; + } + if (respBody.length > this.offset) { + this.emit('data', respBody.slice(this.offset)); + this.offset = respBody.length; + } +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{"stream":201,"util":205}],181:[function(require,module,exports){ +;(function () { + + var object = typeof exports != 'undefined' ? exports : this; // #8: web workers + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + + function InvalidCharacterError(message) { + this.message = message; + } + InvalidCharacterError.prototype = new Error; + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + // encoder + // [https://gist.github.com/999166] by [https://github.com/nignag] + object.btoa || ( + object.btoa = function (input) { + for ( + // initialize result and counter + var block, charCode, idx = 0, map = chars, output = ''; + // if the next input index does not exist: + // change the mapping table to "=" + // check if d has no fractional digits + input.charAt(idx | 0) || (map = '=', idx % 1); + // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 + output += map.charAt(63 & block >> 8 - idx % 1 * 8) + ) { + charCode = input.charCodeAt(idx += 3/4); + if (charCode > 0xFF) { + throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); + } + block = block << 8 | charCode; + } + return output; + }); + + // decoder + // [https://gist.github.com/1020396] by [https://github.com/atk] + object.atob || ( + object.atob = function (input) { + input = input.replace(/=+$/, ''); + if (input.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for ( + // initialize result and counters + var bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = input.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output; + }); + +}()); + +},{}],182:[function(require,module,exports){ +var http = require('http'); + +var https = module.exports; + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key]; +}; + +https.request = function (params, cb) { + if (!params) params = {}; + params.scheme = 'https'; + return http.request.call(this, params, cb); +} + +},{"http":178}],183:[function(require,module,exports){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +},{}],184:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) +},{"_process":185}],185:[function(require,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; + +process.nextTick = (function () { + var canSetImmediate = typeof window !== 'undefined' + && window.setImmediate; + var canMutationObserver = typeof window !== 'undefined' + && window.MutationObserver; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; + + if (canSetImmediate) { + return function (f) { return window.setImmediate(f) }; + } + + var queue = []; + + if (canMutationObserver) { + var hiddenDiv = document.createElement("div"); + var observer = new MutationObserver(function () { + var queueList = queue.slice(); + queue.length = 0; + queueList.forEach(function (fn) { + fn(); + }); + }); + + observer.observe(hiddenDiv, { attributes: true }); + + return function nextTick(fn) { + if (!queue.length) { + hiddenDiv.setAttribute('yes', 'no'); + } + queue.push(fn); + }; + } + + if (canPost) { + window.addEventListener('message', function (ev) { + var source = ev.source; + if ((source === window || source === null) && ev.data === 'process-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); + + return function nextTick(fn) { + queue.push(fn); + window.postMessage('process-tick', '*'); + }; + } + + return function nextTick(fn) { + setTimeout(fn, 0); + }; +})(); + +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +// TODO(shtylman) +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; + +},{}],186:[function(require,module,exports){ +(function (global){ +/*! http://mths.be/punycode v1.2.4 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports; + var freeModule = typeof module == 'object' && module && + module.exports == freeExports && module; + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + while (length--) { + array[length] = fn(array[length]); + } + return array; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings. + * @private + * @param {String} domain The domain name. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + return map(string.split(regexSeparators), fn).join('.'); + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols to a Punycode string of ASCII-only + * symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name to Unicode. Only the + * Punycoded parts of the domain name will be converted, i.e. it doesn't + * matter if you call it on a string that has already been converted to + * Unicode. + * @memberOf punycode + * @param {String} domain The Punycode domain name to convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(domain) { + return mapDomain(domain, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name to Punycode. Only the + * non-ASCII parts of the domain name will be converted, i.e. it doesn't + * matter if you call it with a domain that's already in ASCII. + * @memberOf punycode + * @param {String} domain The domain name to convert, as a Unicode string. + * @returns {String} The Punycode representation of the given domain name. + */ + function toASCII(domain) { + return mapDomain(domain, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.2.4', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],187:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],188:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],189:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":187,"./encode":188}],190:[function(require,module,exports){ +module.exports = require("./lib/_stream_duplex.js") + +},{"./lib/_stream_duplex.js":191}],191:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +module.exports = Duplex; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} +/**/ + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; +}); + +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +}).call(this,require('_process')) +},{"./_stream_readable":193,"./_stream_writable":195,"_process":185,"core-util-is":196,"inherits":231}],192:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; + +},{"./_stream_transform":194,"core-util-is":196,"inherits":231}],193:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events').EventEmitter; + +/**/ +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +var Stream = require('stream'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +function ReadableState(options, stream) { + options = options || {}; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + if (!(this instanceof Readable)) + return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } + + if (state.needReadable) + emitReadable(stream); + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + + + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; +}; + +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; + + if (state.objectMode) + return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } + + if (n <= 0) + return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; + + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } + + if (state.length === 0) + endReadable(this); + + return ret; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; + + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + + +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; + + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); +} + +function emitReadable_(stream) { + stream.emit('readable'); +} + + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } + + function onend() { + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; + + + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); + + state.flowing = true; + process.nextTick(function() { + flow(src); + }); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var dest = this; + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; +} + +function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; + + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } + } + + while (state.pipesCount && null !== (chunk = src.read())) { + + if (state.pipesCount === 1) + write(state.pipes, 0, null); + else + forEach(state.pipes, write); + + src.emit('data', chunk); + + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } + + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; + + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } + + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; +} + +function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } +} + + +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; + + if (!dest) + dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); +}; + +Readable.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); +}; + +function emitDataEvents(stream, startPaused) { + var state = stream._readableState; + + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } + + var paused = startPaused || false; + var readable = false; + + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream.prototype.pipe; + stream.on = stream.addListener = Stream.prototype.on; + + stream.on('readable', function() { + readable = true; + + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); + + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); + + stream.pause = function() { + paused = true; + this.emit('pause'); + }; + + stream.resume = function() { + paused = false; + if (readable) + process.nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; + + // now make it start, just in case it hadn't already. + stream.emit('readable'); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + + + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted && state.calledRead) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +}).call(this,require('_process')) +},{"_process":185,"buffer":69,"core-util-is":196,"events":177,"inherits":231,"isarray":183,"stream":201,"string_decoder/":202}],194:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + + +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + + +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + var ts = this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var rs = stream._readableState; + var ts = stream._transformState; + + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) + throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} + +},{"./_stream_duplex":191,"core-util-is":196,"inherits":231}],195:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. + +module.exports = Writable; + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Stream = require('stream'); + +util.inherits(Writable, Stream); + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; +} + +function WritableState(options, stream) { + options = options || {}; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; +} + +function Writable(options) { + var Duplex = require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + + +function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; +} + +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (typeof cb !== 'function') + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); + + return ret; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); + + return ret; +} + +function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + cb(er); + }); + else + cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); + + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } + + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; +} + +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; + + +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); +} + +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; +} + +}).call(this,require('_process')) +},{"./_stream_duplex":191,"_process":185,"buffer":69,"core-util-is":196,"inherits":231,"stream":201}],196:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return Buffer.isBuffer(arg); +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} +}).call(this,require("buffer").Buffer) +},{"buffer":69}],197:[function(require,module,exports){ +module.exports = require("./lib/_stream_passthrough.js") + +},{"./lib/_stream_passthrough.js":192}],198:[function(require,module,exports){ +var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +},{"./lib/_stream_duplex.js":191,"./lib/_stream_passthrough.js":192,"./lib/_stream_readable.js":193,"./lib/_stream_transform.js":194,"./lib/_stream_writable.js":195,"stream":201}],199:[function(require,module,exports){ +module.exports = require("./lib/_stream_transform.js") + +},{"./lib/_stream_transform.js":194}],200:[function(require,module,exports){ +module.exports = require("./lib/_stream_writable.js") + +},{"./lib/_stream_writable.js":195}],201:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":177,"inherits":231,"readable-stream/duplex.js":190,"readable-stream/passthrough.js":197,"readable-stream/readable.js":198,"readable-stream/transform.js":199,"readable-stream/writable.js":200}],202:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +},{"buffer":69}],203:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var punycode = require('punycode'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a puny coded representation of "domain". + // It only converts the part of the domain name that + // has non ASCII characters. I.e. it dosent matter if + // you call it with a domain that already is in ASCII. + var domainArray = this.hostname.split('.'); + var newOut = []; + for (var i = 0; i < domainArray.length; ++i) { + var s = domainArray[i]; + newOut.push(s.match(/[^A-Za-z0-9_-]/) ? + 'xn--' + punycode.encode(s) : s); + } + this.hostname = newOut.join('.'); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + Object.keys(this).forEach(function(k) { + result[k] = this[k]; + }, this); + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + Object.keys(relative).forEach(function(k) { + if (k !== 'protocol') + result[k] = relative[k]; + }); + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + Object.keys(relative).forEach(function(k) { + result[k] = relative[k]; + }); + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especialy happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host) && (last === '.' || last === '..') || + last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last == '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especialy happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +function isString(arg) { + return typeof arg === "string"; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isNull(arg) { + return arg === null; +} +function isNullOrUndefined(arg) { + return arg == null; +} + +},{"punycode":186,"querystring":189}],204:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],205:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":204,"_process":185,"inherits":231}],206:[function(require,module,exports){ +var indexOf = require('indexof'); + +var Object_keys = function (obj) { + if (Object.keys) return Object.keys(obj) + else { + var res = []; + for (var key in obj) res.push(key) + return res; + } +}; + +var forEach = function (xs, fn) { + if (xs.forEach) return xs.forEach(fn) + else for (var i = 0; i < xs.length; i++) { + fn(xs[i], i, xs); + } +}; + +var defineProp = (function() { + try { + Object.defineProperty({}, '_', {}); + return function(obj, name, value) { + Object.defineProperty(obj, name, { + writable: true, + enumerable: false, + configurable: true, + value: value + }) + }; + } catch(e) { + return function(obj, name, value) { + obj[name] = value; + }; + } +}()); + +var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', +'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', +'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', +'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', +'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; + +function Context() {} +Context.prototype = {}; + +var Script = exports.Script = function NodeScript (code) { + if (!(this instanceof Script)) return new Script(code); + this.code = code; +}; + +Script.prototype.runInContext = function (context) { + if (!(context instanceof Context)) { + throw new TypeError("needs a 'context' argument."); + } + + var iframe = document.createElement('iframe'); + if (!iframe.style) iframe.style = {}; + iframe.style.display = 'none'; + + document.body.appendChild(iframe); + + var win = iframe.contentWindow; + var wEval = win.eval, wExecScript = win.execScript; + + if (!wEval && wExecScript) { + // win.eval() magically appears when this is called in IE: + wExecScript.call(win, 'null'); + wEval = win.eval; + } + + forEach(Object_keys(context), function (key) { + win[key] = context[key]; + }); + forEach(globals, function (key) { + if (context[key]) { + win[key] = context[key]; + } + }); + + var winKeys = Object_keys(win); + + var res = wEval.call(win, this.code); + + forEach(Object_keys(win), function (key) { + // Avoid copying circular objects like `top` and `window` by only + // updating existing context properties or new properties in the `win` + // that was only introduced after the eval. + if (key in context || indexOf(winKeys, key) === -1) { + context[key] = win[key]; + } + }); + + forEach(globals, function (key) { + if (!(key in context)) { + defineProp(context, key, win[key]); + } + }); + + document.body.removeChild(iframe); + + return res; +}; + +Script.prototype.runInThisContext = function () { + return eval(this.code); // maybe... +}; + +Script.prototype.runInNewContext = function (context) { + var ctx = Script.createContext(context); + var res = this.runInContext(ctx); + + forEach(Object_keys(ctx), function (key) { + context[key] = ctx[key]; + }); + + return res; +}; + +forEach(Object_keys(Script.prototype), function (name) { + exports[name] = Script[name] = function (code) { + var s = Script(code); + return s[name].apply(s, [].slice.call(arguments, 1)); + }; +}); + +exports.createScript = function (code) { + return exports.Script(code); +}; + +exports.createContext = Script.createContext = function (context) { + var copy = new Context(); + if(typeof context === 'object') { + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; + }); + } + return copy; +}; + +},{"indexof":207}],207:[function(require,module,exports){ + +var indexOf = [].indexOf; + +module.exports = function(arr, obj){ + if (indexOf) return arr.indexOf(obj); + for (var i = 0; i < arr.length; ++i) { + if (arr[i] === obj) return i; + } + return -1; +}; +},{}],208:[function(require,module,exports){ +// Base58 encoding/decoding +// Originally written by Mike Hearn for BitcoinJ +// Copyright (c) 2011 Google Inc +// Ported to JavaScript by Stefan Thomas +// Merged Buffer refactorings from base58-native by Stephen Pair +// Copyright (c) 2013 BitPay Inc + +var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' +var ALPHABET_MAP = {} +for(var i = 0; i < ALPHABET.length; i++) { + ALPHABET_MAP[ALPHABET.charAt(i)] = i +} +var BASE = 58 + +function encode(buffer) { + if (buffer.length === 0) return '' + + var i, j, digits = [0] + for (i = 0; i < buffer.length; i++) { + for (j = 0; j < digits.length; j++) digits[j] <<= 8 + + digits[0] += buffer[i] + + var carry = 0 + for (j = 0; j < digits.length; ++j) { + digits[j] += carry + + carry = (digits[j] / BASE) | 0 + digits[j] %= BASE + } + + while (carry) { + digits.push(carry % BASE) + + carry = (carry / BASE) | 0 + } + } + + // deal with leading zeros + for (i = 0; buffer[i] === 0 && i < buffer.length - 1; i++) digits.push(0) + + return digits.reverse().map(function(digit) { return ALPHABET[digit] }).join('') +} + +function decode(string) { + if (string.length === 0) return [] + + var i, j, bytes = [0] + for (i = 0; i < string.length; i++) { + var c = string[i] + if (!(c in ALPHABET_MAP)) throw new Error('Non-base58 character') + + for (j = 0; j < bytes.length; j++) bytes[j] *= BASE + bytes[0] += ALPHABET_MAP[c] + + var carry = 0 + for (j = 0; j < bytes.length; ++j) { + bytes[j] += carry + + carry = bytes[j] >> 8 + bytes[j] &= 0xff + } + + while (carry) { + bytes.push(carry & 0xff) + + carry >>= 8 + } + } + + // deal with leading zeros + for (i = 0; string[i] === '1' && i < string.length - 1; i++) bytes.push(0) + + return bytes.reverse() +} + +module.exports = { + encode: encode, + decode: decode +} + +},{}],209:[function(require,module,exports){ +(function (Buffer){ +function BufferPut () { + this.words = []; + this.len = 0; +}; +module.exports = BufferPut; + +BufferPut.prototype.put = function(buf) { + this.words.push({buffer: buf}); + this.len += buf.length; + return this; +}; + +BufferPut.prototype.word8 = function(x) { + this.words.push({bytes: 1, value: x}); + this.len += 1; + return this; +}; + +BufferPut.prototype.floatle = function(x) { + this.words.push({bytes: 'float', endian: 'little', value: x}); + this.len += 4; + return this; +}; + +BufferPut.prototype.varint = function(i) { + if(i < 0xFD) { + this.word8(i); + } else if(i <= 1<<16) { + this.word8(0xFD); + this.word16le(i); + } else if(i <= 1<<32) { + this.word8(0xFE); + this.word32le(i); + } else { + this.word8(0xFF); + this.word64le(i); + } +}; + +[8, 16, 24, 32, 64].forEach(function(bits) { + BufferPut.prototype['word'+bits+'be'] = function(x) { + this.words.push({endian: 'big', bytes: bits / 8, value: x}); + this.len += bits / 8; + return this; + }; + + BufferPut.prototype['word'+bits+'le'] = function(x) { + this.words.push({endian: 'little', bytes: bits / 8, value: x}); + this.len += bits / 8; + return this; + }; +}); + +BufferPut.prototype.pad = function(bytes) { + this.words.push({endian: 'big', bytes: bytes, value: 0}); + this.len += bytes; + return this; +}; + +BufferPut.prototype.length = function() { + return this.len; +}; + +BufferPut.prototype.buffer = function () { + var buf = new Buffer(this.len); + var offset = 0; + this.words.forEach(function(word) { + if(word.buffer) { + word.buffer.copy(buf, offset, 0); + offset += word.buffer.length; + } else if(word.bytes == 'float') { + // s * f * 2^e + var v = Math.abs(word.value); + var s = (word.value >= 0) * 1; + var e = Math.ceil(Math.log(v) / Math.LN2); + var f = v / (1 << e); + + // s:1, e:7, f:23 + // [seeeeeee][efffffff][ffffffff][ffffffff] + buf[offset++] = (s << 7) & ~~(e / 2); + buf[offset++] = ((e & 1) << 7) & ~~(f / (1 << 16)); + buf[offset++] = 0; + buf[offset++] = 0; + offset += 4; + } else { + var big = word.endian === 'big'; + var ix = big ? [ (word.bytes - 1) * 8, -8 ] : [ 0, 8 ]; + for(var i=ix[0]; big ? i >= 0 : i < word.bytes * 8; i += ix[1]) { + if(i >= 32) { + buf[offset++] = Math.floor(word.value / Math.pow(2, i)) & 0xff; + } else { + buf[offset++] = (word.value >> i) & 0xff; + } + } + } + }); + return buf; +}; + +BufferPut.prototype.write = function(stream) { + stream.write(this.buffer()); +}; + +}).call(this,require("buffer").Buffer) +},{"buffer":69}],210:[function(require,module,exports){ +(function (Buffer){ +module.exports = Buffers; + +function Buffers (bufs) { + if (!(this instanceof Buffers)) return new Buffers(bufs); + this.buffers = bufs || []; + this.length = this.buffers.reduce(function (size, buf) { + return size + buf.length + }, 0); +} + +Buffers.prototype.push = function () { + for (var i = 0; i < arguments.length; i++) { + if (!Buffer.isBuffer(arguments[i])) { + throw new TypeError('Tried to push a non-buffer'); + } + } + + for (var i = 0; i < arguments.length; i++) { + var buf = arguments[i]; + this.buffers.push(buf); + this.length += buf.length; + } + return this.length; +}; + +Buffers.prototype.unshift = function () { + for (var i = 0; i < arguments.length; i++) { + if (!Buffer.isBuffer(arguments[i])) { + throw new TypeError('Tried to unshift a non-buffer'); + } + } + + for (var i = 0; i < arguments.length; i++) { + var buf = arguments[i]; + this.buffers.unshift(buf); + this.length += buf.length; + } + return this.length; +}; + +Buffers.prototype.copy = function (dst, dStart, start, end) { + return this.slice(start, end).copy(dst, dStart, 0, end - start); +}; + +Buffers.prototype.splice = function (i, howMany) { + var buffers = this.buffers; + var index = i >= 0 ? i : this.length - i; + var reps = [].slice.call(arguments, 2); + + if (howMany === undefined) { + howMany = this.length - index; + } + else if (howMany > this.length - index) { + howMany = this.length - index; + } + + for (var i = 0; i < reps.length; i++) { + this.length += reps[i].length; + } + + var removed = new Buffers(); + var bytes = 0; + + var startBytes = 0; + for ( + var ii = 0; + ii < buffers.length && startBytes + buffers[ii].length < index; + ii ++ + ) { startBytes += buffers[ii].length } + + if (index - startBytes > 0) { + var start = index - startBytes; + + if (start + howMany < buffers[ii].length) { + removed.push(buffers[ii].slice(start, start + howMany)); + + var orig = buffers[ii]; + //var buf = new Buffer(orig.length - howMany); + var buf0 = new Buffer(start); + for (var i = 0; i < start; i++) { + buf0[i] = orig[i]; + } + + var buf1 = new Buffer(orig.length - start - howMany); + for (var i = start + howMany; i < orig.length; i++) { + buf1[ i - howMany - start ] = orig[i] + } + + if (reps.length > 0) { + var reps_ = reps.slice(); + reps_.unshift(buf0); + reps_.push(buf1); + buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_)); + ii += reps_.length; + reps = []; + } + else { + buffers.splice(ii, 1, buf0, buf1); + //buffers[ii] = buf; + ii += 2; + } + } + else { + removed.push(buffers[ii].slice(start)); + buffers[ii] = buffers[ii].slice(0, start); + ii ++; + } + } + + if (reps.length > 0) { + buffers.splice.apply(buffers, [ ii, 0 ].concat(reps)); + ii += reps.length; + } + + while (removed.length < howMany) { + var buf = buffers[ii]; + var len = buf.length; + var take = Math.min(len, howMany - removed.length); + + if (take === len) { + removed.push(buf); + buffers.splice(ii, 1); + } + else { + removed.push(buf.slice(0, take)); + buffers[ii] = buffers[ii].slice(take); + } + } + + this.length -= removed.length; + + return removed; +}; + +Buffers.prototype.slice = function (i, j) { + var buffers = this.buffers; + if (j === undefined) j = this.length; + if (i === undefined) i = 0; + + if (j > this.length) j = this.length; + + var startBytes = 0; + for ( + var si = 0; + si < buffers.length && startBytes + buffers[si].length <= i; + si ++ + ) { startBytes += buffers[si].length } + + var target = new Buffer(j - i); + + var ti = 0; + for (var ii = si; ti < j - i && ii < buffers.length; ii++) { + var len = buffers[ii].length; + + var start = ti === 0 ? i - startBytes : 0; + var end = ti + len >= j - i + ? Math.min(start + (j - i) - ti, len) + : len + ; + + buffers[ii].copy(target, ti, start, end); + ti += end - start; + } + + return target; +}; + +Buffers.prototype.pos = function (i) { + if (i < 0 || i >= this.length) throw new Error('oob'); + var l = i, bi = 0, bu = null; + for (;;) { + bu = this.buffers[bi]; + if (l < bu.length) { + return {buf: bi, offset: l}; + } else { + l -= bu.length; + } + bi++; + } +}; + +Buffers.prototype.get = function get (i) { + var pos = this.pos(i); + + return this.buffers[pos.buf].get(pos.offset); +}; + +Buffers.prototype.set = function set (i, b) { + var pos = this.pos(i); + + return this.buffers[pos.buf].set(pos.offset, b); +}; + +Buffers.prototype.indexOf = function (needle, offset) { + if ("string" === typeof needle) { + needle = new Buffer(needle); + } else if (needle instanceof Buffer) { + // already a buffer + } else { + throw new Error('Invalid type for a search string'); + } + + if (!needle.length) { + return 0; + } + + if (!this.length) { + return -1; + } + + var i = 0, j = 0, match = 0, mstart, pos = 0; + + // start search from a particular point in the virtual buffer + if (offset) { + var p = this.pos(offset); + i = p.buf; + j = p.offset; + pos = offset; + } + + // for each character in virtual buffer + for (;;) { + while (j >= this.buffers[i].length) { + j = 0; + i++; + + if (i >= this.buffers.length) { + // search string not found + return -1; + } + } + + var char = this.buffers[i][j]; + + if (char == needle[match]) { + // keep track where match started + if (match == 0) { + mstart = { + i: i, + j: j, + pos: pos + }; + } + match++; + if (match == needle.length) { + // full match + return mstart.pos; + } + } else if (match != 0) { + // a partial match ended, go back to match starting position + // this will continue the search at the next character + i = mstart.i; + j = mstart.j; + pos = mstart.pos; + match = 0; + } + + j++; + pos++; + } +}; + +Buffers.prototype.toBuffer = function() { + return this.slice(); +} + +Buffers.prototype.toString = function(encoding, start, end) { + return this.slice(start, end).toString(encoding); +} + +}).call(this,require("buffer").Buffer) +},{"buffer":69}],211:[function(require,module,exports){ +var elliptic = exports; + +elliptic.version = require('../package.json').version; +elliptic.utils = require('./elliptic/utils'); +elliptic.rand = require('./elliptic/rand'); +elliptic.hmacDRBG = require('./elliptic/hmac-drbg'); +elliptic.curve = require('./elliptic/curve'); +elliptic.curves = require('./elliptic/curves'); + +// Protocols +elliptic.ec = require('./elliptic/ec'); + +},{"../package.json":224,"./elliptic/curve":214,"./elliptic/curves":217,"./elliptic/ec":218,"./elliptic/hmac-drbg":221,"./elliptic/rand":222,"./elliptic/utils":223}],212:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"../../elliptic":211,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js":115,"assert":67,"bn.js":65}],213:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"../../elliptic":211,"../curve":214,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js":116,"assert":67,"bn.js":65,"inherits":231}],214:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./base":212,"./edwards":213,"./mont":215,"./short":216,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js":117}],215:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"../../elliptic":211,"../curve":214,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js":118,"assert":67,"bn.js":65,"inherits":231}],216:[function(require,module,exports){ +var assert = require('assert'); +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var bn = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var getNAF = elliptic.utils.getNAF; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new bn(conf.a, 16).toRed(this.red); + this.b = new bn(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new bn(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new bn(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new bn(vec.a, 16), + b: new bn(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : bn.mont(num); + var tinv = new bn(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + var one = new bn(1).toRed(red); + + var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.shrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new bn(1); + var y1 = new bn(0); + var x2 = new bn(0); + var y2 = new bn(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + var r = v.sub(q.mul(u)); + var x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.sign) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.sign) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromX = function pointFromX(odd, x) { + x = new bn(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.sign) { + split.k1.sign = !split.k1.sign; + p = p.neg(true); + } + if (split.k2.sign) { + split.k2.sign = !split.k2.sign; + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; +}; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new bn(x, 16); + this.y = new bn(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + function endoMul(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + } + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + }]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new bn(k, 16); + + if (this.precomputed && this.precomputed.doubles) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + function negate(p) { + return p.neg(); + } + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + step: pre.doubles.points.map(negate) + } + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new bn(0); + } else { + this.x = new bn(x, 16); + this.y = new bn(y, 16); + this.z = new bn(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + // Z = 1 + if (this.zOne) { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + var nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + var nz = this.y.redAdd(this.y); + } else { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + var nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + var ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + var nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + // Z = 1 + if (this.zOne) { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + var nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + var ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + var nz = this.y.redAdd(this.y); + } else { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + var nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + var nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + var ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + var tinv = this.curve.tinv; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new bn(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +},{"../../elliptic":211,"../curve":214,"assert":67,"bn.js":65,"inherits":231}],217:[function(require,module,exports){ +arguments[4][120][0].apply(exports,arguments) +},{"../elliptic":211,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js":120,"assert":67,"bn.js":65,"hash.js":225}],218:[function(require,module,exports){ +var assert = require('assert'); +var bn = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; + +var KeyPair = require('./key'); +var Signature = require('./signature'); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') + options = elliptic.curves[options]; + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof elliptic.curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.shrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash for function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(priv, pub) { + return new KeyPair(this, priv, pub); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new elliptic.hmacDRBG({ + hash: this.hash, + pers: options.pers, + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + nonce: this.n.toArray() + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new bn(2)); + do { + var priv = new bn(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyPair(priv); + } while (true); +}; + +EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.shrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, options) { + key = this.keyPair(key, 'hex'); + msg = this._truncateToN(new bn(msg, 16)); + if (!options) + options = {}; + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray(); + for (var i = bkey.length; i < 21; i++) + bkey.unshift(0); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray(); + for (var i = nonce.length; i < bytes; i++) + nonce.unshift(0); + + // Instantiate Hmac_DRBG + var drbg = new elliptic.hmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new bn(1)); + do { + var k = new bn(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var r = kp.getX().mod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)).mod(this.n); + if (s.cmpn(0) === 0) + continue; + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) + s = this.n.sub(s); + + return new Signature(r, s); + } while (true); +}; + +EC.prototype.verify = function verify(msg, signature, key) { + msg = this._truncateToN(new bn(msg, 16)); + key = this.keyPair(key, 'hex'); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).mod(this.n); + var u2 = sinv.mul(r).mod(this.n); + + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().mod(this.n).cmp(r) === 0; +}; + +},{"../../elliptic":211,"./key":219,"./signature":220,"assert":67,"bn.js":65}],219:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"../../elliptic":211,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js":122,"assert":67,"bn.js":65}],220:[function(require,module,exports){ +arguments[4][123][0].apply(exports,arguments) +},{"../../elliptic":211,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js":123,"assert":67,"bn.js":65}],221:[function(require,module,exports){ +arguments[4][124][0].apply(exports,arguments) +},{"../elliptic":211,"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/hmac-drbg.js":124,"assert":67,"hash.js":225}],222:[function(require,module,exports){ +var assert = require('assert'); +var elliptic = require('../elliptic'); + +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(); + + return r.generate(len); +}; + +function Rand() { +} + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +if (typeof window === 'object') { + if (window.crypto && window.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.crypto.getRandomValues(arr); + return arr; + }; + } else if (window.msCrypto && window.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.msCrypto.getRandomValues(arr); + return arr; + }; + } else { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js + var crypto; + Rand.prototype._rand = function _rand(n) { + if (!crypto) + crypto = require('cry' + 'pto'); + return crypto.randomBytes(n); + }; +} + +},{"../elliptic":211,"assert":67}],223:[function(require,module,exports){ +module.exports=require(125) +},{"/Users/yemeljardi/code/bitcore/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js":125,"assert":67,"bn.js":65}],224:[function(require,module,exports){ +module.exports={ + "name": "elliptic", + "version": "0.15.12", + "description": "EC cryptography", + "main": "lib/elliptic.js", + "scripts": { + "test": "mocha --reporter=spec test/*-test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:indutny/elliptic" + }, + "keywords": [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/elliptic/issues" + }, + "homepage": "https://github.com/indutny/elliptic", + "devDependencies": { + "browserify": "^3.44.2", + "mocha": "^1.18.2", + "uglify-js": "^2.4.13" + }, + "dependencies": { + "bn.js": "^0.15.0", + "hash.js": "^0.2.0", + "inherits": "^2.0.1" + }, + "readme": "# Elliptic [![Build Status](https://secure.travis-ci.org/indutny/elliptic.png)](http://travis-ci.org/indutny/elliptic)\n\nFast elliptic-curve cryptography in a plain javascript implementation.\n\nNOTE: Please take a look at http://safecurves.cr.yp.to/ before choosing a curve\nfor your cryptography operations.\n\n## Incentive\n\nECC is much slower than regular RSA cryptography, the JS implementations are\neven more slower.\n\n## Benchmarks\n\n```bash\n$ node benchmarks/index.js\nBenchmarking: sign\nelliptic#sign x 262 ops/sec ±0.51% (177 runs sampled)\neccjs#sign x 55.91 ops/sec ±0.90% (144 runs sampled)\n------------------------\nFastest is elliptic#sign\n========================\nBenchmarking: verify\nelliptic#verify x 113 ops/sec ±0.50% (166 runs sampled)\neccjs#verify x 48.56 ops/sec ±0.36% (125 runs sampled)\n------------------------\nFastest is elliptic#verify\n========================\nBenchmarking: gen\nelliptic#gen x 294 ops/sec ±0.43% (176 runs sampled)\neccjs#gen x 62.25 ops/sec ±0.63% (129 runs sampled)\n------------------------\nFastest is elliptic#gen\n========================\nBenchmarking: ecdh\nelliptic#ecdh x 136 ops/sec ±0.85% (156 runs sampled)\n------------------------\nFastest is elliptic#ecdh\n========================\n```\n\n## API\n\n### ECDSA\n\n```javascript\nvar EC = require('elliptic').ec;\n\n// Create and initialize EC context\n// (better do it once and reuse it)\nvar ec = new EC('secp256k1');\n\n// Generate keys\nvar key = ec.genKeyPair();\n\n// Sign message (must be an array, or it'll be treated as a hex sequence)\nvar msg = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];\nvar signature = key.sign(msg);\n\n// Export DER encoded signature in Array\nvar derSign = signature.toDER();\n\n// Verify signature\nconsole.log(key.verify(msg, derSign));\n```\n\n### ECDH\n\n```javascript\n// Generate keys\nvar key1 = ec.genKeyPair();\nvar key2 = ec.genKeyPair();\n\nvar shared1 = key1.derive(key2.getPublic());\nvar shared2 = key2.derive(key1.getPublic());\n\nconsole.log('Both shared secrets are BN instances');\nconsole.log(shared1.toString(16));\nconsole.log(shared2.toString(16));\n```\n\nNOTE: `.derive()` returns a [BN][1] instance.\n\n## Supported curves\n\nElliptic.js support following curve types:\n\n* Short Weierstrass\n* Montgomery\n* Edwards\n* Twisted Edwards\n\nFollowing curve 'presets' are embedded into the library:\n\n* `secp256k1`\n* `p192`\n* `p224`\n* `p256`\n* `curve25519`\n* `ed25519`\n\nNOTE: That `curve25519` could not be used for ECDSA, use `ed25519` instead.\n\n### Implementation details\n\nECDSA is using deterministic `k` value generation as per [RFC6979][0]. Most of\nthe curve operations are performed on non-affine coordinates (either projective\nor extended), various windowing techniques are used for different cases.\n\nAll operations are performed in reduction context using [bn.js][1], hashing is\nprovided by [hash.js][2]\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[0]: http://tools.ietf.org/html/rfc6979\n[1]: https://github.com/indutny/bn.js\n[2]: https://github.com/indutny/hash.js\n", + "readmeFilename": "README.md", + "_id": "elliptic@0.15.12", + "_shasum": "bafa7542ebdb9aaa2edf7cdaa86108ce6f12d4e9", + "_from": "https://registry.npmjs.org/elliptic/-/elliptic-0.15.12.tgz", + "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-0.15.12.tgz" +} + +},{}],225:[function(require,module,exports){ +var hash = exports; + +hash.utils = require('./hash/utils'); +hash.common = require('./hash/common'); +hash.sha = require('./hash/sha'); +hash.ripemd = require('./hash/ripemd'); +hash.hmac = require('./hash/hmac'); + +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.ripemd160 = hash.ripemd.ripemd160; + +},{"./hash/common":226,"./hash/hmac":227,"./hash/ripemd":228,"./hash/sha":229,"./hash/utils":230}],226:[function(require,module,exports){ +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + 8) % bytes); + var res = new Array(k + 8); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + } + + return res; +} + +},{"../hash":225}],227:[function(require,module,exports){ +var hmac = exports; + +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (var i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (var i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); +}; + +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; + +},{"../hash":225}],228:[function(require,module,exports){ +var hash = require('../hash'); +var utils = hash.utils; + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = hash.common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; + +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; + +},{"../hash":225}],229:[function(require,module,exports){ +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +var rotr32 = utils.rotr32; +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var BlockHash = hash.common.BlockHash; + +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; + +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash); +exports.sha256 = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; + +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +exports.sha224 = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash.call(this); + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); +} + +utils.inherits(SHA1, BlockHash); +exports.sha1 = SHA1; + +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; + +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + + for (var i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; + +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} + +function p32(x, y, z) { + return x ^ y ^ z; +} + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} + +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z) + if (s === 2) + return maj32(x, y, z) +} + +},{"../hash":225}],230:[function(require,module,exports){ +var utils = exports; +var inherits = require('inherits'); + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 != 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +utils.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') { + w = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + if (w < 0) + w += 0x100000000; + } + res += zero8(w.toString(16)); + } + return res; +} +utils.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +utils.zero8 = zero8; + +function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + if (w < 0) + w += 0x100000000; + res[i] = w; + } + return res; +} +utils.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +utils.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +utils.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +utils.rotl32 = rotl32; + +function sum32(a, b) { + var r = (a + b) & 0xffffffff; + if (r < 0) + r += 0x100000000; + return r; +} +utils.sum32 = sum32; + +function sum32_3(a, b, c) { + var r = (a + b + c) & 0xffffffff; + if (r < 0) + r += 0x100000000; + return r; +} +utils.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + var r = (a + b + c + d) & 0xffffffff; + if (r < 0) + r += 0x100000000; + return r; +} +utils.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + var r = (a + b + c + d + e) & 0xffffffff; + if (r < 0) + r += 0x100000000; + return r; +} +utils.sum32_5 = sum32_5; + +function assert(cond, msg) { + if (!cond) + throw new Error(msg || 'Assertion failed'); +} +utils.assert = assert; + +utils.inherits = inherits; + +},{"inherits":231}],231:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],232:[function(require,module,exports){ +(function (Buffer){ + +var navigator = {}; +navigator.uesrAgent = false; + +var window = {}; +/* + * jsrsasign 4.2.1 (c) 2010-2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +/* +yahoo-min.js +Copyright (c) 2011, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.com/yui/license.html +version: 2.9.0 +*/ +if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var b=arguments,g=null,e,c,f;for(e=0;e":">",'"':""","'":"'","/":"/","`":"`"},d=["toString","valueOf"],e={isArray:function(j){return a.toString.apply(j)===c;},isBoolean:function(j){return typeof j==="boolean";},isFunction:function(j){return(typeof j==="function")||a.toString.apply(j)===h;},isNull:function(j){return j===null;},isNumber:function(j){return typeof j==="number"&&isFinite(j);},isObject:function(j){return(j&&(typeof j==="object"||f.isFunction(j)))||false;},isString:function(j){return typeof j==="string";},isUndefined:function(j){return typeof j==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(l,k){var j,n,m;for(j=0;j"'\/`]/g,function(k){return g[k];});},extend:function(m,n,l){if(!n||!m){throw new Error("extend failed, please check that "+"all dependencies are included.");}var k=function(){},j;k.prototype=n.prototype;m.prototype=new k();m.prototype.constructor=m;m.superclass=n.prototype;if(n.prototype.constructor==a.constructor){n.prototype.constructor=n;}if(l){for(j in l){if(f.hasOwnProperty(l,j)){m.prototype[j]=l[j];}}f._IEEnumFix(m.prototype,l);}},augmentObject:function(n,m){if(!m||!n){throw new Error("Absorb failed, verify dependencies.");}var j=arguments,l,o,k=j[2];if(k&&k!==true){for(l=2;l0)?f.dump(j[l],p-1):t);}else{r.push(j[l]);}r.push(q);}if(r.length>1){r.pop();}r.push("]");}else{r.push("{");for(l in j){if(f.hasOwnProperty(j,l)){r.push(l+m);if(f.isObject(j[l])){r.push((p>0)?f.dump(j[l],p-1):t);}else{r.push(j[l]);}r.push(q);}}if(r.length>1){r.pop();}r.push("}");}return r.join("");},substitute:function(x,y,E,l){var D,C,B,G,t,u,F=[],p,z=x.length,A="dump",r=" ",q="{",m="}",n,w;for(;;){D=x.lastIndexOf(q,z);if(D<0){break;}C=x.indexOf(m,D);if(D+1>C){break;}p=x.substring(D+1,C);G=p;u=null;B=G.indexOf(r);if(B>-1){u=G.substring(B+1);G=G.substring(0,B);}t=y[G];if(E){t=E(G,t,u);}if(f.isObject(t)){if(f.isArray(t)){t=f.dump(t,parseInt(u,10));}else{u=u||"";n=u.indexOf(A);if(n>-1){u=u.substring(4);}w=t.toString();if(w===i||n>-1){t=f.dump(t,parseInt(u,10));}else{t=w;}}}else{if(!f.isString(t)&&!f.isNumber(t)){t="~-"+F.length+"-~";F[F.length]=p;}}x=x.substring(0,D)+t+x.substring(C+1);if(l===false){z=D-1;}}for(D=F.length-1;D>=0;D=D-1){x=x.replace(new RegExp("~-"+D+"-~"),"{"+F[D]+"}","g");}return x;},trim:function(j){try{return j.replace(/^\s+|\s+$/g,"");}catch(k){return j; +}},merge:function(){var n={},k=arguments,j=k.length,m;for(m=0;m>>2]>>>(24-(r%4)*8))&255;q[(n+r)>>>2]|=o<<(24-((n+r)%4)*8)}}else{for(var r=0;r>>2]=p[r>>>2]}}this.sigBytes+=s;return this},clamp:function(){var o=this.words;var n=this.sigBytes;o[n>>>2]&=4294967295<<(32-(n%4)*8);o.length=e.ceil(n/4)},clone:function(){var n=j.clone.call(this);n.words=this.words.slice(0);return n},random:function(p){var o=[];for(var n=0;n>>2]>>>(24-(n%4)*8))&255;q.push((s>>>4).toString(16));q.push((s&15).toString(16))}return q.join("")},parse:function(p){var n=p.length;var q=[];for(var o=0;o>>3]|=parseInt(p.substr(o,2),16)<<(24-(o%8)*4)}return new l.init(q,n/2)}};var d=m.Latin1={stringify:function(q){var r=q.words;var p=q.sigBytes;var n=[];for(var o=0;o>>2]>>>(24-(o%4)*8))&255;n.push(String.fromCharCode(s))}return n.join("")},parse:function(p){var n=p.length;var q=[];for(var o=0;o>>2]|=(p.charCodeAt(o)&255)<<(24-(o%4)*8)}return new l.init(q,n)}};var c=m.Utf8={stringify:function(n){try{return decodeURIComponent(escape(d.stringify(n)))}catch(o){throw new Error("Malformed UTF-8 data")}},parse:function(n){return d.parse(unescape(encodeURIComponent(n)))}};var i=b.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=new l.init();this._nDataBytes=0},_append:function(n){if(typeof n=="string"){n=c.parse(n)}this._data.concat(n);this._nDataBytes+=n.sigBytes},_process:function(w){var q=this._data;var x=q.words;var n=q.sigBytes;var t=this.blockSize;var v=t*4;var u=n/v;if(w){u=e.ceil(u)}else{u=e.max((u|0)-this._minBufferSize,0)}var s=u*t;var r=e.min(s*4,n);if(s){for(var p=0;pe&&(b=a.finalize(b));b.clamp();for(var f=this._oKey=b.clone(),g=this._iKey=b.clone(),h=f.words,j=g.words,d=0;db;){var d;a:{d=l;for(var w=k.sqrt(d),r=2;r<=w;r++)if(!(d%r)){d=!1;break a}d=!0}d&&(8>b&&(s[b]=u(k.pow(l,0.5))),t[b]=u(k.pow(l,1/3)),b++);l++}var n=[],h=h.SHA256=j.extend({_doReset:function(){this._hash=new v.init(s.slice(0))},_doProcessBlock:function(q,h){for(var a=this._hash.words,c=a[0],d=a[1],b=a[2],k=a[3],f=a[4],g=a[5],j=a[6],l=a[7],e=0;64>e;e++){if(16>e)n[e]= +q[h+e]|0;else{var m=n[e-15],p=n[e-2];n[e]=((m<<25|m>>>7)^(m<<14|m>>>18)^m>>>3)+n[e-7]+((p<<15|p>>>17)^(p<<13|p>>>19)^p>>>10)+n[e-16]}m=l+((f<<26|f>>>6)^(f<<21|f>>>11)^(f<<7|f>>>25))+(f&g^~f&j)+t[e]+n[e];p=((c<<30|c>>>2)^(c<<19|c>>>13)^(c<<10|c>>>22))+(c&d^c&b^d&b);l=j;j=g;g=f;f=k+m|0;k=b;b=d;d=c;c=m+p|0}a[0]=a[0]+c|0;a[1]=a[1]+d|0;a[2]=a[2]+b|0;a[3]=a[3]+k|0;a[4]=a[4]+f|0;a[5]=a[5]+g|0;a[6]=a[6]+j|0;a[7]=a[7]+l|0},_doFinalize:function(){var d=this._data,b=d.words,a=8*this._nDataBytes,c=8*d.sigBytes; +b[c>>>5]|=128<<24-c%32;b[(c+64>>>9<<4)+14]=k.floor(a/4294967296);b[(c+64>>>9<<4)+15]=a;d.sigBytes=4*b.length;this._process();return this._hash},clone:function(){var b=j.clone.call(this);b._hash=this._hash.clone();return b}});g.SHA256=j._createHelper(h);g.HmacSHA256=j._createHmacHelper(h)})(Math); +/* +CryptoJS v3.1.2 sha224-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var b=CryptoJS,d=b.lib.WordArray,a=b.algo,c=a.SHA256,a=a.SHA224=c.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=c._doFinalize.call(this);a.sigBytes-=4;return a}});b.SHA224=c._createHelper(a);b.HmacSHA224=c._createHmacHelper(a)})(); +/* +CryptoJS v3.1.2 sha512-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){function a(){return d.create.apply(d,arguments)}for(var n=CryptoJS,r=n.lib.Hasher,e=n.x64,d=e.Word,T=e.WordArray,e=n.algo,ea=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317), +a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291, +2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899), +a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470, +3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],v=[],w=0;80>w;w++)v[w]=a();e=e.SHA512=r.extend({_doReset:function(){this._hash=new T.init([new d.init(1779033703,4089235720),new d.init(3144134277,2227873595),new d.init(1013904242,4271175723),new d.init(2773480762,1595750129),new d.init(1359893119,2917565137),new d.init(2600822924,725511199),new d.init(528734635,4215389547),new d.init(1541459225,327033209)])},_doProcessBlock:function(a,d){for(var f=this._hash.words, +F=f[0],e=f[1],n=f[2],r=f[3],G=f[4],H=f[5],I=f[6],f=f[7],w=F.high,J=F.low,X=e.high,K=e.low,Y=n.high,L=n.low,Z=r.high,M=r.low,$=G.high,N=G.low,aa=H.high,O=H.low,ba=I.high,P=I.low,ca=f.high,Q=f.low,k=w,g=J,z=X,x=K,A=Y,y=L,U=Z,B=M,l=$,h=N,R=aa,C=O,S=ba,D=P,V=ca,E=Q,m=0;80>m;m++){var s=v[m];if(16>m)var j=s.high=a[d+2*m]|0,b=s.low=a[d+2*m+1]|0;else{var j=v[m-15],b=j.high,p=j.low,j=(b>>>1|p<<31)^(b>>>8|p<<24)^b>>>7,p=(p>>>1|b<<31)^(p>>>8|b<<24)^(p>>>7|b<<25),u=v[m-2],b=u.high,c=u.low,u=(b>>>19|c<<13)^(b<< +3|c>>>29)^b>>>6,c=(c>>>19|b<<13)^(c<<3|b>>>29)^(c>>>6|b<<26),b=v[m-7],W=b.high,t=v[m-16],q=t.high,t=t.low,b=p+b.low,j=j+W+(b>>>0

>>0?1:0),b=b+c,j=j+u+(b>>>0>>0?1:0),b=b+t,j=j+q+(b>>>0>>0?1:0);s.high=j;s.low=b}var W=l&R^~l&S,t=h&C^~h&D,s=k&z^k&A^z&A,T=g&x^g&y^x&y,p=(k>>>28|g<<4)^(k<<30|g>>>2)^(k<<25|g>>>7),u=(g>>>28|k<<4)^(g<<30|k>>>2)^(g<<25|k>>>7),c=ea[m],fa=c.high,da=c.low,c=E+((h>>>14|l<<18)^(h>>>18|l<<14)^(h<<23|l>>>9)),q=V+((l>>>14|h<<18)^(l>>>18|h<<14)^(l<<23|h>>>9))+(c>>>0>>0?1: +0),c=c+t,q=q+W+(c>>>0>>0?1:0),c=c+da,q=q+fa+(c>>>0>>0?1:0),c=c+b,q=q+j+(c>>>0>>0?1:0),b=u+T,s=p+s+(b>>>0>>0?1:0),V=S,E=D,S=R,D=C,R=l,C=h,h=B+c|0,l=U+q+(h>>>0>>0?1:0)|0,U=A,B=y,A=z,y=x,z=k,x=g,g=c+b|0,k=q+s+(g>>>0>>0?1:0)|0}J=F.low=J+g;F.high=w+k+(J>>>0>>0?1:0);K=e.low=K+x;e.high=X+z+(K>>>0>>0?1:0);L=n.low=L+y;n.high=Y+A+(L>>>0>>0?1:0);M=r.low=M+B;r.high=Z+U+(M>>>0>>0?1:0);N=G.low=N+h;G.high=$+l+(N>>>0>>0?1:0);O=H.low=O+C;H.high=aa+R+(O>>>0>>0?1:0);P=I.low=P+D; +I.high=ba+S+(P>>>0>>0?1:0);Q=f.low=Q+E;f.high=ca+V+(Q>>>0>>0?1:0)},_doFinalize:function(){var a=this._data,d=a.words,f=8*this._nDataBytes,e=8*a.sigBytes;d[e>>>5]|=128<<24-e%32;d[(e+128>>>10<<5)+30]=Math.floor(f/4294967296);d[(e+128>>>10<<5)+31]=f;a.sigBytes=4*d.length;this._process();return this._hash.toX32()},clone:function(){var a=r.clone.call(this);a._hash=this._hash.clone();return a},blockSize:32});n.SHA512=r._createHelper(e);n.HmacSHA512=r._createHmacHelper(e)})(); +/* +CryptoJS v3.1.2 sha384-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var c=CryptoJS,a=c.x64,b=a.Word,e=a.WordArray,a=c.algo,d=a.SHA512,a=a.SHA384=d.extend({_doReset:function(){this._hash=new e.init([new b.init(3418070365,3238371032),new b.init(1654270250,914150663),new b.init(2438529370,812702999),new b.init(355462360,4144912697),new b.init(1731405415,4290775857),new b.init(2394180231,1750603025),new b.init(3675008525,1694076839),new b.init(1203062813,3204075428)])},_doFinalize:function(){var a=d._doFinalize.call(this);a.sigBytes-=16;return a}});c.SHA384= +d._createHelper(a);c.HmacSHA384=d._createHmacHelper(a)})(); +/* +CryptoJS v3.1.2 md5-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(E){function h(a,f,g,j,p,h,k){a=a+(f&g|~f&j)+p+k;return(a<>>32-h)+f}function k(a,f,g,j,p,h,k){a=a+(f&j|g&~j)+p+k;return(a<>>32-h)+f}function l(a,f,g,j,h,k,l){a=a+(f^g^j)+h+l;return(a<>>32-k)+f}function n(a,f,g,j,h,k,l){a=a+(g^(f|~j))+h+l;return(a<>>32-k)+f}for(var r=CryptoJS,q=r.lib,F=q.WordArray,s=q.Hasher,q=r.algo,a=[],t=0;64>t;t++)a[t]=4294967296*E.abs(E.sin(t+1))|0;q=q.MD5=s.extend({_doReset:function(){this._hash=new F.init([1732584193,4023233417,2562383102,271733878])}, +_doProcessBlock:function(m,f){for(var g=0;16>g;g++){var j=f+g,p=m[j];m[j]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360}var g=this._hash.words,j=m[f+0],p=m[f+1],q=m[f+2],r=m[f+3],s=m[f+4],t=m[f+5],u=m[f+6],v=m[f+7],w=m[f+8],x=m[f+9],y=m[f+10],z=m[f+11],A=m[f+12],B=m[f+13],C=m[f+14],D=m[f+15],b=g[0],c=g[1],d=g[2],e=g[3],b=h(b,c,d,e,j,7,a[0]),e=h(e,b,c,d,p,12,a[1]),d=h(d,e,b,c,q,17,a[2]),c=h(c,d,e,b,r,22,a[3]),b=h(b,c,d,e,s,7,a[4]),e=h(e,b,c,d,t,12,a[5]),d=h(d,e,b,c,u,17,a[6]),c=h(c,d,e,b,v,22,a[7]), +b=h(b,c,d,e,w,7,a[8]),e=h(e,b,c,d,x,12,a[9]),d=h(d,e,b,c,y,17,a[10]),c=h(c,d,e,b,z,22,a[11]),b=h(b,c,d,e,A,7,a[12]),e=h(e,b,c,d,B,12,a[13]),d=h(d,e,b,c,C,17,a[14]),c=h(c,d,e,b,D,22,a[15]),b=k(b,c,d,e,p,5,a[16]),e=k(e,b,c,d,u,9,a[17]),d=k(d,e,b,c,z,14,a[18]),c=k(c,d,e,b,j,20,a[19]),b=k(b,c,d,e,t,5,a[20]),e=k(e,b,c,d,y,9,a[21]),d=k(d,e,b,c,D,14,a[22]),c=k(c,d,e,b,s,20,a[23]),b=k(b,c,d,e,x,5,a[24]),e=k(e,b,c,d,C,9,a[25]),d=k(d,e,b,c,r,14,a[26]),c=k(c,d,e,b,w,20,a[27]),b=k(b,c,d,e,B,5,a[28]),e=k(e,b, +c,d,q,9,a[29]),d=k(d,e,b,c,v,14,a[30]),c=k(c,d,e,b,A,20,a[31]),b=l(b,c,d,e,t,4,a[32]),e=l(e,b,c,d,w,11,a[33]),d=l(d,e,b,c,z,16,a[34]),c=l(c,d,e,b,C,23,a[35]),b=l(b,c,d,e,p,4,a[36]),e=l(e,b,c,d,s,11,a[37]),d=l(d,e,b,c,v,16,a[38]),c=l(c,d,e,b,y,23,a[39]),b=l(b,c,d,e,B,4,a[40]),e=l(e,b,c,d,j,11,a[41]),d=l(d,e,b,c,r,16,a[42]),c=l(c,d,e,b,u,23,a[43]),b=l(b,c,d,e,x,4,a[44]),e=l(e,b,c,d,A,11,a[45]),d=l(d,e,b,c,D,16,a[46]),c=l(c,d,e,b,q,23,a[47]),b=n(b,c,d,e,j,6,a[48]),e=n(e,b,c,d,v,10,a[49]),d=n(d,e,b,c, +C,15,a[50]),c=n(c,d,e,b,t,21,a[51]),b=n(b,c,d,e,A,6,a[52]),e=n(e,b,c,d,r,10,a[53]),d=n(d,e,b,c,y,15,a[54]),c=n(c,d,e,b,p,21,a[55]),b=n(b,c,d,e,w,6,a[56]),e=n(e,b,c,d,D,10,a[57]),d=n(d,e,b,c,u,15,a[58]),c=n(c,d,e,b,B,21,a[59]),b=n(b,c,d,e,s,6,a[60]),e=n(e,b,c,d,z,10,a[61]),d=n(d,e,b,c,q,15,a[62]),c=n(c,d,e,b,x,21,a[63]);g[0]=g[0]+b|0;g[1]=g[1]+c|0;g[2]=g[2]+d|0;g[3]=g[3]+e|0},_doFinalize:function(){var a=this._data,f=a.words,g=8*this._nDataBytes,j=8*a.sigBytes;f[j>>>5]|=128<<24-j%32;var h=E.floor(g/ +4294967296);f[(j+64>>>9<<4)+15]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360;f[(j+64>>>9<<4)+14]=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360;a.sigBytes=4*(f.length+1);this._process();a=this._hash;f=a.words;for(g=0;4>g;g++)j=f[g],f[g]=(j<<8|j>>>24)&16711935|(j<<24|j>>>8)&4278255360;return a},clone:function(){var a=s.clone.call(this);a._hash=this._hash.clone();return a}});r.MD5=s._createHelper(q);r.HmacMD5=s._createHmacHelper(q)})(Math); +/* +CryptoJS v3.1.2 enc-base64-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var h=CryptoJS,j=h.lib.WordArray;h.enc.Base64={stringify:function(b){var e=b.words,f=b.sigBytes,c=this._map;b.clamp();b=[];for(var a=0;a>>2]>>>24-8*(a%4)&255)<<16|(e[a+1>>>2]>>>24-8*((a+1)%4)&255)<<8|e[a+2>>>2]>>>24-8*((a+2)%4)&255,g=0;4>g&&a+0.75*g>>6*(3-g)&63));if(e=c.charAt(64))for(;b.length%4;)b.push(e);return b.join("")},parse:function(b){var e=b.length,f=this._map,c=f.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(e=c));for(var c=[],a=0,d=0;d< +e;d++)if(d%4){var g=f.indexOf(b.charAt(d-1))<<2*(d%4),h=f.indexOf(b.charAt(d))>>>6-2*(d%4);c[a>>>2]|=(g|h)<<24-8*(a%4);a++}return j.create(c,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(); +/* +CryptoJS v3.1.2 cipher-core-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +CryptoJS.lib.Cipher||function(u){var g=CryptoJS,f=g.lib,k=f.Base,l=f.WordArray,q=f.BufferedBlockAlgorithm,r=g.enc.Base64,v=g.algo.EvpKDF,n=f.Cipher=q.extend({cfg:k.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c);this._xformMode=a;this._key=b;this.reset()},reset:function(){q.reset.call(this);this._doReset()},process:function(a){this._append(a); +return this._process()},finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(a){return{encrypt:function(b,c,d){return("string"==typeof c?s:j).encrypt(a,b,c,d)},decrypt:function(b,c,d){return("string"==typeof c?s:j).decrypt(a,b,c,d)}}}});f.StreamCipher=n.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var m=g.mode={},t=function(a,b,c){var d=this._iv;d?this._iv=u:d=this._prevBlock;for(var e= +0;e>>2]&255}};f.BlockCipher=n.extend({cfg:n.cfg.extend({mode:m,padding:h}),reset:function(){n.reset.call(this);var a=this.cfg,b=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var c=a.createEncryptor;else c=a.createDecryptor,this._minBufferSize=1; +this._mode=c.call(a,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),a.unpad(b);return b},blockSize:4});var p=f.CipherParams=k.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),m=(g.format={}).OpenSSL={stringify:function(a){var b=a.ciphertext;a=a.salt; +return(a?l.create([1398893684,1701076831]).concat(a).concat(b):b).toString(r)},parse:function(a){a=r.parse(a);var b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var c=l.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return p.create({ciphertext:a,salt:c})}},j=f.SerializableCipher=k.extend({cfg:k.extend({format:m}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d);b=e.finalize(b);e=e.cfg;return p.create({ciphertext:b,key:c,iv:e.iv,algorithm:a,mode:e.mode,padding:e.padding, +blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),g=(g.kdf={}).OpenSSL={execute:function(a,b,c,d){d||(d=l.random(8));a=v.create({keySize:b+c}).compute(a,d);c=l.create(a.words.slice(b),4*c);a.sigBytes=4*b;return p.create({key:a,iv:c,salt:d})}},s=f.PasswordBasedCipher=j.extend({cfg:j.cfg.extend({kdf:g}),encrypt:function(a, +b,c,d){d=this.cfg.extend(d);c=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=c.iv;a=j.encrypt.call(this,a,b,c.key,d);a.mixIn(c);return a},decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);c=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=c.iv;return j.decrypt.call(this,a,b,c.key,d)}})}(); +/* +CryptoJS v3.1.2 aes-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){for(var q=CryptoJS,x=q.lib.BlockCipher,r=q.algo,j=[],y=[],z=[],A=[],B=[],C=[],s=[],u=[],v=[],w=[],g=[],k=0;256>k;k++)g[k]=128>k?k<<1:k<<1^283;for(var n=0,l=0,k=0;256>k;k++){var f=l^l<<1^l<<2^l<<3^l<<4,f=f>>>8^f&255^99;j[n]=f;y[f]=n;var t=g[n],D=g[t],E=g[D],b=257*g[f]^16843008*f;z[n]=b<<24|b>>>8;A[n]=b<<16|b>>>16;B[n]=b<<8|b>>>24;C[n]=b;b=16843009*E^65537*D^257*t^16843008*n;s[f]=b<<24|b>>>8;u[f]=b<<16|b>>>16;v[f]=b<<8|b>>>24;w[f]=b;n?(n=t^g[g[g[E^t]]],l^=g[g[l]]):n=l=1}var F=[0,1,2,4,8, +16,32,64,128,27,54],r=r.AES=x.extend({_doReset:function(){for(var c=this._key,e=c.words,a=c.sigBytes/4,c=4*((this._nRounds=a+6)+1),b=this._keySchedule=[],h=0;h>>24]<<24|j[d>>>16&255]<<16|j[d>>>8&255]<<8|j[d&255]):(d=d<<8|d>>>24,d=j[d>>>24]<<24|j[d>>>16&255]<<16|j[d>>>8&255]<<8|j[d&255],d^=F[h/a|0]<<24);b[h]=b[h-a]^d}e=this._invKeySchedule=[];for(a=0;aa||4>=h?d:s[j[d>>>24]]^u[j[d>>>16&255]]^v[j[d>>> +8&255]]^w[j[d&255]]},encryptBlock:function(c,e){this._doCryptBlock(c,e,this._keySchedule,z,A,B,C,j)},decryptBlock:function(c,e){var a=c[e+1];c[e+1]=c[e+3];c[e+3]=a;this._doCryptBlock(c,e,this._invKeySchedule,s,u,v,w,y);a=c[e+1];c[e+1]=c[e+3];c[e+3]=a},_doCryptBlock:function(c,e,a,b,h,d,j,m){for(var n=this._nRounds,f=c[e]^a[0],g=c[e+1]^a[1],k=c[e+2]^a[2],p=c[e+3]^a[3],l=4,t=1;t>>24]^h[g>>>16&255]^d[k>>>8&255]^j[p&255]^a[l++],r=b[g>>>24]^h[k>>>16&255]^d[p>>>8&255]^j[f&255]^a[l++],s= +b[k>>>24]^h[p>>>16&255]^d[f>>>8&255]^j[g&255]^a[l++],p=b[p>>>24]^h[f>>>16&255]^d[g>>>8&255]^j[k&255]^a[l++],f=q,g=r,k=s;q=(m[f>>>24]<<24|m[g>>>16&255]<<16|m[k>>>8&255]<<8|m[p&255])^a[l++];r=(m[g>>>24]<<24|m[k>>>16&255]<<16|m[p>>>8&255]<<8|m[f&255])^a[l++];s=(m[k>>>24]<<24|m[p>>>16&255]<<16|m[f>>>8&255]<<8|m[g&255])^a[l++];p=(m[p>>>24]<<24|m[f>>>16&255]<<16|m[g>>>8&255]<<8|m[k&255])^a[l++];c[e]=q;c[e+1]=r;c[e+2]=s;c[e+3]=p},keySize:8});q.AES=x._createHelper(r)})(); +/* +CryptoJS v3.1.2 tripledes-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){function j(b,c){var a=(this._lBlock>>>b^this._rBlock)&c;this._rBlock^=a;this._lBlock^=a<>>b^this._lBlock)&c;this._lBlock^=a;this._rBlock^=a<a;a++){var f=q[a]-1;c[a]=b[f>>>5]>>>31-f%32&1}b=this._subKeys=[];for(f=0;16>f;f++){for(var d=b[f]=[],e=r[f],a=0;24>a;a++)d[a/6|0]|=c[(p[a]-1+e)%28]<<31-a%6,d[4+(a/6|0)]|=c[28+(p[a+24]-1+e)%28]<<31-a%6;d[0]=d[0]<<1|d[0]>>>31;for(a=1;7>a;a++)d[a]>>>= +4*(a-1)+3;d[7]=d[7]<<5|d[7]>>>27}c=this._invSubKeys=[];for(a=0;16>a;a++)c[a]=b[15-a]},encryptBlock:function(b,c){this._doCryptBlock(b,c,this._subKeys)},decryptBlock:function(b,c){this._doCryptBlock(b,c,this._invSubKeys)},_doCryptBlock:function(b,c,a){this._lBlock=b[c];this._rBlock=b[c+1];j.call(this,4,252645135);j.call(this,16,65535);l.call(this,2,858993459);l.call(this,8,16711935);j.call(this,1,1431655765);for(var f=0;16>f;f++){for(var d=a[f],e=this._lBlock,h=this._rBlock,g=0,k=0;8>k;k++)g|=s[k][((h^ +d[k])&t[k])>>>0];this._lBlock=h;this._rBlock=e^g}a=this._lBlock;this._lBlock=this._rBlock;this._rBlock=a;j.call(this,1,1431655765);l.call(this,8,16711935);l.call(this,2,858993459);j.call(this,16,65535);j.call(this,4,252645135);b[c]=this._lBlock;b[c+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});h.DES=e._createHelper(m);g=g.TripleDES=e.extend({_doReset:function(){var b=this._key.words;this._des1=m.createEncryptor(n.create(b.slice(0,2)));this._des2=m.createEncryptor(n.create(b.slice(2,4)));this._des3= +m.createEncryptor(n.create(b.slice(4,6)))},encryptBlock:function(b,c){this._des1.encryptBlock(b,c);this._des2.decryptBlock(b,c);this._des3.encryptBlock(b,c)},decryptBlock:function(b,c){this._des3.decryptBlock(b,c);this._des2.encryptBlock(b,c);this._des1.decryptBlock(b,c)},keySize:6,ivSize:2,blockSize:2});h.TripleDES=e._createHelper(g)})(); +/* +CryptoJS v3.1.2 sha1-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var k=CryptoJS,b=k.lib,m=b.WordArray,l=b.Hasher,d=[],b=k.algo.SHA1=l.extend({_doReset:function(){this._hash=new m.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(n,p){for(var a=this._hash.words,e=a[0],f=a[1],h=a[2],j=a[3],b=a[4],c=0;80>c;c++){if(16>c)d[c]=n[p+c]|0;else{var g=d[c-3]^d[c-8]^d[c-14]^d[c-16];d[c]=g<<1|g>>>31}g=(e<<5|e>>>27)+b+d[c];g=20>c?g+((f&h|~f&j)+1518500249):40>c?g+((f^h^j)+1859775393):60>c?g+((f&h|f&j|h&j)-1894007588):g+((f^h^ +j)-899497514);b=j;j=h;h=f<<30|f>>>2;f=e;e=g}a[0]=a[0]+e|0;a[1]=a[1]+f|0;a[2]=a[2]+h|0;a[3]=a[3]+j|0;a[4]=a[4]+b|0},_doFinalize:function(){var b=this._data,d=b.words,a=8*this._nDataBytes,e=8*b.sigBytes;d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=Math.floor(a/4294967296);d[(e+64>>>9<<4)+15]=a;b.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var b=l.clone.call(this);b._hash=this._hash.clone();return b}});k.SHA1=l._createHelper(b);k.HmacSHA1=l._createHmacHelper(b)})(); +/* +CryptoJS v3.1.2 ripemd160-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/* + +(c) 2012 by Cedric Mesnil. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - 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. + +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. +*/ +(function(){var q=CryptoJS,d=q.lib,n=d.WordArray,p=d.Hasher,d=q.algo,x=n.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),y=n.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),z=n.create([11,14,15,12, +5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),A=n.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),B=n.create([0,1518500249,1859775393,2400959708,2840853838]),C=n.create([1352829926,1548603684,1836072691, +2053994217,0]),d=d.RIPEMD160=p.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,v){for(var b=0;16>b;b++){var c=v+b,f=e[c];e[c]=(f<<8|f>>>24)&16711935|(f<<24|f>>>8)&4278255360}var c=this._hash.words,f=B.words,d=C.words,n=x.words,q=y.words,p=z.words,w=A.words,t,g,h,j,r,u,k,l,m,s;u=t=c[0];k=g=c[1];l=h=c[2];m=j=c[3];s=r=c[4];for(var a,b=0;80>b;b+=1)a=t+e[v+n[b]]|0,a=16>b?a+((g^h^j)+f[0]):32>b?a+((g&h|~g&j)+f[1]):48>b? +a+(((g|~h)^j)+f[2]):64>b?a+((g&j|h&~j)+f[3]):a+((g^(h|~j))+f[4]),a|=0,a=a<>>32-p[b],a=a+r|0,t=r,r=j,j=h<<10|h>>>22,h=g,g=a,a=u+e[v+q[b]]|0,a=16>b?a+((k^(l|~m))+d[0]):32>b?a+((k&m|l&~m)+d[1]):48>b?a+(((k|~l)^m)+d[2]):64>b?a+((k&l|~k&m)+d[3]):a+((k^l^m)+d[4]),a|=0,a=a<>>32-w[b],a=a+s|0,u=s,s=m,m=l<<10|l>>>22,l=k,k=a;a=c[1]+h+m|0;c[1]=c[2]+j+s|0;c[2]=c[3]+r+u|0;c[3]=c[4]+t+k|0;c[4]=c[0]+g+l|0;c[0]=a},_doFinalize:function(){var e=this._data,d=e.words,b=8*this._nDataBytes,c=8*e.sigBytes; +d[c>>>5]|=128<<24-c%32;d[(c+64>>>9<<4)+14]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;e.sigBytes=4*(d.length+1);this._process();e=this._hash;d=e.words;for(b=0;5>b;b++)c=d[b],d[b]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;return e},clone:function(){var d=p.clone.call(this);d._hash=this._hash.clone();return d}});q.RIPEMD160=p._createHelper(d);q.HmacRIPEMD160=p._createHmacHelper(d)})(Math); +/* +CryptoJS v3.1.2 pbkdf2-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var b=CryptoJS,a=b.lib,d=a.Base,m=a.WordArray,a=b.algo,q=a.HMAC,l=a.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:a.SHA1,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,f=q.create(c.hasher,a),g=m.create(),d=m.create([1]),l=g.words,r=d.words,n=c.keySize,c=c.iterations;l.length>6)+b64map.charAt(e&63)}if(b+1==d.length){e=parseInt(d.substring(b,b+1),16);a+=b64map.charAt(e<<2)}else{if(b+2==d.length){e=parseInt(d.substring(b,b+2),16);a+=b64map.charAt(e>>2)+b64map.charAt((e&3)<<4)}}if(b64pad){while((a.length&3)>0){a+=b64pad}}return a}function b64tohex(f){var d="";var e;var b=0;var c;var a;for(e=0;e>2);c=a&3;b=1}else{if(b==1){d+=int2char((c<<2)|(a>>4));c=a&15;b=2}else{if(b==2){d+=int2char(c);d+=int2char(a>>2);c=a&3;b=3}else{d+=int2char((c<<2)|(a>>4));d+=int2char(a&15);b=0}}}}if(b==1){d+=int2char(c<<2)}return d}function b64toBA(e){var d=b64tohex(e);var c;var b=new Array();for(c=0;2*c=0){var d=a*this[f++]+b[e]+h;h=Math.floor(d/67108864);b[e++]=d&67108863}return h}function am2(f,q,r,e,o,a){var k=q&32767,p=q>>15;while(--a>=0){var d=this[f]&32767;var g=this[f++]>>15;var b=p*d+g*k;d=k*d+((b&32767)<<15)+r[e]+(o&1073741823);o=(d>>>30)+(b>>>15)+p*g+(o>>>30);r[e++]=d&1073741823}return o}function am3(f,q,r,e,o,a){var k=q&16383,p=q>>14;while(--a>=0){var d=this[f]&16383;var g=this[f++]>>14;var b=p*d+g*k;d=k*d+((b&16383)<<14)+r[e]+o;o=(d>>28)+(b>>14)+p*g;r[e++]=d&268435455}return o}if(j_lm&&(navigator.appName=="Microsoft Internet Explorer")){BigInteger.prototype.am=am2;dbits=30}else{if(j_lm&&(navigator.appName!="Netscape")){BigInteger.prototype.am=am1;dbits=26}else{BigInteger.prototype.am=am3;dbits=28}}BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=((1<=0;--a){b[a]=this[a]}b.t=this.t;b.s=this.s}function bnpFromInt(a){this.t=1;this.s=(a<0)?-1:0;if(a>0){this[0]=a}else{if(a<-1){this[0]=a+this.DV}else{this.t=0}}}function nbv(a){var b=nbi();b.fromInt(a);return b}function bnpFromString(h,c){var e;if(c==16){e=4}else{if(c==8){e=3}else{if(c==256){e=8}else{if(c==2){e=1}else{if(c==32){e=5}else{if(c==4){e=2}else{this.fromRadix(h,c);return}}}}}}this.t=0;this.s=0;var g=h.length,d=false,f=0;while(--g>=0){var a=(e==8)?h[g]&255:intAt(h,g);if(a<0){if(h.charAt(g)=="-"){d=true}continue}d=false;if(f==0){this[this.t++]=a}else{if(f+e>this.DB){this[this.t-1]|=(a&((1<<(this.DB-f))-1))<>(this.DB-f))}else{this[this.t-1]|=a<=this.DB){f-=this.DB}}if(e==8&&(h[0]&128)!=0){this.s=-1;if(f>0){this[this.t-1]|=((1<<(this.DB-f))-1)<0&&this[this.t-1]==a){--this.t}}function bnToString(c){if(this.s<0){return"-"+this.negate().toString(c)}var e;if(c==16){e=4}else{if(c==8){e=3}else{if(c==2){e=1}else{if(c==32){e=5}else{if(c==4){e=2}else{return this.toRadix(c)}}}}}var g=(1<0){if(j>j)>0){a=true;h=int2char(l)}while(f>=0){if(j>(j+=this.DB-e)}else{l=(this[f]>>(j-=e))&g;if(j<=0){j+=this.DB;--f}}if(l>0){a=true}if(a){h+=int2char(l)}}}return a?h:"0"}function bnNegate(){var a=nbi();BigInteger.ZERO.subTo(this,a);return a}function bnAbs(){return(this.s<0)?this.negate():this}function bnCompareTo(b){var d=this.s-b.s;if(d!=0){return d}var c=this.t;d=c-b.t;if(d!=0){return(this.s<0)?-d:d}while(--c>=0){if((d=this[c]-b[c])!=0){return d}}return 0}function nbits(a){var c=1,b;if((b=a>>>16)!=0){a=b;c+=16}if((b=a>>8)!=0){a=b;c+=8}if((b=a>>4)!=0){a=b;c+=4}if((b=a>>2)!=0){a=b;c+=2}if((b=a>>1)!=0){a=b;c+=1}return c}function bnBitLength(){if(this.t<=0){return 0}return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM))}function bnpDLShiftTo(c,b){var a;for(a=this.t-1;a>=0;--a){b[a+c]=this[a]}for(a=c-1;a>=0;--a){b[a]=0}b.t=this.t+c;b.s=this.s}function bnpDRShiftTo(c,b){for(var a=c;a=0;--d){e[d+f+1]=(this[d]>>a)|h;h=(this[d]&g)<=0;--d){e[d]=0}e[f]=h;e.t=this.t+f+1;e.s=this.s;e.clamp()}function bnpRShiftTo(g,d){d.s=this.s;var e=Math.floor(g/this.DB);if(e>=this.t){d.t=0;return}var b=g%this.DB;var a=this.DB-b;var f=(1<>b;for(var c=e+1;c>b}if(b>0){d[this.t-e-1]|=(this.s&f)<>=this.DB}if(d.t>=this.DB}g+=this.s}else{g+=this.s;while(e>=this.DB}g-=d.s}f.s=(g<0)?-1:0;if(g<-1){f[e++]=this.DV+g}else{if(g>0){f[e++]=g}}f.t=e;f.clamp()}function bnpMultiplyTo(c,e){var b=this.abs(),f=c.abs();var d=b.t;e.t=d+f.t;while(--d>=0){e[d]=0}for(d=0;d=0){d[b]=0}for(b=0;b=a.DV){d[b+a.t]-=a.DV;d[b+a.t+1]=1}}if(d.t>0){d[d.t-1]+=a.am(b,a[b],d,2*b,0,1)}d.s=0;d.clamp()}function bnpDivRemTo(n,h,g){var w=n.abs();if(w.t<=0){return}var k=this.abs();if(k.t0){w.lShiftTo(v,d);k.lShiftTo(v,g)}else{w.copyTo(d);k.copyTo(g)}var p=d.t;var b=d[p-1];if(b==0){return}var o=b*(1<1)?d[p-2]>>this.F2:0);var A=this.FV/o,z=(1<=0){g[g.t++]=1;g.subTo(f,g)}BigInteger.ONE.dlShiftTo(p,f);f.subTo(d,d);while(d.t=0){var c=(g[--u]==b)?this.DM:Math.floor(g[u]*A+(g[u-1]+x)*z);if((g[u]+=d.am(0,c,g,s,0,p))0){g.rShiftTo(v,g)}if(a<0){BigInteger.ZERO.subTo(g,g)}}function bnMod(b){var c=nbi();this.abs().divRemTo(b,null,c);if(this.s<0&&c.compareTo(BigInteger.ZERO)>0){b.subTo(c,c)}return c}function Classic(a){this.m=a}function cConvert(a){if(a.s<0||a.compareTo(this.m)>=0){return a.mod(this.m)}else{return a}}function cRevert(a){return a}function cReduce(a){a.divRemTo(this.m,null,a)}function cMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}function cSqrTo(a,b){a.squareTo(b);this.reduce(b)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1){return 0}var a=this[0];if((a&1)==0){return 0}var b=a&3;b=(b*(2-(a&15)*b))&15;b=(b*(2-(a&255)*b))&255;b=(b*(2-(((a&65535)*b)&65535)))&65535;b=(b*(2-a*b%this.DV))%this.DV;return(b>0)?this.DV-b:-b}function Montgomery(a){this.m=a;this.mp=a.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<(a.DB-15))-1;this.mt2=2*a.t}function montConvert(a){var b=nbi();a.abs().dlShiftTo(this.m.t,b);b.divRemTo(this.m,null,b);if(a.s<0&&b.compareTo(BigInteger.ZERO)>0){this.m.subTo(b,b)}return b}function montRevert(a){var b=nbi();a.copyTo(b);this.reduce(b);return b}function montReduce(a){while(a.t<=this.mt2){a[a.t++]=0}for(var c=0;c>15)*this.mpl)&this.um)<<15))&a.DM;b=c+this.m.t;a[b]+=this.m.am(0,d,a,c,0,this.m.t);while(a[b]>=a.DV){a[b]-=a.DV;a[++b]++}}a.clamp();a.drShiftTo(this.m.t,a);if(a.compareTo(this.m)>=0){a.subTo(this.m,a)}}function montSqrTo(a,b){a.squareTo(b);this.reduce(b)}function montMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return((this.t>0)?(this[0]&1):this.s)==0}function bnpExp(h,j){if(h>4294967295||h<1){return BigInteger.ONE}var f=nbi(),a=nbi(),d=j.convert(this),c=nbits(h)-1;d.copyTo(f);while(--c>=0){j.sqrTo(f,a);if((h&(1<0){j.mulTo(a,d,f)}else{var b=f;f=a;a=b}}return j.revert(f)}function bnModPowInt(b,a){var c;if(b<256||a.isEven()){c=new Classic(a)}else{c=new Montgomery(a)}return this.exp(b,c)}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1); +/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ + */ +function bnClone(){var a=nbi();this.copyTo(a);return a}function bnIntValue(){if(this.s<0){if(this.t==1){return this[0]-this.DV}else{if(this.t==0){return -1}}}else{if(this.t==1){return this[0]}else{if(this.t==0){return 0}}}return((this[1]&((1<<(32-this.DB))-1))<>24}function bnShortValue(){return(this.t==0)?this.s:(this[0]<<16)>>16}function bnpChunkSize(a){return Math.floor(Math.LN2*this.DB/Math.log(a))}function bnSigNum(){if(this.s<0){return -1}else{if(this.t<=0||(this.t==1&&this[0]<=0)){return 0}else{return 1}}}function bnpToRadix(c){if(c==null){c=10}if(this.signum()==0||c<2||c>36){return"0"}var f=this.chunkSize(c);var e=Math.pow(c,f);var i=nbv(e),j=nbi(),h=nbi(),g="";this.divRemTo(i,j,h);while(j.signum()>0){g=(e+h.intValue()).toString(c).substr(1)+g;j.divRemTo(i,j,h)}return h.intValue().toString(c)+g}function bnpFromRadix(m,h){this.fromInt(0);if(h==null){h=10}var f=this.chunkSize(h);var g=Math.pow(h,f),e=false,a=0,l=0;for(var c=0;c=f){this.dMultiply(g);this.dAddOffset(l,0);a=0;l=0}}if(a>0){this.dMultiply(Math.pow(h,a));this.dAddOffset(l,0)}if(e){BigInteger.ZERO.subTo(this,this)}}function bnpFromNumber(f,e,h){if("number"==typeof e){if(f<2){this.fromInt(1)}else{this.fromNumber(f,h);if(!this.testBit(f-1)){this.bitwiseTo(BigInteger.ONE.shiftLeft(f-1),op_or,this)}if(this.isEven()){this.dAddOffset(1,0)}while(!this.isProbablePrime(e)){this.dAddOffset(2,0);if(this.bitLength()>f){this.subTo(BigInteger.ONE.shiftLeft(f-1),this)}}}}else{var d=new Array(),g=f&7;d.length=(f>>3)+1;e.nextBytes(d);if(g>0){d[0]&=((1<0){if(e>e)!=(this.s&this.DM)>>e){c[a++]=f|(this.s<<(this.DB-e))}while(b>=0){if(e<8){f=(this[b]&((1<>(e+=this.DB-8)}else{f=(this[b]>>(e-=8))&255;if(e<=0){e+=this.DB;--b}}if((f&128)!=0){f|=-256}if(a==0&&(this.s&128)!=(f&128)){++a}if(a>0||f!=this.s){c[a++]=f}}}return c}function bnEquals(b){return(this.compareTo(b)==0)}function bnMin(b){return(this.compareTo(b)<0)?this:b}function bnMax(b){return(this.compareTo(b)>0)?this:b}function bnpBitwiseTo(c,h,e){var d,g,b=Math.min(c.t,this.t);for(d=0;d>=16;b+=16}if((a&255)==0){a>>=8;b+=8}if((a&15)==0){a>>=4;b+=4}if((a&3)==0){a>>=2;b+=2}if((a&1)==0){++b}return b}function bnGetLowestSetBit(){for(var a=0;a=this.t){return(this.s!=0)}return((this[a]&(1<<(b%this.DB)))!=0)}function bnpChangeBit(c,b){var a=BigInteger.ONE.shiftLeft(c);this.bitwiseTo(a,b,a);return a}function bnSetBit(a){return this.changeBit(a,op_or)}function bnClearBit(a){return this.changeBit(a,op_andnot)}function bnFlipBit(a){return this.changeBit(a,op_xor)}function bnpAddTo(d,f){var e=0,g=0,b=Math.min(d.t,this.t);while(e>=this.DB}if(d.t>=this.DB}g+=this.s}else{g+=this.s;while(e>=this.DB}g+=d.s}f.s=(g<0)?-1:0;if(g>0){f[e++]=g}else{if(g<-1){f[e++]=this.DV+g}}f.t=e;f.clamp()}function bnAdd(b){var c=nbi();this.addTo(b,c);return c}function bnSubtract(b){var c=nbi();this.subTo(b,c);return c}function bnMultiply(b){var c=nbi();this.multiplyTo(b,c);return c}function bnSquare(){var a=nbi();this.squareTo(a);return a}function bnDivide(b){var c=nbi();this.divRemTo(b,c,null);return c}function bnRemainder(b){var c=nbi();this.divRemTo(b,null,c);return c}function bnDivideAndRemainder(b){var d=nbi(),c=nbi();this.divRemTo(b,d,c);return new Array(d,c)}function bnpDMultiply(a){this[this.t]=this.am(0,a-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(b,a){if(b==0){return}while(this.t<=a){this[this.t++]=0}this[a]+=b;while(this[a]>=this.DV){this[a]-=this.DV;if(++a>=this.t){this[this.t++]=0}++this[a]}}function NullExp(){}function nNop(a){return a}function nMulTo(a,c,b){a.multiplyTo(c,b)}function nSqrTo(a,b){a.squareTo(b)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(a){return this.exp(a,new NullExp())}function bnpMultiplyLowerTo(b,f,e){var d=Math.min(this.t+b.t,f);e.s=0;e.t=d;while(d>0){e[--d]=0}var c;for(c=e.t-this.t;d=0){d[c]=0}for(c=Math.max(e-this.t,0);c2*this.m.t){return a.mod(this.m)}else{if(a.compareTo(this.m)<0){return a}else{var b=nbi();a.copyTo(b);this.reduce(b);return b}}}function barrettRevert(a){return a}function barrettReduce(a){a.drShiftTo(this.m.t-1,this.r2);if(a.t>this.m.t+1){a.t=this.m.t+1;a.clamp()}this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(a.compareTo(this.r2)<0){a.dAddOffset(1,this.m.t+1)}a.subTo(this.r2,a);while(a.compareTo(this.m)>=0){a.subTo(this.m,a)}}function barrettSqrTo(a,b){a.squareTo(b);this.reduce(b)}function barrettMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(q,f){var o=q.bitLength(),h,b=nbv(1),v;if(o<=0){return b}else{if(o<18){h=1}else{if(o<48){h=3}else{if(o<144){h=4}else{if(o<768){h=5}else{h=6}}}}}if(o<8){v=new Classic(f)}else{if(f.isEven()){v=new Barrett(f)}else{v=new Montgomery(f)}}var p=new Array(),d=3,s=h-1,a=(1<1){var A=nbi();v.sqrTo(p[1],A);while(d<=a){p[d]=nbi();v.mulTo(A,p[d-2],p[d]);d+=2}}var l=q.t-1,x,u=true,c=nbi(),y;o=nbits(q[l])-1;while(l>=0){if(o>=s){x=(q[l]>>(o-s))&a}else{x=(q[l]&((1<<(o+1))-1))<<(s-o);if(l>0){x|=q[l-1]>>(this.DB+o-s)}}d=h;while((x&1)==0){x>>=1;--d}if((o-=d)<0){o+=this.DB;--l}if(u){p[x].copyTo(b);u=false}else{while(d>1){v.sqrTo(b,c);v.sqrTo(c,b);d-=2}if(d>0){v.sqrTo(b,c)}else{y=b;b=c;c=y}v.mulTo(c,p[x],b)}while(l>=0&&(q[l]&(1<0){b.rShiftTo(f,b);h.rShiftTo(f,h)}while(b.signum()>0){if((d=b.getLowestSetBit())>0){b.rShiftTo(d,b)}if((d=h.getLowestSetBit())>0){h.rShiftTo(d,h)}if(b.compareTo(h)>=0){b.subTo(h,b);b.rShiftTo(1,b)}else{h.subTo(b,h);h.rShiftTo(1,h)}}if(f>0){h.lShiftTo(f,h)}return h}function bnpModInt(e){if(e<=0){return 0}var c=this.DV%e,b=(this.s<0)?e-1:0;if(this.t>0){if(c==0){b=this[0]%e}else{for(var a=this.t-1;a>=0;--a){b=(c*b+this[a])%e}}}return b}function bnModInverse(f){var j=f.isEven();if((this.isEven()&&j)||f.signum()==0){return BigInteger.ZERO}var i=f.clone(),h=this.clone();var g=nbv(1),e=nbv(0),l=nbv(0),k=nbv(1);while(i.signum()!=0){while(i.isEven()){i.rShiftTo(1,i);if(j){if(!g.isEven()||!e.isEven()){g.addTo(this,g);e.subTo(f,e)}g.rShiftTo(1,g)}else{if(!e.isEven()){e.subTo(f,e)}}e.rShiftTo(1,e)}while(h.isEven()){h.rShiftTo(1,h);if(j){if(!l.isEven()||!k.isEven()){l.addTo(this,l);k.subTo(f,k)}l.rShiftTo(1,l)}else{if(!k.isEven()){k.subTo(f,k)}}k.rShiftTo(1,k)}if(i.compareTo(h)>=0){i.subTo(h,i);if(j){g.subTo(l,g)}e.subTo(k,e)}else{h.subTo(i,h);if(j){l.subTo(g,l)}k.subTo(e,k)}}if(h.compareTo(BigInteger.ONE)!=0){return BigInteger.ZERO}if(k.compareTo(f)>=0){return k.subtract(f)}if(k.signum()<0){k.addTo(f,k)}else{return k}if(k.signum()<0){return k.add(f)}else{return k}}var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(e){var d,b=this.abs();if(b.t==1&&b[0]<=lowprimes[lowprimes.length-1]){for(d=0;d>1;if(f>lowprimes.length){f=lowprimes.length}var b=nbi();for(var e=0;e>8)&255;rng_pool[rng_pptr++]^=(a>>16)&255;rng_pool[rng_pptr++]^=(a>>24)&255;if(rng_pptr>=rng_psize){rng_pptr-=rng_psize}}function rng_seed_time(){rng_seed_int(new Date().getTime())}if(rng_pool==null){rng_pool=new Array();rng_pptr=0;var t;if(navigator.appName=="Netscape"&&navigator.appVersion<"5"&&window.crypto){var z=window.crypto.random(32);for(t=0;t>>8;rng_pool[rng_pptr++]=t&255}rng_pptr=0;rng_seed_time()}function rng_get_byte(){if(rng_state==null){rng_seed_time();rng_state=prng_newstate();rng_state.init(rng_pool);for(rng_pptr=0;rng_pptr=0&&h>0){var f=e.charCodeAt(d--);if(f<128){g[--h]=f}else{if((f>127)&&(f<2048)){g[--h]=(f&63)|128;g[--h]=(f>>6)|192}else{g[--h]=(f&63)|128;g[--h]=((f>>6)&63)|128;g[--h]=(f>>12)|224}}}g[--h]=0;var b=new SecureRandom();var a=new Array();while(h>2){a[0]=0;while(a[0]==0){b.nextBytes(a)}g[--h]=a[0]}g[--h]=2;g[--h]=0;return new BigInteger(g)}function oaep_mgf1_arr(c,a,e){var b="",d=0;while(b.length>24,(d&16711680)>>16,(d&65280)>>8,d&255])));d+=1}return b}var SHA1_SIZE=20;function oaep_pad(l,a,c){if(l.length+2*SHA1_SIZE+2>a){throw"Message too long for RSA"}var h="",d;for(d=0;d0&&a.length>0){this.n=parseBigInt(b,16);this.e=parseInt(a,16)}else{alert("Invalid RSA public key")}}}function RSADoPublic(a){return a.modPowInt(this.e,this.n)}function RSAEncrypt(d){var a=pkcs1pad2(d,(this.n.bitLength()+7)>>3);if(a==null){return null}var e=this.doPublic(a);if(e==null){return null}var b=e.toString(16);if((b.length&1)==0){return b}else{return"0"+b}}function RSAEncryptOAEP(e,d){var a=oaep_pad(e,(this.n.bitLength()+7)>>3,d);if(a==null){return null}var f=this.doPublic(a);if(f==null){return null}var b=f.toString(16);if((b.length&1)==0){return b}else{return"0"+b}}RSAKey.prototype.doPublic=RSADoPublic;RSAKey.prototype.setPublic=RSASetPublic;RSAKey.prototype.encrypt=RSAEncrypt;RSAKey.prototype.encryptOAEP=RSAEncryptOAEP;RSAKey.prototype.type="RSA"; +/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ + */ +function pkcs1unpad2(g,j){var a=g.toByteArray();var f=0;while(f=a.length){return null}}var e="";while(++f191)&&(h<224)){e+=String.fromCharCode(((h&31)<<6)|(a[f+1]&63));++f}else{e+=String.fromCharCode(((h&15)<<12)|((a[f+1]&63)<<6)|(a[f+2]&63));f+=2}}}return e}function oaep_mgf1_str(c,a,e){var b="",d=0;while(b.length>24,(d&16711680)>>16,(d&65280)>>8,d&255]));d+=1}return b}var SHA1_SIZE=20;function oaep_unpad(l,b,e){l=l.toByteArray();var f;for(f=0;f0&&a.length>0){this.n=parseBigInt(c,16);this.e=parseInt(a,16);this.d=parseBigInt(b,16)}else{alert("Invalid RSA private key")}}}function RSASetPrivateEx(g,d,e,c,b,a,h,f){this.isPrivate=true;if(g==null){throw"RSASetPrivateEx N == null"}if(d==null){throw"RSASetPrivateEx E == null"}if(g.length==0){throw"RSASetPrivateEx N.length == 0"}if(d.length==0){throw"RSASetPrivateEx E.length == 0"}if(g!=null&&d!=null&&g.length>0&&d.length>0){this.n=parseBigInt(g,16);this.e=parseInt(d,16);this.d=parseBigInt(e,16);this.p=parseBigInt(c,16);this.q=parseBigInt(b,16);this.dmp1=parseBigInt(a,16);this.dmq1=parseBigInt(h,16);this.coeff=parseBigInt(f,16)}else{alert("Invalid RSA private key in RSASetPrivateEx")}}function RSAGenerate(b,i){var a=new SecureRandom();var f=b>>1;this.e=parseInt(i,16);var c=new BigInteger(i,16);for(;;){for(;;){this.p=new BigInteger(b-f,1,a);if(this.p.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE)==0&&this.p.isProbablePrime(10)){break}}for(;;){this.q=new BigInteger(f,1,a);if(this.q.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE)==0&&this.q.isProbablePrime(10)){break}}if(this.p.compareTo(this.q)<=0){var h=this.p;this.p=this.q;this.q=h}var g=this.p.subtract(BigInteger.ONE);var d=this.q.subtract(BigInteger.ONE);var e=g.multiply(d);if(e.gcd(c).compareTo(BigInteger.ONE)==0){this.n=this.p.multiply(this.q);this.d=c.modInverse(e);this.dmp1=this.d.mod(g);this.dmq1=this.d.mod(d);this.coeff=this.q.modInverse(this.p);break}}}function RSADoPrivate(a){if(this.p==null||this.q==null){return a.modPow(this.d,this.n)}var c=a.mod(this.p).modPow(this.dmp1,this.p);var b=a.mod(this.q).modPow(this.dmq1,this.q);while(c.compareTo(b)<0){c=c.add(this.p)}return c.subtract(b).multiply(this.coeff).mod(this.p).multiply(this.q).add(b)}function RSADecrypt(b){var d=parseBigInt(b,16);var a=this.doPrivate(d);if(a==null){return null}return pkcs1unpad2(a,(this.n.bitLength()+7)>>3)}function RSADecryptOAEP(d,b){var e=parseBigInt(d,16);var a=this.doPrivate(e);if(a==null){return null}return oaep_unpad(a,(this.n.bitLength()+7)>>3,b)}RSAKey.prototype.doPrivate=RSADoPrivate;RSAKey.prototype.setPrivate=RSASetPrivate;RSAKey.prototype.setPrivateEx=RSASetPrivateEx;RSAKey.prototype.generate=RSAGenerate;RSAKey.prototype.decrypt=RSADecrypt;RSAKey.prototype.decryptOAEP=RSADecryptOAEP; +/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ + */ +function ECFieldElementFp(b,a){this.x=a;this.q=b}function feFpEquals(a){if(a==this){return true}return(this.q.equals(a.q)&&this.x.equals(a.x))}function feFpToBigInteger(){return this.x}function feFpNegate(){return new ECFieldElementFp(this.q,this.x.negate().mod(this.q))}function feFpAdd(a){return new ECFieldElementFp(this.q,this.x.add(a.toBigInteger()).mod(this.q))}function feFpSubtract(a){return new ECFieldElementFp(this.q,this.x.subtract(a.toBigInteger()).mod(this.q))}function feFpMultiply(a){return new ECFieldElementFp(this.q,this.x.multiply(a.toBigInteger()).mod(this.q))}function feFpSquare(){return new ECFieldElementFp(this.q,this.x.square().mod(this.q))}function feFpDivide(a){return new ECFieldElementFp(this.q,this.x.multiply(a.toBigInteger().modInverse(this.q)).mod(this.q))}ECFieldElementFp.prototype.equals=feFpEquals;ECFieldElementFp.prototype.toBigInteger=feFpToBigInteger;ECFieldElementFp.prototype.negate=feFpNegate;ECFieldElementFp.prototype.add=feFpAdd;ECFieldElementFp.prototype.subtract=feFpSubtract;ECFieldElementFp.prototype.multiply=feFpMultiply;ECFieldElementFp.prototype.square=feFpSquare;ECFieldElementFp.prototype.divide=feFpDivide;function ECPointFp(c,a,d,b){this.curve=c;this.x=a;this.y=d;if(b==null){this.z=BigInteger.ONE}else{this.z=b}this.zinv=null}function pointFpGetX(){if(this.zinv==null){this.zinv=this.z.modInverse(this.curve.q)}return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpGetY(){if(this.zinv==null){this.zinv=this.z.modInverse(this.curve.q)}return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpEquals(a){if(a==this){return true}if(this.isInfinity()){return a.isInfinity()}if(a.isInfinity()){return this.isInfinity()}var c,b;c=a.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(a.z)).mod(this.curve.q);if(!c.equals(BigInteger.ZERO)){return false}b=a.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(a.z)).mod(this.curve.q);return b.equals(BigInteger.ZERO)}function pointFpIsInfinity(){if((this.x==null)&&(this.y==null)){return true}return this.z.equals(BigInteger.ZERO)&&!this.y.toBigInteger().equals(BigInteger.ZERO)}function pointFpNegate(){return new ECPointFp(this.curve,this.x,this.y.negate(),this.z)}function pointFpAdd(l){if(this.isInfinity()){return l}if(l.isInfinity()){return this}var p=l.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(l.z)).mod(this.curve.q);var o=l.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(l.z)).mod(this.curve.q);if(BigInteger.ZERO.equals(o)){if(BigInteger.ZERO.equals(p)){return this.twice()}return this.curve.getInfinity()}var j=new BigInteger("3");var e=this.x.toBigInteger();var n=this.y.toBigInteger();var c=l.x.toBigInteger();var k=l.y.toBigInteger();var m=o.square();var i=m.multiply(o);var d=e.multiply(m);var g=p.square().multiply(this.z);var a=g.subtract(d.shiftLeft(1)).multiply(l.z).subtract(i).multiply(o).mod(this.curve.q);var h=d.multiply(j).multiply(p).subtract(n.multiply(i)).subtract(g.multiply(p)).multiply(l.z).add(p.multiply(i)).mod(this.curve.q);var f=i.multiply(this.z).multiply(l.z).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(h),f)}function pointFpTwice(){if(this.isInfinity()){return this}if(this.y.toBigInteger().signum()==0){return this.curve.getInfinity()}var g=new BigInteger("3");var c=this.x.toBigInteger();var h=this.y.toBigInteger();var e=h.multiply(this.z);var j=e.multiply(h).mod(this.curve.q);var i=this.curve.a.toBigInteger();var k=c.square().multiply(g);if(!BigInteger.ZERO.equals(i)){k=k.add(this.z.square().multiply(i))}k=k.mod(this.curve.q);var b=k.square().subtract(c.shiftLeft(3).multiply(j)).shiftLeft(1).multiply(e).mod(this.curve.q);var f=k.multiply(g).multiply(c).subtract(j.shiftLeft(1)).shiftLeft(2).multiply(j).subtract(k.square().multiply(k)).mod(this.curve.q);var d=e.square().multiply(e).shiftLeft(3).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(b),this.curve.fromBigInteger(f),d)}function pointFpMultiply(b){if(this.isInfinity()){return this}if(b.signum()==0){return this.curve.getInfinity()}var g=b;var f=g.multiply(new BigInteger("3"));var l=this.negate();var d=this;var c;for(c=f.bitLength()-2;c>0;--c){d=d.twice();var a=f.testBit(c);var j=g.testBit(c);if(a!=j){d=d.add(a?this:l)}}return d}function pointFpMultiplyTwo(c,a,b){var d;if(c.bitLength()>b.bitLength()){d=c.bitLength()-1}else{d=b.bitLength()-1}var f=this.curve.getInfinity();var e=this.add(a);while(d>=0){f=f.twice();if(c.testBit(d)){if(b.testBit(d)){f=f.add(e)}else{f=f.add(this)}}else{if(b.testBit(d)){f=f.add(a)}}--d}return f}ECPointFp.prototype.getX=pointFpGetX;ECPointFp.prototype.getY=pointFpGetY;ECPointFp.prototype.equals=pointFpEquals;ECPointFp.prototype.isInfinity=pointFpIsInfinity;ECPointFp.prototype.negate=pointFpNegate;ECPointFp.prototype.add=pointFpAdd;ECPointFp.prototype.twice=pointFpTwice;ECPointFp.prototype.multiply=pointFpMultiply;ECPointFp.prototype.multiplyTwo=pointFpMultiplyTwo;function ECCurveFp(e,d,c){this.q=e;this.a=this.fromBigInteger(d);this.b=this.fromBigInteger(c);this.infinity=new ECPointFp(this,null,null)}function curveFpGetQ(){return this.q}function curveFpGetA(){return this.a}function curveFpGetB(){return this.b}function curveFpEquals(a){if(a==this){return true}return(this.q.equals(a.q)&&this.a.equals(a.a)&&this.b.equals(a.b))}function curveFpGetInfinity(){return this.infinity}function curveFpFromBigInteger(a){return new ECFieldElementFp(this.q,a)}function curveFpDecodePointHex(d){switch(parseInt(d.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:return null;case 4:case 6:case 7:var a=(d.length-2)/2;var c=d.substr(2,a);var b=d.substr(a+2,a);return new ECPointFp(this,this.fromBigInteger(new BigInteger(c,16)),this.fromBigInteger(new BigInteger(b,16)));default:return null}}ECCurveFp.prototype.getQ=curveFpGetQ;ECCurveFp.prototype.getA=curveFpGetA;ECCurveFp.prototype.getB=curveFpGetB;ECCurveFp.prototype.equals=curveFpEquals;ECCurveFp.prototype.getInfinity=curveFpGetInfinity;ECCurveFp.prototype.fromBigInteger=curveFpFromBigInteger;ECCurveFp.prototype.decodePointHex=curveFpDecodePointHex; +/*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib + */ +ECFieldElementFp.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)};ECPointFp.prototype.getEncoded=function(c){var d=function(h,f){var g=h.toByteArrayUnsigned();if(fg.length){g.unshift(0)}}return g};var a=this.getX().toBigInteger();var e=this.getY().toBigInteger();var b=d(a,32);if(c){if(e.isEven()){b.unshift(2)}else{b.unshift(3)}}else{b.unshift(4);b=b.concat(d(e,32))}return b};ECPointFp.decodeFrom=function(g,c){var f=c[0];var e=c.length-1;var d=c.slice(1,1+e/2);var b=c.slice(1+e/2,1+e);d.unshift(0);b.unshift(0);var a=new BigInteger(d);var h=new BigInteger(b);return new ECPointFp(g,g.fromBigInteger(a),g.fromBigInteger(h))};ECPointFp.decodeFromHex=function(g,c){var f=c.substr(0,2);var e=c.length-2;var d=c.substr(2,e/2);var b=c.substr(2+e/2,e/2);var a=new BigInteger(d,16);var h=new BigInteger(b,16);return new ECPointFp(g,g.fromBigInteger(a),g.fromBigInteger(h))};ECPointFp.prototype.add2D=function(c){if(this.isInfinity()){return c}if(c.isInfinity()){return this}if(this.x.equals(c.x)){if(this.y.equals(c.y)){return this.twice()}return this.curve.getInfinity()}var g=c.x.subtract(this.x);var e=c.y.subtract(this.y);var a=e.divide(g);var d=a.square().subtract(this.x).subtract(c.x);var f=a.multiply(this.x.subtract(d)).subtract(this.y);return new ECPointFp(this.curve,d,f)};ECPointFp.prototype.twice2D=function(){if(this.isInfinity()){return this}if(this.y.toBigInteger().signum()==0){return this.curve.getInfinity()}var b=this.curve.fromBigInteger(BigInteger.valueOf(2));var e=this.curve.fromBigInteger(BigInteger.valueOf(3));var a=this.x.square().multiply(e).add(this.curve.a).divide(this.y.multiply(b));var c=a.square().subtract(this.x.multiply(b));var d=a.multiply(this.x.subtract(c)).subtract(this.y);return new ECPointFp(this.curve,c,d)};ECPointFp.prototype.multiply2D=function(b){if(this.isInfinity()){return this}if(b.signum()==0){return this.curve.getInfinity()}var g=b;var f=g.multiply(new BigInteger("3"));var l=this.negate();var d=this;var c;for(c=f.bitLength()-2;c>0;--c){d=d.twice();var a=f.testBit(c);var j=g.testBit(c);if(a!=j){d=d.add2D(a?this:l)}}return d};ECPointFp.prototype.isOnCurve=function(){var d=this.getX().toBigInteger();var i=this.getY().toBigInteger();var f=this.curve.getA().toBigInteger();var c=this.curve.getB().toBigInteger();var h=this.curve.getQ();var e=i.multiply(i).mod(h);var g=d.multiply(d).multiply(d).add(f.multiply(d)).add(c).mod(h);return e.equals(g)};ECPointFp.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"};ECPointFp.prototype.validate=function(){var c=this.curve.getQ();if(this.isInfinity()){throw new Error("Point is at infinity.")}var a=this.getX().toBigInteger();var b=this.getY().toBigInteger();if(a.compareTo(BigInteger.ONE)<0||a.compareTo(c.subtract(BigInteger.ONE))>0){throw new Error("x coordinate out of bounds")}if(b.compareTo(BigInteger.ONE)<0||b.compareTo(c.subtract(BigInteger.ONE))>0){throw new Error("y coordinate out of bounds")}if(!this.isOnCurve()){throw new Error("Point is not on the curve.")}if(this.multiply(c).isInfinity()){throw new Error("Point is not a scalar multiple of G.")}return true}; +/*! asn1-1.0.4.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(a){var b=a.toString(16);if((b.length%2)==1){b="0"+b}return b};this.bigIntToMinTwosComplementsHex=function(j){var f=j.toString(16);if(f.substr(0,1)!="-"){if(f.length%2==1){f="0"+f}else{if(!f.match(/^[0-7]/)){f="00"+f}}}else{var a=f.substr(1);var e=a.length;if(e%2==1){e+=1}else{if(!f.match(/^[0-7]/)){e+=2}}var g="";for(var d=0;d15){throw"ASN.1 length too long to represent by 8x: n = "+i.toString(16)}var f=128+g;return f.toString(16)+h}};this.getEncodedHex=function(){if(this.hTLV==null||this.isModified){this.hV=this.getFreshValueHex();this.hL=this.getLengthHexFromValue();this.hTLV=this.hT+this.hL+this.hV;this.isModified=false}return this.hTLV};this.getValueHex=function(){this.getEncodedHex();return this.hV};this.getFreshValueHex=function(){return""}};KJUR.asn1.DERAbstractString=function(c){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);var b=null;var a=null;this.getString=function(){return this.s};this.setString=function(d){this.hTLV=null;this.isModified=true;this.s=d;this.hV=stohex(this.s)};this.setStringHex=function(d){this.hTLV=null;this.isModified=true;this.s=null;this.hV=d};this.getFreshValueHex=function(){return this.hV};if(typeof c!="undefined"){if(typeof c=="string"){this.setString(c)}else{if(typeof c.str!="undefined"){this.setString(c.str)}else{if(typeof c.hex!="undefined"){this.setStringHex(c.hex)}}}}};YAHOO.lang.extend(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractTime=function(c){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);var b=null;var a=null;this.localDateToUTC=function(f){utc=f.getTime()+(f.getTimezoneOffset()*60000);var e=new Date(utc);return e};this.formatDate=function(j,l){var e=this.zeroPadding;var k=this.localDateToUTC(j);var m=String(k.getFullYear());if(l=="utc"){m=m.substr(2,2)}var i=e(String(k.getMonth()+1),2);var n=e(String(k.getDate()),2);var f=e(String(k.getHours()),2);var g=e(String(k.getMinutes()),2);var h=e(String(k.getSeconds()),2);return m+i+n+f+g+h+"Z"};this.zeroPadding=function(e,d){if(e.length>=d){return e}return new Array(d-e.length+1).join("0")+e};this.getString=function(){return this.s};this.setString=function(d){this.hTLV=null;this.isModified=true;this.s=d;this.hV=stohex(d)};this.setByDateValue=function(h,j,e,d,f,g){var i=new Date(Date.UTC(h,j-1,e,d,f,g,0));this.setByDate(i)};this.getFreshValueHex=function(){return this.hV}};YAHOO.lang.extend(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractStructured=function(b){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);var a=null;this.setByASN1ObjectArray=function(c){this.hTLV=null;this.isModified=true;this.asn1Array=c};this.appendASN1Object=function(c){this.hTLV=null;this.isModified=true;this.asn1Array.push(c)};this.asn1Array=new Array();if(typeof b!="undefined"){if(typeof b.array!="undefined"){this.asn1Array=b.array}}};YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object);KJUR.asn1.DERBoolean=function(){KJUR.asn1.DERBoolean.superclass.constructor.call(this);this.hT="01";this.hTLV="0101ff"};YAHOO.lang.extend(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object);KJUR.asn1.DERInteger=function(a){KJUR.asn1.DERInteger.superclass.constructor.call(this);this.hT="02";this.setByBigInteger=function(b){this.hTLV=null;this.isModified=true;this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(b)};this.setByInteger=function(c){var b=new BigInteger(String(c),10);this.setByBigInteger(b)};this.setValueHex=function(b){this.hV=b};this.getFreshValueHex=function(){return this.hV};if(typeof a!="undefined"){if(typeof a.bigint!="undefined"){this.setByBigInteger(a.bigint)}else{if(typeof a["int"]!="undefined"){this.setByInteger(a["int"])}else{if(typeof a=="number"){this.setByInteger(a)}else{if(typeof a.hex!="undefined"){this.setValueHex(a.hex)}}}}}};YAHOO.lang.extend(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object);KJUR.asn1.DERBitString=function(a){KJUR.asn1.DERBitString.superclass.constructor.call(this);this.hT="03";this.setHexValueIncludingUnusedBits=function(b){this.hTLV=null;this.isModified=true;this.hV=b};this.setUnusedBitsAndHexValue=function(b,d){if(b<0||7=(b*2))){break}if(d>=200){break}c.push(e);g=e;d++}return c};this.getNthChildIndex_AtObj=function(d,b,e){var c=this.getPosArrayOfChildren_AtObj(d,b);return c[e]};this.getDecendantIndexByNthList=function(e,d,c){if(c.length==0){return d}var f=c.shift();var b=this.getPosArrayOfChildren_AtObj(e,d);return this.getDecendantIndexByNthList(e,b[f],c)};this.getDecendantHexTLVByNthList=function(d,c,b){var a=this.getDecendantIndexByNthList(d,c,b);return this.getHexOfTLV_AtObj(d,a)};this.getDecendantHexVByNthList=function(d,c,b){var a=this.getDecendantIndexByNthList(d,c,b);return this.getHexOfV_AtObj(d,a)}};ASN1HEX.getVbyList=function(d,c,b,e){var a=this.getDecendantIndexByNthList(d,c,b);if(a===undefined){throw"can't find nthList object"}if(e!==undefined){if(d.substr(a,2)!=e){throw"checking tag doesn't match: "+d.substr(a,2)+"!="+e}}return this.getHexOfV_AtObj(d,a)}; +/*! asn1x509-1.0.7.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}if(typeof KJUR.asn1.x509=="undefined"||!KJUR.asn1.x509){KJUR.asn1.x509={}}KJUR.asn1.x509.Certificate=function(g){KJUR.asn1.x509.Certificate.superclass.constructor.call(this);var b=null;var d=null;var f=null;var c=null;var a=null;var e=null;this.setRsaPrvKeyByPEMandPass=function(i,k){var h=PKCS5PKEY.getDecryptedKeyHex(i,k);var j=new RSAKey();j.readPrivateKeyFromASN1HexString(h);this.prvKey=j};this.sign=function(){this.asn1SignatureAlg=this.asn1TBSCert.asn1SignatureAlg;sig=new KJUR.crypto.Signature({alg:"SHA1withRSA"});sig.init(this.prvKey);sig.updateHex(this.asn1TBSCert.getEncodedHex());this.hexSig=sig.sign();this.asn1Sig=new KJUR.asn1.DERBitString({hex:"00"+this.hexSig});var h=new KJUR.asn1.DERSequence({array:[this.asn1TBSCert,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=h.getEncodedHex();this.isModified=false};this.getEncodedHex=function(){if(this.isModified==false&&this.hTLV!=null){return this.hTLV}throw"not signed yet"};this.getPEMString=function(){var j=this.getEncodedHex();var h=CryptoJS.enc.Hex.parse(j);var i=CryptoJS.enc.Base64.stringify(h);var k=i.replace(/(.{64})/g,"$1\r\n");return"-----BEGIN CERTIFICATE-----\r\n"+k+"\r\n-----END CERTIFICATE-----\r\n"};if(typeof g!="undefined"){if(typeof g.tbscertobj!="undefined"){this.asn1TBSCert=g.tbscertobj}if(typeof g.prvkeyobj!="undefined"){this.prvKey=g.prvkeyobj}else{if(typeof g.rsaprvkey!="undefined"){this.prvKey=g.rsaprvkey}else{if((typeof g.rsaprvpem!="undefined")&&(typeof g.rsaprvpas!="undefined")){this.setRsaPrvKeyByPEMandPass(g.rsaprvpem,g.rsaprvpas)}}}}};YAHOO.lang.extend(KJUR.asn1.x509.Certificate,KJUR.asn1.ASN1Object);KJUR.asn1.x509.TBSCertificate=function(a){KJUR.asn1.x509.TBSCertificate.superclass.constructor.call(this);this._initialize=function(){this.asn1Array=new Array();this.asn1Version=new KJUR.asn1.DERTaggedObject({obj:new KJUR.asn1.DERInteger({"int":2})});this.asn1SerialNumber=null;this.asn1SignatureAlg=null;this.asn1Issuer=null;this.asn1NotBefore=null;this.asn1NotAfter=null;this.asn1Subject=null;this.asn1SubjPKey=null;this.extensionsArray=new Array()};this.setSerialNumberByParam=function(b){this.asn1SerialNumber=new KJUR.asn1.DERInteger(b)};this.setSignatureAlgByParam=function(b){this.asn1SignatureAlg=new KJUR.asn1.x509.AlgorithmIdentifier(b)};this.setIssuerByParam=function(b){this.asn1Issuer=new KJUR.asn1.x509.X500Name(b)};this.setNotBeforeByParam=function(b){this.asn1NotBefore=new KJUR.asn1.x509.Time(b)};this.setNotAfterByParam=function(b){this.asn1NotAfter=new KJUR.asn1.x509.Time(b)};this.setSubjectByParam=function(b){this.asn1Subject=new KJUR.asn1.x509.X500Name(b)};this.setSubjectPublicKeyByParam=function(b){this.asn1SubjPKey=new KJUR.asn1.x509.SubjectPublicKeyInfo(b)};this.setSubjectPublicKeyByGetKey=function(c){var b=KEYUTIL.getKey(c);this.asn1SubjPKey=new KJUR.asn1.x509.SubjectPublicKeyInfo(b)};this.appendExtension=function(b){this.extensionsArray.push(b)};this.appendExtensionByName=function(d,b){if(d.toLowerCase()=="basicconstraints"){var c=new KJUR.asn1.x509.BasicConstraints(b);this.appendExtension(c)}else{if(d.toLowerCase()=="keyusage"){var c=new KJUR.asn1.x509.KeyUsage(b);this.appendExtension(c)}else{if(d.toLowerCase()=="crldistributionpoints"){var c=new KJUR.asn1.x509.CRLDistributionPoints(b);this.appendExtension(c)}else{if(d.toLowerCase()=="extkeyusage"){var c=new KJUR.asn1.x509.ExtKeyUsage(b);this.appendExtension(c)}else{throw"unsupported extension name: "+d}}}}};this.getEncodedHex=function(){if(this.asn1NotBefore==null||this.asn1NotAfter==null){throw"notBefore and/or notAfter not set"}var c=new KJUR.asn1.DERSequence({array:[this.asn1NotBefore,this.asn1NotAfter]});this.asn1Array=new Array();this.asn1Array.push(this.asn1Version);this.asn1Array.push(this.asn1SerialNumber);this.asn1Array.push(this.asn1SignatureAlg);this.asn1Array.push(this.asn1Issuer);this.asn1Array.push(c);this.asn1Array.push(this.asn1Subject);this.asn1Array.push(this.asn1SubjPKey);if(this.extensionsArray.length>0){var d=new KJUR.asn1.DERSequence({array:this.extensionsArray});var b=new KJUR.asn1.DERTaggedObject({explicit:true,tag:"a3",obj:d});this.asn1Array.push(b)}var e=new KJUR.asn1.DERSequence({array:this.asn1Array});this.hTLV=e.getEncodedHex();this.isModified=false;return this.hTLV};this._initialize()};YAHOO.lang.extend(KJUR.asn1.x509.TBSCertificate,KJUR.asn1.ASN1Object);KJUR.asn1.x509.Extension=function(b){KJUR.asn1.x509.Extension.superclass.constructor.call(this);var a=null;this.getEncodedHex=function(){var f=new KJUR.asn1.DERObjectIdentifier({oid:this.oid});var e=new KJUR.asn1.DEROctetString({hex:this.getExtnValueHex()});var d=new Array();d.push(f);if(this.critical){d.push(new KJUR.asn1.DERBoolean())}d.push(e);var c=new KJUR.asn1.DERSequence({array:d});return c.getEncodedHex()};this.critical=false;if(typeof b!="undefined"){if(typeof b.critical!="undefined"){this.critical=b.critical}}};YAHOO.lang.extend(KJUR.asn1.x509.Extension,KJUR.asn1.ASN1Object);KJUR.asn1.x509.KeyUsage=function(a){KJUR.asn1.x509.KeyUsage.superclass.constructor.call(this,a);this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.15";if(typeof a!="undefined"){if(typeof a.bin!="undefined"){this.asn1ExtnValue=new KJUR.asn1.DERBitString(a)}}};YAHOO.lang.extend(KJUR.asn1.x509.KeyUsage,KJUR.asn1.x509.Extension);KJUR.asn1.x509.BasicConstraints=function(c){KJUR.asn1.x509.BasicConstraints.superclass.constructor.call(this,c);var a=false;var b=-1;this.getExtnValueHex=function(){var e=new Array();if(this.cA){e.push(new KJUR.asn1.DERBoolean())}if(this.pathLen>-1){e.push(new KJUR.asn1.DERInteger({"int":this.pathLen}))}var d=new KJUR.asn1.DERSequence({array:e});this.asn1ExtnValue=d;return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.19";this.cA=false;this.pathLen=-1;if(typeof c!="undefined"){if(typeof c.cA!="undefined"){this.cA=c.cA}if(typeof c.pathLen!="undefined"){this.pathLen=c.pathLen}}};YAHOO.lang.extend(KJUR.asn1.x509.BasicConstraints,KJUR.asn1.x509.Extension);KJUR.asn1.x509.CRLDistributionPoints=function(a){KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,a);this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.setByDPArray=function(b){this.asn1ExtnValue=new KJUR.asn1.DERSequence({array:b})};this.setByOneURI=function(e){var b=new KJUR.asn1.x509.GeneralNames([{uri:e}]);var d=new KJUR.asn1.x509.DistributionPointName(b);var c=new KJUR.asn1.x509.DistributionPoint({dpobj:d});this.setByDPArray([c])};this.oid="2.5.29.31";if(typeof a!="undefined"){if(typeof a.array!="undefined"){this.setByDPArray(a.array)}else{if(typeof a.uri!="undefined"){this.setByOneURI(a.uri)}}}};YAHOO.lang.extend(KJUR.asn1.x509.CRLDistributionPoints,KJUR.asn1.x509.Extension);KJUR.asn1.x509.ExtKeyUsage=function(a){KJUR.asn1.x509.ExtKeyUsage.superclass.constructor.call(this,a);this.setPurposeArray=function(b){this.asn1ExtnValue=new KJUR.asn1.DERSequence();for(var c=0;c0){var c=new KJUR.asn1.DERSequence({array:this.aRevokedCert});this.asn1Array.push(c)}var d=new KJUR.asn1.DERSequence({array:this.asn1Array});this.hTLV=d.getEncodedHex();this.isModified=false;return this.hTLV};this._initialize=function(){this.asn1Version=null;this.asn1SignatureAlg=null;this.asn1Issuer=null;this.asn1ThisUpdate=null;this.asn1NextUpdate=null;this.aRevokedCert=new Array()};this._initialize()};YAHOO.lang.extend(KJUR.asn1.x509.TBSCertList,KJUR.asn1.ASN1Object);KJUR.asn1.x509.CRLEntry=function(c){KJUR.asn1.x509.CRLEntry.superclass.constructor.call(this);var b=null;var a=null;this.setCertSerial=function(d){this.sn=new KJUR.asn1.DERInteger(d)};this.setRevocationDate=function(d){this.time=new KJUR.asn1.x509.Time(d)};this.getEncodedHex=function(){var d=new KJUR.asn1.DERSequence({array:[this.sn,this.time]});this.TLV=d.getEncodedHex();return this.TLV};if(typeof c!="undefined"){if(typeof c.time!="undefined"){this.setRevocationDate(c.time)}if(typeof c.sn!="undefined"){this.setCertSerial(c.sn)}}};YAHOO.lang.extend(KJUR.asn1.x509.CRLEntry,KJUR.asn1.ASN1Object);KJUR.asn1.x509.X500Name=function(a){KJUR.asn1.x509.X500Name.superclass.constructor.call(this);this.asn1Array=new Array();this.setByString=function(b){var c=b.split("/");c.shift();for(var d=0;dd){throw"key is too short for SigAlg: keylen="+j+","+a}var b="0001";var k="00"+c;var g="";var l=d-b.length-k.length;for(var f=0;f=0;--p){q=q.twice2D();q.z=BigInteger.ONE;if(o.testBit(p)){if(n.testBit(p)){q=q.add2D(t)}else{q=q.add2D(s)}}else{if(n.testBit(p)){q=q.add2D(r)}}}return q}this.getBigRandom=function(i){return new BigInteger(i.bitLength(),a).mod(i.subtract(BigInteger.ONE)).add(BigInteger.ONE)};this.setNamedCurve=function(i){this.ecparams=KJUR.crypto.ECParameterDB.getByName(i);this.prvKeyHex=null;this.pubKeyHex=null;this.curveName=i};this.setPrivateKeyHex=function(i){this.isPrivate=true;this.prvKeyHex=i};this.setPublicKeyHex=function(i){this.isPublic=true;this.pubKeyHex=i};this.generateKeyPairHex=function(){var k=this.ecparams.n;var n=this.getBigRandom(k);var l=this.ecparams.G.multiply(n);var q=l.getX().toBigInteger();var o=l.getY().toBigInteger();var i=this.ecparams.keylen/4;var m=("0000000000"+n.toString(16)).slice(-i);var r=("0000000000"+q.toString(16)).slice(-i);var p=("0000000000"+o.toString(16)).slice(-i);var j="04"+r+p;this.setPrivateKeyHex(m);this.setPublicKeyHex(j);return{ecprvhex:m,ecpubhex:j}};this.signWithMessageHash=function(i){return this.signHex(i,this.prvKeyHex)};this.signHex=function(o,j){var t=new BigInteger(j,16);var l=this.ecparams.n;var q=new BigInteger(o,16);do{var m=this.getBigRandom(l);var u=this.ecparams.G;var p=u.multiply(m);var i=p.getX().toBigInteger().mod(l)}while(i.compareTo(BigInteger.ZERO)<=0);var v=m.modInverse(l).multiply(q.add(t.multiply(i))).mod(l);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(i,v)};this.sign=function(m,u){var q=u;var j=this.ecparams.n;var p=BigInteger.fromByteArrayUnsigned(m);do{var l=this.getBigRandom(j);var t=this.ecparams.G;var o=t.multiply(l);var i=o.getX().toBigInteger().mod(j)}while(i.compareTo(BigInteger.ZERO)<=0);var v=l.modInverse(j).multiply(p.add(q.multiply(i))).mod(j);return this.serializeSig(i,v)};this.verifyWithMessageHash=function(j,i){return this.verifyHex(j,i,this.pubKeyHex)};this.verifyHex=function(m,i,p){var l,j;var o=KJUR.crypto.ECDSA.parseSigHex(i);l=o.r;j=o.s;var k;k=ECPointFp.decodeFromHex(this.ecparams.curve,p);var n=new BigInteger(m,16);return this.verifyRaw(n,l,j,k)};this.verify=function(o,p,j){var l,i;if(Bitcoin.Util.isArray(p)){var n=this.parseSig(p);l=n.r;i=n.s}else{if("object"===typeof p&&p.r&&p.s){l=p.r;i=p.s}else{throw"Invalid value for signature"}}var k;if(j instanceof ECPointFp){k=j}else{if(Bitcoin.Util.isArray(j)){k=ECPointFp.decodeFrom(this.ecparams.curve,j)}else{throw"Invalid format for pubkey value, must be byte array or ECPointFp"}}var m=BigInteger.fromByteArrayUnsigned(o);return this.verifyRaw(m,l,i,k)};this.verifyRaw=function(o,i,w,m){var l=this.ecparams.n;var u=this.ecparams.G;if(i.compareTo(BigInteger.ONE)<0||i.compareTo(l)>=0){return false}if(w.compareTo(BigInteger.ONE)<0||w.compareTo(l)>=0){return false}var p=w.modInverse(l);var k=o.multiply(p).mod(l);var j=i.multiply(p).mod(l);var q=u.multiply(k).add(m.multiply(j));var t=q.getX().toBigInteger().mod(l);return t.equals(i)};this.serializeSig=function(k,j){var l=k.toByteArraySigned();var i=j.toByteArraySigned();var m=[];m.push(2);m.push(l.length);m=m.concat(l);m.push(2);m.push(i.length);m=m.concat(i);m.unshift(m.length);m.unshift(48);return m};this.parseSig=function(n){var m;if(n[0]!=48){throw new Error("Signature not a valid DERSequence")}m=2;if(n[m]!=2){throw new Error("First element in signature must be a DERInteger")}var l=n.slice(m+2,m+2+n[m+1]);m+=2+n[m+1];if(n[m]!=2){throw new Error("Second element in signature must be a DERInteger")}var i=n.slice(m+2,m+2+n[m+1]);m+=2+n[m+1];var k=BigInteger.fromByteArrayUnsigned(l);var j=BigInteger.fromByteArrayUnsigned(i);return{r:k,s:j}};this.parseSigCompact=function(m){if(m.length!==65){throw"Signature has the wrong length"}var j=m[0]-27;if(j<0||j>7){throw"Invalid signature type"}var o=this.ecparams.n;var l=BigInteger.fromByteArrayUnsigned(m.slice(1,33)).mod(o);var k=BigInteger.fromByteArrayUnsigned(m.slice(33,65)).mod(o);return{r:l,s:k,i:j}};if(h!==undefined){if(h.curve!==undefined){this.curveName=h.curve}}if(this.curveName===undefined){this.curveName=e}this.setNamedCurve(this.curveName);if(h!==undefined){if(h.prv!==undefined){this.setPrivateKeyHex(h.prv)}if(h.pub!==undefined){this.setPublicKeyHex(h.pub)}}};KJUR.crypto.ECDSA.parseSigHex=function(a){var b=KJUR.crypto.ECDSA.parseSigHexInHexRS(a);var d=new BigInteger(b.r,16);var c=new BigInteger(b.s,16);return{r:d,s:c}};KJUR.crypto.ECDSA.parseSigHexInHexRS=function(c){if(c.substr(0,2)!="30"){throw"signature is not a ASN.1 sequence"}var b=ASN1HEX.getPosArrayOfChildren_AtObj(c,0);if(b.length!=2){throw"number of signature ASN.1 sequence elements seem wrong"}var g=b[0];var f=b[1];if(c.substr(g,2)!="02"){throw"1st item of sequene of signature is not ASN.1 integer"}if(c.substr(f,2)!="02"){throw"2nd item of sequene of signature is not ASN.1 integer"}var e=ASN1HEX.getHexOfV_AtObj(c,g);var d=ASN1HEX.getHexOfV_AtObj(c,f);return{r:e,s:d}};KJUR.crypto.ECDSA.asn1SigToConcatSig=function(c){var d=KJUR.crypto.ECDSA.parseSigHexInHexRS(c);var b=d.r;var a=d.s;if(b.substr(0,2)=="00"&&(((b.length/2)*8)%(16*8))==8){b=b.substr(2)}if(a.substr(0,2)=="00"&&(((a.length/2)*8)%(16*8))==8){a=a.substr(2)}if((((b.length/2)*8)%(16*8))!=0){throw"unknown ECDSA sig r length error"}if((((a.length/2)*8)%(16*8))!=0){throw"unknown ECDSA sig s length error"}return b+a};KJUR.crypto.ECDSA.concatSigToASN1Sig=function(a){if((((a.length/2)*8)%(16*8))!=0){throw"unknown ECDSA concatinated r-s sig length error"}var c=a.substr(0,a.length/2);var b=a.substr(a.length/2);return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(c,b)};KJUR.crypto.ECDSA.hexRSSigToASN1Sig=function(b,a){var d=new BigInteger(b,16);var c=new BigInteger(a,16);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(d,c)};KJUR.crypto.ECDSA.biRSSigToASN1Sig=function(e,c){var b=new KJUR.asn1.DERInteger({bigint:e});var a=new KJUR.asn1.DERInteger({bigint:c});var d=new KJUR.asn1.DERSequence({array:[b,a]});return d.getEncodedHex()}; +/*! ecparam-1.0.0.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.crypto=="undefined"||!KJUR.crypto){KJUR.crypto={}}KJUR.crypto.ECParameterDB=new function(){var b={};var c={};function a(d){return new BigInteger(d,16)}this.getByName=function(e){var d=e;if(typeof c[d]!="undefined"){d=c[e]}if(typeof b[d]!="undefined"){return b[d]}throw"unregistered EC curve name: "+d};this.regist=function(A,l,o,g,m,e,j,f,k,u,d,x){b[A]={};var s=a(o);var z=a(g);var y=a(m);var t=a(e);var w=a(j);var r=new ECCurveFp(s,z,y);var q=r.decodePointHex("04"+f+k);b[A]["name"]=A;b[A]["keylen"]=l;b[A]["curve"]=r;b[A]["G"]=q;b[A]["n"]=t;b[A]["h"]=w;b[A]["oid"]=d;b[A]["info"]=x;for(var v=0;v0||K.compareTo(u)>0||BigInteger.ZERO.compareTo(J)>0||J.compareTo(u)>0){throw"invalid DSA signature"}var I=J.modInverse(u);var A=D.multiply(I).mod(u);var v=K.multiply(I).mod(u);var F=G.modPow(A,z).multiply(H.modPow(v,z)).mod(z).mod(u);return F.compareTo(K)==0};this.parseASN1Signature=function(u){try{var y=new BigInteger(ASN1HEX.getVbyList(u,0,[0],"02"),16);var v=new BigInteger(ASN1HEX.getVbyList(u,0,[1],"02"),16);return[y,v]}catch(w){throw"malformed DSA signature"}};function d(E,w,B,v,u,C){var z=KJUR.crypto.Util.hashString(w,E.toLowerCase());var z=z.substr(0,u.bitLength()/4);var A=new BigInteger(z,16);var y=n(BigInteger.ONE.add(BigInteger.ONE),u.subtract(BigInteger.ONE));var F=(B.modPow(y,v)).mod(u);var D=(y.modInverse(u).multiply(A.add(C.multiply(F)))).mod(u);var G=new Array();G[0]=F;G[1]=D;return G}function r(v){var u=openpgp.config.config.prefer_hash_algorithm;switch(Math.round(v.bitLength()/8)){case 20:if(u!=2&&u>11&&u!=10&&u<8){return 2}return u;case 28:if(u>11&&u<8){return 11}return u;case 32:if(u>10&&u<8){return 8}return u;default:util.print_debug("DSA select hash algorithm: returning null for an unknown length of q");return null}}this.select_hash_algorithm=r;function m(I,K,J,B,z,u,F,G){var C=KJUR.crypto.Util.hashString(B,I.toLowerCase());var C=C.substr(0,u.bitLength()/4);var D=new BigInteger(C,16);if(BigInteger.ZERO.compareTo(K)>0||K.compareTo(u)>0||BigInteger.ZERO.compareTo(J)>0||J.compareTo(u)>0){util.print_error("invalid DSA Signature");return null}var H=J.modInverse(u);var A=D.multiply(H).mod(u);var v=K.multiply(H).mod(u);var E=F.modPow(A,z).multiply(G.modPow(v,z)).mod(z).mod(u);return E.compareTo(K)==0}function a(z){var A=new BigInteger(z,primeCenterie);var y=j(q,512);var u=t(p,q,z);var v;do{v=new BigInteger(q.bitCount(),rand)}while(x.compareTo(BigInteger.ZERO)!=1&&x.compareTo(q)!=-1);var w=g.modPow(x,p);return{x:v,q:A,p:y,g:u,y:w}}function j(y,z,w){if(z%64!=0){return false}var u;var v;do{u=w(bitcount,true);v=u.subtract(BigInteger.ONE);u=u.subtract(v.remainder(y))}while(!u.isProbablePrime(primeCenterie)||u.bitLength()!=l);return u}function t(B,z,A,w){var u=B.subtract(BigInteger.ONE);var y=u.divide(z);var v;do{v=w(A)}while(v.compareTo(u)!=-1&&v.compareTo(BigInteger.ONE)!=1);return v.modPow(y,B)}function o(w,y,u){var v;do{v=u(y,false)}while(v.compareTo(w)!=-1&&v.compareTo(BigInteger.ZERO)!=1);return v}function i(v,w){k=o(v);var u=g.modPow(k,w).mod(v);return u}function h(B,w,y,v,z,u){var A=B(v);s=(w.modInverse(z).multiply(A.add(u.multiply(y)))).mod(z);return s}this.sign=d;this.verify=m;function n(w,u){if(u.compareTo(w)<=0){return}var v=u.subtract(w);var y=e(v.bitLength());while(y>v){y=e(v.bitLength())}return w.add(y)}function e(w){if(w<0){return null}var u=Math.floor((w+7)/8);var v=c(u);if(w%8>0){v=String.fromCharCode((Math.pow(2,w%8)-1)&v.charCodeAt(0))+v.substring(1)}return new BigInteger(f(v),16)}function c(w){var u="";for(var v=0;v=s*2){break}}var x={};x.keyhex=v.substr(0,g[o]["keylen"]*2);x.ivhex=v.substr(g[o]["keylen"]*2,g[o]["ivlen"]*2);return x};var a=function(n,t,p,u){var q=CryptoJS.enc.Base64.parse(n);var o=CryptoJS.enc.Hex.stringify(q);var s=g[t]["proc"];var r=s(o,p,u);return r};var f=function(n,q,o,s){var p=g[q]["eproc"];var r=p(n,o,s);return r};return{version:"1.0.5",getHexFromPEM:function(o,r){var p=o;if(p.indexOf("BEGIN "+r)==-1){throw"can't find PEM header: "+r}p=p.replace("-----BEGIN "+r+"-----","");p=p.replace("-----END "+r+"-----","");var q=p.replace(/\s+/g,"");var n=b64tohex(q);return n},getDecryptedKeyHexByKeyIV:function(o,r,q,p){var n=b(r);return n(o,q,p)},parsePKCS5PEM:function(n){return l(n)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(o,n,p){return h(o,n,p)},decryptKeyB64:function(n,p,o,q){return a(n,p,o,q)},getDecryptedKeyHex:function(w,v){var o=l(w);var r=o.type;var p=o.cipher;var n=o.ivsalt;var q=o.data;var u=h(p,v,n);var t=u.keyhex;var s=a(q,p,t,n);return s},getRSAKeyFromEncryptedPKCS5PEM:function(p,o){var q=this.getDecryptedKeyHex(p,o);var n=new RSAKey();n.readPrivateKeyFromASN1HexString(q);return n},getEryptedPKCS5PEMFromPrvKeyHex:function(q,x,r,p){var n="";if(typeof r=="undefined"||r==null){r="AES-256-CBC"}if(typeof g[r]=="undefined"){throw"PKCS5PKEY unsupported algorithm: "+r}if(typeof p=="undefined"||p==null){var t=g[r]["ivlen"];var s=k(t);p=s.toUpperCase()}var w=h(r,x,p);var v=w.keyhex;var u=f(q,r,v,p);var o=u.replace(/(.{64})/g,"$1\r\n");var n="-----BEGIN RSA PRIVATE KEY-----\r\n";n+="Proc-Type: 4,ENCRYPTED\r\n";n+="DEK-Info: "+r+","+p+"\r\n";n+="\r\n";n+=o;n+="\r\n-----END RSA PRIVATE KEY-----\r\n";return n},getEryptedPKCS5PEMFromRSAKey:function(C,D,o,s){var A=new KJUR.asn1.DERInteger({"int":0});var v=new KJUR.asn1.DERInteger({bigint:C.n});var z=new KJUR.asn1.DERInteger({"int":C.e});var B=new KJUR.asn1.DERInteger({bigint:C.d});var t=new KJUR.asn1.DERInteger({bigint:C.p});var r=new KJUR.asn1.DERInteger({bigint:C.q});var y=new KJUR.asn1.DERInteger({bigint:C.dmp1});var u=new KJUR.asn1.DERInteger({bigint:C.dmq1});var x=new KJUR.asn1.DERInteger({bigint:C.coeff});var E=new KJUR.asn1.DERSequence({array:[A,v,z,B,t,r,y,u,x]});var w=E.getEncodedHex();return this.getEryptedPKCS5PEMFromPrvKeyHex(w,D,o,s)},newEncryptedPKCS5PEM:function(n,o,r,s){if(typeof o=="undefined"||o==null){o=1024}if(typeof r=="undefined"||r==null){r="10001"}var p=new RSAKey();p.generate(o,r);var q=null;if(typeof s=="undefined"||s==null){q=this.getEncryptedPKCS5PEMFromRSAKey(pkey,n)}else{q=this.getEncryptedPKCS5PEMFromRSAKey(pkey,n,s)}return q},getRSAKeyFromPlainPKCS8PEM:function(p){if(p.match(/ENCRYPTED/)){throw"pem shall be not ENCRYPTED"}var o=this.getHexFromPEM(p,"PRIVATE KEY");var n=this.getRSAKeyFromPlainPKCS8Hex(o);return n},getRSAKeyFromPlainPKCS8Hex:function(q){var p=ASN1HEX.getPosArrayOfChildren_AtObj(q,0);if(p.length!=3){throw"outer DERSequence shall have 3 elements: "+p.length}var o=ASN1HEX.getHexOfTLV_AtObj(q,p[1]);if(o!="300d06092a864886f70d0101010500"){throw"PKCS8 AlgorithmIdentifier is not rsaEnc: "+o}var o=ASN1HEX.getHexOfTLV_AtObj(q,p[1]);var r=ASN1HEX.getHexOfTLV_AtObj(q,p[2]);var s=ASN1HEX.getHexOfV_AtObj(r,0);var n=new RSAKey();n.readPrivateKeyFromASN1HexString(s);return n},parseHexOfEncryptedPKCS8:function(u){var q={};var p=ASN1HEX.getPosArrayOfChildren_AtObj(u,0);if(p.length!=2){throw"malformed format: SEQUENCE(0).items != 2: "+p.length}q.ciphertext=ASN1HEX.getHexOfV_AtObj(u,p[1]);var w=ASN1HEX.getPosArrayOfChildren_AtObj(u,p[0]);if(w.length!=2){throw"malformed format: SEQUENCE(0.0).items != 2: "+w.length}if(ASN1HEX.getHexOfV_AtObj(u,w[0])!="2a864886f70d01050d"){throw"this only supports pkcs5PBES2"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(u,w[1]);if(w.length!=2){throw"malformed format: SEQUENCE(0.0.1).items != 2: "+n.length}var o=ASN1HEX.getPosArrayOfChildren_AtObj(u,n[1]);if(o.length!=2){throw"malformed format: SEQUENCE(0.0.1.1).items != 2: "+o.length}if(ASN1HEX.getHexOfV_AtObj(u,o[0])!="2a864886f70d0307"){throw"this only supports TripleDES"}q.encryptionSchemeAlg="TripleDES";q.encryptionSchemeIV=ASN1HEX.getHexOfV_AtObj(u,o[1]);var r=ASN1HEX.getPosArrayOfChildren_AtObj(u,n[0]);if(r.length!=2){throw"malformed format: SEQUENCE(0.0.1.0).items != 2: "+r.length}if(ASN1HEX.getHexOfV_AtObj(u,r[0])!="2a864886f70d01050c"){throw"this only supports pkcs5PBKDF2"}var v=ASN1HEX.getPosArrayOfChildren_AtObj(u,r[1]);if(v.length<2){throw"malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+v.length}q.pbkdf2Salt=ASN1HEX.getHexOfV_AtObj(u,v[0]);var s=ASN1HEX.getHexOfV_AtObj(u,v[1]);try{q.pbkdf2Iter=parseInt(s,16)}catch(t){throw"malformed format pbkdf2Iter: "+s}return q},getPBKDF2KeyHexFromParam:function(s,n){var r=CryptoJS.enc.Hex.parse(s.pbkdf2Salt);var o=s.pbkdf2Iter;var q=CryptoJS.PBKDF2(n,r,{keySize:192/32,iterations:o});var p=CryptoJS.enc.Hex.stringify(q);return p},getPlainPKCS8HexFromEncryptedPKCS8PEM:function(v,w){var p=this.getHexFromPEM(v,"ENCRYPTED PRIVATE KEY");var n=this.parseHexOfEncryptedPKCS8(p);var s=PKCS5PKEY.getPBKDF2KeyHexFromParam(n,w);var t={};t.ciphertext=CryptoJS.enc.Hex.parse(n.ciphertext);var r=CryptoJS.enc.Hex.parse(s);var q=CryptoJS.enc.Hex.parse(n.encryptionSchemeIV);var u=CryptoJS.TripleDES.decrypt(t,r,{iv:q});var o=CryptoJS.enc.Hex.stringify(u);return o},getRSAKeyFromEncryptedPKCS8PEM:function(q,p){var o=this.getPlainPKCS8HexFromEncryptedPKCS8PEM(q,p);var n=this.getRSAKeyFromPlainPKCS8Hex(o);return n},getKeyFromEncryptedPKCS8PEM:function(q,o){var n=this.getPlainPKCS8HexFromEncryptedPKCS8PEM(q,o);var p=this.getKeyFromPlainPrivatePKCS8Hex(n);return p},parsePlainPrivatePKCS8Hex:function(q){var o={};o.algparam=null;if(q.substr(0,2)!="30"){throw"malformed plain PKCS8 private key(code:001)"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(q,0);if(p.length!=3){throw"malformed plain PKCS8 private key(code:002)"}if(q.substr(p[1],2)!="30"){throw"malformed PKCS8 private key(code:003)"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(q,p[1]);if(n.length!=2){throw"malformed PKCS8 private key(code:004)"}if(q.substr(n[0],2)!="06"){throw"malformed PKCS8 private key(code:005)"}o.algoid=ASN1HEX.getHexOfV_AtObj(q,n[0]);if(q.substr(n[1],2)=="06"){o.algparam=ASN1HEX.getHexOfV_AtObj(q,n[1])}if(q.substr(p[2],2)!="04"){throw"malformed PKCS8 private key(code:006)"}o.keyidx=ASN1HEX.getStartPosOfV_AtObj(q,p[2]);return o},getKeyFromPlainPrivatePKCS8PEM:function(o){var n=this.getHexFromPEM(o,"PRIVATE KEY");var p=this.getKeyFromPlainPrivatePKCS8Hex(n);return p},getKeyFromPlainPrivatePKCS8Hex:function(n){var p=this.parsePlainPrivatePKCS8Hex(n);if(p.algoid=="2a864886f70d010101"){this.parsePrivateRawRSAKeyHexAtObj(n,p);var o=p.key;var q=new RSAKey();q.setPrivateEx(o.n,o.e,o.d,o.p,o.q,o.dp,o.dq,o.co);return q}else{if(p.algoid=="2a8648ce3d0201"){this.parsePrivateRawECKeyHexAtObj(n,p);if(KJUR.crypto.OID.oidhex2name[p.algparam]===undefined){throw"KJUR.crypto.OID.oidhex2name undefined: "+p.algparam}var r=KJUR.crypto.OID.oidhex2name[p.algparam];var q=new KJUR.crypto.ECDSA({curve:r,prv:p.key});return q}else{throw"unsupported private key algorithm"}}},getRSAKeyFromPublicPKCS8PEM:function(o){var p=this.getHexFromPEM(o,"PUBLIC KEY");var n=this.getRSAKeyFromPublicPKCS8Hex(p);return n},getKeyFromPublicPKCS8PEM:function(o){var p=this.getHexFromPEM(o,"PUBLIC KEY");var n=this.getKeyFromPublicPKCS8Hex(p);return n},getKeyFromPublicPKCS8Hex:function(o){var n=this.parsePublicPKCS8Hex(o);if(n.algoid=="2a864886f70d010101"){var r=this.parsePublicRawRSAKeyHex(n.key);var p=new RSAKey();p.setPublic(r.n,r.e);return p}else{if(n.algoid=="2a8648ce3d0201"){if(KJUR.crypto.OID.oidhex2name[n.algparam]===undefined){throw"KJUR.crypto.OID.oidhex2name undefined: "+n.algparam}var q=KJUR.crypto.OID.oidhex2name[n.algparam];var p=new KJUR.crypto.ECDSA({curve:q,pub:n.key});return p}else{throw"unsupported public key algorithm"}}},parsePublicRawRSAKeyHex:function(p){var n={};if(p.substr(0,2)!="30"){throw"malformed RSA key(code:001)"}var o=ASN1HEX.getPosArrayOfChildren_AtObj(p,0);if(o.length!=2){throw"malformed RSA key(code:002)"}if(p.substr(o[0],2)!="02"){throw"malformed RSA key(code:003)"}n.n=ASN1HEX.getHexOfV_AtObj(p,o[0]);if(p.substr(o[1],2)!="02"){throw"malformed RSA key(code:004)"}n.e=ASN1HEX.getHexOfV_AtObj(p,o[1]);return n},parsePrivateRawRSAKeyHexAtObj:function(o,q){var p=q.keyidx;if(o.substr(p,2)!="30"){throw"malformed RSA private key(code:001)"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(o,p);if(n.length!=9){throw"malformed RSA private key(code:002)"}q.key={};q.key.n=ASN1HEX.getHexOfV_AtObj(o,n[1]);q.key.e=ASN1HEX.getHexOfV_AtObj(o,n[2]);q.key.d=ASN1HEX.getHexOfV_AtObj(o,n[3]);q.key.p=ASN1HEX.getHexOfV_AtObj(o,n[4]);q.key.q=ASN1HEX.getHexOfV_AtObj(o,n[5]);q.key.dp=ASN1HEX.getHexOfV_AtObj(o,n[6]);q.key.dq=ASN1HEX.getHexOfV_AtObj(o,n[7]);q.key.co=ASN1HEX.getHexOfV_AtObj(o,n[8])},parsePrivateRawECKeyHexAtObj:function(o,q){var p=q.keyidx;if(o.substr(p,2)!="30"){throw"malformed ECC private key(code:001)"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(o,p);if(n.length!=3){throw"malformed ECC private key(code:002)"}if(o.substr(n[1],2)!="04"){throw"malformed ECC private key(code:003)"}q.key=ASN1HEX.getHexOfV_AtObj(o,n[1])},parsePublicPKCS8Hex:function(q){var o={};o.algparam=null;var p=ASN1HEX.getPosArrayOfChildren_AtObj(q,0);if(p.length!=2){throw"outer DERSequence shall have 2 elements: "+p.length}var r=p[0];if(q.substr(r,2)!="30"){throw"malformed PKCS8 public key(code:001)"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(q,r);if(n.length!=2){throw"malformed PKCS8 public key(code:002)"}if(q.substr(n[0],2)!="06"){throw"malformed PKCS8 public key(code:003)"}o.algoid=ASN1HEX.getHexOfV_AtObj(q,n[0]);if(q.substr(n[1],2)=="06"){o.algparam=ASN1HEX.getHexOfV_AtObj(q,n[1])}if(q.substr(p[1],2)!="03"){throw"malformed PKCS8 public key(code:004)"}o.key=ASN1HEX.getHexOfV_AtObj(q,p[1]).substr(2);return o},getRSAKeyFromPublicPKCS8Hex:function(r){var q=ASN1HEX.getPosArrayOfChildren_AtObj(r,0);if(q.length!=2){throw"outer DERSequence shall have 2 elements: "+q.length}var p=ASN1HEX.getHexOfTLV_AtObj(r,q[0]);if(p!="300d06092a864886f70d0101010500"){throw"PKCS8 AlgorithmId is not rsaEncryption"}if(r.substr(q[1],2)!="03"){throw"PKCS8 Public Key is not BITSTRING encapslated."}var t=ASN1HEX.getStartPosOfV_AtObj(r,q[1])+2;if(r.substr(t,2)!="30"){throw"PKCS8 Public Key is not SEQUENCE."}var n=ASN1HEX.getPosArrayOfChildren_AtObj(r,t);if(n.length!=2){throw"inner DERSequence shall have 2 elements: "+n.length}if(r.substr(n[0],2)!="02"){throw"N is not ASN.1 INTEGER"}if(r.substr(n[1],2)!="02"){throw"E is not ASN.1 INTEGER"}var u=ASN1HEX.getHexOfV_AtObj(r,n[0]);var s=ASN1HEX.getHexOfV_AtObj(r,n[1]);var o=new RSAKey();o.setPublic(u,s);return o},}}(); +/*! keyutil-1.0.4.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +var KEYUTIL=function(){var d=function(p,r,q){return k(CryptoJS.AES,p,r,q)};var e=function(p,r,q){return k(CryptoJS.TripleDES,p,r,q)};var a=function(p,r,q){return k(CryptoJS.DES,p,r,q)};var k=function(s,x,u,q){var r=CryptoJS.enc.Hex.parse(x);var w=CryptoJS.enc.Hex.parse(u);var p=CryptoJS.enc.Hex.parse(q);var t={};t.key=w;t.iv=p;t.ciphertext=r;var v=s.decrypt(t,w,{iv:p});return CryptoJS.enc.Hex.stringify(v)};var l=function(p,r,q){return g(CryptoJS.AES,p,r,q)};var o=function(p,r,q){return g(CryptoJS.TripleDES,p,r,q)};var f=function(p,r,q){return g(CryptoJS.DES,p,r,q)};var g=function(t,y,v,q){var s=CryptoJS.enc.Hex.parse(y);var x=CryptoJS.enc.Hex.parse(v);var p=CryptoJS.enc.Hex.parse(q);var w=t.encrypt(s,x,{iv:p});var r=CryptoJS.enc.Hex.parse(w.toString());var u=CryptoJS.enc.Base64.stringify(r);return u};var i={"AES-256-CBC":{proc:d,eproc:l,keylen:32,ivlen:16},"AES-192-CBC":{proc:d,eproc:l,keylen:24,ivlen:16},"AES-128-CBC":{proc:d,eproc:l,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:e,eproc:o,keylen:24,ivlen:8},"DES-CBC":{proc:a,eproc:f,keylen:8,ivlen:8}};var c=function(p){return i[p]["proc"]};var m=function(p){var r=CryptoJS.lib.WordArray.random(p);var q=CryptoJS.enc.Hex.stringify(r);return q};var n=function(t){var u={};if(t.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"))){u.cipher=RegExp.$1;u.ivsalt=RegExp.$2}if(t.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"))){u.type=RegExp.$1}var r=-1;var v=0;if(t.indexOf("\r\n\r\n")!=-1){r=t.indexOf("\r\n\r\n");v=2}if(t.indexOf("\n\n")!=-1){r=t.indexOf("\n\n");v=1}var q=t.indexOf("-----END");if(r!=-1&&q!=-1){var p=t.substring(r+v*2,q-v);p=p.replace(/\s+/g,"");u.data=p}return u};var j=function(q,y,p){var v=p.substring(0,16);var t=CryptoJS.enc.Hex.parse(v);var r=CryptoJS.enc.Utf8.parse(y);var u=i[q]["keylen"]+i[q]["ivlen"];var x="";var w=null;for(;;){var s=CryptoJS.algo.MD5.create();if(w!=null){s.update(w)}s.update(r);s.update(t);w=s.finalize();x=x+CryptoJS.enc.Hex.stringify(w);if(x.length>=u*2){break}}var z={};z.keyhex=x.substr(0,i[q]["keylen"]*2);z.ivhex=x.substr(i[q]["keylen"]*2,i[q]["ivlen"]*2);return z};var b=function(p,v,r,w){var s=CryptoJS.enc.Base64.parse(p);var q=CryptoJS.enc.Hex.stringify(s);var u=i[v]["proc"];var t=u(q,r,w);return t};var h=function(p,s,q,u){var r=i[s]["eproc"];var t=r(p,q,u);return t};return{version:"1.0.0",getHexFromPEM:function(q,u){var r=q;if(r.indexOf("BEGIN "+u)==-1){throw"can't find PEM header: "+u}r=r.replace("-----BEGIN "+u+"-----","");r=r.replace("-----END "+u+"-----","");var t=r.replace(/\s+/g,"");var p=b64tohex(t);return p},getDecryptedKeyHexByKeyIV:function(q,t,s,r){var p=c(t);return p(q,s,r)},parsePKCS5PEM:function(p){return n(p)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(q,p,r){return j(q,p,r)},decryptKeyB64:function(p,r,q,s){return b(p,r,q,s)},getDecryptedKeyHex:function(y,x){var q=n(y);var t=q.type;var r=q.cipher;var p=q.ivsalt;var s=q.data;var w=j(r,x,p);var v=w.keyhex;var u=b(s,r,v,p);return u},getRSAKeyFromEncryptedPKCS5PEM:function(r,q){var s=this.getDecryptedKeyHex(r,q);var p=new RSAKey();p.readPrivateKeyFromASN1HexString(s);return p},getEncryptedPKCS5PEMFromPrvKeyHex:function(x,s,A,t,r){var p="";if(typeof t=="undefined"||t==null){t="AES-256-CBC"}if(typeof i[t]=="undefined"){throw"KEYUTIL unsupported algorithm: "+t}if(typeof r=="undefined"||r==null){var v=i[t]["ivlen"];var u=m(v);r=u.toUpperCase()}var z=j(t,A,r);var y=z.keyhex;var w=h(s,t,y,r);var q=w.replace(/(.{64})/g,"$1\r\n");var p="-----BEGIN "+x+" PRIVATE KEY-----\r\n";p+="Proc-Type: 4,ENCRYPTED\r\n";p+="DEK-Info: "+t+","+r+"\r\n";p+="\r\n";p+=q;p+="\r\n-----END "+x+" PRIVATE KEY-----\r\n";return p},getEncryptedPKCS5PEMFromRSAKey:function(D,E,r,t){var B=new KJUR.asn1.DERInteger({"int":0});var w=new KJUR.asn1.DERInteger({bigint:D.n});var A=new KJUR.asn1.DERInteger({"int":D.e});var C=new KJUR.asn1.DERInteger({bigint:D.d});var u=new KJUR.asn1.DERInteger({bigint:D.p});var s=new KJUR.asn1.DERInteger({bigint:D.q});var z=new KJUR.asn1.DERInteger({bigint:D.dmp1});var v=new KJUR.asn1.DERInteger({bigint:D.dmq1});var y=new KJUR.asn1.DERInteger({bigint:D.coeff});var F=new KJUR.asn1.DERSequence({array:[B,w,A,C,u,s,z,v,y]});var x=F.getEncodedHex();return this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",x,E,r,t)},newEncryptedPKCS5PEM:function(p,q,t,u){if(typeof q=="undefined"||q==null){q=1024}if(typeof t=="undefined"||t==null){t="10001"}var r=new RSAKey();r.generate(q,t);var s=null;if(typeof u=="undefined"||u==null){s=this.getEncryptedPKCS5PEMFromRSAKey(r,p)}else{s=this.getEncryptedPKCS5PEMFromRSAKey(r,p,u)}return s},getRSAKeyFromPlainPKCS8PEM:function(r){if(r.match(/ENCRYPTED/)){throw"pem shall be not ENCRYPTED"}var q=this.getHexFromPEM(r,"PRIVATE KEY");var p=this.getRSAKeyFromPlainPKCS8Hex(q);return p},getRSAKeyFromPlainPKCS8Hex:function(s){var r=ASN1HEX.getPosArrayOfChildren_AtObj(s,0);if(r.length!=3){throw"outer DERSequence shall have 3 elements: "+r.length}var q=ASN1HEX.getHexOfTLV_AtObj(s,r[1]);if(q!="300d06092a864886f70d0101010500"){throw"PKCS8 AlgorithmIdentifier is not rsaEnc: "+q}var q=ASN1HEX.getHexOfTLV_AtObj(s,r[1]);var t=ASN1HEX.getHexOfTLV_AtObj(s,r[2]);var u=ASN1HEX.getHexOfV_AtObj(t,0);var p=new RSAKey();p.readPrivateKeyFromASN1HexString(u);return p},parseHexOfEncryptedPKCS8:function(w){var s={};var r=ASN1HEX.getPosArrayOfChildren_AtObj(w,0);if(r.length!=2){throw"malformed format: SEQUENCE(0).items != 2: "+r.length}s.ciphertext=ASN1HEX.getHexOfV_AtObj(w,r[1]);var y=ASN1HEX.getPosArrayOfChildren_AtObj(w,r[0]);if(y.length!=2){throw"malformed format: SEQUENCE(0.0).items != 2: "+y.length}if(ASN1HEX.getHexOfV_AtObj(w,y[0])!="2a864886f70d01050d"){throw"this only supports pkcs5PBES2"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(w,y[1]);if(y.length!=2){throw"malformed format: SEQUENCE(0.0.1).items != 2: "+p.length}var q=ASN1HEX.getPosArrayOfChildren_AtObj(w,p[1]);if(q.length!=2){throw"malformed format: SEQUENCE(0.0.1.1).items != 2: "+q.length}if(ASN1HEX.getHexOfV_AtObj(w,q[0])!="2a864886f70d0307"){throw"this only supports TripleDES"}s.encryptionSchemeAlg="TripleDES";s.encryptionSchemeIV=ASN1HEX.getHexOfV_AtObj(w,q[1]);var t=ASN1HEX.getPosArrayOfChildren_AtObj(w,p[0]);if(t.length!=2){throw"malformed format: SEQUENCE(0.0.1.0).items != 2: "+t.length}if(ASN1HEX.getHexOfV_AtObj(w,t[0])!="2a864886f70d01050c"){throw"this only supports pkcs5PBKDF2"}var x=ASN1HEX.getPosArrayOfChildren_AtObj(w,t[1]);if(x.length<2){throw"malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+x.length}s.pbkdf2Salt=ASN1HEX.getHexOfV_AtObj(w,x[0]);var u=ASN1HEX.getHexOfV_AtObj(w,x[1]);try{s.pbkdf2Iter=parseInt(u,16)}catch(v){throw"malformed format pbkdf2Iter: "+u}return s},getPBKDF2KeyHexFromParam:function(u,p){var t=CryptoJS.enc.Hex.parse(u.pbkdf2Salt);var q=u.pbkdf2Iter;var s=CryptoJS.PBKDF2(p,t,{keySize:192/32,iterations:q});var r=CryptoJS.enc.Hex.stringify(s);return r},getPlainPKCS8HexFromEncryptedPKCS8PEM:function(x,y){var r=this.getHexFromPEM(x,"ENCRYPTED PRIVATE KEY");var p=this.parseHexOfEncryptedPKCS8(r);var u=KEYUTIL.getPBKDF2KeyHexFromParam(p,y);var v={};v.ciphertext=CryptoJS.enc.Hex.parse(p.ciphertext);var t=CryptoJS.enc.Hex.parse(u);var s=CryptoJS.enc.Hex.parse(p.encryptionSchemeIV);var w=CryptoJS.TripleDES.decrypt(v,t,{iv:s});var q=CryptoJS.enc.Hex.stringify(w);return q},getRSAKeyFromEncryptedPKCS8PEM:function(s,r){var q=this.getPlainPKCS8HexFromEncryptedPKCS8PEM(s,r);var p=this.getRSAKeyFromPlainPKCS8Hex(q);return p},getKeyFromEncryptedPKCS8PEM:function(s,q){var p=this.getPlainPKCS8HexFromEncryptedPKCS8PEM(s,q);var r=this.getKeyFromPlainPrivatePKCS8Hex(p);return r},parsePlainPrivatePKCS8Hex:function(s){var q={};q.algparam=null;if(s.substr(0,2)!="30"){throw"malformed plain PKCS8 private key(code:001)"}var r=ASN1HEX.getPosArrayOfChildren_AtObj(s,0);if(r.length!=3){throw"malformed plain PKCS8 private key(code:002)"}if(s.substr(r[1],2)!="30"){throw"malformed PKCS8 private key(code:003)"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(s,r[1]);if(p.length!=2){throw"malformed PKCS8 private key(code:004)"}if(s.substr(p[0],2)!="06"){throw"malformed PKCS8 private key(code:005)"}q.algoid=ASN1HEX.getHexOfV_AtObj(s,p[0]);if(s.substr(p[1],2)=="06"){q.algparam=ASN1HEX.getHexOfV_AtObj(s,p[1])}if(s.substr(r[2],2)!="04"){throw"malformed PKCS8 private key(code:006)"}q.keyidx=ASN1HEX.getStartPosOfV_AtObj(s,r[2]);return q},getKeyFromPlainPrivatePKCS8PEM:function(q){var p=this.getHexFromPEM(q,"PRIVATE KEY");var r=this.getKeyFromPlainPrivatePKCS8Hex(p);return r},getKeyFromPlainPrivatePKCS8Hex:function(p){var w=this.parsePlainPrivatePKCS8Hex(p);if(w.algoid=="2a864886f70d010101"){this.parsePrivateRawRSAKeyHexAtObj(p,w);var u=w.key;var z=new RSAKey();z.setPrivateEx(u.n,u.e,u.d,u.p,u.q,u.dp,u.dq,u.co);return z}else{if(w.algoid=="2a8648ce3d0201"){this.parsePrivateRawECKeyHexAtObj(p,w);if(KJUR.crypto.OID.oidhex2name[w.algparam]===undefined){throw"KJUR.crypto.OID.oidhex2name undefined: "+w.algparam}var v=KJUR.crypto.OID.oidhex2name[w.algparam];var z=new KJUR.crypto.ECDSA({curve:v});z.setPublicKeyHex(w.pubkey);z.setPrivateKeyHex(w.key);z.isPublic=false;return z}else{if(w.algoid=="2a8648ce380401"){var t=ASN1HEX.getVbyList(p,0,[1,1,0],"02");var s=ASN1HEX.getVbyList(p,0,[1,1,1],"02");var y=ASN1HEX.getVbyList(p,0,[1,1,2],"02");var B=ASN1HEX.getVbyList(p,0,[2,0],"02");var r=new BigInteger(t,16);var q=new BigInteger(s,16);var x=new BigInteger(y,16);var A=new BigInteger(B,16);var z=new KJUR.crypto.DSA();z.setPrivate(r,q,x,null,A);return z}else{throw"unsupported private key algorithm"}}}},getRSAKeyFromPublicPKCS8PEM:function(q){var r=this.getHexFromPEM(q,"PUBLIC KEY");var p=this.getRSAKeyFromPublicPKCS8Hex(r);return p},getKeyFromPublicPKCS8PEM:function(q){var r=this.getHexFromPEM(q,"PUBLIC KEY");var p=this.getKeyFromPublicPKCS8Hex(r);return p},getKeyFromPublicPKCS8Hex:function(q){var p=this.parsePublicPKCS8Hex(q);if(p.algoid=="2a864886f70d010101"){var u=this.parsePublicRawRSAKeyHex(p.key);var r=new RSAKey();r.setPublic(u.n,u.e);return r}else{if(p.algoid=="2a8648ce3d0201"){if(KJUR.crypto.OID.oidhex2name[p.algparam]===undefined){throw"KJUR.crypto.OID.oidhex2name undefined: "+p.algparam}var s=KJUR.crypto.OID.oidhex2name[p.algparam];var r=new KJUR.crypto.ECDSA({curve:s,pub:p.key});return r}else{if(p.algoid=="2a8648ce380401"){var t=p.algparam;var v=ASN1HEX.getHexOfV_AtObj(p.key,0);var r=new KJUR.crypto.DSA();r.setPublic(new BigInteger(t.p,16),new BigInteger(t.q,16),new BigInteger(t.g,16),new BigInteger(v,16));return r}else{throw"unsupported public key algorithm"}}}},parsePublicRawRSAKeyHex:function(r){var p={};if(r.substr(0,2)!="30"){throw"malformed RSA key(code:001)"}var q=ASN1HEX.getPosArrayOfChildren_AtObj(r,0);if(q.length!=2){throw"malformed RSA key(code:002)"}if(r.substr(q[0],2)!="02"){throw"malformed RSA key(code:003)"}p.n=ASN1HEX.getHexOfV_AtObj(r,q[0]);if(r.substr(q[1],2)!="02"){throw"malformed RSA key(code:004)"}p.e=ASN1HEX.getHexOfV_AtObj(r,q[1]);return p},parsePrivateRawRSAKeyHexAtObj:function(q,s){var r=s.keyidx;if(q.substr(r,2)!="30"){throw"malformed RSA private key(code:001)"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(q,r);if(p.length!=9){throw"malformed RSA private key(code:002)"}s.key={};s.key.n=ASN1HEX.getHexOfV_AtObj(q,p[1]);s.key.e=ASN1HEX.getHexOfV_AtObj(q,p[2]);s.key.d=ASN1HEX.getHexOfV_AtObj(q,p[3]);s.key.p=ASN1HEX.getHexOfV_AtObj(q,p[4]);s.key.q=ASN1HEX.getHexOfV_AtObj(q,p[5]);s.key.dp=ASN1HEX.getHexOfV_AtObj(q,p[6]);s.key.dq=ASN1HEX.getHexOfV_AtObj(q,p[7]);s.key.co=ASN1HEX.getHexOfV_AtObj(q,p[8])},parsePrivateRawECKeyHexAtObj:function(p,t){var q=t.keyidx;var r=ASN1HEX.getVbyList(p,q,[1],"04");var s=ASN1HEX.getVbyList(p,q,[2,0],"03").substr(2);t.key=r;t.pubkey=s},parsePublicPKCS8Hex:function(s){var q={};q.algparam=null;var r=ASN1HEX.getPosArrayOfChildren_AtObj(s,0);if(r.length!=2){throw"outer DERSequence shall have 2 elements: "+r.length}var t=r[0];if(s.substr(t,2)!="30"){throw"malformed PKCS8 public key(code:001)"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(s,t);if(p.length!=2){throw"malformed PKCS8 public key(code:002)"}if(s.substr(p[0],2)!="06"){throw"malformed PKCS8 public key(code:003)"}q.algoid=ASN1HEX.getHexOfV_AtObj(s,p[0]);if(s.substr(p[1],2)=="06"){q.algparam=ASN1HEX.getHexOfV_AtObj(s,p[1])}else{if(s.substr(p[1],2)=="30"){q.algparam={};q.algparam.p=ASN1HEX.getVbyList(s,p[1],[0],"02");q.algparam.q=ASN1HEX.getVbyList(s,p[1],[1],"02");q.algparam.g=ASN1HEX.getVbyList(s,p[1],[2],"02")}}if(s.substr(r[1],2)!="03"){throw"malformed PKCS8 public key(code:004)"}q.key=ASN1HEX.getHexOfV_AtObj(s,r[1]).substr(2);return q},getRSAKeyFromPublicPKCS8Hex:function(t){var s=ASN1HEX.getPosArrayOfChildren_AtObj(t,0);if(s.length!=2){throw"outer DERSequence shall have 2 elements: "+s.length}var r=ASN1HEX.getHexOfTLV_AtObj(t,s[0]);if(r!="300d06092a864886f70d0101010500"){throw"PKCS8 AlgorithmId is not rsaEncryption"}if(t.substr(s[1],2)!="03"){throw"PKCS8 Public Key is not BITSTRING encapslated."}var v=ASN1HEX.getStartPosOfV_AtObj(t,s[1])+2;if(t.substr(v,2)!="30"){throw"PKCS8 Public Key is not SEQUENCE."}var p=ASN1HEX.getPosArrayOfChildren_AtObj(t,v);if(p.length!=2){throw"inner DERSequence shall have 2 elements: "+p.length}if(t.substr(p[0],2)!="02"){throw"N is not ASN.1 INTEGER"}if(t.substr(p[1],2)!="02"){throw"E is not ASN.1 INTEGER"}var w=ASN1HEX.getHexOfV_AtObj(t,p[0]);var u=ASN1HEX.getHexOfV_AtObj(t,p[1]);var q=new RSAKey();q.setPublic(w,u);return q},}}();KEYUTIL.getKey=function(c,o,i){if(typeof RSAKey!="undefined"&&c instanceof RSAKey){return c}if(typeof KJUR.crypto.ECDSA!="undefined"&&c instanceof KJUR.crypto.ECDSA){return c}if(typeof KJUR.crypto.DSA!="undefined"&&c instanceof KJUR.crypto.DSA){return c}if(c.xy!==undefined&&c.curve!==undefined){return new KJUR.crypto.ECDSA({prv:c.xy,curve:c.curve})}if(c.n!==undefined&&c.e!==undefined&&c.d!==undefined&&c.p!==undefined&&c.q!==undefined&&c.dp!==undefined&&c.dq!==undefined&&c.co!==undefined){var n=new RSAKey();n.setPrivateEx(c.n,c.e,c.d,c.p,c.q,c.dp,c.dq,c.co);return n}if(c.p!==undefined&&c.q!==undefined&&c.g!==undefined&&c.y!==undefined&&c.x!==undefined){var n=new KJUR.crypto.DSA();n.setPrivate(c.p,c.q,c.g,c.y,c.x);return n}if(c.d!==undefined&&c.curve!==undefined){return new KJUR.crypto.ECDSA({pub:c.d,curve:c.curve})}if(c.n!==undefined&&c.e){var n=new RSAKey();n.setPublic(c.n,c.e);return n}if(c.p!==undefined&&c.q!==undefined&&c.g!==undefined&&c.y!==undefined&&c.x===undefined){var n=new KJUR.crypto.DSA();n.setPublic(c.p,c.q,c.g,c.y);return n}if(c.indexOf("-END CERTIFICATE-",0)!=-1||c.indexOf("-END X509 CERTIFICATE-",0)!=-1||c.indexOf("-END TRUSTED CERTIFICATE-",0)!=-1){return X509.getPublicKeyFromCertPEM(c)}if(i==="pkcs8pub"){return KEYUTIL.getKeyFromPublicPKCS8Hex(c)}if(c.indexOf("-END PUBLIC KEY-")!=-1){return KEYUTIL.getKeyFromPublicPKCS8PEM(c)}if(i==="pkcs5prv"){var n=new RSAKey();n.readPrivateKeyFromASN1HexString(c);return n}if(i==="pkcs5prv"){var n=new RSAKey();n.readPrivateKeyFromASN1HexString(c);return n}if(c.indexOf("-END RSA PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")==-1){var n=new RSAKey();n.readPrivateKeyFromPEMString(c);return n}if(c.indexOf("-END DSA PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")==-1){var m=this.getHexFromPEM(c,"DSA PRIVATE KEY");var b=ASN1HEX.getVbyList(m,0,[1],"02");var a=ASN1HEX.getVbyList(m,0,[2],"02");var e=ASN1HEX.getVbyList(m,0,[3],"02");var k=ASN1HEX.getVbyList(m,0,[4],"02");var l=ASN1HEX.getVbyList(m,0,[5],"02");var n=new KJUR.crypto.DSA();n.setPrivate(new BigInteger(b,16),new BigInteger(a,16),new BigInteger(e,16),new BigInteger(k,16),new BigInteger(l,16));return n}if(c.indexOf("-END PRIVATE KEY-")!=-1){return KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(c)}if(c.indexOf("-END RSA PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")!=-1){return KEYUTIL.getRSAKeyFromEncryptedPKCS5PEM(c,o)}if(c.indexOf("-END EC PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")!=-1){var m=KEYUTIL.getDecryptedKeyHex(c,o);var n=ASN1HEX.getVbyList(m,0,[1],"04");var j=ASN1HEX.getVbyList(m,0,[2,0],"06");var d=ASN1HEX.getVbyList(m,0,[3,0],"03").substr(2);var h="";if(KJUR.crypto.OID.oidhex2name[j]!==undefined){h=KJUR.crypto.OID.oidhex2name[j]}else{throw"undefined OID(hex) in KJUR.crypto.OID: "+j}var f=new KJUR.crypto.ECDSA({name:h});f.setPublicKeyHex(d);f.setPrivateKeyHex(n);f.isPublic=false;return f}if(c.indexOf("-END DSA PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")!=-1){var m=KEYUTIL.getDecryptedKeyHex(c,o);var b=ASN1HEX.getVbyList(m,0,[1],"02");var a=ASN1HEX.getVbyList(m,0,[2],"02");var e=ASN1HEX.getVbyList(m,0,[3],"02");var k=ASN1HEX.getVbyList(m,0,[4],"02");var l=ASN1HEX.getVbyList(m,0,[5],"02");var n=new KJUR.crypto.DSA();n.setPrivate(new BigInteger(b,16),new BigInteger(a,16),new BigInteger(e,16),new BigInteger(k,16),new BigInteger(l,16));return n}if(c.indexOf("-END ENCRYPTED PRIVATE KEY-")!=-1){return KEYUTIL.getKeyFromEncryptedPKCS8PEM(c,o)}throw"not supported argument"};KEYUTIL.generateKeypair=function(a,c){if(a=="RSA"){var b=c;var h=new RSAKey();h.generate(b,"10001");var f=new RSAKey();var e=h.n.toString(16);var i=h.e.toString(16);f.setPublic(e,i);var k={};k.prvKeyObj=h;k.pubKeyObj=f;return k}else{if(a=="EC"){var d=c;var g=new KJUR.crypto.ECDSA({curve:d});var j=g.generateKeyPairHex();var h=new KJUR.crypto.ECDSA({curve:d});h.setPrivateKeyHex(j.ecprvhex);var f=new KJUR.crypto.ECDSA({curve:d});f.setPublicKeyHex(j.ecpubhex);var k={};k.prvKeyObj=h;k.pubKeyObj=f;return k}else{throw"unknown algorithm: "+a}}};KEYUTIL.getPEM=function(a,r,o,g,j){var v=KJUR.asn1;var u=KJUR.crypto;function p(s){var w=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{"int":{bigint:s.n}},{"int":s.e},{"int":{bigint:s.d}},{"int":{bigint:s.p}},{"int":{bigint:s.q}},{"int":{bigint:s.dmp1}},{"int":{bigint:s.dmq1}},{"int":{bigint:s.coeff}}]});return w}function q(w){var s=KJUR.asn1.ASN1Util.newObject({seq:[{"int":1},{octstr:{hex:w.prvKeyHex}},{tag:["a0",true,{oid:{name:w.curveName}}]},{tag:["a1",true,{bitstr:{hex:"00"+w.pubKeyHex}}]}]});return s}function n(s){var w=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{"int":{bigint:s.p}},{"int":{bigint:s.q}},{"int":{bigint:s.g}},{"int":{bigint:s.y}},{"int":{bigint:s.x}}]});return w}if(((typeof RSAKey!="undefined"&&a instanceof RSAKey)||(typeof u.DSA!="undefined"&&a instanceof u.DSA)||(typeof u.ECDSA!="undefined"&&a instanceof u.ECDSA))&&a.isPublic==true&&(r===undefined||r=="PKCS8PUB")){var t=new KJUR.asn1.x509.SubjectPublicKeyInfo(a);var m=t.getEncodedHex();return v.ASN1Util.getPEMStringFromHex(m,"PUBLIC KEY")}if(r=="PKCS1PRV"&&typeof RSAKey!="undefined"&&a instanceof RSAKey&&(o===undefined||o==null)&&a.isPrivate==true){var t=p(a);var m=t.getEncodedHex();return v.ASN1Util.getPEMStringFromHex(m,"RSA PRIVATE KEY")}if(r=="PKCS1PRV"&&typeof RSAKey!="undefined"&&a instanceof KJUR.crypto.ECDSA&&(o===undefined||o==null)&&a.isPrivate==true){var f=new KJUR.asn1.DERObjectIdentifier({name:a.curveName});var l=f.getEncodedHex();var e=q(a);var k=e.getEncodedHex();var i="";i+=v.ASN1Util.getPEMStringFromHex(l,"EC PARAMETERS");i+=v.ASN1Util.getPEMStringFromHex(k,"EC PRIVATE KEY");return i}if(r=="PKCS1PRV"&&typeof KJUR.crypto.DSA!="undefined"&&a instanceof KJUR.crypto.DSA&&(o===undefined||o==null)&&a.isPrivate==true){var t=n(a);var m=t.getEncodedHex();return v.ASN1Util.getPEMStringFromHex(m,"DSA PRIVATE KEY")}if(r=="PKCS5PRV"&&typeof RSAKey!="undefined"&&a instanceof RSAKey&&(o!==undefined&&o!=null)&&a.isPrivate==true){var t=p(a);var m=t.getEncodedHex();if(g===undefined){g="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",m,o,g)}if(r=="PKCS5PRV"&&typeof KJUR.crypto.ECDSA!="undefined"&&a instanceof KJUR.crypto.ECDSA&&(o!==undefined&&o!=null)&&a.isPrivate==true){var t=q(a);var m=t.getEncodedHex();if(g===undefined){g="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",m,o,g)}if(r=="PKCS5PRV"&&typeof KJUR.crypto.DSA!="undefined"&&a instanceof KJUR.crypto.DSA&&(o!==undefined&&o!=null)&&a.isPrivate==true){var t=n(a);var m=t.getEncodedHex();if(g===undefined){g="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",m,o,g)}var h=function(w,s){var y=b(w,s);var x=new KJUR.asn1.ASN1Util.newObject({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:y.pbkdf2Salt}},{"int":y.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:y.encryptionSchemeIV}}]}]}]},{octstr:{hex:y.ciphertext}}]});return x.getEncodedHex()};var b=function(D,E){var x=100;var C=CryptoJS.lib.WordArray.random(8);var B="DES-EDE3-CBC";var s=CryptoJS.lib.WordArray.random(8);var y=CryptoJS.PBKDF2(E,C,{keySize:192/32,iterations:x});var z=CryptoJS.enc.Hex.parse(D);var A=CryptoJS.TripleDES.encrypt(z,y,{iv:s})+"";var w={};w.ciphertext=A;w.pbkdf2Salt=CryptoJS.enc.Hex.stringify(C);w.pbkdf2Iter=x;w.encryptionSchemeAlg=B;w.encryptionSchemeIV=CryptoJS.enc.Hex.stringify(s);return w};if(r=="PKCS8PRV"&&typeof RSAKey!="undefined"&&a instanceof RSAKey&&a.isPrivate==true){var d=p(a);var c=d.getEncodedHex();var t=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{seq:[{oid:{name:"rsaEncryption"}},{"null":true}]},{octstr:{hex:c}}]});var m=t.getEncodedHex();if(o===undefined||o==null){return v.ASN1Util.getPEMStringFromHex(m,"PRIVATE KEY")}else{var k=h(m,o);return v.ASN1Util.getPEMStringFromHex(k,"ENCRYPTED PRIVATE KEY")}}if(r=="PKCS8PRV"&&typeof KJUR.crypto.ECDSA!="undefined"&&a instanceof KJUR.crypto.ECDSA&&a.isPrivate==true){var d=new KJUR.asn1.ASN1Util.newObject({seq:[{"int":1},{octstr:{hex:a.prvKeyHex}},{tag:["a1",true,{bitstr:{hex:"00"+a.pubKeyHex}}]}]});var c=d.getEncodedHex();var t=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:a.curveName}}]},{octstr:{hex:c}}]});var m=t.getEncodedHex();if(o===undefined||o==null){return v.ASN1Util.getPEMStringFromHex(m,"PRIVATE KEY")}else{var k=h(m,o);return v.ASN1Util.getPEMStringFromHex(k,"ENCRYPTED PRIVATE KEY")}}if(r=="PKCS8PRV"&&typeof KJUR.crypto.DSA!="undefined"&&a instanceof KJUR.crypto.DSA&&a.isPrivate==true){var d=new KJUR.asn1.DERInteger({bigint:a.x});var c=d.getEncodedHex();var t=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{seq:[{oid:{name:"dsa"}},{seq:[{"int":{bigint:a.p}},{"int":{bigint:a.q}},{"int":{bigint:a.g}}]}]},{octstr:{hex:c}}]});var m=t.getEncodedHex();if(o===undefined||o==null){return v.ASN1Util.getPEMStringFromHex(m,"PRIVATE KEY")}else{var k=h(m,o);return v.ASN1Util.getPEMStringFromHex(k,"ENCRYPTED PRIVATE KEY")}}throw"unsupported object nor format"}; +/*! rsapem-1.1.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +function _rsapem_pemToBase64(b){var a=b;a=a.replace("-----BEGIN RSA PRIVATE KEY-----","");a=a.replace("-----END RSA PRIVATE KEY-----","");a=a.replace(/[ \n]+/g,"");return a}function _rsapem_getPosArrayOfChildrenFromHex(d){var j=new Array();var k=ASN1HEX.getStartPosOfV_AtObj(d,0);var f=ASN1HEX.getPosOfNextSibling_AtObj(d,k);var h=ASN1HEX.getPosOfNextSibling_AtObj(d,f);var b=ASN1HEX.getPosOfNextSibling_AtObj(d,h);var l=ASN1HEX.getPosOfNextSibling_AtObj(d,b);var e=ASN1HEX.getPosOfNextSibling_AtObj(d,l);var g=ASN1HEX.getPosOfNextSibling_AtObj(d,e);var c=ASN1HEX.getPosOfNextSibling_AtObj(d,g);var i=ASN1HEX.getPosOfNextSibling_AtObj(d,c);j.push(k,f,h,b,l,e,g,c,i);return j}function _rsapem_getHexValueArrayOfChildrenFromHex(i){var o=_rsapem_getPosArrayOfChildrenFromHex(i);var r=ASN1HEX.getHexOfV_AtObj(i,o[0]);var f=ASN1HEX.getHexOfV_AtObj(i,o[1]);var j=ASN1HEX.getHexOfV_AtObj(i,o[2]);var k=ASN1HEX.getHexOfV_AtObj(i,o[3]);var c=ASN1HEX.getHexOfV_AtObj(i,o[4]);var b=ASN1HEX.getHexOfV_AtObj(i,o[5]);var h=ASN1HEX.getHexOfV_AtObj(i,o[6]);var g=ASN1HEX.getHexOfV_AtObj(i,o[7]);var l=ASN1HEX.getHexOfV_AtObj(i,o[8]);var m=new Array();m.push(r,f,j,k,c,b,h,g,l);return m}function _rsapem_readPrivateKeyFromASN1HexString(c){var b=_rsapem_getHexValueArrayOfChildrenFromHex(c);this.setPrivateEx(b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8])}function _rsapem_readPrivateKeyFromPEMString(e){var c=_rsapem_pemToBase64(e);var d=b64tohex(c);var b=_rsapem_getHexValueArrayOfChildrenFromHex(d);this.setPrivateEx(b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8])}RSAKey.prototype.readPrivateKeyFromPEMString=_rsapem_readPrivateKeyFromPEMString;RSAKey.prototype.readPrivateKeyFromASN1HexString=_rsapem_readPrivateKeyFromASN1HexString; +/*! rsasign-1.2.7.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +var _RE_HEXDECONLY=new RegExp("");_RE_HEXDECONLY.compile("[^0-9a-f]","gi");function _rsasign_getHexPaddedDigestInfoForString(d,e,a){var b=function(f){return KJUR.crypto.Util.hashString(f,a)};var c=b(d);return KJUR.crypto.Util.getPaddedDigestInfoHex(c,a,e)}function _zeroPaddingOfSignature(e,d){var c="";var a=d/4-e.length;for(var b=0;b>24,(d&16711680)>>16,(d&65280)>>8,d&255]))));d+=1}return b}function _rsasign_signStringPSS(e,a,d){var c=function(f){return KJUR.crypto.Util.hashHex(f,a)};var b=c(rstrtohex(e));if(d===undefined){d=-1}return this.signWithMessageHashPSS(b,a,d)}function _rsasign_signWithMessageHashPSS(l,a,k){var b=hextorstr(l);var g=b.length;var m=this.n.bitLength()-1;var c=Math.ceil(m/8);var d;var o=function(i){return KJUR.crypto.Util.hashHex(i,a)};if(k===-1||k===undefined){k=g}else{if(k===-2){k=c-g-2}else{if(k<-2){throw"invalid salt length"}}}if(c<(g+k+2)){throw"data too long"}var f="";if(k>0){f=new Array(k);new SecureRandom().nextBytes(f);f=String.fromCharCode.apply(String,f)}var n=hextorstr(o(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+b+f)));var j=[];for(d=0;d>(8*c-m))&255;q[0]&=~p;for(d=0;dthis.n.bitLength()){return 0}var i=this.doPublic(b);var e=i.toString(16).replace(/^1f+00/,"");var g=_rsasign_getAlgNameAndHashFromHexDisgestInfo(e);if(g.length==0){return false}var d=g[0];var h=g[1];var a=function(k){return KJUR.crypto.Util.hashString(k,d)};var c=a(f);return(h==c)}function _rsasign_verifyWithMessageHash(e,a){a=a.replace(_RE_HEXDECONLY,"");a=a.replace(/[ \n]+/g,"");var b=parseBigInt(a,16);if(b.bitLength()>this.n.bitLength()){return 0}var h=this.doPublic(b);var g=h.toString(16).replace(/^1f+00/,"");var c=_rsasign_getAlgNameAndHashFromHexDisgestInfo(g);if(c.length==0){return false}var d=c[0];var f=c[1];return(f==e)}function _rsasign_verifyStringPSS(c,b,a,f){var e=function(g){return KJUR.crypto.Util.hashHex(g,a)};var d=e(rstrtohex(c));if(f===undefined){f=-1}return this.verifyWithMessageHashPSS(d,b,a,f)}function _rsasign_verifyWithMessageHashPSS(f,s,l,c){var k=new BigInteger(s,16);if(k.bitLength()>this.n.bitLength()){return false}var r=function(i){return KJUR.crypto.Util.hashHex(i,l)};var j=hextorstr(f);var h=j.length;var g=this.n.bitLength()-1;var m=Math.ceil(g/8);var q;if(c===-1||c===undefined){c=h}else{if(c===-2){c=m-h-2}else{if(c<-2){throw"invalid salt length"}}}if(m<(h+c+2)){throw"data too long"}var a=this.doPublic(k).toByteArray();for(q=0;q>(8*m-g))&255;if((d.charCodeAt(0)&p)!==0){throw"bits beyond keysize not zero"}var n=pss_mgf1_str(e,d.length,r);var o=[];for(q=0;q=0;){delete D[n[A]]}}}return q.call(C,B,D)};x=s({"":x},"")}return x}})();/*! jws-3.0.2 (c) 2013 Kenji Urushima | kjur.github.com/jsjws/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.jws=="undefined"||!KJUR.jws){KJUR.jws={}}KJUR.jws.JWS=function(){this.parseJWS=function(n,p){if((this.parsedJWS!==undefined)&&(p||(this.parsedJWS.sigvalH!==undefined))){return}if(n.match(/^([^.]+)\.([^.]+)\.([^.]+)$/)==null){throw"JWS signature is not a form of 'Head.Payload.SigValue'."}var q=RegExp.$1;var l=RegExp.$2;var r=RegExp.$3;var t=q+"."+l;this.parsedJWS={};this.parsedJWS.headB64U=q;this.parsedJWS.payloadB64U=l;this.parsedJWS.sigvalB64U=r;this.parsedJWS.si=t;if(!p){var o=b64utohex(r);var m=parseBigInt(o,16);this.parsedJWS.sigvalH=o;this.parsedJWS.sigvalBI=m}var k=b64utoutf8(q);var s=b64utoutf8(l);this.parsedJWS.headS=k;this.parsedJWS.payloadS=s;if(!this.isSafeJSONString(k,this.parsedJWS,"headP")){throw"malformed JSON string for JWS Head: "+k}};function b(l,k){return utf8tob64u(l)+"."+utf8tob64u(k)}function f(m,l){var k=function(n){return KJUR.crypto.Util.hashString(n,l)};if(k==null){throw"hash function not defined in jsrsasign: "+l}return k(m)}function h(q,n,k,o,m){var p=b(q,n);var l=parseBigInt(k,16);return _rsasign_verifySignatureWithArgs(p,l,o,m)}this.verifyJWSByNE=function(m,l,k){this.parseJWS(m);return _rsasign_verifySignatureWithArgs(this.parsedJWS.si,this.parsedJWS.sigvalBI,l,k)};this.verifyJWSByKey=function(n,m){this.parseJWS(n);var k=c(this.parsedJWS.headP);var l=this.parsedJWS.headP.alg.substr(0,2)=="PS";if(m.hashAndVerify){return m.hashAndVerify(k,new Buffer(this.parsedJWS.si,"utf8").toString("base64"),b64utob64(this.parsedJWS.sigvalB64U),"base64",l)}else{if(l){return m.verifyStringPSS(this.parsedJWS.si,this.parsedJWS.sigvalH,k)}else{return m.verifyString(this.parsedJWS.si,this.parsedJWS.sigvalH)}}};this.verifyJWSByPemX509Cert=function(m,k){this.parseJWS(m);var l=new X509();l.readCertPEM(k);return l.subjectPublicKeyRSA.verifyString(this.parsedJWS.si,this.parsedJWS.sigvalH)};function c(l){var m=l.alg;var k="";if(m!="RS256"&&m!="RS512"&&m!="PS256"&&m!="PS512"){throw"JWS signature algorithm not supported: "+m}if(m.substr(2)=="256"){k="sha256"}if(m.substr(2)=="512"){k="sha512"}return k}function e(k){return c(jsonParse(k))}function j(k,p,s,m,q,r){var n=new RSAKey();n.setPrivate(m,q,r);var l=e(k);var o=n.signString(s,l);return o}function i(q,p,o,n,m){var k=null;if(typeof m=="undefined"){k=e(q)}else{k=c(m)}var l=m.alg.substr(0,2)=="PS";if(n.hashAndSign){return b64tob64u(n.hashAndSign(k,o,"binary","base64",l))}else{if(l){return hextob64u(n.signStringPSS(o,k))}else{return hextob64u(n.signString(o,k))}}}function g(p,m,o,l,n){var k=b(p,m);return j(p,m,k,o,l,n)}this.generateJWSByNED=function(r,n,q,m,p){if(!this.isSafeJSONString(r)){throw"JWS Head is not safe JSON string: "+r}var l=b(r,n);var o=j(r,n,l,q,m,p);var k=hextob64u(o);this.parsedJWS={};this.parsedJWS.headB64U=l.split(".")[0];this.parsedJWS.payloadB64U=l.split(".")[1];this.parsedJWS.sigvalB64U=k;return l+"."+k};this.generateJWSByKey=function(p,n,k){var o={};if(!this.isSafeJSONString(p,o,"headP")){throw"JWS Head is not safe JSON string: "+p}var m=b(p,n);var l=i(p,n,m,k,o.headP);this.parsedJWS={};this.parsedJWS.headB64U=m.split(".")[0];this.parsedJWS.payloadB64U=m.split(".")[1];this.parsedJWS.sigvalB64U=l;return m+"."+l};function d(q,p,o,l){var n=new RSAKey();n.readPrivateKeyFromPEMString(l);var k=e(q);var m=n.signString(o,k);return m}this.generateJWSByP1PrvKey=function(p,n,k){if(!this.isSafeJSONString(p)){throw"JWS Head is not safe JSON string: "+p}var m=b(p,n);var o=d(p,n,m,k);var l=hextob64u(o);this.parsedJWS={};this.parsedJWS.headB64U=m.split(".")[0];this.parsedJWS.payloadB64U=m.split(".")[1];this.parsedJWS.sigvalB64U=l;return m+"."+l}};KJUR.jws.JWS.sign=function(b,p,i,l,k){var j=KJUR.jws.JWS;if(!j.isSafeJSONString(p)){throw"JWS Head is not safe JSON string: "+sHead}var e=j.readSafeJSONString(p);if((b==""||b==null)&&e.alg!==undefined){b=e.alg}if((b!=""&&b!=null)&&e.alg===undefined){e.alg=b;p=JSON.stringify(e)}var d=null;if(j.jwsalg2sigalg[b]===undefined){throw"unsupported alg name: "+b}else{d=j.jwsalg2sigalg[b]}var c=utf8tob64u(p);var g=utf8tob64u(i);var n=c+"."+g;var m="";if(d.substr(0,4)=="Hmac"){if(l===undefined){throw"hexadecimal key shall be specified for HMAC"}var h=new KJUR.crypto.Mac({alg:d,pass:hextorstr(l)});h.updateString(n);m=h.doFinal()}else{if(d.indexOf("withECDSA")!=-1){var o=new KJUR.crypto.Signature({alg:d});o.init(l,k);o.updateString(n);hASN1Sig=o.sign();m=KJUR.crypto.ECDSA.asn1SigToConcatSig(hASN1Sig)}else{if(d!="none"){var o=new KJUR.crypto.Signature({alg:d});o.init(l,k);o.updateString(n);m=o.sign()}}}var f=hextob64u(m);return n+"."+f};KJUR.jws.JWS.verify=function(d,m){var k=KJUR.jws.JWS;var l=d.split(".");var c=l[0];var h=l[1];var o=c+"."+h;var n=b64utohex(l[2]);var f=k.readSafeJSONString(b64utoutf8(l[0]));var b=null;if(f.alg===undefined){throw"algorithm not specified in header"}else{b=f.alg}var e=null;if(k.jwsalg2sigalg[f.alg]===undefined){throw"unsupported alg name: "+b}else{e=k.jwsalg2sigalg[b]}if(e=="none"){return true}else{if(e.substr(0,4)=="Hmac"){if(m===undefined){throw"hexadecimal key shall be specified for HMAC"}var j=new KJUR.crypto.Mac({alg:e,pass:hextorstr(m)});j.updateString(o);hSig2=j.doFinal();return n==hSig2}else{if(e.indexOf("withECDSA")!=-1){var g=null;try{g=KJUR.crypto.ECDSA.concatSigToASN1Sig(n)}catch(i){return false}var p=new KJUR.crypto.Signature({alg:e});p.init(m);p.updateString(o);return p.verify(g)}else{var p=new KJUR.crypto.Signature({alg:e});p.init(m);p.updateString(o);return p.verify(n)}}}};KJUR.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none",};KJUR.jws.JWS.isSafeJSONString=function(d,c,e){var f=null;try{f=jsonParse(d);if(typeof f!="object"){return 0}if(f.constructor===Array){return 0}if(c){c[e]=f}return 1}catch(b){return 0}};KJUR.jws.JWS.readSafeJSONString=function(c){var d=null;try{d=jsonParse(c);if(typeof d!="object"){return null}if(d.constructor===Array){return null}return d}catch(b){return null}};KJUR.jws.JWS.getEncodedSignatureValueFromJWS=function(b){if(b.match(/^[^.]+\.[^.]+\.([^.]+)$/)==null){throw"JWS signature is not a form of 'Head.Payload.SigValue'."}return RegExp.$1};KJUR.jws.IntDate=function(){};KJUR.jws.IntDate.get=function(b){if(b=="now"){return KJUR.jws.IntDate.getNow()}else{if(b=="now + 1hour"){return KJUR.jws.IntDate.getNow()+60*60}else{if(b=="now + 1day"){return KJUR.jws.IntDate.getNow()+60*60*24}else{if(b=="now + 1month"){return KJUR.jws.IntDate.getNow()+60*60*24*30}else{if(b=="now + 1year"){return KJUR.jws.IntDate.getNow()+60*60*24*365}else{if(b.match(/Z$/)){return KJUR.jws.IntDate.getZulu(b)}else{if(b.match(/^[0-9]+$/)){return parseInt(b)}}}}}}}throw"unsupported format: "+b};KJUR.jws.IntDate.getZulu=function(h){if(a=h.match(/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z/)){var g=parseInt(RegExp.$1);var i=parseInt(RegExp.$2)-1;var c=parseInt(RegExp.$3);var b=parseInt(RegExp.$4);var e=parseInt(RegExp.$5);var f=parseInt(RegExp.$6);var j=new Date(Date.UTC(g,i,c,b,e,f));return ~~(j/1000)}throw"unsupported format: "+h};KJUR.jws.IntDate.getNow=function(){var b=~~(new Date()/1000);return b};KJUR.jws.IntDate.intDate2UTCString=function(b){var c=new Date(b*1000);return c.toUTCString()};KJUR.jws.IntDate.intDate2Zulu=function(f){var j=new Date(f*1000);var i=("0000"+j.getUTCFullYear()).slice(-4);var h=("00"+(j.getUTCMonth()+1)).slice(-2);var c=("00"+j.getUTCDate()).slice(-2);var b=("00"+j.getUTCHours()).slice(-2);var e=("00"+j.getUTCMinutes()).slice(-2);var g=("00"+j.getUTCSeconds()).slice(-2);return i+h+c+b+e+g+"Z"};/*! jwsjs-2.0.0 (c) 2013 Kenji Urushima | kjur.github.com/jsjws/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.jws=="undefined"||!KJUR.jws){KJUR.jws={}}KJUR.jws.JWSJS=function(){this.aHeader=[];this.sPayload="";this.aSignature=[];this.init=function(){this.aHeader=[];this.sPayload="";this.aSignature=[]};this.initWithJWS=function(b){this.init();var a=new KJUR.jws.JWS();a.parseJWS(b);this.aHeader.push(a.parsedJWS.headB64U);this.sPayload=a.parsedJWS.payloadB64U;this.aSignature.push(a.parsedJWS.sigvalB64U)};this.addSignatureByHeaderKey=function(d,a){var c=b64utoutf8(this.sPayload);var b=new KJUR.jws.JWS();var e=b.generateJWSByP1PrvKey(d,c,a);this.aHeader.push(b.parsedJWS.headB64U);this.aSignature.push(b.parsedJWS.sigvalB64U)};this.addSignatureByHeaderPayloadKey=function(d,c,a){var b=new KJUR.jws.JWS();var e=b.generateJWSByP1PrvKey(d,c,a);this.aHeader.push(b.parsedJWS.headB64U);this.sPayload=b.parsedJWS.payloadB64U;this.aSignature.push(b.parsedJWS.sigvalB64U)};this.verifyWithCerts=function(b){if(this.aHeader.length!=b.length){throw"num headers does not match with num certs"}if(this.aSignature.length!=b.length){throw"num signatures does not match with num certs"}var j=this.sPayload;var f="";for(var c=0;c + * Build: `lodash modern -o ./dist/lodash.js` + * Copyright 2012-2013 The Dojo Foundation + * Based on Underscore.js 1.5.2 + * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre ES5 environments */ + var undefined; + + /** Used to pool arrays and objects used internally */ + var arrayPool = [], + objectPool = []; + + /** Used to generate unique IDs */ + var idCounter = 0; + + /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ + var keyPrefix = +new Date + ''; + + /** Used as the size when optimizations are enabled for large arrays */ + var largeArraySize = 75; + + /** Used as the max size of the `arrayPool` and `objectPool` */ + var maxPoolSize = 40; + + /** Used to detect and test whitespace */ + var whitespace = ( + // whitespace + ' \t\x0B\f\xA0\ufeff' + + + // line terminators + '\n\r\u2028\u2029' + + + // unicode category "Zs" space separators + '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' + ); + + /** Used to match empty string literals in compiled template source */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** + * Used to match ES6 template delimiters + * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match regexp flags from their coerced string values */ + var reFlags = /\w*$/; + + /** Used to detected named functions */ + var reFuncName = /^\s*function[ \n\r\t]+\w/; + + /** Used to match "interpolate" template delimiters */ + var reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match leading whitespace and zeros to be removed */ + var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); + + /** Used to ensure capturing order of template delimiters */ + var reNoMatch = /($^)/; + + /** Used to detect functions containing a `this` reference */ + var reThis = /\bthis\b/; + + /** Used to match unescaped characters in compiled string literals */ + var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; + + /** Used to assign default `context` object properties */ + var contextProps = [ + 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', + 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', + 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify */ + var templateCounter = 0; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + /** Used to identify object classifications that `_.clone` supports */ + var cloneableClasses = {}; + cloneableClasses[funcClass] = false; + cloneableClasses[argsClass] = cloneableClasses[arrayClass] = + cloneableClasses[boolClass] = cloneableClasses[dateClass] = + cloneableClasses[numberClass] = cloneableClasses[objectClass] = + cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; + + /** Used as an internal `_.debounce` options object */ + var debounceOptions = { + 'leading': false, + 'maxWait': 0, + 'trailing': false + }; + + /** Used as the property descriptor for `__bindData__` */ + var descriptor = { + 'configurable': false, + 'enumerable': false, + 'value': null, + 'writable': false + }; + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** Used to escape characters for inclusion in compiled string literals */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Used as a reference to the global object */ + var root = (objectTypes[typeof window] && window) || this; + + /** Detect free variable `exports` */ + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + /** Detect free variable `module` */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports` */ + var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ + var freeGlobal = objectTypes[typeof global] && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.indexOf` without support for binary searches + * or `fromIndex` constraints. + * + * @private + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value or `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array ? array.length : 0; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * An implementation of `_.contains` for cache objects that mimics the return + * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache object to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var type = typeof value; + cache = cache.cache; + + if (type == 'boolean' || value == null) { + return cache[value] ? 0 : -1; + } + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value; + cache = (cache = cache[type]) && cache[key]; + + return type == 'object' + ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) + : (cache ? 0 : -1); + } + + /** + * Adds a given value to the corresponding cache object. + * + * @private + * @param {*} value The value to add to the cache. + */ + function cachePush(value) { + var cache = this.cache, + type = typeof value; + + if (type == 'boolean' || value == null) { + cache[value] = true; + } else { + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value, + typeCache = cache[type] || (cache[type] = {}); + + if (type == 'object') { + (typeCache[key] || (typeCache[key] = [])).push(value); + } else { + typeCache[key] = true; + } + } + } + + /** + * Used by `_.max` and `_.min` as the default callback when a given + * collection is a string value. + * + * @private + * @param {string} value The character to inspect. + * @returns {number} Returns the code unit of given character. + */ + function charAtCallback(value) { + return value.charCodeAt(0); + } + + /** + * Used by `sortBy` to compare transformed `collection` elements, stable sorting + * them in ascending order. + * + * @private + * @param {Object} a The object to compare to `b`. + * @param {Object} b The object to compare to `a`. + * @returns {number} Returns the sort order indicator of `1` or `-1`. + */ + function compareAscending(a, b) { + var ac = a.criteria, + bc = b.criteria, + index = -1, + length = ac.length; + + while (++index < length) { + var value = ac[index], + other = bc[index]; + + if (value !== other) { + if (value > other || typeof value == 'undefined') { + return 1; + } + if (value < other || typeof other == 'undefined') { + return -1; + } + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to return the same value for + // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 + // + // This also ensures a stable sort in V8 and other engines. + // See http://code.google.com/p/v8/issues/detail?id=90 + return a.index - b.index; + } + + /** + * Creates a cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [array=[]] The array to search. + * @returns {null|Object} Returns the cache object or `null` if caching should not be used. + */ + function createCache(array) { + var index = -1, + length = array.length, + first = array[0], + mid = array[(length / 2) | 0], + last = array[length - 1]; + + if (first && typeof first == 'object' && + mid && typeof mid == 'object' && last && typeof last == 'object') { + return false; + } + var cache = getObject(); + cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; + + var result = getObject(); + result.array = array; + result.cache = cache; + result.push = cachePush; + + while (++index < length) { + result.push(array[index]); + } + return result; + } + + /** + * Used by `template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {string} match The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(match) { + return '\\' + stringEscapes[match]; + } + + /** + * Gets an array from the array pool or creates a new one if the pool is empty. + * + * @private + * @returns {Array} The array from the pool. + */ + function getArray() { + return arrayPool.pop() || []; + } + + /** + * Gets an object from the object pool or creates a new one if the pool is empty. + * + * @private + * @returns {Object} The object from the pool. + */ + function getObject() { + return objectPool.pop() || { + 'array': null, + 'cache': null, + 'criteria': null, + 'false': false, + 'index': 0, + 'null': false, + 'number': null, + 'object': null, + 'push': null, + 'string': null, + 'true': false, + 'undefined': false, + 'value': null + }; + } + + /** + * Releases the given array back to the array pool. + * + * @private + * @param {Array} [array] The array to release. + */ + function releaseArray(array) { + array.length = 0; + if (arrayPool.length < maxPoolSize) { + arrayPool.push(array); + } + } + + /** + * Releases the given object back to the object pool. + * + * @private + * @param {Object} [object] The object to release. + */ + function releaseObject(object) { + var cache = object.cache; + if (cache) { + releaseObject(cache); + } + object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; + if (objectPool.length < maxPoolSize) { + objectPool.push(object); + } + } + + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used instead of `Array#slice` to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|string} collection The collection to slice. + * @param {number} start The start index. + * @param {number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new `lodash` function using the given context object. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} [context=root] The context object. + * @returns {Function} Returns the `lodash` function. + */ + function runInContext(context) { + // Avoid issues with some ES3 environments that attempt to use values, named + // after built-in constructors like `Object`, for the creation of literals. + // ES5 clears this up by stating that literals must use built-in constructors. + // See http://es5.github.io/#x11.1.5. + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Native constructor references */ + var Array = context.Array, + Boolean = context.Boolean, + Date = context.Date, + Function = context.Function, + Math = context.Math, + Number = context.Number, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** + * Used for `Array` method references. + * + * Normally `Array.prototype` would suffice, however, using an array literal + * avoids issues in Narwhal. + */ + var arrayRef = []; + + /** Used for native method references */ + var objectProto = Object.prototype; + + /** Used to restore the original `_` reference in `noConflict` */ + var oldDash = context._; + + /** Used to resolve the internal [[Class]] of values */ + var toString = objectProto.toString; + + /** Used to detect if a method is native */ + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + /** Native method shortcuts */ + var ceil = Math.ceil, + clearTimeout = context.clearTimeout, + floor = Math.floor, + fnToString = Function.prototype.toString, + getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + hasOwnProperty = objectProto.hasOwnProperty, + push = arrayRef.push, + setTimeout = context.setTimeout, + splice = arrayRef.splice, + unshift = arrayRef.unshift; + + /** Used to set meta data on functions */ + var defineProperty = (function() { + // IE 8 only accepts DOM elements + try { + var o = {}, + func = isNative(func = Object.defineProperty) && func, + result = func(o, o, o) && func; + } catch(e) { } + return result; + }()); + + /* Native method shortcuts for methods with the same name as other `lodash` methods */ + var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, + nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, + nativeIsFinite = context.isFinite, + nativeIsNaN = context.isNaN, + nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, + nativeMax = Math.max, + nativeMin = Math.min, + nativeParseInt = context.parseInt, + nativeRandom = Math.random; + + /** Used to lookup a built-in constructor by [[Class]] */ + var ctorByClass = {}; + ctorByClass[arrayClass] = Array; + ctorByClass[boolClass] = Boolean; + ctorByClass[dateClass] = Date; + ctorByClass[funcClass] = Function; + ctorByClass[objectClass] = Object; + ctorByClass[numberClass] = Number; + ctorByClass[regexpClass] = RegExp; + ctorByClass[stringClass] = String; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps the given value to enable intuitive + * method chaining. + * + * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, + * and `unshift` + * + * Chaining is supported in custom builds as long as the `value` method is + * implicitly or explicitly included in the build. + * + * The chainable wrapper functions are: + * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, + * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, + * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, + * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, + * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, + * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, + * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, + * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, + * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, + * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, + * and `zip` + * + * The non-chainable wrapper functions are: + * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, + * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, + * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, + * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, + * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, + * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, + * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, + * `template`, `unescape`, `uniqueId`, and `value` + * + * The wrapper functions `first` and `last` return wrapped values when `n` is + * provided, otherwise they return unwrapped values. + * + * Explicit chaining can be enabled by using the `_.chain` method. + * + * @name _ + * @constructor + * @category Chaining + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns a `lodash` instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(num) { + * return num * num; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor + return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) + ? value + : new lodashWrapper(value); + } + + /** + * A fast path for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap in a `lodash` instance. + * @param {boolean} chainAll A flag to enable chaining for all methods + * @returns {Object} Returns a `lodash` instance. + */ + function lodashWrapper(value, chainAll) { + this.__chain__ = !!chainAll; + this.__wrapped__ = value; + } + // ensure `new lodashWrapper` is an instance of `lodash` + lodashWrapper.prototype = lodash.prototype; + + /** + * An object used to flag environments features. + * + * @static + * @memberOf _ + * @type Object + */ + var support = lodash.support = {}; + + /** + * Detect if functions can be decompiled by `Function#toString` + * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). + * + * @memberOf _.support + * @type boolean + */ + support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); + + /** + * Detect if `Function#name` is supported (all but IE). + * + * @memberOf _.support + * @type boolean + */ + support.funcNames = typeof Function.name == 'string'; + + /** + * By default, the template delimiters used by Lo-Dash are similar to those in + * embedded Ruby (ERB). Change the following template settings to use alternative + * delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': /<%-([\s\S]+?)%>/g, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': /<%([\s\S]+?)%>/g, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type string + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type Object + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type Function + */ + '_': lodash + } + }; + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.bind` that creates the bound function and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new bound function. + */ + function baseBind(bindData) { + var func = bindData[0], + partialArgs = bindData[2], + thisArg = bindData[4]; + + function bound() { + // `Function#bind` spec + // http://es5.github.io/#x15.3.4.5 + if (partialArgs) { + // avoid `arguments` object deoptimizations by using `slice` instead + // of `Array.prototype.slice.call` and not assigning `arguments` to a + // variable as a ternary expression + var args = slice(partialArgs); + push.apply(args, arguments); + } + // mimic the constructor's `return` behavior + // http://es5.github.io/#x13.2.2 + if (this instanceof bound) { + // ensure `new bound` is an instance of `func` + var thisBinding = baseCreate(func.prototype), + result = func.apply(thisBinding, args || arguments); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisArg, args || arguments); + } + setBindData(bound, bindData); + return bound; + } + + /** + * The base implementation of `_.clone` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates clones with source counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, callback, stackA, stackB) { + if (callback) { + var result = callback(value); + if (typeof result != 'undefined') { + return result; + } + } + // inspect [[Class]] + var isObj = isObject(value); + if (isObj) { + var className = toString.call(value); + if (!cloneableClasses[className]) { + return value; + } + var ctor = ctorByClass[className]; + switch (className) { + case boolClass: + case dateClass: + return new ctor(+value); + + case numberClass: + case stringClass: + return new ctor(value); + + case regexpClass: + result = ctor(value.source, reFlags.exec(value)); + result.lastIndex = value.lastIndex; + return result; + } + } else { + return value; + } + var isArr = isArray(value); + if (isDeep) { + // check for circular references and return corresponding clone + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); + + var length = stackA.length; + while (length--) { + if (stackA[length] == value) { + return stackB[length]; + } + } + result = isArr ? ctor(value.length) : {}; + } + else { + result = isArr ? slice(value) : assign({}, value); + } + // add array properties assigned by `RegExp#exec` + if (isArr) { + if (hasOwnProperty.call(value, 'index')) { + result.index = value.index; + } + if (hasOwnProperty.call(value, 'input')) { + result.input = value.input; + } + } + // exit for shallow clone + if (!isDeep) { + return result; + } + // add the source value to the stack of traversed objects + // and associate it with its clone + stackA.push(value); + stackB.push(result); + + // recursively populate clone (susceptible to call stack limits) + (isArr ? forEach : forOwn)(value, function(objValue, key) { + result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); + }); + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } + return result; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + function baseCreate(prototype, properties) { + return isObject(prototype) ? nativeCreate(prototype) : {}; + } + // fallback for browsers without `Object.create` + if (!nativeCreate) { + baseCreate = (function() { + function Object() {} + return function(prototype) { + if (isObject(prototype)) { + Object.prototype = prototype; + var result = new Object; + Object.prototype = null; + } + return result || context.Object(); + }; + }()); + } + + /** + * The base implementation of `_.createCallback` without support for creating + * "_.pluck" or "_.where" style callbacks. + * + * @private + * @param {*} [func=identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of the created callback. + * @param {number} [argCount] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + */ + function baseCreateCallback(func, thisArg, argCount) { + if (typeof func != 'function') { + return identity; + } + // exit early for no `thisArg` or already bound by `Function#bind` + if (typeof thisArg == 'undefined' || !('prototype' in func)) { + return func; + } + var bindData = func.__bindData__; + if (typeof bindData == 'undefined') { + if (support.funcNames) { + bindData = !func.name; + } + bindData = bindData || !support.funcDecomp; + if (!bindData) { + var source = fnToString.call(func); + if (!support.funcNames) { + bindData = !reFuncName.test(source); + } + if (!bindData) { + // checks if `func` references the `this` keyword and stores the result + bindData = reThis.test(source); + setBindData(func, bindData); + } + } + } + // exit early if there are no `this` references or `func` is bound + if (bindData === false || (bindData !== true && bindData[1] & 1)) { + return func; + } + switch (argCount) { + case 1: return function(value) { + return func.call(thisArg, value); + }; + case 2: return function(a, b) { + return func.call(thisArg, a, b); + }; + case 3: return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + } + return bind(func, thisArg); + } + + /** + * The base implementation of `createWrapper` that creates the wrapper and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new function. + */ + function baseCreateWrapper(bindData) { + var func = bindData[0], + bitmask = bindData[1], + partialArgs = bindData[2], + partialRightArgs = bindData[3], + thisArg = bindData[4], + arity = bindData[5]; + + var isBind = bitmask & 1, + isBindKey = bitmask & 2, + isCurry = bitmask & 4, + isCurryBound = bitmask & 8, + key = func; + + function bound() { + var thisBinding = isBind ? thisArg : this; + if (partialArgs) { + var args = slice(partialArgs); + push.apply(args, arguments); + } + if (partialRightArgs || isCurry) { + args || (args = slice(arguments)); + if (partialRightArgs) { + push.apply(args, partialRightArgs); + } + if (isCurry && args.length < arity) { + bitmask |= 16 & ~32; + return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); + } + } + args || (args = arguments); + if (isBindKey) { + func = thisBinding[key]; + } + if (this instanceof bound) { + thisBinding = baseCreate(func.prototype); + var result = func.apply(thisBinding, args); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisBinding, args); + } + setBindData(bound, bindData); + return bound; + } + + /** + * The base implementation of `_.difference` that accepts a single array + * of values to exclude. + * + * @private + * @param {Array} array The array to process. + * @param {Array} [values] The array of values to exclude. + * @returns {Array} Returns a new array of filtered values. + */ + function baseDifference(array, values) { + var index = -1, + indexOf = getIndexOf(), + length = array ? array.length : 0, + isLarge = length >= largeArraySize && indexOf === baseIndexOf, + result = []; + + if (isLarge) { + var cache = createCache(values); + if (cache) { + indexOf = cacheIndexOf; + values = cache; + } else { + isLarge = false; + } + } + while (++index < length) { + var value = array[index]; + if (indexOf(values, value) < 0) { + result.push(value); + } + } + if (isLarge) { + releaseObject(values); + } + return result; + } + + /** + * The base implementation of `_.flatten` without support for callback + * shorthands or `thisArg` binding. + * + * @private + * @param {Array} array The array to flatten. + * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. + * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. + * @param {number} [fromIndex=0] The index to start from. + * @returns {Array} Returns a new flattened array. + */ + function baseFlatten(array, isShallow, isStrict, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + + if (value && typeof value == 'object' && typeof value.length == 'number' + && (isArray(value) || isArguments(value))) { + // recursively flatten arrays (susceptible to call stack limits) + if (!isShallow) { + value = baseFlatten(value, isShallow, isStrict); + } + var valIndex = -1, + valLength = value.length, + resIndex = result.length; + + result.length += valLength; + while (++valIndex < valLength) { + result[resIndex++] = value[valIndex]; + } + } else if (!isStrict) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.isEqual`, without support for `thisArg` binding, + * that allows partial "_.where" style comparisons. + * + * @private + * @param {*} a The value to compare. + * @param {*} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. + * @param {Array} [stackA=[]] Tracks traversed `a` objects. + * @param {Array} [stackB=[]] Tracks traversed `b` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { + // used to indicate that when comparing objects, `a` has at least the properties of `b` + if (callback) { + var result = callback(a, b); + if (typeof result != 'undefined') { + return !!result; + } + } + // exit early for identical values + if (a === b) { + // treat `+0` vs. `-0` as not equal + return a !== 0 || (1 / a == 1 / b); + } + var type = typeof a, + otherType = typeof b; + + // exit early for unlike primitive values + if (a === a && + !(a && objectTypes[type]) && + !(b && objectTypes[otherType])) { + return false; + } + // exit early for `null` and `undefined` avoiding ES3's Function#call behavior + // http://es5.github.io/#x15.3.4.4 + if (a == null || b == null) { + return a === b; + } + // compare [[Class]] names + var className = toString.call(a), + otherClass = toString.call(b); + + if (className == argsClass) { + className = objectClass; + } + if (otherClass == argsClass) { + otherClass = objectClass; + } + if (className != otherClass) { + return false; + } + switch (className) { + case boolClass: + case dateClass: + // coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0` treating invalid dates coerced to `NaN` as not equal + return +a == +b; + + case numberClass: + // treat `NaN` vs. `NaN` as equal + return (a != +a) + ? b != +b + // but treat `+0` vs. `-0` as not equal + : (a == 0 ? (1 / a == 1 / b) : a == +b); + + case regexpClass: + case stringClass: + // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) + // treat string primitives and their corresponding object instances as equal + return a == String(b); + } + var isArr = className == arrayClass; + if (!isArr) { + // unwrap any `lodash` wrapped values + var aWrapped = hasOwnProperty.call(a, '__wrapped__'), + bWrapped = hasOwnProperty.call(b, '__wrapped__'); + + if (aWrapped || bWrapped) { + return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB); + } + // exit for functions and DOM nodes + if (className != objectClass) { + return false; + } + // in older versions of Opera, `arguments` objects have `Array` constructors + var ctorA = a.constructor, + ctorB = b.constructor; + + // non `Object` object instances with different constructors are not equal + if (ctorA != ctorB && + !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && + ('constructor' in a && 'constructor' in b) + ) { + return false; + } + } + // assume cyclic structures are equal + // the algorithm for detecting cyclic structures is adapted from ES 5.1 + // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); + + var length = stackA.length; + while (length--) { + if (stackA[length] == a) { + return stackB[length] == b; + } + } + var size = 0; + result = true; + + // add `a` and `b` to the stack of traversed objects + stackA.push(a); + stackB.push(b); + + // recursively compare objects and arrays (susceptible to call stack limits) + if (isArr) { + // compare lengths to determine if a deep comparison is necessary + length = a.length; + size = b.length; + result = size == length; + + if (result || isWhere) { + // deep compare the contents, ignoring non-numeric properties + while (size--) { + var index = length, + value = b[size]; + + if (isWhere) { + while (index--) { + if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { + break; + } + } + } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { + break; + } + } + } + } + else { + // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` + // which, in this case, is more costly + forIn(b, function(value, key, b) { + if (hasOwnProperty.call(b, key)) { + // count the number of properties. + size++; + // deep compare each property value. + return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); + } + }); + + if (result && !isWhere) { + // ensure both objects have the same number of properties + forIn(a, function(value, key, a) { + if (hasOwnProperty.call(a, key)) { + // `size` will be `-1` if `a` has more properties than `b` + return (result = --size > -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } + return result; + } + + /** + * The base implementation of `_.merge` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} [callback] The function to customize merging properties. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + */ + function baseMerge(object, source, callback, stackA, stackB) { + (isArray(source) ? forEach : forOwn)(source, function(source, key) { + var found, + isArr, + result = source, + value = object[key]; + + if (source && ((isArr = isArray(source)) || isPlainObject(source))) { + // avoid merging previously merged cyclic sources + var stackLength = stackA.length; + while (stackLength--) { + if ((found = stackA[stackLength] == source)) { + value = stackB[stackLength]; + break; + } + } + if (!found) { + var isShallow; + if (callback) { + result = callback(value, source); + if ((isShallow = typeof result != 'undefined')) { + value = result; + } + } + if (!isShallow) { + value = isArr + ? (isArray(value) ? value : []) + : (isPlainObject(value) ? value : {}); + } + // add `source` and associated `value` to the stack of traversed objects + stackA.push(source); + stackB.push(value); + + // recursively merge objects and arrays (susceptible to call stack limits) + if (!isShallow) { + baseMerge(value, source, callback, stackA, stackB); + } + } + } + else { + if (callback) { + result = callback(value, source); + if (typeof result == 'undefined') { + result = source; + } + } + if (typeof result != 'undefined') { + value = result; + } + } + object[key] = value; + }); + } + + /** + * The base implementation of `_.random` without argument juggling or support + * for returning floating-point numbers. + * + * @private + * @param {number} min The minimum possible value. + * @param {number} max The maximum possible value. + * @returns {number} Returns a random number. + */ + function baseRandom(min, max) { + return min + floor(nativeRandom() * (max - min + 1)); + } + + /** + * The base implementation of `_.uniq` without support for callback shorthands + * or `thisArg` binding. + * + * @private + * @param {Array} array The array to process. + * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. + * @param {Function} [callback] The function called per iteration. + * @returns {Array} Returns a duplicate-value-free array. + */ + function baseUniq(array, isSorted, callback) { + var index = -1, + indexOf = getIndexOf(), + length = array ? array.length : 0, + result = []; + + var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, + seen = (callback || isLarge) ? getArray() : result; + + if (isLarge) { + var cache = createCache(seen); + indexOf = cacheIndexOf; + seen = cache; + } + while (++index < length) { + var value = array[index], + computed = callback ? callback(value, index, array) : value; + + if (isSorted + ? !index || seen[seen.length - 1] !== computed + : indexOf(seen, computed) < 0 + ) { + if (callback || isLarge) { + seen.push(computed); + } + result.push(value); + } + } + if (isLarge) { + releaseArray(seen.array); + releaseObject(seen); + } else if (callback) { + releaseArray(seen); + } + return result; + } + + /** + * Creates a function that aggregates a collection, creating an object composed + * of keys generated from the results of running each element of the collection + * through a callback. The given `setter` function sets the keys and values + * of the composed object. + * + * @private + * @param {Function} setter The setter function. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter) { + return function(collection, callback, thisArg) { + var result = {}; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + setter(result, value, callback(value, index, collection), collection); + } + } else { + forOwn(collection, function(value, key, collection) { + setter(result, value, callback(value, key, collection), collection); + }); + } + return result; + }; + } + + /** + * Creates a function that, when called, either curries or invokes `func` + * with an optional `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of method flags to compose. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` + * 8 - `_.curry` (bound) + * 16 - `_.partial` + * 32 - `_.partialRight` + * @param {Array} [partialArgs] An array of arguments to prepend to those + * provided to the new function. + * @param {Array} [partialRightArgs] An array of arguments to append to those + * provided to the new function. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new function. + */ + function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { + var isBind = bitmask & 1, + isBindKey = bitmask & 2, + isCurry = bitmask & 4, + isCurryBound = bitmask & 8, + isPartial = bitmask & 16, + isPartialRight = bitmask & 32; + + if (!isBindKey && !isFunction(func)) { + throw new TypeError; + } + if (isPartial && !partialArgs.length) { + bitmask &= ~16; + isPartial = partialArgs = false; + } + if (isPartialRight && !partialRightArgs.length) { + bitmask &= ~32; + isPartialRight = partialRightArgs = false; + } + var bindData = func && func.__bindData__; + if (bindData && bindData !== true) { + // clone `bindData` + bindData = slice(bindData); + if (bindData[2]) { + bindData[2] = slice(bindData[2]); + } + if (bindData[3]) { + bindData[3] = slice(bindData[3]); + } + // set `thisBinding` is not previously bound + if (isBind && !(bindData[1] & 1)) { + bindData[4] = thisArg; + } + // set if previously bound but not currently (subsequent curried functions) + if (!isBind && bindData[1] & 1) { + bitmask |= 8; + } + // set curried arity if not yet set + if (isCurry && !(bindData[1] & 4)) { + bindData[5] = arity; + } + // append partial left arguments + if (isPartial) { + push.apply(bindData[2] || (bindData[2] = []), partialArgs); + } + // append partial right arguments + if (isPartialRight) { + unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); + } + // merge flags + bindData[1] |= bitmask; + return createWrapper.apply(null, bindData); + } + // fast path for `_.bind` + var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; + return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); + } + + /** + * Used by `escape` to convert characters to HTML entities. + * + * @private + * @param {string} match The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeHtmlChar(match) { + return htmlEscapes[match]; + } + + /** + * Gets the appropriate "indexOf" function. If the `_.indexOf` method is + * customized, this method returns the custom method, otherwise it returns + * the `baseIndexOf` function. + * + * @private + * @returns {Function} Returns the "indexOf" function. + */ + function getIndexOf() { + var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; + return result; + } + + /** + * Checks if `value` is a native function. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. + */ + function isNative(value) { + return typeof value == 'function' && reNative.test(value); + } + + /** + * Sets `this` binding data on a given function. + * + * @private + * @param {Function} func The function to set data on. + * @param {Array} value The data array to set. + */ + var setBindData = !defineProperty ? noop : function(func, value) { + descriptor.value = value; + defineProperty(func, '__bindData__', descriptor); + }; + + /** + * A fallback implementation of `isPlainObject` which checks if a given value + * is an object created by the `Object` constructor, assuming objects created + * by the `Object` constructor have no inherited enumerable properties and that + * there are no `Object.prototype` extensions. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + var ctor, + result; + + // avoid non Object objects, `arguments` objects, and DOM elements + if (!(value && toString.call(value) == objectClass) || + (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) { + return false; + } + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + forIn(value, function(value, key) { + result = key; + }); + return typeof result == 'undefined' || hasOwnProperty.call(value, result); + } + + /** + * Used by `unescape` to convert HTML entities to characters. + * + * @private + * @param {string} match The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + function unescapeHtmlChar(match) { + return htmlUnescapes[match]; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Checks if `value` is an `arguments` object. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. + * @example + * + * (function() { return _.isArguments(arguments); })(1, 2, 3); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == argsClass || false; + } + + /** + * Checks if `value` is an array. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an array, else `false`. + * @example + * + * (function() { return _.isArray(arguments); })(); + * // => false + * + * _.isArray([1, 2, 3]); + * // => true + */ + var isArray = nativeIsArray || function(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == arrayClass || false; + }; + + /** + * A fallback implementation of `Object.keys` which produces an array of the + * given object's own enumerable property names. + * + * @private + * @type Function + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + */ + var shimKeys = function(object) { + var index, iterable = object, result = []; + if (!iterable) return result; + if (!(objectTypes[typeof object])) return result; + for (index in iterable) { + if (hasOwnProperty.call(iterable, index)) { + result.push(index); + } + } + return result + }; + + /** + * Creates an array composed of the own enumerable property names of an object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + * @example + * + * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); + * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) + */ + var keys = !nativeKeys ? shimKeys : function(object) { + if (!isObject(object)) { + return []; + } + return nativeKeys(object); + }; + + /** + * Used to convert characters to HTML entities: + * + * Though the `>` character is escaped for symmetry, characters like `>` and `/` + * don't require escaping in HTML and have no special meaning unless they're part + * of a tag or an unquoted attribute value. + * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") + */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to convert HTML entities to characters */ + var htmlUnescapes = invert(htmlEscapes); + + /** Used to match HTML entities and HTML characters */ + var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), + reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); + + /*--------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources will overwrite property assignments of previous + * sources. If a callback is provided it will be executed to produce the + * assigned values. The callback is bound to `thisArg` and invoked with two + * arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @type Function + * @alias extend + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize assigning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); + * // => { 'name': 'fred', 'employer': 'slate' } + * + * var defaults = _.partialRight(_.assign, function(a, b) { + * return typeof a == 'undefined' ? b : a; + * }); + * + * var object = { 'name': 'barney' }; + * defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var assign = function(object, source, guard) { + var index, iterable = object, result = iterable; + if (!iterable) return result; + var args = arguments, + argsIndex = 0, + argsLength = typeof guard == 'number' ? 2 : args.length; + if (argsLength > 3 && typeof args[argsLength - 2] == 'function') { + var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2); + } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') { + callback = args[--argsLength]; + } + while (++argsIndex < argsLength) { + iterable = args[argsIndex]; + if (iterable && objectTypes[typeof iterable]) { + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]; + } + } + } + return result + }; + + /** + * Creates a clone of `value`. If `isDeep` is `true` nested objects will also + * be cloned, otherwise they will be assigned by reference. If a callback + * is provided it will be executed to produce the cloned values. If the + * callback returns `undefined` cloning will be handled by the method instead. + * The callback is bound to `thisArg` and invoked with one argument; (value). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var shallow = _.clone(characters); + * shallow[0] === characters[0]; + * // => true + * + * var deep = _.clone(characters, true); + * deep[0] === characters[0]; + * // => false + * + * _.mixin({ + * 'clone': _.partialRight(_.clone, function(value) { + * return _.isElement(value) ? value.cloneNode(false) : undefined; + * }) + * }); + * + * var clone = _.clone(document.body); + * clone.childNodes.length; + * // => 0 + */ + function clone(value, isDeep, callback, thisArg) { + // allows working with "Collections" methods without using their `index` + // and `collection` arguments for `isDeep` and `callback` + if (typeof isDeep != 'boolean' && isDeep != null) { + thisArg = callback; + callback = isDeep; + isDeep = false; + } + return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); + } + + /** + * Creates a deep clone of `value`. If a callback is provided it will be + * executed to produce the cloned values. If the callback returns `undefined` + * cloning will be handled by the method instead. The callback is bound to + * `thisArg` and invoked with one argument; (value). + * + * Note: This method is loosely based on the structured clone algorithm. Functions + * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and + * objects created by constructors other than `Object` are cloned to plain `Object` objects. + * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the deep cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var deep = _.cloneDeep(characters); + * deep[0] === characters[0]; + * // => false + * + * var view = { + * 'label': 'docs', + * 'node': element + * }; + * + * var clone = _.cloneDeep(view, function(value) { + * return _.isElement(value) ? value.cloneNode(true) : undefined; + * }); + * + * clone.node == view.node; + * // => false + */ + function cloneDeep(value, callback, thisArg) { + return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); + } + + /** + * Creates an object that inherits from the given `prototype` object. If a + * `properties` object is provided its own enumerable properties are assigned + * to the created object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? assign(result, properties) : result; + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object for all destination properties that resolve to `undefined`. Once a + * property is set, additional defaults of the same property will be ignored. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param- {Object} [guard] Allows working with `_.reduce` without using its + * `key` and `object` arguments as sources. + * @returns {Object} Returns the destination object. + * @example + * + * var object = { 'name': 'barney' }; + * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var defaults = function(object, source, guard) { + var index, iterable = object, result = iterable; + if (!iterable) return result; + var args = arguments, + argsIndex = 0, + argsLength = typeof guard == 'number' ? 2 : args.length; + while (++argsIndex < argsLength) { + iterable = args[argsIndex]; + if (iterable && objectTypes[typeof iterable]) { + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + if (typeof result[index] == 'undefined') result[index] = iterable[index]; + } + } + } + return result + }; + + /** + * This method is like `_.findIndex` except that it returns the key of the + * first element that passes the callback check, instead of the element itself. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to search. + * @param {Function|Object|string} [callback=identity] The function called per + * iteration. If a property name or object is provided it will be used to + * create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {string|undefined} Returns the key of the found element, else `undefined`. + * @example + * + * var characters = { + * 'barney': { 'age': 36, 'blocked': false }, + * 'fred': { 'age': 40, 'blocked': true }, + * 'pebbles': { 'age': 1, 'blocked': false } + * }; + * + * _.findKey(characters, function(chr) { + * return chr.age < 40; + * }); + * // => 'barney' (property order is not guaranteed across environments) + * + * // using "_.where" callback shorthand + * _.findKey(characters, { 'age': 1 }); + * // => 'pebbles' + * + * // using "_.pluck" callback shorthand + * _.findKey(characters, 'blocked'); + * // => 'fred' + */ + function findKey(object, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forOwn(object, function(value, key, object) { + if (callback(value, key, object)) { + result = key; + return false; + } + }); + return result; + } + + /** + * This method is like `_.findKey` except that it iterates over elements + * of a `collection` in the opposite order. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to search. + * @param {Function|Object|string} [callback=identity] The function called per + * iteration. If a property name or object is provided it will be used to + * create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {string|undefined} Returns the key of the found element, else `undefined`. + * @example + * + * var characters = { + * 'barney': { 'age': 36, 'blocked': true }, + * 'fred': { 'age': 40, 'blocked': false }, + * 'pebbles': { 'age': 1, 'blocked': true } + * }; + * + * _.findLastKey(characters, function(chr) { + * return chr.age < 40; + * }); + * // => returns `pebbles`, assuming `_.findKey` returns `barney` + * + * // using "_.where" callback shorthand + * _.findLastKey(characters, { 'age': 40 }); + * // => 'fred' + * + * // using "_.pluck" callback shorthand + * _.findLastKey(characters, 'blocked'); + * // => 'pebbles' + */ + function findLastKey(object, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forOwnRight(object, function(value, key, object) { + if (callback(value, key, object)) { + result = key; + return false; + } + }); + return result; + } + + /** + * Iterates over own and inherited enumerable properties of an object, + * executing the callback for each property. The callback is bound to `thisArg` + * and invoked with three arguments; (value, key, object). Callbacks may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forIn(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) + */ + var forIn = function(collection, callback, thisArg) { + var index, iterable = collection, result = iterable; + if (!iterable) return result; + if (!objectTypes[typeof iterable]) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + for (index in iterable) { + if (callback(iterable[index], index, collection) === false) return result; + } + return result + }; + + /** + * This method is like `_.forIn` except that it iterates over elements + * of a `collection` in the opposite order. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forInRight(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move' + */ + function forInRight(object, callback, thisArg) { + var pairs = []; + + forIn(object, function(value, key) { + pairs.push(key, value); + }); + + var length = pairs.length; + callback = baseCreateCallback(callback, thisArg, 3); + while (length--) { + if (callback(pairs[length--], pairs[length], object) === false) { + break; + } + } + return object; + } + + /** + * Iterates over own enumerable properties of an object, executing the callback + * for each property. The callback is bound to `thisArg` and invoked with three + * arguments; (value, key, object). Callbacks may exit iteration early by + * explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) + */ + var forOwn = function(collection, callback, thisArg) { + var index, iterable = collection, result = iterable; + if (!iterable) return result; + if (!objectTypes[typeof iterable]) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + if (callback(iterable[index], index, collection) === false) return result; + } + return result + }; + + /** + * This method is like `_.forOwn` except that it iterates over elements + * of a `collection` in the opposite order. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' + */ + function forOwnRight(object, callback, thisArg) { + var props = keys(object), + length = props.length; + + callback = baseCreateCallback(callback, thisArg, 3); + while (length--) { + var key = props[length]; + if (callback(object[key], key, object) === false) { + break; + } + } + return object; + } + + /** + * Creates a sorted array of property names of all enumerable properties, + * own and inherited, of `object` that have function values. + * + * @static + * @memberOf _ + * @alias methods + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names that have function values. + * @example + * + * _.functions(_); + * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] + */ + function functions(object) { + var result = []; + forIn(object, function(value, key) { + if (isFunction(value)) { + result.push(key); + } + }); + return result.sort(); + } + + /** + * Checks if the specified property name exists as a direct property of `object`, + * instead of an inherited property. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @param {string} key The name of the property to check. + * @returns {boolean} Returns `true` if key is a direct property, else `false`. + * @example + * + * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); + * // => true + */ + function has(object, key) { + return object ? hasOwnProperty.call(object, key) : false; + } + + /** + * Creates an object composed of the inverted keys and values of the given object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to invert. + * @returns {Object} Returns the created inverted object. + * @example + * + * _.invert({ 'first': 'fred', 'second': 'barney' }); + * // => { 'fred': 'first', 'barney': 'second' } + */ + function invert(object) { + var index = -1, + props = keys(object), + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index]; + result[object[key]] = key; + } + return result; + } + + /** + * Checks if `value` is a boolean value. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. + * @example + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + value && typeof value == 'object' && toString.call(value) == boolClass || false; + } + + /** + * Checks if `value` is a date. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a date, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + */ + function isDate(value) { + return value && typeof value == 'object' && toString.call(value) == dateClass || false; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + */ + function isElement(value) { + return value && value.nodeType === 1 || false; + } + + /** + * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a + * length of `0` and objects with no own enumerable properties are considered + * "empty". + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object|string} value The value to inspect. + * @returns {boolean} Returns `true` if the `value` is empty, else `false`. + * @example + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({}); + * // => true + * + * _.isEmpty(''); + * // => true + */ + function isEmpty(value) { + var result = true; + if (!value) { + return result; + } + var className = toString.call(value), + length = value.length; + + if ((className == arrayClass || className == stringClass || className == argsClass ) || + (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { + return !length; + } + forOwn(value, function() { + return (result = false); + }); + return result; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent to each other. If a callback is provided it will be executed + * to compare values. If the callback returns `undefined` comparisons will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (a, b). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} a The value to compare. + * @param {*} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'name': 'fred' }; + * var copy = { 'name': 'fred' }; + * + * object == copy; + * // => false + * + * _.isEqual(object, copy); + * // => true + * + * var words = ['hello', 'goodbye']; + * var otherWords = ['hi', 'goodbye']; + * + * _.isEqual(words, otherWords, function(a, b) { + * var reGreet = /^(?:hello|hi)$/i, + * aGreet = _.isString(a) && reGreet.test(a), + * bGreet = _.isString(b) && reGreet.test(b); + * + * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; + * }); + * // => true + */ + function isEqual(a, b, callback, thisArg) { + return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); + } + + /** + * Checks if `value` is, or can be coerced to, a finite number. + * + * Note: This is not the same as native `isFinite` which will return true for + * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is finite, else `false`. + * @example + * + * _.isFinite(-101); + * // => true + * + * _.isFinite('10'); + * // => true + * + * _.isFinite(true); + * // => false + * + * _.isFinite(''); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + function isFinite(value) { + return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); + } + + /** + * Checks if `value` is a function. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + */ + function isFunction(value) { + return typeof value == 'function'; + } + + /** + * Checks if `value` is the language type of Object. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // check if the value is the ECMAScript language type of Object + // http://es5.github.io/#x8 + // and avoid a V8 bug + // http://code.google.com/p/v8/issues/detail?id=2291 + return !!(value && objectTypes[typeof value]); + } + + /** + * Checks if `value` is `NaN`. + * + * Note: This is not the same as native `isNaN` which will return `true` for + * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // `NaN` as a primitive is the only value that is not equal to itself + // (perform the [[Class]] check first to avoid errors with some host objects in IE) + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(undefined); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is a number. + * + * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a number, else `false`. + * @example + * + * _.isNumber(8.4 * 5); + * // => true + */ + function isNumber(value) { + return typeof value == 'number' || + value && typeof value == 'object' && toString.call(value) == numberClass || false; + } + + /** + * Checks if `value` is an object created by the `Object` constructor. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * _.isPlainObject(new Shape); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + */ + var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { + if (!(value && toString.call(value) == objectClass)) { + return false; + } + var valueOf = value.valueOf, + objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); + + return objProto + ? (value == objProto || getPrototypeOf(value) == objProto) + : shimIsPlainObject(value); + }; + + /** + * Checks if `value` is a regular expression. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. + * @example + * + * _.isRegExp(/fred/); + * // => true + */ + function isRegExp(value) { + return value && typeof value == 'object' && toString.call(value) == regexpClass || false; + } + + /** + * Checks if `value` is a string. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a string, else `false`. + * @example + * + * _.isString('fred'); + * // => true + */ + function isString(value) { + return typeof value == 'string' || + value && typeof value == 'object' && toString.call(value) == stringClass || false; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + */ + function isUndefined(value) { + return typeof value == 'undefined'; + } + + /** + * Creates an object with the same keys as `object` and values generated by + * running each own enumerable property of `object` through the callback. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new object with values of the results of each `callback` execution. + * @example + * + * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + * + * var characters = { + * 'fred': { 'name': 'fred', 'age': 40 }, + * 'pebbles': { 'name': 'pebbles', 'age': 1 } + * }; + * + * // using "_.pluck" callback shorthand + * _.mapValues(characters, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } + */ + function mapValues(object, callback, thisArg) { + var result = {}; + callback = lodash.createCallback(callback, thisArg, 3); + + forOwn(object, function(value, key, object) { + result[key] = callback(value, key, object); + }); + return result; + } + + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined` into the destination object. Subsequent sources + * will overwrite property assignments of previous sources. If a callback is + * provided it will be executed to produce the merged values of the destination + * and source properties. If the callback returns `undefined` merging will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize merging properties. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * var names = { + * 'characters': [ + * { 'name': 'barney' }, + * { 'name': 'fred' } + * ] + * }; + * + * var ages = { + * 'characters': [ + * { 'age': 36 }, + * { 'age': 40 } + * ] + * }; + * + * _.merge(names, ages); + * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } + * + * var food = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var otherFood = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(food, otherFood, function(a, b) { + * return _.isArray(a) ? a.concat(b) : undefined; + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } + */ + function merge(object) { + var args = arguments, + length = 2; + + if (!isObject(object)) { + return object; + } + // allows working with `_.reduce` and `_.reduceRight` without using + // their `index` and `collection` arguments + if (typeof args[2] != 'number') { + length = args.length; + } + if (length > 3 && typeof args[length - 2] == 'function') { + var callback = baseCreateCallback(args[--length - 1], args[length--], 2); + } else if (length > 2 && typeof args[length - 1] == 'function') { + callback = args[--length]; + } + var sources = slice(arguments, 1, length), + index = -1, + stackA = getArray(), + stackB = getArray(); + + while (++index < length) { + baseMerge(object, sources[index], callback, stackA, stackB); + } + releaseArray(stackA); + releaseArray(stackB); + return object; + } + + /** + * Creates a shallow clone of `object` excluding the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a callback is provided it will be executed for each + * property of `object` omitting the properties the callback returns truey + * for. The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|...string|string[]} [callback] The properties to omit or the + * function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object without the omitted properties. + * @example + * + * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); + * // => { 'name': 'fred' } + * + * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { + * return typeof value == 'number'; + * }); + * // => { 'name': 'fred' } + */ + function omit(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var props = []; + forIn(object, function(value, key) { + props.push(key); + }); + props = baseDifference(props, baseFlatten(arguments, true, false, 1)); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + result[key] = object[key]; + } + } else { + callback = lodash.createCallback(callback, thisArg, 3); + forIn(object, function(value, key, object) { + if (!callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * Creates a two dimensional array of an object's key-value pairs, + * i.e. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns new array of key-value pairs. + * @example + * + * _.pairs({ 'barney': 36, 'fred': 40 }); + * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) + */ + function pairs(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + var key = props[index]; + result[index] = [key, object[key]]; + } + return result; + } + + /** + * Creates a shallow clone of `object` composed of the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a callback is provided it will be executed for each + * property of `object` picking the properties the callback returns truey + * for. The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|...string|string[]} [callback] The function called per + * iteration or property names to pick, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object composed of the picked properties. + * @example + * + * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); + * // => { 'name': 'fred' } + * + * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { + * return key.charAt(0) != '_'; + * }); + * // => { 'name': 'fred' } + */ + function pick(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var index = -1, + props = baseFlatten(arguments, true, false, 1), + length = isObject(object) ? props.length : 0; + + while (++index < length) { + var key = props[index]; + if (key in object) { + result[key] = object[key]; + } + } + } else { + callback = lodash.createCallback(callback, thisArg, 3); + forIn(object, function(value, key, object) { + if (callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * An alternative to `_.reduce` this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable properties through a callback, with each callback execution + * potentially mutating the `accumulator` object. The callback is bound to + * `thisArg` and invoked with four arguments; (accumulator, value, key, object). + * Callbacks may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { + * num *= num; + * if (num % 2) { + * return result.push(num) < 3; + * } + * }); + * // => [1, 9, 25] + * + * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function transform(object, callback, accumulator, thisArg) { + var isArr = isArray(object); + if (accumulator == null) { + if (isArr) { + accumulator = []; + } else { + var ctor = object && object.constructor, + proto = ctor && ctor.prototype; + + accumulator = baseCreate(proto); + } + } + if (callback) { + callback = lodash.createCallback(callback, thisArg, 4); + (isArr ? forEach : forOwn)(object, function(value, index, object) { + return callback(accumulator, value, index, object); + }); + } + return accumulator; + } + + /** + * Creates an array composed of the own enumerable property values of `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property values. + * @example + * + * _.values({ 'one': 1, 'two': 2, 'three': 3 }); + * // => [1, 2, 3] (property order is not guaranteed across environments) + */ + function values(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array of elements from the specified indexes, or keys, of the + * `collection`. Indexes may be specified as individual arguments or as arrays + * of indexes. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` + * to retrieve, specified as individual indexes or arrays of indexes. + * @returns {Array} Returns a new array of elements corresponding to the + * provided indexes. + * @example + * + * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); + * // => ['a', 'c', 'e'] + * + * _.at(['fred', 'barney', 'pebbles'], 0, 2); + * // => ['fred', 'pebbles'] + */ + function at(collection) { + var args = arguments, + index = -1, + props = baseFlatten(args, true, false, 1), + length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, + result = Array(length); + + while(++index < length) { + result[index] = collection[props[index]]; + } + return result; + } + + /** + * Checks if a given value is present in a collection using strict equality + * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the + * offset from the end of the collection. + * + * @static + * @memberOf _ + * @alias include + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {*} target The value to check for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {boolean} Returns `true` if the `target` element is found, else `false`. + * @example + * + * _.contains([1, 2, 3], 1); + * // => true + * + * _.contains([1, 2, 3], 1, 2); + * // => false + * + * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.contains('pebbles', 'eb'); + * // => true + */ + function contains(collection, target, fromIndex) { + var index = -1, + indexOf = getIndexOf(), + length = collection ? collection.length : 0, + result = false; + + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; + if (isArray(collection)) { + result = indexOf(collection, target, fromIndex) > -1; + } else if (typeof length == 'number') { + result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; + } else { + forOwn(collection, function(value) { + if (++index >= fromIndex) { + return !(result = value === target); + } + }); + } + return result; + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through the callback. The corresponding value + * of each key is the number of times the key was returned by the callback. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); + }); + + /** + * Checks if the given callback returns truey value for **all** elements of + * a collection. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if all elements passed the callback check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes']); + * // => false + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.every(characters, 'age'); + * // => true + * + * // using "_.where" callback shorthand + * _.every(characters, { 'age': 36 }); + * // => false + */ + function every(collection, callback, thisArg) { + var result = true; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + if (!(result = !!callback(collection[index], index, collection))) { + break; + } + } + } else { + forOwn(collection, function(value, index, collection) { + return (result = !!callback(value, index, collection)); + }); + } + return result; + } + + /** + * Iterates over elements of a collection, returning an array of all elements + * the callback returns truey for. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that passed the callback check. + * @example + * + * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [2, 4, 6] + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.filter(characters, 'blocked'); + * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] + * + * // using "_.where" callback shorthand + * _.filter(characters, { 'age': 36 }); + * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] + */ + function filter(collection, callback, thisArg) { + var result = []; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + result.push(value); + } + } + } else { + forOwn(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result.push(value); + } + }); + } + return result; + } + + /** + * Iterates over elements of a collection, returning the first element that + * the callback returns truey for. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias detect, findWhere + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the found element, else `undefined`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true }, + * { 'name': 'pebbles', 'age': 1, 'blocked': false } + * ]; + * + * _.find(characters, function(chr) { + * return chr.age < 40; + * }); + * // => { 'name': 'barney', 'age': 36, 'blocked': false } + * + * // using "_.where" callback shorthand + * _.find(characters, { 'age': 1 }); + * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } + * + * // using "_.pluck" callback shorthand + * _.find(characters, 'blocked'); + * // => { 'name': 'fred', 'age': 40, 'blocked': true } + */ + function find(collection, callback, thisArg) { + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + return value; + } + } + } else { + var result; + forOwn(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + } + + /** + * This method is like `_.find` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the found element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(num) { + * return num % 2 == 1; + * }); + * // => 3 + */ + function findLast(collection, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forEachRight(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + + /** + * Iterates over elements of a collection, executing the callback for each + * element. The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). Callbacks may exit iteration early by + * explicitly returning `false`. + * + * Note: As with other "Collections" methods, objects with a `length` property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); + * // => logs each number and returns '1,2,3' + * + * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + * // => logs each number and returns the object (property order is not guaranteed across environments) + */ + function forEach(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0; + + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + if (typeof length == 'number') { + while (++index < length) { + if (callback(collection[index], index, collection) === false) { + break; + } + } + } else { + forOwn(collection, callback); + } + return collection; + } + + /** + * This method is like `_.forEach` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); + * // => logs each number from right to left and returns '3,2,1' + */ + function forEachRight(collection, callback, thisArg) { + var length = collection ? collection.length : 0; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + if (typeof length == 'number') { + while (length--) { + if (callback(collection[length], length, collection) === false) { + break; + } + } + } else { + var props = keys(collection); + length = props.length; + forOwn(collection, function(value, key, collection) { + key = props ? props[--length] : --length; + return callback(collection[key], key, collection); + }); + } + return collection; + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of a collection through the callback. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false` + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using "_.pluck" callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of the collection through the given callback. The corresponding + * value of each key is the last element responsible for generating the key. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keys = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keys, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ + var indexBy = createAggregator(function(result, value, key) { + result[key] = value; + }); + + /** + * Invokes the method named by `methodName` on each element in the `collection` + * returning an array of the results of each invoked method. Additional arguments + * will be provided to each invoked method. If `methodName` is a function it + * will be invoked for, and `this` bound to, each element in the `collection`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|string} methodName The name of the method to invoke or + * the function invoked per iteration. + * @param {...*} [arg] Arguments to invoke the method with. + * @returns {Array} Returns a new array of the results of each invoked method. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + function invoke(collection, methodName) { + var args = slice(arguments, 2), + index = -1, + isFunc = typeof methodName == 'function', + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); + }); + return result; + } + + /** + * Creates an array of values by running each element in the collection + * through the callback. The callback is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias collect + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of the results of each `callback` execution. + * @example + * + * _.map([1, 2, 3], function(num) { return num * 3; }); + * // => [3, 6, 9] + * + * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); + * // => [3, 6, 9] (property order is not guaranteed across environments) + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(characters, 'name'); + * // => ['barney', 'fred'] + */ + function map(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + if (typeof length == 'number') { + var result = Array(length); + while (++index < length) { + result[index] = callback(collection[index], index, collection); + } + } else { + result = []; + forOwn(collection, function(value, key, collection) { + result[++index] = callback(value, key, collection); + }); + } + return result; + } + + /** + * Retrieves the maximum value of a collection. If the collection is empty or + * falsey `-Infinity` is returned. If a callback is provided it will be executed + * for each value in the collection to generate the criterion by which the value + * is ranked. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.max(characters, function(chr) { return chr.age; }); + * // => { 'name': 'fred', 'age': 40 }; + * + * // using "_.pluck" callback shorthand + * _.max(characters, 'age'); + * // => { 'name': 'fred', 'age': 40 }; + */ + function max(collection, callback, thisArg) { + var computed = -Infinity, + result = computed; + + // allows working with functions like `_.map` without using + // their `index` argument as a callback + if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { + callback = null; + } + if (callback == null && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value > result) { + result = value; + } + } + } else { + callback = (callback == null && isString(collection)) + ? charAtCallback + : lodash.createCallback(callback, thisArg, 3); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current > computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the minimum value of a collection. If the collection is empty or + * falsey `Infinity` is returned. If a callback is provided it will be executed + * for each value in the collection to generate the criterion by which the value + * is ranked. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.min(characters, function(chr) { return chr.age; }); + * // => { 'name': 'barney', 'age': 36 }; + * + * // using "_.pluck" callback shorthand + * _.min(characters, 'age'); + * // => { 'name': 'barney', 'age': 36 }; + */ + function min(collection, callback, thisArg) { + var computed = Infinity, + result = computed; + + // allows working with functions like `_.map` without using + // their `index` argument as a callback + if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { + callback = null; + } + if (callback == null && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value < result) { + result = value; + } + } + } else { + callback = (callback == null && isString(collection)) + ? charAtCallback + : lodash.createCallback(callback, thisArg, 3); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current < computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the value of a specified property from all elements in the collection. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {string} property The name of the property to pluck. + * @returns {Array} Returns a new array of property values. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.pluck(characters, 'name'); + * // => ['barney', 'fred'] + */ + var pluck = map; + + /** + * Reduces a collection to a value which is the accumulated result of running + * each element in the collection through the callback, where each successive + * callback execution consumes the return value of the previous execution. If + * `accumulator` is not provided the first element of the collection will be + * used as the initial `accumulator` value. The callback is bound to `thisArg` + * and invoked with four arguments; (accumulator, value, index|key, collection). + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] Initial value of the accumulator. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var sum = _.reduce([1, 2, 3], function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function reduce(collection, callback, accumulator, thisArg) { + if (!collection) return accumulator; + var noaccum = arguments.length < 3; + callback = lodash.createCallback(callback, thisArg, 4); + + var index = -1, + length = collection.length; + + if (typeof length == 'number') { + if (noaccum) { + accumulator = collection[++index]; + } + while (++index < length) { + accumulator = callback(accumulator, collection[index], index, collection); + } + } else { + forOwn(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection) + }); + } + return accumulator; + } + + /** + * This method is like `_.reduce` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] Initial value of the accumulator. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var list = [[0, 1], [2, 3], [4, 5]]; + * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, callback, accumulator, thisArg) { + var noaccum = arguments.length < 3; + callback = lodash.createCallback(callback, thisArg, 4); + forEachRight(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The opposite of `_.filter` this method returns the elements of a + * collection that the callback does **not** return truey for. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that failed the callback check. + * @example + * + * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [1, 3, 5] + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.reject(characters, 'blocked'); + * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] + * + * // using "_.where" callback shorthand + * _.reject(characters, { 'age': 36 }); + * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] + */ + function reject(collection, callback, thisArg) { + callback = lodash.createCallback(callback, thisArg, 3); + return filter(collection, function(value, index, collection) { + return !callback(value, index, collection); + }); + } + + /** + * Retrieves a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Allows working with functions like `_.map` + * without using their `index` arguments as `n`. + * @returns {Array} Returns the random sample(s) of `collection`. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ + function sample(collection, n, guard) { + if (collection && typeof collection.length != 'number') { + collection = values(collection); + } + if (n == null || guard) { + return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; + } + var result = shuffle(collection); + result.length = nativeMin(nativeMax(0, n), result.length); + return result; + } + + /** + * Creates an array of shuffled values, using a version of the Fisher-Yates + * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns a new shuffled collection. + * @example + * + * _.shuffle([1, 2, 3, 4, 5, 6]); + * // => [4, 1, 6, 3, 5, 2] + */ + function shuffle(collection) { + var index = -1, + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + var rand = baseRandom(0, ++index); + result[index] = result[rand]; + result[rand] = value; + }); + return result; + } + + /** + * Gets the size of the `collection` by returning `collection.length` for arrays + * and array-like objects or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns `collection.length` or number of own enumerable properties. + * @example + * + * _.size([1, 2]); + * // => 2 + * + * _.size({ 'one': 1, 'two': 2, 'three': 3 }); + * // => 3 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + var length = collection ? collection.length : 0; + return typeof length == 'number' ? length : keys(collection).length; + } + + /** + * Checks if the callback returns a truey value for **any** element of a + * collection. The function returns as soon as it finds a passing value and + * does not iterate over the entire collection. The callback is bound to + * `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if any element passed the callback check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.some(characters, 'blocked'); + * // => true + * + * // using "_.where" callback shorthand + * _.some(characters, { 'age': 1 }); + * // => false + */ + function some(collection, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + if ((result = callback(collection[index], index, collection))) { + break; + } + } + } else { + forOwn(collection, function(value, index, collection) { + return !(result = callback(value, index, collection)); + }); + } + return !!result; + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through the callback. This method + * performs a stable sort, that is, it will preserve the original sort order + * of equal elements. The callback is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an array of property names is provided for `callback` the collection + * will be sorted by each property value. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of sorted elements. + * @example + * + * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); + * // => [3, 1, 2] + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 }, + * { 'name': 'barney', 'age': 26 }, + * { 'name': 'fred', 'age': 30 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(_.sortBy(characters, 'age'), _.values); + * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] + * + * // sorting by multiple properties + * _.map(_.sortBy(characters, ['name', 'age']), _.values); + * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] + */ + function sortBy(collection, callback, thisArg) { + var index = -1, + isArr = isArray(callback), + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + if (!isArr) { + callback = lodash.createCallback(callback, thisArg, 3); + } + forEach(collection, function(value, key, collection) { + var object = result[++index] = getObject(); + if (isArr) { + object.criteria = map(callback, function(key) { return value[key]; }); + } else { + (object.criteria = getArray())[0] = callback(value, key, collection); + } + object.index = index; + object.value = value; + }); + + length = result.length; + result.sort(compareAscending); + while (length--) { + var object = result[length]; + result[length] = object.value; + if (!isArr) { + releaseArray(object.criteria); + } + releaseObject(object); + } + return result; + } + + /** + * Converts the `collection` to an array. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to convert. + * @returns {Array} Returns the new converted array. + * @example + * + * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); + * // => [2, 3, 4] + */ + function toArray(collection) { + if (collection && typeof collection.length == 'number') { + return slice(collection); + } + return values(collection); + } + + /** + * Performs a deep comparison of each element in a `collection` to the given + * `properties` object, returning an array of all elements that have equivalent + * property values. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Object} props The object of property values to filter by. + * @returns {Array} Returns a new array of elements that have the given properties. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, + * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.where(characters, { 'age': 36 }); + * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] + * + * _.where(characters, { 'pets': ['dino'] }); + * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] + */ + var where = filter; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are all falsey. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result.push(value); + } + } + return result; + } + + /** + * Creates an array excluding all values of the provided arrays using strict + * equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to process. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); + * // => [1, 3, 4] + */ + function difference(array) { + return baseDifference(array, baseFlatten(arguments, true, true, 1)); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element that passes the callback check, instead of the element itself. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true }, + * { 'name': 'pebbles', 'age': 1, 'blocked': false } + * ]; + * + * _.findIndex(characters, function(chr) { + * return chr.age < 20; + * }); + * // => 2 + * + * // using "_.where" callback shorthand + * _.findIndex(characters, { 'age': 36 }); + * // => 0 + * + * // using "_.pluck" callback shorthand + * _.findIndex(characters, 'blocked'); + * // => 1 + */ + function findIndex(array, callback, thisArg) { + var index = -1, + length = array ? array.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length) { + if (callback(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of a `collection` from right to left. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': true }, + * { 'name': 'fred', 'age': 40, 'blocked': false }, + * { 'name': 'pebbles', 'age': 1, 'blocked': true } + * ]; + * + * _.findLastIndex(characters, function(chr) { + * return chr.age > 30; + * }); + * // => 1 + * + * // using "_.where" callback shorthand + * _.findLastIndex(characters, { 'age': 36 }); + * // => 0 + * + * // using "_.pluck" callback shorthand + * _.findLastIndex(characters, 'blocked'); + * // => 2 + */ + function findLastIndex(array, callback, thisArg) { + var length = array ? array.length : 0; + callback = lodash.createCallback(callback, thisArg, 3); + while (length--) { + if (callback(array[length], length, array)) { + return length; + } + } + return -1; + } + + /** + * Gets the first element or first `n` elements of an array. If a callback + * is provided elements at the beginning of the array are returned as long + * as the callback returns truey. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias head, take + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback] The function called + * per element or the number of elements to return. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the first element(s) of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([1, 2, 3], 2); + * // => [1, 2] + * + * _.first([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [1, 2] + * + * var characters = [ + * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.first(characters, 'blocked'); + * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] + * + * // using "_.where" callback shorthand + * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); + * // => ['barney', 'fred'] + */ + function first(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = -1; + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array ? array[0] : undefined; + } + } + return slice(array, 0, nativeMin(nativeMax(0, n), length)); + } + + /** + * Flattens a nested array (the nesting can be to any depth). If `isShallow` + * is truey, the array will only be flattened a single level. If a callback + * is provided each element of the array is passed through the callback before + * flattening. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to flatten. + * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new flattened array. + * @example + * + * _.flatten([1, [2], [3, [[4]]]]); + * // => [1, 2, 3, 4]; + * + * _.flatten([1, [2], [3, [[4]]]], true); + * // => [1, 2, 3, [[4]]]; + * + * var characters = [ + * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, + * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } + * ]; + * + * // using "_.pluck" callback shorthand + * _.flatten(characters, 'pets'); + * // => ['hoppy', 'baby puss', 'dino'] + */ + function flatten(array, isShallow, callback, thisArg) { + // juggle arguments + if (typeof isShallow != 'boolean' && isShallow != null) { + thisArg = callback; + callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow; + isShallow = false; + } + if (callback != null) { + array = map(array, callback, thisArg); + } + return baseFlatten(array, isShallow); + } + + /** + * Gets the index at which the first occurrence of `value` is found using + * strict equality for comparisons, i.e. `===`. If the array is already sorted + * providing `true` for `fromIndex` will run a faster binary search. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value or `-1`. + * @example + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2); + * // => 1 + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 4 + * + * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + if (typeof fromIndex == 'number') { + var length = array ? array.length : 0; + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); + } else if (fromIndex) { + var index = sortedIndex(array, value); + return array[index] === value ? index : -1; + } + return baseIndexOf(array, value, fromIndex); + } + + /** + * Gets all but the last element or last `n` elements of an array. If a + * callback is provided elements at the end of the array are excluded from + * the result as long as the callback returns truey. The callback is bound + * to `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + * + * _.initial([1, 2, 3], 2); + * // => [1] + * + * _.initial([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [1] + * + * var characters = [ + * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.initial(characters, 'blocked'); + * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] + * + * // using "_.where" callback shorthand + * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); + * // => ['barney', 'fred'] + */ + function initial(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = lodash.createCallback(callback, thisArg, 3); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : callback || n; + } + return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); + } + + /** + * Creates an array of unique values present in all provided arrays using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of shared values. + * @example + * + * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2] + */ + function intersection() { + var args = [], + argsIndex = -1, + argsLength = arguments.length, + caches = getArray(), + indexOf = getIndexOf(), + trustIndexOf = indexOf === baseIndexOf, + seen = getArray(); + + while (++argsIndex < argsLength) { + var value = arguments[argsIndex]; + if (isArray(value) || isArguments(value)) { + args.push(value); + caches.push(trustIndexOf && value.length >= largeArraySize && + createCache(argsIndex ? args[argsIndex] : seen)); + } + } + var array = args[0], + index = -1, + length = array ? array.length : 0, + result = []; + + outer: + while (++index < length) { + var cache = caches[0]; + value = array[index]; + + if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { + argsIndex = argsLength; + (cache || seen).push(value); + while (--argsIndex) { + cache = caches[argsIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { + continue outer; + } + } + result.push(value); + } + } + while (argsLength--) { + cache = caches[argsLength]; + if (cache) { + releaseObject(cache); + } + } + releaseArray(caches); + releaseArray(seen); + return result; + } + + /** + * Gets the last element or last `n` elements of an array. If a callback is + * provided elements at the end of the array are returned as long as the + * callback returns truey. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback] The function called + * per element or the number of elements to return. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the last element(s) of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + * + * _.last([1, 2, 3], 2); + * // => [2, 3] + * + * _.last([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [2, 3] + * + * var characters = [ + * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.pluck(_.last(characters, 'blocked'), 'name'); + * // => ['fred', 'pebbles'] + * + * // using "_.where" callback shorthand + * _.last(characters, { 'employer': 'na' }); + * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] + */ + function last(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = lodash.createCallback(callback, thisArg, 3); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array ? array[length - 1] : undefined; + } + } + return slice(array, nativeMax(0, length - n)); + } + + /** + * Gets the index at which the last occurrence of `value` is found using strict + * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used + * as the offset from the end of the collection. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value or `-1`. + * @example + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); + * // => 4 + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var index = array ? array.length : 0; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Removes all provided values from the given array using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to modify. + * @param {...*} [value] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ + function pull(array) { + var args = arguments, + argsIndex = 0, + argsLength = args.length, + length = array ? array.length : 0; + + while (++argsIndex < argsLength) { + var index = -1, + value = args[argsIndex]; + while (++index < length) { + if (array[index] === value) { + splice.call(array, index--, 1); + length--; + } + } + } + return array; + } + + /** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to but not including `end`. If `start` is less than `stop` a + * zero-length range is created unless a negative `step` is specified. + * + * @static + * @memberOf _ + * @category Arrays + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns a new range array. + * @example + * + * _.range(4); + * // => [0, 1, 2, 3] + * + * _.range(1, 5); + * // => [1, 2, 3, 4] + * + * _.range(0, 20, 5); + * // => [0, 5, 10, 15] + * + * _.range(0, -4, -1); + * // => [0, -1, -2, -3] + * + * _.range(1, 4, 0); + * // => [1, 1, 1] + * + * _.range(0); + * // => [] + */ + function range(start, end, step) { + start = +start || 0; + step = typeof step == 'number' ? step : (+step || 1); + + if (end == null) { + end = start; + start = 0; + } + // use `Array(length)` so engines like Chakra and V8 avoid slower modes + // http://youtu.be/XAqIpGU8ZZk#t=17m25s + var index = -1, + length = nativeMax(0, ceil((end - start) / (step || 1))), + result = Array(length); + + while (++index < length) { + result[index] = start; + start += step; + } + return result; + } + + /** + * Removes all elements from an array that the callback returns truey for + * and returns an array of removed elements. The callback is bound to `thisArg` + * and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to modify. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4, 5, 6]; + * var evens = _.remove(array, function(num) { return num % 2 == 0; }); + * + * console.log(array); + * // => [1, 3, 5] + * + * console.log(evens); + * // => [2, 4, 6] + */ + function remove(array, callback, thisArg) { + var index = -1, + length = array ? array.length : 0, + result = []; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (callback(value, index, array)) { + result.push(value); + splice.call(array, index--, 1); + length--; + } + } + return result; + } + + /** + * The opposite of `_.initial` this method gets all but the first element or + * first `n` elements of an array. If a callback function is provided elements + * at the beginning of the array are excluded from the result as long as the + * callback returns truey. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias drop, tail + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + * + * _.rest([1, 2, 3], 2); + * // => [3] + * + * _.rest([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [3] + * + * var characters = [ + * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.pluck(_.rest(characters, 'blocked'), 'name'); + * // => ['fred', 'pebbles'] + * + * // using "_.where" callback shorthand + * _.rest(characters, { 'employer': 'slate' }); + * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] + */ + function rest(array, callback, thisArg) { + if (typeof callback != 'number' && callback != null) { + var n = 0, + index = -1, + length = array ? array.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); + } + return slice(array, n); + } + + /** + * Uses a binary search to determine the smallest index at which a value + * should be inserted into a given sorted array in order to maintain the sort + * order of the array. If a callback is provided it will be executed for + * `value` and each element of `array` to compute their sort ranking. The + * callback is bound to `thisArg` and invoked with one argument; (value). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([20, 30, 50], 40); + * // => 2 + * + * // using "_.pluck" callback shorthand + * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 2 + * + * var dict = { + * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } + * }; + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return dict.wordToNumber[word]; + * }); + * // => 2 + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return this.wordToNumber[word]; + * }, dict); + * // => 2 + */ + function sortedIndex(array, value, callback, thisArg) { + var low = 0, + high = array ? array.length : low; + + // explicitly reference `identity` for better inlining in Firefox + callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; + value = callback(value); + + while (low < high) { + var mid = (low + high) >>> 1; + (callback(array[mid]) < value) + ? low = mid + 1 + : high = mid; + } + return low; + } + + /** + * Creates an array of unique values, in order, of the provided arrays using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of combined values. + * @example + * + * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2, 3, 5, 4] + */ + function union() { + return baseUniq(baseFlatten(arguments, true, true)); + } + + /** + * Creates a duplicate-value-free version of an array using strict equality + * for comparisons, i.e. `===`. If the array is sorted, providing + * `true` for `isSorted` will use a faster algorithm. If a callback is provided + * each element of `array` is passed through the callback before uniqueness + * is computed. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Arrays + * @param {Array} array The array to process. + * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a duplicate-value-free array. + * @example + * + * _.uniq([1, 2, 1, 3, 1]); + * // => [1, 2, 3] + * + * _.uniq([1, 1, 2, 2, 3], true); + * // => [1, 2, 3] + * + * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); + * // => ['A', 'b', 'C'] + * + * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); + * // => [1, 2.5, 3] + * + * // using "_.pluck" callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniq(array, isSorted, callback, thisArg) { + // juggle arguments + if (typeof isSorted != 'boolean' && isSorted != null) { + thisArg = callback; + callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; + isSorted = false; + } + if (callback != null) { + callback = lodash.createCallback(callback, thisArg, 3); + } + return baseUniq(array, isSorted, callback); + } + + /** + * Creates an array excluding all provided values using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to filter. + * @param {...*} [value] The values to exclude. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); + * // => [2, 3, 4] + */ + function without(array) { + return baseDifference(array, slice(arguments, 1)); + } + + /** + * Creates an array that is the symmetric difference of the provided arrays. + * See http://en.wikipedia.org/wiki/Symmetric_difference. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of values. + * @example + * + * _.xor([1, 2, 3], [5, 2, 1, 4]); + * // => [3, 5, 4] + * + * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); + * // => [1, 4, 5] + */ + function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArray(array) || isArguments(array)) { + var result = result + ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result))) + : array; + } + } + return result || []; + } + + /** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second + * elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @alias unzip + * @category Arrays + * @param {...Array} [array] Arrays to process. + * @returns {Array} Returns a new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ + function zip() { + var array = arguments.length > 1 ? arguments : arguments[0], + index = -1, + length = array ? max(pluck(array, 'length')) : 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = pluck(array, index); + } + return result; + } + + /** + * Creates an object composed from arrays of `keys` and `values`. Provide + * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` + * or two arrays, one of `keys` and one of corresponding `values`. + * + * @static + * @memberOf _ + * @alias object + * @category Arrays + * @param {Array} keys The array of keys. + * @param {Array} [values=[]] The array of values. + * @returns {Object} Returns an object composed of the given keys and + * corresponding values. + * @example + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ + function zipObject(keys, values) { + var index = -1, + length = keys ? keys.length : 0, + result = {}; + + if (!values && length && !isArray(keys[0])) { + values = []; + } + while (++index < length) { + var key = keys[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that executes `func`, with the `this` binding and + * arguments of the created function, only after being called `n` times. + * + * @static + * @memberOf _ + * @category Functions + * @param {number} n The number of times the function must be called before + * `func` is executed. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('Done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'Done saving!', after all saves have completed + */ + function after(n, func) { + if (!isFunction(func)) { + throw new TypeError; + } + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that, when called, invokes `func` with the `this` + * binding of `thisArg` and prepends any additional `bind` arguments to those + * provided to the bound function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to bind. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var func = function(greeting) { + * return greeting + ' ' + this.name; + * }; + * + * func = _.bind(func, { 'name': 'fred' }, 'hi'); + * func(); + * // => 'hi fred' + */ + function bind(func, thisArg) { + return arguments.length > 2 + ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) + : createWrapper(func, 1, null, null, thisArg); + } + + /** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all the function properties + * of `object` will be bound. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...string} [methodName] The object method names to + * bind, specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { console.log('clicked ' + this.label); } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs', when the button is clicked + */ + function bindAll(object) { + var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), + index = -1, + length = funcs.length; + + while (++index < length) { + var key = funcs[index]; + object[key] = createWrapper(object[key], 1, null, null, object); + } + return object; + } + + /** + * Creates a function that, when called, invokes the method at `object[key]` + * and prepends any additional `bindKey` arguments to those provided to the bound + * function. This method differs from `_.bind` by allowing bound functions to + * reference methods that will be redefined or don't yet exist. + * See http://michaux.ca/articles/lazy-function-definition-pattern. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'name': 'fred', + * 'greet': function(greeting) { + * return greeting + ' ' + this.name; + * } + * }; + * + * var func = _.bindKey(object, 'greet', 'hi'); + * func(); + * // => 'hi fred' + * + * object.greet = function(greeting) { + * return greeting + 'ya ' + this.name + '!'; + * }; + * + * func(); + * // => 'hiya fred!' + */ + function bindKey(object, key) { + return arguments.length > 2 + ? createWrapper(key, 19, slice(arguments, 2), null, object) + : createWrapper(key, 3, null, null, object); + } + + /** + * Creates a function that is the composition of the provided functions, + * where each function consumes the return value of the function that follows. + * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. + * Each function is executed with the `this` binding of the composed function. + * + * @static + * @memberOf _ + * @category Functions + * @param {...Function} [func] Functions to compose. + * @returns {Function} Returns the new composed function. + * @example + * + * var realNameMap = { + * 'pebbles': 'penelope' + * }; + * + * var format = function(name) { + * name = realNameMap[name.toLowerCase()] || name; + * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); + * }; + * + * var greet = function(formatted) { + * return 'Hiya ' + formatted + '!'; + * }; + * + * var welcome = _.compose(greet, format); + * welcome('pebbles'); + * // => 'Hiya Penelope!' + */ + function compose() { + var funcs = arguments, + length = funcs.length; + + while (length--) { + if (!isFunction(funcs[length])) { + throw new TypeError; + } + } + return function() { + var args = arguments, + length = funcs.length; + + while (length--) { + args = [funcs[length].apply(this, args)]; + } + return args[0]; + }; + } + + /** + * Creates a function which accepts one or more arguments of `func` that when + * invoked either executes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` can be specified + * if `func.length` is not sufficient. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @returns {Function} Returns the new curried function. + * @example + * + * var curried = _.curry(function(a, b, c) { + * console.log(a + b + c); + * }); + * + * curried(1)(2)(3); + * // => 6 + * + * curried(1, 2)(3); + * // => 6 + * + * curried(1, 2, 3); + * // => 6 + */ + function curry(func, arity) { + arity = typeof arity == 'number' ? arity : (+arity || func.length); + return createWrapper(func, 4, null, null, null, arity); + } + + /** + * Creates a function that will delay the execution of `func` until after + * `wait` milliseconds have elapsed since the last time it was invoked. + * Provide an options object to indicate that `func` should be invoked on + * the leading and/or trailing edge of the `wait` timeout. Subsequent calls + * to the debounced function will return the result of the last `func` call. + * + * Note: If `leading` and `trailing` options are `true` `func` will be called + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to debounce. + * @param {number} wait The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. + * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * var lazyLayout = _.debounce(calculateLayout, 150); + * jQuery(window).on('resize', lazyLayout); + * + * // execute `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * }); + * + * // ensure `batchLog` is executed once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * source.addEventListener('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * }, false); + */ + function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (!isFunction(func)) { + throw new TypeError; + } + wait = nativeMax(0, wait) || 0; + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = options.leading; + maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); + trailing = 'trailing' in options ? options.trailing : trailing; + } + var delayed = function() { + var remaining = wait - (now() - stamp); + if (remaining <= 0) { + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + var isCalled = trailingCall; + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } else { + timeoutId = setTimeout(delayed, remaining); + } + }; + + var maxDelayed = function() { + if (timeoutId) { + clearTimeout(timeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (trailing || (maxWait !== wait)) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + }; + + return function() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + return result; + }; + } + + /** + * Defers executing the `func` function until the current call stack has cleared. + * Additional arguments will be provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to defer. + * @param {...*} [arg] Arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { console.log(text); }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ + function defer(func) { + if (!isFunction(func)) { + throw new TypeError; + } + var args = slice(arguments, 1); + return setTimeout(function() { func.apply(undefined, args); }, 1); + } + + /** + * Executes the `func` function after `wait` milliseconds. Additional arguments + * will be provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay execution. + * @param {...*} [arg] Arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { console.log(text); }, 1000, 'later'); + * // => logs 'later' after one second + */ + function delay(func, wait) { + if (!isFunction(func)) { + throw new TypeError; + } + var args = slice(arguments, 2); + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it will be used to determine the cache key for storing the result + * based on the arguments provided to the memoized function. By default, the + * first argument provided to the memoized function is used as the cache key. + * The `func` is executed with the `this` binding of the memoized function. + * The result cache is exposed as the `cache` property on the memoized function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] A function used to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var fibonacci = _.memoize(function(n) { + * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); + * }); + * + * fibonacci(9) + * // => 34 + * + * var data = { + * 'fred': { 'name': 'fred', 'age': 40 }, + * 'pebbles': { 'name': 'pebbles', 'age': 1 } + * }; + * + * // modifying the result cache + * var get = _.memoize(function(name) { return data[name]; }, _.identity); + * get('pebbles'); + * // => { 'name': 'pebbles', 'age': 1 } + * + * get.cache.pebbles.name = 'penelope'; + * get('pebbles'); + * // => { 'name': 'penelope', 'age': 1 } + */ + function memoize(func, resolver) { + if (!isFunction(func)) { + throw new TypeError; + } + var memoized = function() { + var cache = memoized.cache, + key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; + + return hasOwnProperty.call(cache, key) + ? cache[key] + : (cache[key] = func.apply(this, arguments)); + } + memoized.cache = {}; + return memoized; + } + + /** + * Creates a function that is restricted to execute `func` once. Repeat calls to + * the function will return the value of the first call. The `func` is executed + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` executes `createApplication` once + */ + function once(func) { + var ran, + result; + + if (!isFunction(func)) { + throw new TypeError; + } + return function() { + if (ran) { + return result; + } + ran = true; + result = func.apply(this, arguments); + + // clear the `func` variable so the function may be garbage collected + func = null; + return result; + }; + } + + /** + * Creates a function that, when called, invokes `func` with any additional + * `partial` arguments prepended to those provided to the new function. This + * method is similar to `_.bind` except it does **not** alter the `this` binding. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { return greeting + ' ' + name; }; + * var hi = _.partial(greet, 'hi'); + * hi('fred'); + * // => 'hi fred' + */ + function partial(func) { + return createWrapper(func, 16, slice(arguments, 1)); + } + + /** + * This method is like `_.partial` except that `partial` arguments are + * appended to those provided to the new function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var defaultsDeep = _.partialRight(_.merge, _.defaults); + * + * var options = { + * 'variable': 'data', + * 'imports': { 'jq': $ } + * }; + * + * defaultsDeep(options, _.templateSettings); + * + * options.variable + * // => 'data' + * + * options.imports + * // => { '_': _, 'jq': $ } + */ + function partialRight(func) { + return createWrapper(func, 32, null, slice(arguments, 1)); + } + + /** + * Creates a function that, when executed, will only call the `func` function + * at most once per every `wait` milliseconds. Provide an options object to + * indicate that `func` should be invoked on the leading and/or trailing edge + * of the `wait` timeout. Subsequent calls to the throttled function will + * return the result of the last `func` call. + * + * Note: If `leading` and `trailing` options are `true` `func` will be called + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to throttle. + * @param {number} wait The number of milliseconds to throttle executions to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * var throttled = _.throttle(updatePosition, 100); + * jQuery(window).on('scroll', throttled); + * + * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes + * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { + * 'trailing': false + * })); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (!isFunction(func)) { + throw new TypeError; + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? options.leading : leading; + trailing = 'trailing' in options ? options.trailing : trailing; + } + debounceOptions.leading = leading; + debounceOptions.maxWait = wait; + debounceOptions.trailing = trailing; + + return debounce(func, wait, debounceOptions); + } + + /** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Additional arguments provided to the function are appended + * to those provided to the wrapper function. The wrapper is executed with + * the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('Fred, Wilma, & Pebbles'); + * // => '

Fred, Wilma, & Pebbles

' + */ + function wrap(value, wrapper) { + return createWrapper(wrapper, 16, [value]); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new function. + * @example + * + * var object = { 'name': 'fred' }; + * var getter = _.constant(object); + * getter() === object; + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + /** + * Produces a callback bound to an optional `thisArg`. If `func` is a property + * name the created callback will return the property value for a given element. + * If `func` is an object the created callback will return `true` for elements + * that contain the equivalent object properties, otherwise it will return `false`. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} [func=identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of the created callback. + * @param {number} [argCount] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // wrap to create custom callback shorthands + * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { + * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); + * return !match ? func(callback, thisArg) : function(object) { + * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; + * }; + * }); + * + * _.filter(characters, 'age__gt38'); + * // => [{ 'name': 'fred', 'age': 40 }] + */ + function createCallback(func, thisArg, argCount) { + var type = typeof func; + if (func == null || type == 'function') { + return baseCreateCallback(func, thisArg, argCount); + } + // handle "_.pluck" style callback shorthands + if (type != 'object') { + return property(func); + } + var props = keys(func), + key = props[0], + a = func[key]; + + // handle "_.where" style callback shorthands + if (props.length == 1 && a === a && !isObject(a)) { + // fast path the common case of providing an object with a single + // property containing a primitive value + return function(object) { + var b = object[key]; + return a === b && (a !== 0 || (1 / a == 1 / b)); + }; + } + return function(object) { + var length = props.length, + result = false; + + while (length--) { + if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) { + break; + } + } + return result; + }; + } + + /** + * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their + * corresponding HTML entities. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} string The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('Fred, Wilma, & Pebbles'); + * // => 'Fred, Wilma, & Pebbles' + */ + function escape(string) { + return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); + } + + /** + * This method returns the first argument provided to it. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'name': 'fred' }; + * _.identity(object) === object; + * // => true + */ + function identity(value) { + return value; + } + + /** + * Adds function properties of a source object to the destination object. + * If `object` is a function methods will be added to its prototype as well. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Function|Object} [object=lodash] object The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options] The options object. + * @param {boolean} [options.chain=true] Specify whether the functions added are chainable. + * @example + * + * function capitalize(string) { + * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + * } + * + * _.mixin({ 'capitalize': capitalize }); + * _.capitalize('fred'); + * // => 'Fred' + * + * _('fred').capitalize().value(); + * // => 'Fred' + * + * _.mixin({ 'capitalize': capitalize }, { 'chain': false }); + * _('fred').capitalize(); + * // => 'Fred' + */ + function mixin(object, source, options) { + var chain = true, + methodNames = source && functions(source); + + if (!source || (!options && !methodNames.length)) { + if (options == null) { + options = source; + } + ctor = lodashWrapper; + source = object; + object = lodash; + methodNames = functions(source); + } + if (options === false) { + chain = false; + } else if (isObject(options) && 'chain' in options) { + chain = options.chain; + } + var ctor = object, + isFunc = isFunction(ctor); + + forEach(methodNames, function(methodName) { + var func = object[methodName] = source[methodName]; + if (isFunc) { + ctor.prototype[methodName] = function() { + var chainAll = this.__chain__, + value = this.__wrapped__, + args = [value]; + + push.apply(args, arguments); + var result = func.apply(object, args); + if (chain || chainAll) { + if (value === result && isObject(result)) { + return this; + } + result = new ctor(result); + result.__chain__ = chainAll; + } + return result; + }; + } + }); + } + + /** + * Reverts the '_' variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @memberOf _ + * @category Utilities + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + context._ = oldDash; + return this; + } + + /** + * A no-operation function. + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var object = { 'name': 'fred' }; + * _.noop(object) === undefined; + * // => true + */ + function noop() { + // no operation performed + } + + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var stamp = _.now(); + * _.defer(function() { console.log(_.now() - stamp); }); + * // => logs the number of milliseconds it took for the deferred function to be called + */ + var now = isNative(now = Date.now) && now || function() { + return new Date().getTime(); + }; + + /** + * Converts the given value into an integer of the specified radix. + * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the + * `value` is a hexadecimal, in which case a `radix` of `16` is used. + * + * Note: This method avoids differences in native ES3 and ES5 `parseInt` + * implementations. See http://es5.github.io/#E. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} value The value to parse. + * @param {number} [radix] The radix used to interpret the value to parse. + * @returns {number} Returns the new integer value. + * @example + * + * _.parseInt('08'); + * // => 8 + */ + var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) { + // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt` + return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0); + }; + + /** + * Creates a "_.pluck" style function, which returns the `key` value of a + * given object. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} key The name of the property to retrieve. + * @returns {Function} Returns the new function. + * @example + * + * var characters = [ + * { 'name': 'fred', 'age': 40 }, + * { 'name': 'barney', 'age': 36 } + * ]; + * + * var getName = _.property('name'); + * + * _.map(characters, getName); + * // => ['barney', 'fred'] + * + * _.sortBy(characters, getName); + * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] + */ + function property(key) { + return function(object) { + return object[key]; + }; + } + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is provided a number between `0` and the given number will be + * returned. If `floating` is truey or either `min` or `max` are floats a + * floating-point number will be returned instead of an integer. + * + * @static + * @memberOf _ + * @category Utilities + * @param {number} [min=0] The minimum possible value. + * @param {number} [max=1] The maximum possible value. + * @param {boolean} [floating=false] Specify returning a floating-point number. + * @returns {number} Returns a random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(min, max, floating) { + var noMin = min == null, + noMax = max == null; + + if (floating == null) { + if (typeof min == 'boolean' && noMax) { + floating = min; + min = 1; + } + else if (!noMax && typeof max == 'boolean') { + floating = max; + noMax = true; + } + } + if (noMin && noMax) { + max = 1; + } + min = +min || 0; + if (noMax) { + max = min; + min = 0; + } else { + max = +max || 0; + } + if (floating || min % 1 || max % 1) { + var rand = nativeRandom(); + return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max); + } + return baseRandom(min, max); + } + + /** + * Resolves the value of property `key` on `object`. If `key` is a function + * it will be invoked with the `this` binding of `object` and its result returned, + * else the property value is returned. If `object` is falsey then `undefined` + * is returned. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} object The object to inspect. + * @param {string} key The name of the property to resolve. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { + * 'cheese': 'crumpets', + * 'stuff': function() { + * return 'nonsense'; + * } + * }; + * + * _.result(object, 'cheese'); + * // => 'crumpets' + * + * _.result(object, 'stuff'); + * // => 'nonsense' + */ + function result(object, key) { + if (object) { + var value = object[key]; + return isFunction(value) ? object[key]() : value; + } + } + + /** + * A micro-templating method that handles arbitrary delimiters, preserves + * whitespace, and correctly escapes quotes within interpolated code. + * + * Note: In the development build, `_.template` utilizes sourceURLs for easier + * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl + * + * For more information on precompiling templates see: + * http://lodash.com/custom-builds + * + * For more information on Chrome extension sandboxes see: + * http://developer.chrome.com/stable/extensions/sandboxingEval.html + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} text The template text. + * @param {Object} data The data object used to populate the text. + * @param {Object} [options] The options object. + * @param {RegExp} [options.escape] The "escape" delimiter. + * @param {RegExp} [options.evaluate] The "evaluate" delimiter. + * @param {Object} [options.imports] An object to import into the template as local variables. + * @param {RegExp} [options.interpolate] The "interpolate" delimiter. + * @param {string} [sourceURL] The sourceURL of the template's compiled source. + * @param {string} [variable] The data object variable name. + * @returns {Function|string} Returns a compiled function when no `data` object + * is given, else it returns the interpolated text. + * @example + * + * // using the "interpolate" delimiter to create a compiled template + * var compiled = _.template('hello <%= name %>'); + * compiled({ 'name': 'fred' }); + * // => 'hello fred' + * + * // using the "escape" delimiter to escape HTML in data property values + * _.template('<%- value %>', { 'value': '