minterjs-util
Version:
Utils for Minter
82 lines (79 loc) • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isValidPublic = isValidPublic;
exports.publicToAddress = publicToAddress;
exports.publicToString = publicToString;
var _secp256k = require("secp256k1");
var _keccak = require("ethereum-cryptography/keccak");
var _assert = _interopRequireDefault(require("assert"));
var _prefix = require("./prefix.js");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Returns the ethereum address of a given public key.
* Accepts "Ethereum public keys" and SEC1 encoded keys.
* @param {Buffer|Uint8Array} publicKey
* @return {Buffer}
*/
function publicToAddress(publicKey) {
publicKey = (0, _prefix.toBuffer)(publicKey);
if (publicKey.length === 32) {
throw new Error('Mp... public can\'t be converted to address because first byte is dropped');
}
if (publicKey.length === 33) {
// compressed to uncompressed
publicKey = Buffer.from((0, _secp256k.publicKeyConvert)(publicKey, false)).slice(1);
}
if (publicKey.length === 65) {
// uncompressed to Ethereum
publicKey = publicKey.slice(1);
}
(0, _assert["default"])(publicKey.length === 64);
// Only take the lower 160bits of the hash
return (0, _keccak.keccak256)(publicKey).slice(-20);
}
/**
* Return Minter style public key string
* @param {Buffer|Uint8Array|string} publicKey
* @return {string}
*/
function publicToString(publicKey) {
publicKey = (0, _prefix.toBuffer)(publicKey);
if (!Buffer.isBuffer(publicKey)) {
throw new TypeError('Public key should be of type Buffer');
}
if (publicKey.length === 64) {
// Ethereum style to uncompressed
publicKey = Buffer.concat([Buffer.from([4]), publicKey]);
}
if (publicKey.length === 65) {
// uncompressed to compressed
publicKey = Buffer.from((0, _secp256k.publicKeyConvert)(publicKey, true));
}
if (publicKey.length === 33) {
publicKey = publicKey.slice(1);
}
(0, _assert["default"])(publicKey.length === 32);
return "Mp".concat(publicKey.toString('hex'));
}
/**
* Checks if the public key satisfies the rules of the curve secp256k1
* and the requirements of Minter.
* @param {string|Buffer} publicKey - Compressed key without first byte, starts with `Mp` if is string
* @return {boolean}
*/
function isValidPublic(publicKey) {
if (typeof publicKey === 'string') {
if (!(0, _prefix.isValidPublicKeyString)(publicKey)) {
return false;
}
publicKey = (0, _prefix.mToBuffer)(publicKey);
}
if (publicKey.length !== 32) {
return false;
}
// convert Minter to compressed: add first byte
var compressed = Buffer.concat([Buffer.from([3]), publicKey]);
return (0, _secp256k.publicKeyVerify)(compressed);
}