UNPKG

n8n-nodes-wax

Version:

n8n Community Node Package for the WAX Blockchain

1,626 lines (1,283 loc) 604 kB
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.eosjs_ecc = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ (function (Buffer){ "use strict"; var randomBytes = require('randombytes'); var ByteBuffer = require('bytebuffer'); var crypto = require('browserify-aes'); var assert = require('assert'); var PublicKey = require('./key_public'); var PrivateKey = require('./key_private'); var hash = require('./hash'); var Long = ByteBuffer.Long; module.exports = { encrypt: encrypt, decrypt: decrypt }; /** Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem @throws {Error|TypeError} - "Invalid Key, ..." @arg {PrivateKey} private_key - required and used for decryption @arg {PublicKey} public_key - required and used to calcualte the shared secret @arg {string} [nonce = uniqueNonce()] - assigned a random unique uint64 @return {object} @property {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys. @property {Buffer} message - Plain text message @property {number} checksum - shared secret checksum */ function encrypt(private_key, public_key, message) { var nonce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : uniqueNonce(); return crypt(private_key, public_key, nonce, message); } /** Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem @arg {PrivateKey} private_key - required and used for decryption @arg {PublicKey} public_key - required and used to calcualte the shared secret @arg {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys. @arg {Buffer} message - Encrypted or plain text message @arg {number} checksum - shared secret checksum @throws {Error|TypeError} - "Invalid Key, ..." @return {Buffer} - message */ function decrypt(private_key, public_key, nonce, message, checksum) { return crypt(private_key, public_key, nonce, message, checksum).message; } /** @arg {Buffer} message - Encrypted or plain text message (see checksum) @arg {number} checksum - shared secret checksum (null to encrypt, non-null to decrypt) @private */ function crypt(private_key, public_key, nonce, message, checksum) { private_key = PrivateKey(private_key); if (!private_key) throw new TypeError('private_key is required'); public_key = PublicKey(public_key); if (!public_key) throw new TypeError('public_key is required'); nonce = toLongObj(nonce); if (!nonce) throw new TypeError('nonce is required'); if (!Buffer.isBuffer(message)) { if (typeof message !== 'string') throw new TypeError('message should be buffer or string'); message = new Buffer(message, 'binary'); } if (checksum && typeof checksum !== 'number') throw new TypeError('checksum should be a number'); var S = private_key.getSharedSecret(public_key); var ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); ebuf.writeUint64(nonce); ebuf.append(S.toString('binary'), 'binary'); ebuf = new Buffer(ebuf.copy(0, ebuf.offset).toBinary(), 'binary'); var encryption_key = hash.sha512(ebuf); // D E B U G // console.log('crypt', { // priv_to_pub: private_key.toPublic().toString(), // pub: public_key.toString(), // nonce: nonce.toString(), // message: message.length, // checksum, // S: S.toString('hex'), // encryption_key: encryption_key.toString('hex'), // }) var iv = encryption_key.slice(32, 48); var key = encryption_key.slice(0, 32); // check is first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits. var check = hash.sha256(encryption_key); check = check.slice(0, 4); var cbuf = ByteBuffer.fromBinary(check.toString('binary'), ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); check = cbuf.readUint32(); if (checksum) { if (check !== checksum) throw new Error('Invalid key'); message = cryptoJsDecrypt(message, key, iv); } else { message = cryptoJsEncrypt(message, key, iv); } return { nonce: nonce, message: message, checksum: check }; } /** This method does not use a checksum, the returned data must be validated some other way. @arg {string|Buffer} message - ciphertext binary format @arg {string<utf8>|Buffer} key - 256bit @arg {string<utf8>|Buffer} iv - 128bit @return {Buffer} */ function cryptoJsDecrypt(message, key, iv) { assert(message, "Missing cipher text"); message = toBinaryBuffer(message); var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); // decipher.setAutoPadding(true) message = Buffer.concat([decipher.update(message), decipher["final"]()]); return message; } /** This method does not use a checksum, the returned data must be validated some other way. @arg {string|Buffer} message - plaintext binary format @arg {string<utf8>|Buffer} key - 256bit @arg {string<utf8>|Buffer} iv - 128bit @return {Buffer} */ function cryptoJsEncrypt(message, key, iv) { assert(message, "Missing plain text"); message = toBinaryBuffer(message); var cipher = crypto.createCipheriv('aes-256-cbc', key, iv); // cipher.setAutoPadding(true) message = Buffer.concat([cipher.update(message), cipher["final"]()]); return message; } /** @return {string} unique 64 bit unsigned number string. Being time based, this is careful to never choose the same nonce twice. This value could be recorded in the blockchain for a long time. */ function uniqueNonce() { if (unique_nonce_entropy === null) { var b = new Uint8Array(randomBytes(2)); unique_nonce_entropy = parseInt(b[0] << 8 | b[1], 10); } var _long = Long.fromNumber(Date.now()); var entropy = ++unique_nonce_entropy % 0xFFFF; // console.log('uniqueNonce date\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) // console.log('uniqueNonce entropy\t', ByteBuffer.allocate(8).writeUint64(Long.fromNumber(entropy)).toHex(0)) _long = _long.shiftLeft(16).or(Long.fromNumber(entropy)); // console.log('uniqueNonce final\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) return _long.toString(); } var unique_nonce_entropy = null; // for(let i=1; i < 10; i++) key.uniqueNonce() var toLongObj = function toLongObj(o) { return o ? Long.isLong(o) ? o : Long.fromString(o) : o; }; var toBinaryBuffer = function toBinaryBuffer(o) { return o ? Buffer.isBuffer(o) ? o : new Buffer(o, 'binary') : o; }; }).call(this,require("buffer").Buffer) },{"./hash":7,"./key_private":9,"./key_public":10,"assert":24,"browserify-aes":37,"buffer":52,"bytebuffer":53,"randombytes":79}],2:[function(require,module,exports){ "use strict"; var Aes = require("./aes"); var PrivateKey = require("./key_private"); var PublicKey = require("./key_public"); var Signature = require("./signature"); var key_utils = require("./key_utils"); var hash = require("./hash"); /** [Wallet Import Format](https://en.bitcoin.it/wiki/Wallet_import_format) @typedef {string} wif */ /** EOSKey.. @typedef {string} pubkey */ /** @namespace */ var ecc = { /** Initialize by running some self-checking code. This should take a second to gather additional CPU entropy used during private key generation. Initialization happens once even if called multiple times. @return {Promise} */ initialize: PrivateKey.initialize, /** Does not pause to gather CPU entropy. @return {Promise<PrivateKey>} test key */ unsafeRandomKey: function unsafeRandomKey() { return PrivateKey.unsafeRandomKey().then(function (key) { return key.toString(); }); }, /** @arg {number} [cpuEntropyBits = 0] gather additional entropy from a CPU mining algorithm. This will already happen once by default. @return {Promise<wif>} @example ecc.randomKey().then(privateKey => { console.log('Private Key:\t', privateKey) // wif console.log('Public Key:\t', ecc.privateToPublic(privateKey)) // EOSkey... }) */ randomKey: function randomKey(cpuEntropyBits) { return PrivateKey.randomKey(cpuEntropyBits).then(function (key) { return key.toString(); }); }, /** @arg {string} seed - any length string. This is private. The same seed produces the same private key every time. At least 128 random bits should be used to produce a good private key. @return {wif} @example ecc.seedPrivate('secret') === wif */ seedPrivate: function seedPrivate(seed) { return PrivateKey.fromSeed(seed).toString(); }, /** @arg {wif} wif @arg {string} [pubkey_prefix = 'EOS'] - public key prefix @return {pubkey} @example ecc.privateToPublic(wif) === pubkey */ privateToPublic: function privateToPublic(wif) { var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS'; return PrivateKey(wif).toPublic().toString(pubkey_prefix); }, /** @arg {pubkey} pubkey - like EOSKey.. @arg {string} [pubkey_prefix = 'EOS'] @return {boolean} valid @example ecc.isValidPublic(pubkey) === true */ isValidPublic: function isValidPublic(pubkey) { var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS'; return PublicKey.isValid(pubkey, pubkey_prefix); }, /** @arg {wif} wif @return {boolean} valid @example ecc.isValidPrivate(wif) === true */ isValidPrivate: function isValidPrivate(wif) { return PrivateKey.isValid(wif); }, /** Create a signature using data or a hash. @arg {string|Buffer} data @arg {wif|PrivateKey} privateKey @arg {String} [encoding = 'utf8'] - data encoding (if string) @return {string} string signature @example ecc.sign('I am alive', wif) */ sign: function sign(data, privateKey) { var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8'; if (encoding === true) { throw new TypeError('API changed, use signHash(..) instead'); } else { if (encoding === false) { console.log('Warning: ecc.sign hashData parameter was removed'); } } return Signature.sign(data, privateKey, encoding).toString(); }, /** @arg {String|Buffer} dataSha256 - sha256 hash 32 byte buffer or string @arg {wif|PrivateKey} privateKey @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) @return {string} string signature */ signHash: function signHash(dataSha256, privateKey) { var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex'; return Signature.signHash(dataSha256, privateKey, encoding).toString(); }, /** Verify signed data. @arg {string|Buffer} signature - buffer or hex string @arg {string|Buffer} data @arg {pubkey|PublicKey} pubkey @arg {boolean} [hashData = true] - sha256 hash data before verify @return {boolean} @example ecc.verify(signature, 'I am alive', pubkey) === true */ verify: function verify(signature, data, pubkey) { var encoding = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'utf8'; if (encoding === true) { throw new TypeError('API changed, use verifyHash(..) instead'); } else { if (encoding === false) { console.log('Warning: ecc.verify hashData parameter was removed'); } } signature = Signature.from(signature); return signature.verify(data, pubkey, encoding); }, verifyHash: function verifyHash(signature, dataSha256, pubkey) { var encoding = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'hex'; signature = Signature.from(signature); return signature.verifyHash(dataSha256, pubkey, encoding); }, /** Recover the public key used to create the signature. @arg {String|Buffer} signature (EOSbase58sig.., Hex, Buffer) @arg {String|Buffer} data - full data @arg {String} [encoding = 'utf8'] - data encoding (if data is a string) @return {pubkey} @example ecc.recover(signature, 'I am alive') === pubkey */ recover: function recover(signature, data) { var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8'; if (encoding === true) { throw new TypeError('API changed, use recoverHash(signature, data) instead'); } else { if (encoding === false) { console.log('Warning: ecc.recover hashData parameter was removed'); } } signature = Signature.from(signature); return signature.recover(data, encoding).toString(); }, /** @arg {String|Buffer} signature (EOSbase58sig.., Hex, Buffer) @arg {String|Buffer} dataSha256 - sha256 hash 32 byte buffer or hex string @arg {String} [encoding = 'hex'] - dataSha256 encoding (if dataSha256 is a string) @return {PublicKey} */ recoverHash: function recoverHash(signature, dataSha256) { var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex'; signature = Signature.from(signature); return signature.recoverHash(dataSha256, encoding).toString(); }, /** @arg {string|Buffer} data - always binary, you may need Buffer.from(data, 'hex') @arg {string} [encoding = 'hex'] - result encoding 'hex', 'binary' or 'base64' @return {string|Buffer} - Buffer when encoding is null, or string @example ecc.sha256('hashme') === '02208b..' @example ecc.sha256(Buffer.from('02208b', 'hex')) === '29a23..' */ sha256: function sha256(data) { var resultEncoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'hex'; return hash.sha256(data, resultEncoding); } }; module.exports = ecc; },{"./aes":1,"./hash":7,"./key_private":9,"./key_public":10,"./key_utils":11,"./signature":13}],3:[function(require,module,exports){ "use strict"; var Aes = require("./aes"); var PrivateKey = require("./key_private"); var PublicKey = require("./key_public"); var Signature = require("./signature"); var key_utils = require("./key_utils"); module.exports = { Aes: Aes, PrivateKey: PrivateKey, PublicKey: PublicKey, Signature: Signature, key_utils: key_utils }; },{"./aes":1,"./key_private":9,"./key_public":10,"./key_utils":11,"./signature":13}],4:[function(require,module,exports){ (function (Buffer){ "use strict"; var assert = require('assert'); // from github.com/bitcoinjs/bitcoinjs-lib from github.com/cryptocoinjs/ecdsa var crypto = require('./hash'); var enforceType = require('./enforce_types'); var BigInteger = require('bigi'); var ECSignature = require('./ecsignature'); // https://tools.ietf.org/html/rfc6979#section-3.2 function deterministicGenerateK(curve, hash, d, checkSig, nonce) { enforceType('Buffer', hash); enforceType(BigInteger, d); if (nonce) { hash = crypto.sha256(Buffer.concat([hash, new Buffer(nonce)])); } // sanity check assert.equal(hash.length, 32, 'Hash must be 256 bit'); var x = d.toBuffer(32); var k = new Buffer(32); var v = new Buffer(32); // Step B v.fill(1); // Step C k.fill(0); // Step D k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k); // Step E v = crypto.HmacSHA256(v, k); // Step F k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k); // Step G v = crypto.HmacSHA256(v, k); // Step H1/H2a, ignored as tlen === qlen (256 bit) // Step H2b v = crypto.HmacSHA256(v, k); var T = BigInteger.fromBuffer(v); // Step H3, repeat until T is within the interval [1, n - 1] while (T.signum() <= 0 || T.compareTo(curve.n) >= 0 || !checkSig(T)) { k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0])]), k); v = crypto.HmacSHA256(v, k); // Step H1/H2a, again, ignored as tlen === qlen (256 bit) // Step H2b again v = crypto.HmacSHA256(v, k); T = BigInteger.fromBuffer(v); } return T; } function sign(curve, hash, d, nonce) { var e = BigInteger.fromBuffer(hash); var n = curve.n; var G = curve.G; var r, s; var k = deterministicGenerateK(curve, hash, d, function (k) { // find canonically valid signature var Q = G.multiply(k); if (curve.isInfinity(Q)) return false; r = Q.affineX.mod(n); if (r.signum() === 0) return false; s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); if (s.signum() === 0) return false; return true; }, nonce); var N_OVER_TWO = n.shiftRight(1); // enforce low S values, see bip62: 'low s values in signatures' if (s.compareTo(N_OVER_TWO) > 0) { s = n.subtract(s); } return ECSignature(r, s); } function verifyRaw(curve, e, signature, Q) { var n = curve.n; var G = curve.G; var r = signature.r; var s = signature.s; // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] if (r.signum() <= 0 || r.compareTo(n) >= 0) return false; if (s.signum() <= 0 || s.compareTo(n) >= 0) return false; // c = s^-1 mod n var c = s.modInverse(n); // 1.4.4 Compute u1 = es^−1 mod n // u2 = rs^−1 mod n var u1 = e.multiply(c).mod(n); var u2 = r.multiply(c).mod(n); // 1.4.5 Compute R = (xR, yR) = u1G + u2Q var R = G.multiplyTwo(u1, Q, u2); // 1.4.5 (cont.) Enforce R is not at infinity if (curve.isInfinity(R)) return false; // 1.4.6 Convert the field element R.x to an integer var xR = R.affineX; // 1.4.7 Set v = xR mod n var v = xR.mod(n); // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" return v.equals(r); } function verify(curve, hash, signature, Q) { // 1.4.2 H = Hash(M), already done by the user // 1.4.3 e = H var e = BigInteger.fromBuffer(hash); return verifyRaw(curve, e, signature, Q); } /** * Recover a public key from a signature. * * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public * Key Recovery Operation". * * http://www.secg.org/download/aid-780/sec1-v2.pdf */ function recoverPubKey(curve, e, signature, i) { assert.strictEqual(i & 3, i, 'Recovery param is more than two bits'); var n = curve.n; var G = curve.G; var r = signature.r; var s = signature.s; assert(r.signum() > 0 && r.compareTo(n) < 0, 'Invalid r value'); assert(s.signum() > 0 && s.compareTo(n) < 0, 'Invalid s value'); // 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; // 1.1 Let x = r + jn var x = isSecondKey ? r.add(n) : r; var R = curve.pointFromX(isYOdd, x); // 1.4 Check that nR is at infinity var nR = R.multiply(n); assert(curve.isInfinity(nR), 'nR is not a valid curve point'); // Compute -e from e var eNeg = e.negate().mod(n); // 1.6.1 Compute Q = r^-1 (sR - eG) // Q = r^-1 (sR + -eG) var rInv = r.modInverse(n); var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv); curve.validate(Q); return Q; } /** * Calculate pubkey extraction parameter. * * When extracting a pubkey from a signature, we have to * distinguish four different cases. Rather than putting this * burden on the verifier, Bitcoin includes a 2-bit value with the * signature. * * This function simply tries all four cases and returns the value * that resulted in a successful pubkey recovery. */ function calcPubKeyRecoveryParam(curve, e, signature, Q) { for (var i = 0; i < 4; i++) { var Qprime = recoverPubKey(curve, e, signature, i); // 1.6.2 Verify Q if (Qprime.equals(Q)) { return i; } } throw new Error('Unable to find valid recovery factor'); } module.exports = { calcPubKeyRecoveryParam: calcPubKeyRecoveryParam, deterministicGenerateK: deterministicGenerateK, recoverPubKey: recoverPubKey, sign: sign, verify: verify, verifyRaw: verifyRaw }; }).call(this,require("buffer").Buffer) },{"./ecsignature":5,"./enforce_types":6,"./hash":7,"assert":24,"bigi":32,"buffer":52}],5:[function(require,module,exports){ (function (Buffer){ "use strict"; var assert = require('assert'); // from https://github.com/bitcoinjs/bitcoinjs-lib var enforceType = require('./enforce_types'); var BigInteger = require('bigi'); function ECSignature(r, s) { enforceType(BigInteger, r); enforceType(BigInteger, s); function toCompact(i, compressed) { if (compressed) i += 4; i += 27; var buffer = new Buffer(65); buffer.writeUInt8(i, 0); r.toBuffer(32).copy(buffer, 1); s.toBuffer(32).copy(buffer, 33); return buffer; } function toDER() { var rBa = r.toDERInteger(); var sBa = s.toDERInteger(); var sequence = []; // INTEGER sequence.push(0x02, rBa.length); sequence = sequence.concat(rBa); // INTEGER sequence.push(0x02, sBa.length); sequence = sequence.concat(sBa); // SEQUENCE sequence.unshift(0x30, sequence.length); return new Buffer(sequence); } function toScriptSignature(hashType) { var hashTypeBuffer = new Buffer(1); hashTypeBuffer.writeUInt8(hashType, 0); return Buffer.concat([toDER(), hashTypeBuffer]); } return { r: r, s: s, toCompact: toCompact, toDER: toDER, toScriptSignature: toScriptSignature }; } // Import operations ECSignature.parseCompact = function (buffer) { assert.equal(buffer.length, 65, 'Invalid signature length'); var i = buffer.readUInt8(0) - 27; // At most 3 bits assert.equal(i, i & 7, 'Invalid signature parameter'); var compressed = !!(i & 4); // Recovery param only i = i & 3; var r = BigInteger.fromBuffer(buffer.slice(1, 33)); var s = BigInteger.fromBuffer(buffer.slice(33)); return { compressed: compressed, i: i, signature: ECSignature(r, s) }; }; ECSignature.fromDER = function (buffer) { assert.equal(buffer.readUInt8(0), 0x30, 'Not a DER sequence'); assert.equal(buffer.readUInt8(1), buffer.length - 2, 'Invalid sequence length'); assert.equal(buffer.readUInt8(2), 0x02, 'Expected a DER integer'); var rLen = buffer.readUInt8(3); assert(rLen > 0, 'R length is zero'); var offset = 4 + rLen; assert.equal(buffer.readUInt8(offset), 0x02, 'Expected a DER integer (2)'); var sLen = buffer.readUInt8(offset + 1); assert(sLen > 0, 'S length is zero'); var rB = buffer.slice(4, offset); var sB = buffer.slice(offset + 2); offset += 2 + sLen; if (rLen > 1 && rB.readUInt8(0) === 0x00) { assert(rB.readUInt8(1) & 0x80, 'R value excessively padded'); } if (sLen > 1 && sB.readUInt8(0) === 0x00) { assert(sB.readUInt8(1) & 0x80, 'S value excessively padded'); } assert.equal(offset, buffer.length, 'Invalid DER encoding'); var r = BigInteger.fromDERInteger(rB); var s = BigInteger.fromDERInteger(sB); assert(r.signum() >= 0, 'R value is negative'); assert(s.signum() >= 0, 'S value is negative'); return ECSignature(r, s); }; // FIXME: 0x00, 0x04, 0x80 are SIGHASH_* boundary constants, importing Transaction causes a circular dependency ECSignature.parseScriptSignature = function (buffer) { var hashType = buffer.readUInt8(buffer.length - 1); var hashTypeMod = hashType & ~0x80; assert(hashTypeMod > 0x00 && hashTypeMod < 0x04, 'Invalid hashType'); return { signature: ECSignature.fromDER(buffer.slice(0, -1)), hashType: hashType }; }; module.exports = ECSignature; }).call(this,require("buffer").Buffer) },{"./enforce_types":6,"assert":24,"bigi":32,"buffer":52}],6:[function(require,module,exports){ (function (Buffer){ "use strict"; module.exports = function enforce(type, value) { // Copied from https://github.com/bitcoinjs/bitcoinjs-lib switch (type) { case 'Array': { if (Array.isArray(value)) return; break; } case 'Boolean': { if (typeof value === 'boolean') return; break; } case 'Buffer': { if (Buffer.isBuffer(value)) return; break; } case 'Number': { if (typeof value === 'number') return; break; } case 'String': { if (typeof value === 'string') return; break; } default: { if (getName(value.constructor) === getName(type)) return; } } throw new TypeError('Expected ' + (getName(type) || type) + ', got ' + value); }; function getName(fn) { // Why not fn.name: https://kangax.github.io/compat-table/es6/#function_name_property var match = fn.toString().match(/function (.*?)\(/); return match ? match[1] : null; } }).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")}) },{"../node_modules/is-buffer/index.js":72}],7:[function(require,module,exports){ "use strict"; var createHash = require('create-hash'); var createHmac = require('create-hmac'); /** @namespace hash */ /** @arg {string|Buffer} data @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' @return {string|Buffer} - Buffer when resultEncoding is null, or string */ function sha1(data, resultEncoding) { return createHash('sha1').update(data).digest(resultEncoding); } /** @arg {string|Buffer} data @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' @return {string|Buffer} - Buffer when resultEncoding is null, or string */ function sha256(data, resultEncoding) { return createHash('sha256').update(data).digest(resultEncoding); } /** @arg {string|Buffer} data @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' @return {string|Buffer} - Buffer when resultEncoding is null, or string */ function sha512(data, resultEncoding) { return createHash('sha512').update(data).digest(resultEncoding); } function HmacSHA256(buffer, secret) { return createHmac('sha256', secret).update(buffer).digest(); } function ripemd160(data) { try { return createHash('rmd160').update(data).digest(); } catch (e) { return createHash('ripemd160').update(data).digest(); } } // function hash160(buffer) { // return ripemd160(sha256(buffer)) // } // // function hash256(buffer) { // return sha256(sha256(buffer)) // } // // function HmacSHA512(buffer, secret) { // return crypto.createHmac('sha512', secret).update(buffer).digest() // } module.exports = { sha1: sha1, sha256: sha256, sha512: sha512, HmacSHA256: HmacSHA256, ripemd160: ripemd160 // hash160: hash160, // hash256: hash256, // HmacSHA512: HmacSHA512 }; },{"create-hash":56,"create-hmac":59}],8:[function(require,module,exports){ "use strict"; var commonApi = require('./api_common'); var objectApi = require('./api_object'); var ecc = Object.assign({}, commonApi, objectApi); module.exports = ecc; },{"./api_common":2,"./api_object":3}],9:[function(require,module,exports){ (function (Buffer){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var ecurve = require('ecurve'); var Point = ecurve.Point; var secp256k1 = ecurve.getCurveByName('secp256k1'); var BigInteger = require('bigi'); var assert = require('assert'); var hash = require('./hash'); var PublicKey = require('./key_public'); var keyUtils = require('./key_utils'); var createHash = require('create-hash'); var promiseAsync = require('./promise-async'); var G = secp256k1.G; var n = secp256k1.n; module.exports = PrivateKey; /** @typedef {string} wif - https://en.bitcoin.it/wiki/Wallet_import_format @typedef {string} pubkey - EOSKey.. @typedef {ecurve.Point} Point */ /** @param {BigInteger} d */ function PrivateKey(d) { if (typeof d === 'string') { return PrivateKey.fromString(d); } else if (Buffer.isBuffer(d)) { return PrivateKey.fromBuffer(d); } else if ((0, _typeof2["default"])(d) === 'object' && BigInteger.isBigInteger(d.d)) { return PrivateKey(d.d); } if (!BigInteger.isBigInteger(d)) { throw new TypeError('Invalid private key'); } /** @return {string} private key like PVT_K1_base58privatekey.. */ function toString() { // todo, use PVT_K1_ // return 'PVT_K1_' + keyUtils.checkEncode(toBuffer(), 'K1') return toWif(); } /** @return {wif} */ function toWif() { var private_key = toBuffer(); // checksum includes the version private_key = Buffer.concat([new Buffer([0x80]), private_key]); return keyUtils.checkEncode(private_key, 'sha256x2'); } var public_key; /** @return {Point} */ function toPublic() { if (public_key) { // cache // S L O W in the browser return public_key; } var Q = secp256k1.G.multiply(d); return public_key = PublicKey.fromPoint(Q); } function toBuffer() { return d.toBuffer(32); } /** ECIES @arg {string|Object} pubkey wif, PublicKey object @return {Buffer} 64 byte shared secret */ function getSharedSecret(public_key) { public_key = PublicKey(public_key); var KB = public_key.toUncompressed().toBuffer(); var KBP = Point.fromAffine(secp256k1, BigInteger.fromBuffer(KB.slice(1, 33)), // x BigInteger.fromBuffer(KB.slice(33, 65)) // y ); var r = toBuffer(); var P = KBP.multiply(BigInteger.fromBuffer(r)); var S = P.affineX.toBuffer({ size: 32 }); // SHA512 used in ECIES return hash.sha512(S); } // /** ECIES TODO unit test // @arg {string|Object} pubkey wif, PublicKey object // @return {Buffer} 64 byte shared secret // */ // function getSharedSecret(public_key) { // public_key = PublicKey(public_key).toUncompressed() // var P = public_key.Q.multiply( d ); // var S = P.affineX.toBuffer({size: 32}); // // ECIES, adds an extra sha512 // return hash.sha512(S); // } /** @arg {string} name - child key name. @return {PrivateKey} @example activePrivate = masterPrivate.getChildKey('owner').getChildKey('active') @example activePrivate.getChildKey('mycontract').getChildKey('myperm') */ function getChildKey(name) { // console.error('WARNING: getChildKey untested against eosd'); // no eosd impl yet var index = createHash('sha256').update(toBuffer()).update(name).digest(); return PrivateKey(index); } function toHex() { return toBuffer().toString('hex'); } return { d: d, toWif: toWif, toString: toString, toPublic: toPublic, toBuffer: toBuffer, getSharedSecret: getSharedSecret, getChildKey: getChildKey }; } /** @private */ function parseKey(privateStr) { assert.equal((0, _typeof2["default"])(privateStr), 'string', 'privateStr'); var match = privateStr.match(/^PVT_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/); if (match === null) { // legacy WIF - checksum includes the version var versionKey = keyUtils.checkDecode(privateStr, 'sha256x2'); var version = versionKey.readUInt8(0); assert.equal(0x80, version, "Expected version ".concat(0x80, ", instead got ", version)); var _privateKey = PrivateKey.fromBuffer(versionKey.slice(1)); var _keyType = 'K1'; var format = 'WIF'; return { privateKey: _privateKey, format: format, keyType: _keyType }; } assert(match.length === 3, 'Expecting private key like: PVT_K1_base58privateKey..'); var _match = (0, _slicedToArray2["default"])(match, 3), keyType = _match[1], keyString = _match[2]; assert.equal(keyType, 'K1', 'K1 private key expected'); var privateKey = PrivateKey.fromBuffer(keyUtils.checkDecode(keyString, keyType)); return { privateKey: privateKey, format: 'PVT', keyType: keyType }; } PrivateKey.fromHex = function (hex) { return PrivateKey.fromBuffer(new Buffer(hex, 'hex')); }; PrivateKey.fromBuffer = function (buf) { if (!Buffer.isBuffer(buf)) { throw new Error("Expecting parameter to be a Buffer type"); } if (buf.length === 33 && buf[32] === 1) { // remove compression flag buf = buf.slice(0, -1); } if (32 !== buf.length) { throw new Error("Expecting 32 bytes, instead got ".concat(buf.length)); } return PrivateKey(BigInteger.fromBuffer(buf)); }; /** @arg {string} seed - any length string. This is private, the same seed produces the same private key every time. @return {PrivateKey} */ PrivateKey.fromSeed = function (seed) { // generate_private_key if (!(typeof seed === 'string')) { throw new Error('seed must be of type string'); } return PrivateKey.fromBuffer(hash.sha256(seed)); }; /** @arg {wif} key @return {boolean} true if key is in the Wallet Import Format */ PrivateKey.isWif = function (text) { try { assert(parseKey(text).format === 'WIF'); return true; } catch (e) { return false; } }; /** @arg {wif|Buffer|PrivateKey} key @return {boolean} true if key is convertable to a private key object. */ PrivateKey.isValid = function (key) { try { PrivateKey(key); return true; } catch (e) { return false; } }; /** @deprecated */ PrivateKey.fromWif = function (str) { console.log('PrivateKey.fromWif is deprecated, please use PrivateKey.fromString'); return PrivateKey.fromString(str); }; /** @throws {AssertError|Error} parsing key @arg {string} privateStr Eosio or Wallet Import Format (wif) -- a secret */ PrivateKey.fromString = function (privateStr) { return parseKey(privateStr).privateKey; }; /** Create a new random private key. Call initialize() first to run some self-checking code and gather some CPU entropy. @arg {number} [cpuEntropyBits = 0] - additional CPU entropy, this already happens once so it should not be needed again. @return {Promise<PrivateKey>} - random private key */ PrivateKey.randomKey = function () { var cpuEntropyBits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; return PrivateKey.initialize().then(function () { return PrivateKey.fromBuffer(keyUtils.random32ByteBuffer({ cpuEntropyBits: cpuEntropyBits })); }); }; /** @return {Promise<PrivateKey>} for testing, does not require initialize(). */ PrivateKey.unsafeRandomKey = function () { return Promise.resolve(PrivateKey.fromBuffer(keyUtils.random32ByteBuffer({ safe: false }))); }; var initialized = false, unitTested = false; /** Run self-checking code and gather CPU entropy. Initialization happens once even if called multiple times. @return {Promise} */ function initialize() { if (initialized) { return; } unitTest(); keyUtils.addEntropy.apply(keyUtils, (0, _toConsumableArray2["default"])(keyUtils.cpuEntropy())); assert(keyUtils.entropyCount() >= 128, 'insufficient entropy'); initialized = true; } PrivateKey.initialize = promiseAsync(initialize); /** Unit test basic private and public key functionality. @throws {AssertError} */ function unitTest() { var pvt = PrivateKey(hash.sha256('')); var pvtError = 'key comparison test failed on a known private key'; assert.equal(pvt.toWif(), '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss', pvtError); assert.equal(pvt.toString(), '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss', pvtError); // assert.equal(pvt.toString(), 'PVT_K1_2jH3nnhxhR3zPUcsKaWWZC9ZmZAnKm3GAnFD1xynGJE1Znuvjd', pvtError) var pub = pvt.toPublic(); var pubError = 'pubkey string comparison test failed on a known public key'; assert.equal(pub.toString(), 'EOS859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM', pubError); // assert.equal(pub.toString(), 'PUB_K1_859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2Ht7beeX', pubError) // assert.equal(pub.toStringLegacy(), 'EOS859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM', pubError) doesNotThrow(function () { return PrivateKey.fromString(pvt.toWif()); }, 'converting known wif from string'); doesNotThrow(function () { return PrivateKey.fromString(pvt.toString()); }, 'converting known pvt from string'); doesNotThrow(function () { return PublicKey.fromString(pub.toString()); }, 'converting known public key from string'); // doesNotThrow(() => PublicKey.fromString(pub.toStringLegacy()), 'converting known public key from string') unitTested = true; } /** @private */ var doesNotThrow = function doesNotThrow(cb, msg) { try { cb(); } catch (error) { error.message = "".concat(msg, " ==> ").concat(error.message); throw error; } }; }).call(this,require("buffer").Buffer) },{"./hash":7,"./key_public":10,"./key_utils":11,"./promise-async":12,"@babel/runtime/helpers/interopRequireDefault":16,"@babel/runtime/helpers/slicedToArray":21,"@babel/runtime/helpers/toConsumableArray":22,"@babel/runtime/helpers/typeof":23,"assert":24,"bigi":32,"buffer":52,"create-hash":56,"ecurve":64}],10:[function(require,module,exports){ (function (Buffer){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var assert = require('assert'); var ecurve = require('ecurve'); var BigInteger = require('bigi'); var secp256k1 = ecurve.getCurveByName('secp256k1'); var hash = require('./hash'); var keyUtils = require('./key_utils'); var G = secp256k1.G; var n = secp256k1.n; module.exports = PublicKey; /** @param {string|Buffer|PublicKey|ecurve.Point} public key @param {string} [pubkey_prefix = 'EOS'] */ function PublicKey(Q) { var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS'; if (typeof Q === 'string') { var publicKey = PublicKey.fromString(Q, pubkey_prefix); assert(publicKey != null, 'Invalid public key'); return publicKey; } else if (Buffer.isBuffer(Q)) { return PublicKey.fromBuffer(Q); } else if ((0, _typeof2["default"])(Q) === 'object' && Q.Q) { return PublicKey(Q.Q); } assert.equal((0, _typeof2["default"])(Q), 'object', 'Invalid public key'); assert.equal((0, _typeof2["default"])(Q.compressed), 'boolean', 'Invalid public key'); function toBuffer() { var compressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Q.compressed; return Q.getEncoded(compressed); } var pubdata; // cache // /** // @todo secp224r1 // @return {string} PUB_K1_base58pubkey.. // */ // function toString() { // if(pubdata) { // return pubdata // } // pubdata = `PUB_K1_` + keyUtils.checkEncode(toBuffer(), 'K1') // return pubdata; // } /** @todo rename to toStringLegacy * @arg {string} [pubkey_prefix = 'EOS'] - public key prefix */ function toString() { var pubkey_prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'EOS'; return pubkey_prefix + keyUtils.checkEncode(toBuffer()); } function toUncompressed() { var buf = Q.getEncoded(false); var point = ecurve.Point.decodeFrom(secp256k1, buf); return PublicKey.fromPoint(point); } /** @deprecated */ function child(offset) { console.error('Deprecated warning: PublicKey.child'); assert(Buffer.isBuffer(offset), "Buffer required: offset"); assert.equal(offset.length, 32, "offset length"); offset = Buffer.concat([toBuffer(), offset]); offset = hash.sha256(offset); var c = BigInteger.fromBuffer(offset); if (c.compareTo(n) >= 0) throw new Error("Child offset went out of bounds, try again"); var cG = G.multiply(c); var Qprime = Q.add(cG); if (secp256k1.isInfinity(Qprime)) throw new Error("Child offset derived to an invalid key, try again"); return PublicKey.fromPoint(Qprime); } function toHex() { return toBuffer().toString('hex'); } return { Q: Q, toString: toString, // toStringLegacy, toUncompressed: toUncompressed, toBuffer: toBuffer, child: child, toHex: toHex }; } /** @param {string|Buffer|PublicKey|ecurve.Point} pubkey - public key @param {string} [pubkey_prefix = 'EOS'] */ PublicKey.isValid = function (pubkey) { var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS'; try { PublicKey(pubkey, pubkey_prefix); return true; } catch (e) { return false; } }; PublicKey.fromBinary = function (bin) { return PublicKey.fromBuffer(new Buffer(bin, 'binary')); }; PublicKey.fromBuffer = function (buffer) { return PublicKey(ecurve.Point.decodeFrom(secp256k1, buffer)); }; PublicKey.fromPoint = function (point) { return PublicKey(point); }; /** @arg {string} public_key - like PUB_K1_base58pubkey.. @arg {string} [pubkey_prefix = 'EOS'] - public key prefix @return PublicKey or `null` (invalid) */ PublicKey.fromString = function (public_key) { var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS'; try { return PublicKey.fromStringOrThrow(public_key, pubkey_prefix); } catch (e) { return null; } }; /** @arg {string} public_key - like PUB_K1_base58pubkey.. @arg {string} [pubkey_prefix = 'EOS'] - public key prefix @throws {Error} if public key is invalid @return PublicKey */ PublicKey.fromStringOrThrow = function (public_key) { var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS'; assert.equal((0, _typeof2["default"])(public_key), 'string', 'public_key'); var match = public_key.match(/^PUB_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/); if (match === null) { // legacy var prefix_match = new RegExp("^" + pubkey_prefix); if (prefix_match.test(public_key)) { public_key = public_key.substring(pubkey_prefix.length); } return PublicKey.fromBuffer(keyUtils.checkDecode(public_key)); } assert(match.length === 3, 'Expecting public key like: PUB_K1_base58pubkey..'); var _match = (0, _slicedToArray2["default"])(match, 3), keyType = _match[1], keyString = _match[2]; assert.equal(keyType, 'K1', 'K1 private key expected'); return PublicKey.fromBuffer(keyUtils.checkDecode(keyString, keyType)); }; PublicKey.fromHex = function (hex) { return PublicKey.fromBuffer(new Buffer(hex, 'hex')); }; PublicKey.fromStringHex = function (hex) { return PublicKey.fromString(new Buffer(hex, 'hex')); }; }).call(this,require("buffer").Buffer) },{"./hash":7,"./key_utils":11,"@babel/runtime/helpers/interopRequireDefault":16,"@babel/runtime/helpers/slicedToArray":21,"@babel/runtime/helpers/typeof":23,"assert":24,"bigi":32,"buffer":52,"ecurve":64}],11:[function(require,module,exports){ (function (Buffer){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var base58 = require('bs58'); var assert = require('assert'); var randomBytes = require('randombytes'); var hash = require('./hash'); module.exports = { random32ByteBuffer: random32ByteBuffer, addEntropy: addEntropy, cpuEntropy: cpuEntropy, entropyCount: function entropyCount() { return _entropyCount; }, checkDecode: checkDecode, checkEncode: checkEncode }; var entropyPos = 0, _entropyCount = 0; var externalEntropyArray = randomBytes(101); /** Additional forms of entropy are used. A week random number generator can run out of entropy. This should ensure even the worst random number implementation will be reasonably safe. @arg {number} [cpuEntropyBits = 0] generate entropy on the fly. This is not required, entropy can be added in advanced via addEntropy or initialize(). @arg {boolean} [safe = true] false for testing, otherwise this will be true to ensure initialize() was called. @return a random buffer obtained from the secure random number generator. Additional entropy is used. */ function random32ByteBuffer() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$cpuEntropyBits = _ref.cpuEntropyBits, cpuEntropyBits = _ref$cpuEntropyBits === void 0 ? 0 : _ref$cpuEntropyBits, _ref$safe = _ref.safe, safe = _ref$safe === void 0 ? true : _ref$safe; assert.equal((0, _typeof2["default"])(cpuEntropyBits), 'number', 'cpuEntropyBits'); assert.equal((0, _typeof2["default"])(safe), 'boolean', 'boolean'); if (safe) { assert(_entropyCount >= 128, 'Call initialize() to add entropy'); } // if(entropyCount > 0) { // console.log(`Additional private key entropy: ${entropyCount} events`) // } var hash_array = []; hash_array.push(randomBytes(32)); hash_array.push(Buffer.from(cpuEntropy(cpuEntropyBits))); hash_array.push(externalEntropyArray); hash_array.push(browserEntropy()); return hash.sha256(Buffer.concat(hash_array)); } /** Adds entropy. This may be called many times while the amount of data saved is accumulatively reduced to 101 integers. Data is retained in RAM for the life of this module. @example React <code> componentDidMount() { this.refs.MyComponent.addEventListener("mousemove", this.onEntropyEvent, {capture: false, passive: true}) } componentWillUnmount() { this.refs.MyComponent.removeEventListener("mousemove", this.onEntropyEvent); } onEntropyEvent = (e) => { if(e.type === 'mousemove') key_utils.addEntropy(e.pageX, e.pageY, e.screenX, e.screenY) else console.log('onEntropyEvent Unknown', e.type, e) } </code> */ function addEntropy() { assert.equal(externalEntropyArray.length, 101, 'externalEntropyArray'); for (var _len = arguments.length, ints = new Array(_len), _key = 0; _key < _len; _key++) { ints[_key] = arguments[_key]; } _entropyCount += ints.length; for (var _i = 0, _ints = ints; _i < _ints.length; _i++) { var i = _ints[_i]; var pos = entropyPos++ % 101; var i2 = externalEntropyArray[pos] += i; if (i2 > 9007199254740991) externalEntropyArray[pos] = 0; } } /** This runs in just under 1 second and ensures a minimum of cpuEntropyBits bits of entropy are gathered. Based on more-entropy. @see https://github.com/keybase/more-entropy/blob/master/src/generator.iced @arg {number} [cpuEntropyBits = 128] @return {array} counts gathered by measuring variations in the CPU speed during floating point operations. */ function cpuEntropy() { var cpuEntropyBits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 128; var collected = []; var lastCount = null; var lowEntropySamples = 0; while (collected.length < cpuEntropyBits) { var count = floatingPointCount(); if (lastCount != null) { var delta = count - lastCount; if (Math.abs(delta) < 1) { lowEntropySamples++; continue; } // how many bits of entropy were in this sample var bits = Math.floor(log2(Math.abs(delta)) + 1); if (bits < 4) { if (bits < 2) { lowEntropySamples++; } continue; } collected.push(delta); } lastCount = count; } if (lowEntropySamples > 10) { var pct = Number(lowEntropySamples / cpuEntropyBits * 100).toFixed(2); // Is this algorithm getting inefficient? console.warn("WARN: ".concat(pct, "% low CPU entropy re-sampled")); } return collected; } /** @private Count while performing floating point operations during a fixed time (7 ms for example). Using a fixed time makes this algorithm predictable in runtime. */ function floatingPointCount() { var workMinMs = 7; var d = Date.now(); var i = 0, x = 0; while (Date.now() < d + workMinMs + 1) { x = Math.sin(Math.sqrt(Math.log(++i + x))); } return i; } var log2 = function log2(x) { return Math.log(x) / Math.LN2; }; /** @private Attempt to gather and hash information from the browser's window, history, and supported mime types. For non-browser environments this simply includes secure random data. In any event, the information is re-hashed in a loop for 25 milliseconds seconds. @return {Buffer} 32 bytes */ function browserEntropy() { var entropyStr = Array(randomBytes(101)).join(); try { entropyStr += new Date().toString() + " " + window.screen.height + " " + window.screen.width + " " + window.screen.colorDepth + " " + " " + window.screen.availHeight + " " + window.screen.availWidth + " " + window.screen.pixelDepth + navigator.language + " " + window.location + " " + window.history.length; for (var i = 0, mimeType; i < navigator.mimeTypes.length; i++) { mimeType = navigator.mimeTypes[i]; entropyStr += mimeType.description + " " + mimeType.type + " " + mimeType.suffixes + " "; } } catch (error) { //nodejs:ReferenceError: window is not defined entropyStr += hash.sha256(new Date().toString()); } var b = new Buffer(entropyStr); entropyStr += b.toString('binary') + " " + new Date().toString(); var entropy = entropyStr; var start_t = Date.now(); while (Date.now() - start_t < 25) { e