New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

eosjs-ecc

Package Overview
Dependencies
Maintainers
8
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

eosjs-ecc - npm Package Compare versions

Comparing version 4.0.4 to 4.0.7-ea61ee8.0

206

lib/aes.js

@@ -1,37 +0,42 @@

'use strict';
"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
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
*/
/**
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);
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);
}
/**

@@ -50,6 +55,7 @@ Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem

*/
function decrypt(private_key, public_key, nonce, message, checksum) {
return crypt(private_key, public_key, nonce, message, checksum).message;
return crypt(private_key, public_key, nonce, message, checksum).message;
}
/**

@@ -60,54 +66,55 @@ @arg {Buffer} message - Encrypted or plain text message (see checksum)

*/
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');
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');
if (!Buffer.isBuffer(message)) {
if (typeof message !== 'string') throw new TypeError('message should be buffer or string');
message = new Buffer(message, 'binary');
}
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);
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'),
// })
// 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 iv = encryption_key.slice(32, 48);
var key = encryption_key.slice(0, 32);
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();
// 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);
}
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 };
return {
nonce: nonce,
message: message,
checksum: check
};
}
/** This method does not use a checksum, the returned data must be validated some other way.

@@ -121,11 +128,12 @@

*/
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;
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.

@@ -138,34 +146,40 @@ @arg {string|Buffer} message - plaintext binary format

*/
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;
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();
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 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;
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;
return o ? Buffer.isBuffer(o) ? o : new Buffer(o, 'binary') : o;
};
"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");
/**

@@ -14,2 +18,3 @@ [Wallet Import Format](https://en.bitcoin.it/wiki/Wallet_import_format)

*/
/**

@@ -21,192 +26,191 @@ EOSKey..

/** @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();
});
},
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,
/**
@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();
},
/**
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 {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 {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 {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 {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
@return {boolean} valid
@example ecc.isValidPrivate(wif) === true
*/
isValidPrivate: function isValidPrivate(wif) {
return PrivateKey.isValid(wif);
},
/**
@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);
},
/**
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';
/**
@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);
},
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 {wif} wif
@return {boolean} valid
@example ecc.isValidPrivate(wif) === true
*/
isValidPrivate: function isValidPrivate(wif) {
return PrivateKey.isValid(wif);
},
/**
@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';
/**
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';
return Signature.signHash(dataSha256, privateKey, encoding).toString();
},
if (encoding === true) {
throw new TypeError('API changed, use signHash(..) instead');
} else {
if (encoding === false) {
console.log('Warning: ecc.sign hashData parameter was removed');
}
}
/**
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';
return Signature.sign(data, privateKey, encoding).toString();
},
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);
},
/**
@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();
},
verifyHash: function verifyHash(signature, dataSha256, pubkey) {
var encoding = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'hex';
/**
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';
signature = Signature.from(signature);
return signature.verifyHash(dataSha256, pubkey, encoding);
},
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';
/**
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();
},
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');
}
}
/**
@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.recover(data, encoding).toString();
},
signature = Signature.from(signature);
return signature.recoverHash(dataSha256, 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);
}
/** @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;
"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: Aes,
PrivateKey: PrivateKey,
PublicKey: PublicKey,
Signature: Signature,
key_utils: key_utils
};

@@ -1,7 +0,13 @@

'use strict';
"use strict";
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
/* eslint-env mocha */

@@ -13,16 +19,31 @@ var assert = require('assert');

var wif = '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss';
describe('Common API', function () {
it('unsafeRandomKey', async function () {
var pvt = await ecc.unsafeRandomKey();
assert.equal(typeof pvt === 'undefined' ? 'undefined' : _typeof(pvt), 'string', 'pvt');
assert(/^5[HJK]/.test(wif));
// assert(/^PVT_K1_/.test(pvt)) // todo
});
it('unsafeRandomKey',
/*#__PURE__*/
(0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee() {
var pvt;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return ecc.unsafeRandomKey();
case 2:
pvt = _context.sent;
assert.equal((0, _typeof2["default"])(pvt), 'string', 'pvt');
assert(/^5[HJK]/.test(wif)); // assert(/^PVT_K1_/.test(pvt)) // todo
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
})));
it('seedPrivate', function () {
assert.equal(ecc.seedPrivate(''), wif);
// assert.equal(ecc.seedPrivate(''), 'PVT_K1_2jH3nnhxhR3zPUcsKaWWZC9ZmZAnKm3GAnFD1xynGJE1Znuvjd')
assert.equal(ecc.seedPrivate(''), wif); // assert.equal(ecc.seedPrivate(''), 'PVT_K1_2jH3nnhxhR3zPUcsKaWWZC9ZmZAnKm3GAnFD1xynGJE1Znuvjd')
});
it('privateToPublic', function () {

@@ -33,134 +54,50 @@ // const pub = 'PUB_K1_859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2Ht7beeX'

});
it('isValidPublic', function () {
var keys = [[true, 'PUB_K1_859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2Ht7beeX'], [true, 'EOS859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM'], [false, 'MMM859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM'], [false, 'EOS859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVm', 'EOS'], [true, 'PUB859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM', 'PUB'], [false, 'PUB859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVm', 'PUB']];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
var key = _keys[_i];
var _key = _slicedToArray(key, 3),
valid = _key[0],
pubkey = _key[1],
prefix = _key[2];
var _key = (0, _slicedToArray2["default"])(key, 3),
valid = _key[0],
pubkey = _key[1],
prefix = _key[2];
assert.equal(valid, ecc.isValidPublic(pubkey, prefix), pubkey);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
assert.equal(valid, ecc.isValidPublic(pubkey, prefix), pubkey);
}
});
it('isValidPrivate', function () {
var keys = [[true, '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss'], [false, '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjsm']];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = keys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var key = _step2.value;
assert.equal(key[0], ecc.isValidPrivate(key[1]), key[1]);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
for (var _i2 = 0, _keys2 = keys; _i2 < _keys2.length; _i2++) {
var key = _keys2[_i2];
assert.equal(key[0], ecc.isValidPrivate(key[1]), key[1]);
}
});
it('hashs', function () {
var hashes = [
// ['sha1', 'da39a3ee5e6b4b0d3255bfef95601890afd80709'],
var hashes = [// ['sha1', 'da39a3ee5e6b4b0d3255bfef95601890afd80709'],
['sha256', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855']];
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = hashes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var hash = _step3.value;
assert.equal(ecc[hash[0]](''), hash[1]);
assert.equal(ecc[hash[0]](Buffer.from('')), hash[1]);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
for (var _i3 = 0, _hashes = hashes; _i3 < _hashes.length; _i3++) {
var hash = _hashes[_i3];
assert.equal(ecc[hash[0]](''), hash[1]);
assert.equal(ecc[hash[0]](Buffer.from('')), hash[1]);
}
});
it('signatures', function () {
var pvt = ecc.seedPrivate('');
var pubkey = ecc.privateToPublic(pvt);
var data = 'hi';
var dataSha256 = ecc.sha256(data);
var sigs = [ecc.sign(data, pvt), ecc.signHash(dataSha256, pvt)];
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = sigs[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var sig = _step4.value;
assert(ecc.verify(sig, data, pubkey), 'verify data');
assert(ecc.verifyHash(sig, dataSha256, pubkey), 'verify hash');
assert.equal(pubkey, ecc.recover(sig, data), 'recover from data');
assert.equal(pubkey, ecc.recoverHash(sig, dataSha256), 'recover from hash');
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
for (var _i4 = 0, _sigs = sigs; _i4 < _sigs.length; _i4++) {
var sig = _sigs[_i4];
assert(ecc.verify(sig, data, pubkey), 'verify data');
assert(ecc.verifyHash(sig, dataSha256, pubkey), 'verify hash');
assert.equal(pubkey, ecc.recover(sig, data), 'recover from data');
assert.equal(pubkey, ecc.recoverHash(sig, dataSha256), 'recover from hash');
}
});
});
describe('Common API (initialized)', function () {

@@ -170,3 +107,2 @@ it('initialize', function () {

});
it('randomKey', function () {

@@ -176,7 +112,6 @@ var cpuEntropyBits = 1;

var pvt = ecc.unsafeRandomKey().then(function (pvt) {
assert.equal(typeof pvt === 'undefined' ? 'undefined' : _typeof(pvt), 'string', 'pvt');
assert(/^5[HJK]/.test(wif));
// assert(/^PVT_K1_/.test(pvt))
assert.equal((0, _typeof2["default"])(pvt), 'string', 'pvt');
assert(/^5[HJK]/.test(wif)); // assert(/^PVT_K1_/.test(pvt))
});
});
});

@@ -1,13 +0,16 @@

'use strict';
"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
var ECSignature = require('./ecsignature'); // https://tools.ietf.org/html/rfc6979#section-3.2
function deterministicGenerateK(curve, hash, d, checkSig, nonce) {
enforceType('Buffer', hash);

@@ -18,44 +21,32 @@ enforceType(BigInteger, d);

hash = crypto.sha256(Buffer.concat([hash, new Buffer(nonce)]));
}
} // sanity check
// 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);
var v = new Buffer(32); // Step B
// Step B
v.fill(1);
v.fill(1); // Step C
// Step C
k.fill(0);
k.fill(0); // Step D
// Step D
k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k);
k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k); // Step E
// Step E
v = crypto.HmacSHA256(v, k);
v = crypto.HmacSHA256(v, k); // Step F
// Step F
k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k);
k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k); // Step G
// Step G
v = crypto.HmacSHA256(v, k);
v = crypto.HmacSHA256(v, k); // Step H1/H2a, ignored as tlen === qlen (256 bit)
// Step H2b
// 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]
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);
v = crypto.HmacSHA256(v, k); // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
// Step H2b again
// Step H1/H2a, again, ignored as tlen === qlen (256 bit)
// Step H2b again
v = crypto.HmacSHA256(v, k);
T = BigInteger.fromBuffer(v);

@@ -68,7 +59,5 @@ }

function sign(curve, hash, d, nonce) {
var e = BigInteger.fromBuffer(hash);
var n = curve.n;
var G = curve.G;
var r, s;

@@ -78,17 +67,11 @@ var k = deterministicGenerateK(curve, hash, d, function (k) {

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'
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) {

@@ -104,31 +87,22 @@ s = n.subtract(s);

var G = curve.G;
var r = signature.r;
var s = signature.s;
var s = signature.s; // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1]
// 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;
if (s.signum() <= 0 || s.compareTo(n) >= 0) return false; // c = s^-1 mod n
// c = s^-1 mod n
var c = s.modInverse(n);
var c = s.modInverse(n); // 1.4.4 Compute u1 = es^−1 mod n
// u2 = rs^−1 mod 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);
var u2 = r.multiply(c).mod(n); // 1.4.5 Compute R = (xR, yR) = u1G + u2Q
// 1.4.5 Compute R = (xR, yR) = u1G + u2Q
var R = G.multiplyTwo(u1, Q, u2);
var R = G.multiplyTwo(u1, Q, u2); // 1.4.5 (cont.) Enforce R is not at infinity
// 1.4.5 (cont.) Enforce R is not at infinity
if (curve.isInfinity(R)) return false;
if (curve.isInfinity(R)) return false; // 1.4.6 Convert the field element R.x to an integer
// 1.4.6 Convert the field element R.x to an integer
var xR = R.affineX;
var xR = R.affineX; // 1.4.7 Set v = xR mod n
// 1.4.7 Set v = xR mod n
var v = xR.mod(n);
var v = xR.mod(n); // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
// 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
return v.equals(r);

@@ -143,3 +117,2 @@ }

}
/**

@@ -153,42 +126,32 @@ * Recover a public key from a signature.

*/
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');
assert(s.signum() > 0 && s.compareTo(n) < 0, 'Invalid s value'); // A set LSB signifies that the y-coordinate is odd
// A set LSB signifies that the y-coordinate is odd
var isYOdd = i & 1;
// The more significant bit specifies whether we should use the
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 isSecondKey = i >> 1; // 1.1 Let x = r + jn
var x = isSecondKey ? r.add(n) : r;
var R = curve.pointFromX(isYOdd, x);
var R = curve.pointFromX(isYOdd, x); // 1.4 Check that nR is at infinity
// 1.4 Check that nR is at infinity
var nR = R.multiply(n);
assert(curve.isInfinity(nR), 'nR is not a valid curve point');
assert(curve.isInfinity(nR), 'nR is not a valid curve point'); // Compute -e from e
// Compute -e from e
var eNeg = e.negate().mod(n);
var eNeg = e.negate().mod(n); // 1.6.1 Compute Q = r^-1 (sR - eG)
// Q = r^-1 (sR + -eG)
// 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;
}
/**

@@ -205,7 +168,8 @@ * Calculate pubkey extraction parameter.

*/
function calcPubKeyRecoveryParam(curve, e, signature, Q) {
for (var i = 0; i < 4; i++) {
var Qprime = recoverPubKey(curve, e, signature, i);
var Qprime = recoverPubKey(curve, e, signature, i); // 1.6.2 Verify Q
// 1.6.2 Verify Q
if (Qprime.equals(Q)) {

@@ -212,0 +176,0 @@ return i;

@@ -1,4 +0,6 @@

'use strict';
"use strict";
var assert = require('assert'); // from https://github.com/bitcoinjs/bitcoinjs-lib
var enforceType = require('./enforce_types');

@@ -15,9 +17,6 @@

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;

@@ -29,16 +28,11 @@ }

var sBa = s.toDERInteger();
var sequence = []; // INTEGER
var sequence = [];
// INTEGER
sequence.push(0x02, rBa.length);
sequence = sequence.concat(rBa);
sequence = sequence.concat(rBa); // INTEGER
// INTEGER
sequence.push(0x02, sBa.length);
sequence = sequence.concat(sBa);
sequence = sequence.concat(sBa); // SEQUENCE
// SEQUENCE
sequence.unshift(0x30, sequence.length);
return new Buffer(sequence);

@@ -50,24 +44,25 @@ }

hashTypeBuffer.writeUInt8(hashType, 0);
return Buffer.concat([toDER(), hashTypeBuffer]);
}
return { r: r, s: s, toCompact: toCompact, toDER: toDER, toScriptSignature: toScriptSignature };
}
return {
r: r,
s: s,
toCompact: toCompact,
toDER: toDER,
toScriptSignature: toScriptSignature
};
} // Import operations
// Import operations
ECSignature.parseCompact = function (buffer) {
assert.equal(buffer.length, 65, 'Invalid signature length');
var i = buffer.readUInt8(0) - 27;
var i = buffer.readUInt8(0) - 27; // At most 3 bits
// At most 3 bits
assert.equal(i, i & 7, 'Invalid signature parameter');
var compressed = !!(i & 4);
var compressed = !!(i & 4); // Recovery param only
// Recovery param only
i = i & 3;
var r = BigInteger.fromBuffer(buffer.slice(1, 33));
var s = BigInteger.fromBuffer(buffer.slice(33));
return {

@@ -84,12 +79,8 @@ compressed: compressed,

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);

@@ -110,16 +101,12 @@ var sB = buffer.slice(offset + 2);

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
// 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 {

@@ -126,0 +113,0 @@ signature: ECSignature.fromDER(buffer.slice(0, -1)),

@@ -1,2 +0,2 @@

'use strict';
"use strict";

@@ -3,0 +3,0 @@ module.exports = function enforce(type, value) {

@@ -1,6 +0,6 @@

'use strict';
"use strict";
var createHash = require('create-hash');
var createHmac = require('create-hmac');
/** @namespace hash */

@@ -12,6 +12,7 @@

*/
function sha1(data, resultEncoding) {
return createHash('sha1').update(data).digest(resultEncoding);
return createHash('sha1').update(data).digest(resultEncoding);
}
/** @arg {string|Buffer} data

@@ -21,6 +22,7 @@ @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64'

*/
function sha256(data, resultEncoding) {
return createHash('sha256').update(data).digest(resultEncoding);
return createHash('sha256').update(data).digest(resultEncoding);
}
/** @arg {string|Buffer} data

@@ -30,15 +32,15 @@ @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64'

*/
function sha512(data, resultEncoding) {
return createHash('sha512').update(data).digest(resultEncoding);
return createHash('sha512').update(data).digest(resultEncoding);
}
function HmacSHA256(buffer, secret) {
return createHmac('sha256', secret).update(buffer).digest();
return createHmac('sha256', secret).update(buffer).digest();
}
function ripemd160(data) {
return createHash('rmd160').update(data).digest();
}
// function hash160(buffer) {
return createHash('rmd160').update(data).digest();
} // function hash160(buffer) {
// return ripemd160(sha256(buffer))

@@ -50,3 +52,2 @@ // }

// }
//

@@ -57,11 +58,12 @@ // function HmacSHA512(buffer, secret) {

module.exports = {
sha1: sha1,
sha256: sha256,
sha512: sha512,
HmacSHA256: HmacSHA256,
ripemd160: ripemd160
// hash160: hash160,
// hash256: hash256,
// HmacSHA512: HmacSHA512
sha1: sha1,
sha256: sha256,
sha512: sha512,
HmacSHA256: HmacSHA256,
ripemd160: ripemd160 // hash160: hash160,
// hash256: hash256,
// HmacSHA512: HmacSHA512
};

@@ -1,8 +0,8 @@

'use strict';
"use strict";
var commonApi = require('./api_common');
var objectApi = require('./api_object');
var ecc = Object.assign({}, commonApi, objectApi);
module.exports = ecc;

@@ -1,19 +0,28 @@

'use strict';
"use strict";
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
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');

@@ -23,5 +32,3 @@

var n = secp256k1.n;
module.exports = PrivateKey;
/**

@@ -36,153 +43,173 @@ @typedef {string} wif - https://en.bitcoin.it/wiki/Wallet_import_format

*/
function PrivateKey(d) {
if (typeof d === 'string') {
return PrivateKey.fromString(d);
} else if (Buffer.isBuffer(d)) {
return PrivateKey.fromBuffer(d);
} else if ((typeof d === 'undefined' ? 'undefined' : _typeof(d)) === 'object' && BigInteger.isBigInteger(d.d)) {
return PrivateKey(d.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');
}
if (!BigInteger.isBigInteger(d)) {
throw new TypeError('Invalid private key');
}
/** @return {string} private key like PVT_K1_base58privatekey.. */
/** @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');
}
function toString() {
// todo, use PVT_K1_
// return 'PVT_K1_' + keyUtils.checkEncode(toBuffer(), 'K1')
return toWif();
}
/**
@return {wif}
*/
var public_key = void 0;
/**
@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 toWif() {
var private_key = toBuffer(); // checksum includes the version
function toBuffer() {
return d.toBuffer(32);
}
private_key = Buffer.concat([new Buffer([0x80]), private_key]);
return keyUtils.checkEncode(private_key, 'sha256x2');
}
/**
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);
var public_key;
/**
@return {Point}
*/
function toPublic() {
if (public_key) {
// cache
// S L O W in the browser
return public_key;
}
// /** 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);
// }
var Q = secp256k1.G.multiply(d);
return public_key = PublicKey.fromPoint(Q);
}
/**
@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 toBuffer() {
return d.toBuffer(32);
}
/**
ECIES
@arg {string|Object} pubkey wif, PublicKey object
@return {Buffer} 64 byte shared secret
*/
function toHex() {
return toBuffer().toString('hex');
}
return {
d: d,
toWif: toWif,
toString: toString,
toPublic: toPublic,
toBuffer: toBuffer,
getSharedSecret: getSharedSecret,
getChildKey: getChildKey
};
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 */
/** @private */
function parseKey(privateStr) {
assert.equal(typeof privateStr === 'undefined' ? 'undefined' : _typeof(privateStr), 'string', 'privateStr');
var match = privateStr.match(/^PVT_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/);
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 ' + 0x80 + ', instead got ' + version);
var _privateKey = PrivateKey.fromBuffer(versionKey.slice(1));
var _keyType = 'K1';
var format = 'WIF';
return { privateKey: _privateKey, format: format, keyType: _keyType };
}
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));
assert(match.length === 3, 'Expecting private key like: PVT_K1_base58privateKey..');
var _privateKey = PrivateKey.fromBuffer(versionKey.slice(1));
var _match = _slicedToArray(match, 3),
keyType = _match[1],
keyString = _match[2];
var _keyType = 'K1';
var format = 'WIF';
return {
privateKey: _privateKey,
format: format,
keyType: _keyType
};
}
assert.equal(keyType, 'K1', 'K1 private key expected');
var privateKey = PrivateKey.fromBuffer(keyUtils.checkDecode(keyString, keyType));
return { privateKey: privateKey, format: 'PVT', 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'));
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 ' + buf.length);
}
return PrivateKey(BigInteger.fromBuffer(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));
};
/**

@@ -194,10 +221,12 @@ @arg {string} seed - any length string. This is private, the same seed

*/
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));
// generate_private_key
if (!(typeof seed === 'string')) {
throw new Error('seed must be of type string');
}
return PrivateKey.fromBuffer(hash.sha256(seed));
};
/**

@@ -207,11 +236,12 @@ @arg {wif} key

*/
PrivateKey.isWif = function (text) {
try {
assert(parseKey(text).format === 'WIF');
return true;
} catch (e) {
return false;
}
try {
assert(parseKey(text).format === 'WIF');
return true;
} catch (e) {
return false;
}
};
/**

@@ -221,17 +251,19 @@ @arg {wif|Buffer|PrivateKey} key

*/
PrivateKey.isValid = function (key) {
try {
PrivateKey(key);
return true;
} catch (e) {
return false;
}
try {
PrivateKey(key);
return true;
} catch (e) {
return false;
}
};
/** @deprecated */
/** @deprecated */
PrivateKey.fromWif = function (str) {
console.log('PrivateKey.fromWif is deprecated, please use PrivateKey.fromString');
return PrivateKey.fromString(str);
console.log('PrivateKey.fromWif is deprecated, please use PrivateKey.fromString');
return PrivateKey.fromString(str);
};
/**

@@ -241,6 +273,7 @@ @throws {AssertError|Error} parsing key

*/
PrivateKey.fromString = function (privateStr) {
return parseKey(privateStr).privateKey;
return parseKey(privateStr).privateKey;
};
/**

@@ -257,15 +290,21 @@ Create a new 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 }));
});
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 })));
return Promise.resolve(PrivateKey.fromBuffer(keyUtils.random32ByteBuffer({
safe: false
})));
};

@@ -275,3 +314,2 @@

unitTested = false;
/**

@@ -284,16 +322,15 @@ Run self-checking code and gather CPU entropy.

*/
function initialize() {
if (initialized) {
return;
}
if (initialized) {
return;
}
unitTest();
keyUtils.addEntropy.apply(keyUtils, _toConsumableArray(keyUtils.cpuEntropy()));
assert(keyUtils.entropyCount() >= 128, 'insufficient entropy');
initialized = true;
unitTest();
keyUtils.addEntropy.apply(keyUtils, (0, _toConsumableArray2["default"])(keyUtils.cpuEntropy()));
assert(keyUtils.entropyCount() >= 128, 'insufficient entropy');
initialized = true;
}
PrivateKey.initialize = promiseAsync(initialize);
/**

@@ -304,38 +341,36 @@ Unit test basic private and public key functionality.

*/
function unitTest() {
var pvt = PrivateKey(hash.sha256(''));
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 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)
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')
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;
unitTested = true;
}
/** @private */
/** @private */
var doesNotThrow = function doesNotThrow(cb, msg) {
try {
cb();
} catch (error) {
error.message = msg + ' ==> ' + error.message;
throw error;
}
try {
cb();
} catch (error) {
error.message = "".concat(msg, " ==> ").concat(error.message);
throw error;
}
};

@@ -1,13 +0,19 @@

'use strict';
"use strict";
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
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');

@@ -17,5 +23,3 @@

var n = secp256k1.n;
module.exports = PublicKey;
/**

@@ -25,90 +29,82 @@ @param {string|Buffer|PublicKey|ecurve.Point} public key

*/
function PublicKey(Q) {
var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS';
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 ((typeof Q === 'undefined' ? 'undefined' : _typeof(Q)) === 'object' && Q.Q) {
return PublicKey(Q.Q);
}
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(typeof Q === 'undefined' ? 'undefined' : _typeof(Q), 'object', 'Invalid public key');
assert.equal(_typeof(Q.compressed), 'boolean', 'Invalid public key');
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;
function toBuffer() {
var compressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Q.compressed;
return Q.getEncoded(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;
// }
var pubdata = void 0; // cache
/** @todo rename to toStringLegacy
* @arg {string} [pubkey_prefix = 'EOS'] - public key prefix
*/
// /**
// @todo secp224r1
// @return {string} PUB_K1_base58pubkey..
// */
// function toString() {
// if(pubdata) {
// return pubdata
// }
// pubdata = `PUB_K1_` + keyUtils.checkEncode(toBuffer(), 'K1')
// return pubdata;
// }
function toString() {
var pubkey_prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'EOS';
return pubkey_prefix + keyUtils.checkEncode(toBuffer());
}
/** @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';
function toUncompressed() {
var buf = Q.getEncoded(false);
var point = ecurve.Point.decodeFrom(secp256k1, buf);
return PublicKey.fromPoint(point);
}
/** @deprecated */
return pubkey_prefix + keyUtils.checkEncode(toBuffer());
}
function toUncompressed() {
var buf = Q.getEncoded(false);
var point = ecurve.Point.decodeFrom(secp256k1, buf);
return PublicKey.fromPoint(point);
}
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);
}
/** @deprecated */
function child(offset) {
console.error('Deprecated warning: PublicKey.child');
function toHex() {
return toBuffer().toString('hex');
}
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
};
return {
Q: Q,
toString: toString,
// toStringLegacy,
toUncompressed: toUncompressed,
toBuffer: toBuffer,
child: child,
toHex: toHex
};
}
/**

@@ -118,25 +114,26 @@ @param {string|Buffer|PublicKey|ecurve.Point} pubkey - public key

*/
PublicKey.isValid = function (pubkey) {
var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS';
var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS';
try {
PublicKey(pubkey, pubkey_prefix);
return true;
} catch (e) {
return false;
}
try {
PublicKey(pubkey, pubkey_prefix);
return true;
} catch (e) {
return false;
}
};
PublicKey.fromBinary = function (bin) {
return PublicKey.fromBuffer(new Buffer(bin, 'binary'));
return PublicKey.fromBuffer(new Buffer(bin, 'binary'));
};
PublicKey.fromBuffer = function (buffer) {
return PublicKey(ecurve.Point.decodeFrom(secp256k1, buffer));
return PublicKey(ecurve.Point.decodeFrom(secp256k1, buffer));
};
PublicKey.fromPoint = function (point) {
return PublicKey(point);
return PublicKey(point);
};
/**

@@ -147,12 +144,13 @@ @arg {string} public_key - like PUB_K1_base58pubkey..

*/
PublicKey.fromString = function (public_key) {
var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS';
var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS';
try {
return PublicKey.fromStringOrThrow(public_key, pubkey_prefix);
} catch (e) {
return null;
}
try {
return PublicKey.fromStringOrThrow(public_key, pubkey_prefix);
} catch (e) {
return null;
}
};
/**

@@ -166,31 +164,36 @@ @arg {string} public_key - like PUB_K1_base58pubkey..

*/
PublicKey.fromStringOrThrow = function (public_key) {
var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS';
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]+)$/);
assert.equal(typeof public_key === 'undefined' ? 'undefined' : _typeof(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));
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);
}
assert(match.length === 3, 'Expecting public key like: PUB_K1_base58pubkey..');
var _match = _slicedToArray(match, 3),
keyType = _match[1],
keyString = _match[2];
return PublicKey.fromBuffer(keyUtils.checkDecode(public_key));
}
assert.equal(keyType, 'K1', 'K1 private key expected');
return PublicKey.fromBuffer(keyUtils.checkDecode(keyString, keyType));
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'));
return PublicKey.fromBuffer(new Buffer(hex, 'hex'));
};
PublicKey.fromStringHex = function (hex) {
return PublicKey.fromString(new Buffer(hex, 'hex'));
return PublicKey.fromString(new Buffer(hex, 'hex'));
};

@@ -1,7 +0,11 @@

'use strict';
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
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');

@@ -12,17 +16,14 @@

module.exports = {
random32ByteBuffer: random32ByteBuffer,
addEntropy: addEntropy,
cpuEntropy: cpuEntropy,
entropyCount: function entropyCount() {
return _entropyCount;
},
checkDecode: checkDecode,
checkEncode: checkEncode
random32ByteBuffer: random32ByteBuffer,
addEntropy: addEntropy,
cpuEntropy: cpuEntropy,
entropyCount: function entropyCount() {
return _entropyCount;
},
checkDecode: checkDecode,
checkEncode: checkEncode
};
var entropyPos = 0,
_entropyCount = 0;
var externalEntropyArray = randomBytes(101);
/**

@@ -39,28 +40,27 @@ 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.

*/
function random32ByteBuffer() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$cpuEntropyBits = _ref.cpuEntropyBits,
cpuEntropyBits = _ref$cpuEntropyBits === undefined ? 0 : _ref$cpuEntropyBits,
_ref$safe = _ref.safe,
safe = _ref$safe === undefined ? true : _ref$safe;
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(typeof cpuEntropyBits === 'undefined' ? 'undefined' : _typeof(cpuEntropyBits), 'number', 'cpuEntropyBits');
assert.equal(typeof safe === 'undefined' ? 'undefined' : _typeof(safe), 'boolean', 'boolean');
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 (safe) {
assert(_entropyCount >= 128, 'Call initialize() to add entropy');
} // if(entropyCount > 0) {
// console.log(`Additional private key entropy: ${entropyCount} events`)
// }
// 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));
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));
}
/**

@@ -86,38 +86,20 @@ Adds entropy. This may be called many times while the amount of data saved

*/
function addEntropy() {
assert.equal(externalEntropyArray.length, 101, 'externalEntropyArray');
assert.equal(externalEntropyArray.length, 101, 'externalEntropyArray');
for (var _len = arguments.length, ints = Array(_len), _key = 0; _key < _len; _key++) {
ints[_key] = arguments[_key];
}
for (var _len = arguments.length, ints = new Array(_len), _key = 0; _key < _len; _key++) {
ints[_key] = arguments[_key];
}
_entropyCount += ints.length;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
_entropyCount += ints.length;
try {
for (var _iterator = ints[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var i = _step.value;
var pos = entropyPos++ % 101;
var i2 = externalEntropyArray[pos] += i;
if (i2 > 9007199254740991) externalEntropyArray[pos] = 0;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
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;
}
}
/**

@@ -132,36 +114,46 @@ This runs in just under 1 second and ensures a minimum of cpuEntropyBits

*/
function cpuEntropy() {
var cpuEntropyBits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 128;
var cpuEntropyBits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 128;
var collected = [];
var lastCount = null;
var lowEntropySamples = 0;
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);
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++;
}
lastCount = count;
continue;
}
collected.push(delta);
}
if (lowEntropySamples > 10) {
var pct = Number(lowEntropySamples / cpuEntropyBits * 100).toFixed(2);
// Is this algorithm getting inefficient?
console.warn('WARN: ' + pct + '% low CPU entropy re-sampled');
}
return collected;
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;
}
/**

@@ -173,17 +165,20 @@ @private

*/
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 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;
return Math.log(x) / Math.LN2;
};
/**

@@ -195,26 +190,30 @@ @private

*/
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;
var entropyStr = Array(randomBytes(101)).join();
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());
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 b = new Buffer(entropyStr);
entropyStr += b.toString('binary') + " " + new Date().toString();
var entropy = entropyStr;
var start_t = Date.now();
var entropy = entropyStr;
var start_t = Date.now();
while (Date.now() - start_t < 25) {
entropy = hash.sha256(entropy);
}return entropy;
while (Date.now() - start_t < 25) {
entropy = hash.sha256(entropy);
}
return entropy;
}
/**

@@ -225,20 +224,24 @@ @arg {Buffer} keyBuffer data

*/
function checkEncode(keyBuffer) {
var keyType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var keyType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
assert(Buffer.isBuffer(keyBuffer), 'expecting keyBuffer<Buffer>');
assert(Buffer.isBuffer(keyBuffer), 'expecting keyBuffer<Buffer>');
if (keyType === 'sha256x2') {
// legacy
var checksum = hash.sha256(hash.sha256(keyBuffer)).slice(0, 4);
return base58.encode(Buffer.concat([keyBuffer, checksum]));
} else {
var check = [keyBuffer];
if (keyType) {
check.push(Buffer.from(keyType));
}
var _checksum = hash.ripemd160(Buffer.concat(check)).slice(0, 4);
return base58.encode(Buffer.concat([keyBuffer, _checksum]));
if (keyType === 'sha256x2') {
// legacy
var checksum = hash.sha256(hash.sha256(keyBuffer)).slice(0, 4);
return base58.encode(Buffer.concat([keyBuffer, checksum]));
} else {
var check = [keyBuffer];
if (keyType) {
check.push(Buffer.from(keyType));
}
var _checksum = hash.ripemd160(Buffer.concat(check)).slice(0, 4);
return base58.encode(Buffer.concat([keyBuffer, _checksum]));
}
}
/**

@@ -249,27 +252,30 @@ @arg {Buffer} keyString data

*/
function checkDecode(keyString) {
var keyType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var keyType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
assert(keyString != null, 'private key expected');
var buffer = new Buffer(base58.decode(keyString));
var checksum = buffer.slice(-4);
var key = buffer.slice(0, -4);
var newCheck;
assert(keyString != null, 'private key expected');
var buffer = new Buffer(base58.decode(keyString));
var checksum = buffer.slice(-4);
var key = buffer.slice(0, -4);
if (keyType === 'sha256x2') {
// legacy
newCheck = hash.sha256(hash.sha256(key)).slice(0, 4); // WIF (legacy)
} else {
var check = [key];
var newCheck = void 0;
if (keyType === 'sha256x2') {
// legacy
newCheck = hash.sha256(hash.sha256(key)).slice(0, 4); // WIF (legacy)
} else {
var check = [key];
if (keyType) {
check.push(Buffer.from(keyType));
}
newCheck = hash.ripemd160(Buffer.concat(check)).slice(0, 4); //PVT
if (keyType) {
check.push(Buffer.from(keyType));
}
if (checksum.toString() !== newCheck.toString()) {
throw new Error('Invalid checksum, ' + (checksum.toString('hex') + ' != ' + newCheck.toString('hex')));
}
newCheck = hash.ripemd160(Buffer.concat(check)).slice(0, 4); //PVT
}
return key;
if (checksum.toString('hex') !== newCheck.toString('hex')) {
throw new Error('Invalid checksum, ' + "".concat(checksum.toString('hex'), " != ").concat(newCheck.toString('hex')));
}
return key;
}

@@ -1,2 +0,2 @@

'use strict';
"use strict";

@@ -11,8 +11,5 @@ /* eslint-env mocha */

Signature = ecc.Signature;
describe('Object API', function () {
var pvt = PrivateKey('5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3');
var pub = pvt.toPublic();
describe('secp256k1 keys', function () {

@@ -23,25 +20,20 @@ it('randomKey', function () {

});
it('private to public', function () {
assert.equal(pub.toString(),
// 'PUB_K1_6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5BoDq63',
assert.equal(pub.toString(), // 'PUB_K1_6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5BoDq63',
'EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV', 'pub.toString');
});
it('PrivateKey constructors', function () {
assert(pvt.toWif() === PrivateKey(pvt.toWif()).toWif());
assert(pvt.toWif() === PrivateKey(pvt.toBuffer()).toWif());
assert(pvt.toWif() === PrivateKey(pvt).toWif());
assert(pvt.toWif() === PrivateKey(pvt).toWif()); // 01 suffix indicates a compressed public key (normally this is omitted)
// 01 suffix indicates a compressed public key (normally this is omitted)
var pvtCompressFlag = Buffer.concat([pvt.toBuffer(), Buffer.from('01', 'hex')]);
assert(pvt.toWif() === PrivateKey(pvtCompressFlag).toWif());
assert.throws(function () {
assert["throws"](function () {
return PrivateKey();
}, /Invalid private key/);
assert.throws(function () {
assert["throws"](function () {
return PrivateKey.fromHex('ff');
}, /Expecting 32 bytes/);
assert.throws(function () {
assert["throws"](function () {
return PrivateKey.fromBuffer('ff');

@@ -53,3 +45,2 @@ }, /Expecting parameter to be a Buffer type/);

});
it('Helpers', function () {

@@ -59,3 +50,2 @@ assert.equal(PrivateKey.isWif('5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3'), true, 'isWif');

});
it('PublicKey constructors', function () {

@@ -65,3 +55,3 @@ assert(pub.toString() === PublicKey(pub.toString()).toString());

assert(pub.toString() === PublicKey(pub).toString());
assert.throws(function () {
assert["throws"](function () {
return PublicKey();

@@ -71,3 +61,2 @@ }, /Invalid public key/);

});
/** @todo secp224r1 */

@@ -74,0 +63,0 @@ // it('PrivateKey secp224r1', () => {

@@ -14,3 +14,3 @@ "use strict";

return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];

@@ -22,3 +22,3 @@ }

try {
resolve(func.apply(undefined, args));
resolve(func.apply(void 0, args));
} catch (err) {

@@ -25,0 +25,0 @@ reject(err);

@@ -1,14 +0,23 @@

'use strict';
"use strict";
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var ecdsa = require('./ecdsa');
var hash = require('./hash');
var curve = require('ecurve').getCurveByName('secp256k1');
var assert = require('assert');
var BigInteger = require('bigi');
var keyUtils = require('./key_utils');
var PublicKey = require('./key_public');
var PrivateKey = require('./key_private');

@@ -19,151 +28,173 @@

function Signature(r, s, i) {
assert.equal(r != null, true, 'Missing parameter');
assert.equal(s != null, true, 'Missing parameter');
assert.equal(i != null, true, 'Missing parameter');
assert.equal(r != null, true, 'Missing parameter');
assert.equal(s != null, true, 'Missing parameter');
assert.equal(i != null, true, 'Missing parameter');
/**
Verify signed data.
@arg {String|Buffer} data - full data
@arg {pubkey|PublicKey} pubkey - EOSKey..
@arg {String} [encoding = 'utf8'] - data encoding (if data is a string)
@return {boolean}
*/
/**
Verify signed data.
@arg {String|Buffer} data - full data
@arg {pubkey|PublicKey} pubkey - EOSKey..
@arg {String} [encoding = 'utf8'] - data encoding (if data is a string)
@return {boolean}
*/
function verify(data, pubkey) {
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8';
function verify(data, pubkey) {
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8';
if (typeof data === 'string') {
data = Buffer.from(data, encoding);
}
assert(Buffer.isBuffer(data), 'data is a required String or Buffer');
data = hash.sha256(data);
return verifyHash(data, pubkey);
if (typeof data === 'string') {
data = Buffer.from(data, encoding);
}
/**
Verify a buffer of exactally 32 bytes in size (sha256(text))
@arg {String|Buffer} dataSha256 - 32 byte buffer or string
@arg {String|PublicKey} pubkey - EOSKey..
@arg {String} [encoding = 'hex'] - dataSha256 encoding (if string)
@return {boolean}
*/
function verifyHash(dataSha256, pubkey) {
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex';
assert(Buffer.isBuffer(data), 'data is a required String or Buffer');
data = hash.sha256(data);
return verifyHash(data, pubkey);
}
/**
Verify a buffer of exactally 32 bytes in size (sha256(text))
@arg {String|Buffer} dataSha256 - 32 byte buffer or string
@arg {String|PublicKey} pubkey - EOSKey..
@arg {String} [encoding = 'hex'] - dataSha256 encoding (if string)
@return {boolean}
*/
if (typeof dataSha256 === 'string') {
dataSha256 = Buffer.from(dataSha256, encoding);
}
if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 bytes required");
var publicKey = PublicKey(pubkey);
assert(publicKey, 'pubkey required');
function verifyHash(dataSha256, pubkey) {
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex';
return ecdsa.verify(curve, dataSha256, { r: r, s: s }, publicKey.Q);
};
if (typeof dataSha256 === 'string') {
dataSha256 = Buffer.from(dataSha256, encoding);
}
/** @deprecated
Verify hex data by converting to a buffer then hashing.
@return {boolean}
*/
function verifyHex(hex, pubkey) {
console.log('Deprecated: use verify(data, pubkey, "hex")');
if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 bytes required");
var publicKey = PublicKey(pubkey);
assert(publicKey, 'pubkey required');
return ecdsa.verify(curve, dataSha256, {
r: r,
s: s
}, publicKey.Q);
}
var buf = Buffer.from(hex, 'hex');
return verify(buf, pubkey);
};
;
/** @deprecated
Verify hex data by converting to a buffer then hashing.
@return {boolean}
*/
/**
Recover the public key used to create this signature using full data.
@arg {String|Buffer} data - full data
@arg {String} [encoding = 'utf8'] - data encoding (if string)
@return {PublicKey}
*/
function recover(data) {
var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'utf8';
function verifyHex(hex, pubkey) {
console.log('Deprecated: use verify(data, pubkey, "hex")');
var buf = Buffer.from(hex, 'hex');
return verify(buf, pubkey);
}
if (typeof data === 'string') {
data = Buffer.from(data, encoding);
}
assert(Buffer.isBuffer(data), 'data is a required String or Buffer');
data = hash.sha256(data);
;
/**
Recover the public key used to create this signature using full data.
@arg {String|Buffer} data - full data
@arg {String} [encoding = 'utf8'] - data encoding (if string)
@return {PublicKey}
*/
return recoverHash(data);
};
function recover(data) {
var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'utf8';
/**
@arg {String|Buffer} dataSha256 - sha256 hash 32 byte buffer or hex string
@arg {String} [encoding = 'hex'] - dataSha256 encoding (if string)
@return {PublicKey}
*/
function recoverHash(dataSha256) {
var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'hex';
if (typeof data === 'string') {
data = Buffer.from(data, encoding);
}
if (typeof dataSha256 === 'string') {
dataSha256 = Buffer.from(dataSha256, encoding);
}
if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) {
throw new Error("dataSha256: 32 byte String or buffer requred");
}
assert(Buffer.isBuffer(data), 'data is a required String or Buffer');
data = hash.sha256(data);
return recoverHash(data);
}
var e = BigInteger.fromBuffer(dataSha256);
var i2 = i;
i2 -= 27;
i2 = i2 & 3;
var Q = ecdsa.recoverPubKey(curve, e, { r: r, s: s, i: i }, i2);
return PublicKey.fromPoint(Q);
};
;
/**
@arg {String|Buffer} dataSha256 - sha256 hash 32 byte buffer or hex string
@arg {String} [encoding = 'hex'] - dataSha256 encoding (if string)
@return {PublicKey}
*/
function toBuffer() {
var buf;
buf = new Buffer(65);
buf.writeUInt8(i, 0);
r.toBuffer(32).copy(buf, 1);
s.toBuffer(32).copy(buf, 33);
return buf;
};
function recoverHash(dataSha256) {
var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'hex';
function toHex() {
return toBuffer().toString("hex");
};
if (typeof dataSha256 === 'string') {
dataSha256 = Buffer.from(dataSha256, encoding);
}
var signatureCache = void 0;
if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) {
throw new Error("dataSha256: 32 byte String or buffer requred");
}
function toString() {
if (signatureCache) {
return signatureCache;
}
signatureCache = 'SIG_K1_' + keyUtils.checkEncode(toBuffer(), 'K1');
return signatureCache;
var e = BigInteger.fromBuffer(dataSha256);
var i2 = i;
i2 -= 27;
i2 = i2 & 3;
var Q = ecdsa.recoverPubKey(curve, e, {
r: r,
s: s,
i: i
}, i2);
return PublicKey.fromPoint(Q);
}
;
function toBuffer() {
var buf;
buf = new Buffer(65);
buf.writeUInt8(i, 0);
r.toBuffer(32).copy(buf, 1);
s.toBuffer(32).copy(buf, 33);
return buf;
}
;
function toHex() {
return toBuffer().toString("hex");
}
;
var signatureCache;
function toString() {
if (signatureCache) {
return signatureCache;
}
return {
r: r, s: s, i: i,
toBuffer: toBuffer,
verify: verify,
verifyHash: verifyHash,
verifyHex: verifyHex, // deprecated
recover: recover,
recoverHash: recoverHash,
toHex: toHex,
toString: toString,
signatureCache = 'SIG_K1_' + keyUtils.checkEncode(toBuffer(), 'K1');
return signatureCache;
}
/** @deprecated use verify (same arguments and return) */
verifyBuffer: function verifyBuffer() {
console.log('Deprecated: use signature.verify instead (same arguments)');
return verify.apply(undefined, arguments);
},
return {
r: r,
s: s,
i: i,
toBuffer: toBuffer,
verify: verify,
verifyHash: verifyHash,
verifyHex: verifyHex,
// deprecated
recover: recover,
recoverHash: recoverHash,
toHex: toHex,
toString: toString,
/** @deprecated use recover (same arguments and return) */
recoverPublicKey: function recoverPublicKey() {
console.log('Deprecated: use signature.recover instead (same arguments)');
return recover.apply(undefined, arguments);
},
/** @deprecated use verify (same arguments and return) */
verifyBuffer: function verifyBuffer() {
console.log('Deprecated: use signature.verify instead (same arguments)');
return verify.apply(void 0, arguments);
},
/** @deprecated use recoverHash (same arguments and return) */
recoverPublicKeyFromBuffer: function recoverPublicKeyFromBuffer() {
console.log('Deprecated: use signature.recoverHash instead (same arguments)');
return recoverHash.apply(undefined, arguments);
}
};
/** @deprecated use recover (same arguments and return) */
recoverPublicKey: function recoverPublicKey() {
console.log('Deprecated: use signature.recover instead (same arguments)');
return recover.apply(void 0, arguments);
},
/** @deprecated use recoverHash (same arguments and return) */
recoverPublicKeyFromBuffer: function recoverPublicKeyFromBuffer() {
console.log('Deprecated: use signature.recoverHash instead (same arguments)');
return recoverHash.apply(void 0, arguments);
}
};
}
/**

@@ -178,13 +209,15 @@ Hash and sign arbitrary data.

*/
Signature.sign = function (data, privateKey) {
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8';
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8';
if (typeof data === 'string') {
data = Buffer.from(data, encoding);
}
assert(Buffer.isBuffer(data), 'data is a required String or Buffer');
data = hash.sha256(data);
return Signature.signHash(data, privateKey);
if (typeof data === 'string') {
data = Buffer.from(data, encoding);
}
assert(Buffer.isBuffer(data), 'data is a required String or Buffer');
data = hash.sha256(data);
return Signature.signHash(data, privateKey);
};
/**

@@ -199,50 +232,56 @@ Sign a buffer of exactally 32 bytes in size (sha256(text))

*/
Signature.signHash = function (dataSha256, privateKey) {
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex';
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex';
if (typeof dataSha256 === 'string') {
dataSha256 = Buffer.from(dataSha256, encoding);
if (typeof dataSha256 === 'string') {
dataSha256 = Buffer.from(dataSha256, encoding);
}
if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 byte buffer requred");
privateKey = PrivateKey(privateKey);
assert(privateKey, 'privateKey required');
var der, e, ecsignature, i, lenR, lenS, nonce;
i = null;
nonce = 0;
e = BigInteger.fromBuffer(dataSha256);
while (true) {
ecsignature = ecdsa.sign(curve, dataSha256, privateKey.d, nonce++);
der = ecsignature.toDER();
lenR = der[3];
lenS = der[5 + lenR];
if (lenR === 32 && lenS === 32) {
i = ecdsa.calcPubKeyRecoveryParam(curve, e, ecsignature, privateKey.toPublic().Q);
i += 4; // compressed
i += 27; // compact // 24 or 27 :( forcing odd-y 2nd key candidate)
break;
}
if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 byte buffer requred");
privateKey = PrivateKey(privateKey);
assert(privateKey, 'privateKey required');
if (nonce % 10 === 0) {
console.log("WARN: " + nonce + " attempts to find canonical signature");
}
}
var der, e, ecsignature, i, lenR, lenS, nonce;
i = null;
nonce = 0;
e = BigInteger.fromBuffer(dataSha256);
while (true) {
ecsignature = ecdsa.sign(curve, dataSha256, privateKey.d, nonce++);
der = ecsignature.toDER();
lenR = der[3];
lenS = der[5 + lenR];
if (lenR === 32 && lenS === 32) {
i = ecdsa.calcPubKeyRecoveryParam(curve, e, ecsignature, privateKey.toPublic().Q);
i += 4; // compressed
i += 27; // compact // 24 or 27 :( forcing odd-y 2nd key candidate)
break;
}
if (nonce % 10 === 0) {
console.log("WARN: " + nonce + " attempts to find canonical signature");
}
}
return Signature(ecsignature.r, ecsignature.s, i);
return Signature(ecsignature.r, ecsignature.s, i);
};
Signature.fromBuffer = function (buf) {
var i, r, s;
assert(Buffer.isBuffer(buf), 'Buffer is required');
assert.equal(buf.length, 65, 'Invalid signature length');
i = buf.readUInt8(0);
assert.equal(i - 27, i - 27 & 7, 'Invalid signature parameter');
r = BigInteger.fromBuffer(buf.slice(1, 33));
s = BigInteger.fromBuffer(buf.slice(33));
return Signature(r, s, i);
var i, r, s;
assert(Buffer.isBuffer(buf), 'Buffer is required');
assert.equal(buf.length, 65, 'Invalid signature length');
i = buf.readUInt8(0);
assert.equal(i - 27, i - 27 & 7, 'Invalid signature parameter');
r = BigInteger.fromBuffer(buf.slice(1, 33));
s = BigInteger.fromBuffer(buf.slice(33));
return Signature(r, s, i);
};
Signature.fromHex = function (hex) {
return Signature.fromBuffer(Buffer.from(hex, "hex"));
return Signature.fromBuffer(Buffer.from(hex, "hex"));
};
/**

@@ -252,10 +291,11 @@ @arg {string} signature - like SIG_K1_base58signature..

*/
Signature.fromString = function (signature) {
try {
return Signature.fromStringOrThrow(signature);
} catch (e) {
return null;
}
try {
return Signature.fromStringOrThrow(signature);
} catch (e) {
return null;
}
};
/**

@@ -266,15 +306,16 @@ @arg {string} signature - like SIG_K1_base58signature..

*/
Signature.fromStringOrThrow = function (signature) {
assert.equal(typeof signature === 'undefined' ? 'undefined' : _typeof(signature), 'string', 'signature');
var match = signature.match(/^SIG_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/);
assert(match != null && match.length === 3, 'Expecting signature like: SIG_K1_base58signature..');
assert.equal((0, _typeof2["default"])(signature), 'string', 'signature');
var match = signature.match(/^SIG_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/);
assert(match != null && match.length === 3, 'Expecting signature like: SIG_K1_base58signature..');
var _match = _slicedToArray(match, 3),
keyType = _match[1],
keyString = _match[2];
var _match = (0, _slicedToArray2["default"])(match, 3),
keyType = _match[1],
keyString = _match[2];
assert.equal(keyType, 'K1', 'K1 signature expected');
return Signature.fromBuffer(keyUtils.checkDecode(keyString, keyType));
assert.equal(keyType, 'K1', 'K1 signature expected');
return Signature.fromBuffer(keyUtils.checkDecode(keyString, keyType));
};
/**

@@ -284,9 +325,13 @@ @arg {String|Signature} o - hex string

*/
Signature.from = function (o) {
var signature = o ? o.r && o.s && o.i ? o : typeof o === 'string' && o.length === 130 ? Signature.fromHex(o) : typeof o === 'string' && o.length !== 130 ? Signature.fromStringOrThrow(o) : Buffer.isBuffer(o) ? Signature.fromBuffer(o) : null : o; /*null or undefined*/
var signature = o ? o.r && o.s && o.i ? o : typeof o === 'string' && o.length === 130 ? Signature.fromHex(o) : typeof o === 'string' && o.length !== 130 ? Signature.fromStringOrThrow(o) : Buffer.isBuffer(o) ? Signature.fromBuffer(o) : null : o;
/*null or undefined*/
if (!signature) {
throw new TypeError('signature should be a hex string or buffer');
}
return signature;
if (!signature) {
throw new TypeError('signature should be a hex string or buffer');
}
return signature;
};
{
"name": "eosjs-ecc",
"version": "4.0.4",
"version": "4.0.7-ea61ee8.0",
"description": "Elliptic curve cryptography functions",
"keywords": "ECC, Private Key, Public Key, Signature, AES, Encryption, Decryption",
"keywords": [
"ECC",
"Private Key",
"Public Key",
"Signature",
"AES",
"Encryption",
"Decryption"
],
"main": "lib/index.js",

@@ -15,13 +23,13 @@ "files": [

"test_lib": "mocha --use_strict lib/*.test.js",
"coverage": "nyc --reporter=html npm test",
"coveralls": "npm run coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls",
"build": "npm run build_lib && npm run build_browser",
"coverage": "nyc --reporter=lcov --reporter=text npm test",
"coveralls": "yarn coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls",
"build": "yarn build_lib && yarn build_browser",
"build_lib": "rm -f lib/* && babel src --out-dir lib",
"build_browser": "mkdir -p lib && browserify -o lib/eosjs-ecc.js -s eosjs_ecc lib/index.js",
"build_browser_test": "npm run build && browserify -o dist/test.js lib/*.test.js",
"build_browser_test": "yarn build && browserify -o dist/test.js lib/*.test.js",
"documentation": "node_modules/documentation/bin/documentation.js",
"minimize": "uglifyjs lib/eosjs-ecc.js -o lib/eosjs-ecc.min.js --source-map --compress --mangle",
"docs": "npm run documentation -- readme src/api_common.js --section \"Common API\" --shallow",
"minimize": "terser lib/eosjs-ecc.js -o lib/eosjs-ecc.min.js --source-map --compress --mangle",
"docs": "yarn documentation -- readme src/api_common.js --section \"Common API\" --shallow",
"srisum": "npx srisum lib/eosjs-ecc.*",
"prepublishOnly": "npm run build && npm run test_lib && npm run minimize && npm run docs && npm run srisum"
"prepublishOnly": "yarn build && yarn minimize && yarn test_lib && yarn docs"
},

@@ -33,29 +41,37 @@ "repository": {

"dependencies": {
"bigi": "^1.4.2",
"browserify-aes": "^1.0.6",
"bs58": "^4.0.1",
"bytebuffer": "^5.0.1",
"create-hash": "^1.1.3",
"create-hmac": "^1.1.6",
"ecurve": "^1.0.5",
"randombytes": "^2.0.5"
"@babel/runtime": "7.4.4",
"bigi": "1.4.2",
"browserify-aes": "1.0.6",
"bs58": "4.0.1",
"bytebuffer": "5.0.1",
"create-hash": "1.1.3",
"create-hmac": "1.1.6",
"ecurve": "1.0.5",
"randombytes": "2.0.5"
},
"license": "MIT",
"devDependencies": {
"babel-cli": "6.26.0",
"babel-core": "^6.26.3",
"babel-preset-es2015": "6.24.1",
"browserify": "14.4.0",
"coveralls": "^3.0.0",
"documentation": "^8.1.1",
"istanbul": "^0.4.5",
"mocha": "^5.2.0",
"nyc": "^13.0.1",
"uglify-js": "3.4.2"
"@babel/cli": "7.4.4",
"@babel/core": "7.4.4",
"@babel/plugin-transform-runtime": "7.4.4",
"@babel/preset-env": "7.4.4",
"browserify": "16.2.3",
"coveralls": "3.0.3",
"documentation": "8.1.1",
"istanbul": "0.4.5",
"mocha": "5.2.0",
"nyc": "14.1.0",
"terser": "3.17.0"
},
"nyc": {
"temp-directory": "./coverage/.nyc_output"
},
"babel": {
"presets": [
"es2015"
"@babel/preset-env"
],
"plugins": [
"@babel/plugin-transform-runtime"
]
}
}

@@ -18,3 +18,3 @@ [![NPM](https://img.shields.io/npm/v/eosjs-ecc.svg)](https://www.npmjs.org/package/eosjs-ecc)

- Install with: `npm install eosjs-ecc`
- Install with: `yarn add eosjs-ecc`
- Html script tag, see [releases](https://github.com/EOSIO/eosjs-ecc/releases) for the correct **version** and its matching script **integrity** hash.

@@ -315,4 +315,4 @@

cd eosjs-ecc
npm install
npm run build_browser
yarn
yarn build_browser
# builds: ./dist/eosjs-ecc.js

@@ -319,0 +319,0 @@ # Verify release hash

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc