Socket
Socket
Sign inDemoInstall

@celo/utils

Package Overview
Dependencies
Maintainers
9
Versions
144
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@celo/utils - npm Package Compare versions

Comparing version 5.0.6 to 6.0.0-beta.0

22

lib/address.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidAddress = exports.isValidPrivateKey = exports.publicKeyToAddress = exports.privateKeyToPublicKey = exports.privateKeyToAddress = exports.toChecksumAddress = exports.isValidChecksumAddress = exports.trimLeading0x = exports.NULL_ADDRESS = exports.normalizeAddressWith0x = exports.normalizeAddress = exports.mapAddressListOnto = exports.mapAddressListDataOnto = exports.isHexString = exports.hexToBuffer = exports.getAddressChunks = exports.findAddressIndex = exports.eqAddress = exports.ensureLeading0x = exports.bufferToHex = void 0;
var address_1 = require("@celo/base/lib/address");
var util_1 = require("@ethereumjs/util");
const address_1 = require("@celo/base/lib/address");
const util_1 = require("@ethereumjs/util");
// Exports moved to @celo/base, forwarding them

@@ -25,19 +25,11 @@ // here for backwards compatibility

Object.defineProperty(exports, "toChecksumAddress", { enumerable: true, get: function () { return util_2.toChecksumAddress; } });
var privateKeyToAddress = function (privateKey) {
return (0, util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, util_1.privateToAddress)((0, address_1.hexToBuffer)(privateKey)).toString('hex')));
};
const privateKeyToAddress = (privateKey) => (0, util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, util_1.privateToAddress)((0, address_1.hexToBuffer)(privateKey)).toString('hex')));
exports.privateKeyToAddress = privateKeyToAddress;
var privateKeyToPublicKey = function (privateKey) {
return (0, util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, util_1.privateToPublic)((0, address_1.hexToBuffer)(privateKey)).toString('hex')));
};
const privateKeyToPublicKey = (privateKey) => (0, util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, util_1.privateToPublic)((0, address_1.hexToBuffer)(privateKey)).toString('hex')));
exports.privateKeyToPublicKey = privateKeyToPublicKey;
var publicKeyToAddress = function (publicKey) {
return (0, util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, util_1.pubToAddress)((0, util_1.toBuffer)((0, address_1.ensureLeading0x)(publicKey)), true).toString('hex')));
};
const publicKeyToAddress = (publicKey) => (0, util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, util_1.pubToAddress)((0, util_1.toBuffer)((0, address_1.ensureLeading0x)(publicKey)), true).toString('hex')));
exports.publicKeyToAddress = publicKeyToAddress;
var isValidPrivateKey = function (privateKey) {
return privateKey.startsWith('0x') && (0, util_1.isValidPrivate)((0, address_1.hexToBuffer)(privateKey));
};
const isValidPrivateKey = (privateKey) => privateKey.startsWith('0x') && (0, util_1.isValidPrivate)((0, address_1.hexToBuffer)(privateKey));
exports.isValidPrivateKey = isValidPrivateKey;
var isValidAddress = function (input) {
const isValidAddress = (input) => {
if ('string' !== typeof input) {

@@ -44,0 +36,0 @@ return false;

@@ -7,4 +7,4 @@ "use strict";

exports.CELO_AMOUNT_FOR_ESTIMATE = exports.DOLLAR_AMOUNT_FOR_ESTIMATE = void 0;
var bignumber_js_1 = __importDefault(require("bignumber.js"));
var WEI_PER_UNIT = 1000000000000000000;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const WEI_PER_UNIT = 1000000000000000000;
// A small amount returns a rate closer to the median rate

@@ -11,0 +11,0 @@ exports.DOLLAR_AMOUNT_FOR_ESTIMATE = new bignumber_js_1.default(0.01 * WEI_PER_UNIT); // 0.01 dollar

import * as base from '@celo/base/lib/collections';
import BigNumber from 'bignumber.js';
export { intersection, notEmpty, zeroRange, zip, zip3 } from '@celo/base/lib/collections';
export declare type AddressListItem = base.AddressListItem<BigNumber>;
export type AddressListItem = base.AddressListItem<BigNumber>;
export declare function linkedListChange(sortedList: AddressListItem[], change: AddressListItem): {

@@ -6,0 +6,0 @@ lesser: string;

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

exports.linkedListChanges = exports.linkedListChange = exports.zip3 = exports.zip = exports.zeroRange = exports.notEmpty = exports.intersection = void 0;
var base = __importStar(require("@celo/base/lib/collections"));
const base = __importStar(require("@celo/base/lib/collections"));
// Exports moved to @celo/base, forwarding them

@@ -38,3 +38,3 @@ // here for backwards compatibility

// BigNumber comparator
var bigNumberComparator = function (a, b) { return a.lt(b); };
const bigNumberComparator = (a, b) => a.lt(b);
function linkedListChange(sortedList, change) {

@@ -41,0 +41,0 @@ return base.linkedListChange(sortedList, change, bigNumberComparator);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getContactNameHash = exports.isContact = exports.getContactPhoneNumber = void 0;
var web3_utils_1 = require("web3-utils");
const web3_utils_1 = require("web3-utils");
// Exports moved to @celo/base, forwarding them

@@ -13,3 +13,3 @@ // here for backwards compatibility

*/
var getContactNameHash = function (contact) {
const getContactNameHash = (contact) => {
if (!contact) {

@@ -16,0 +16,0 @@ throw new Error('Invalid contact');

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.trimUncompressedPrefix = exports.ensureUncompressed = exports.ensureCompressed = exports.isCompressed = exports.computeSharedSecret = void 0;
var address_1 = require("@celo/base/lib/address");
var crypto_1 = require("crypto");
const address_1 = require("@celo/base/lib/address");
const crypto_1 = require("crypto");
function computeSharedSecret(privateKey, publicKey) {
var ecdh = (0, crypto_1.createECDH)('secp256k1');
const ecdh = (0, crypto_1.createECDH)('secp256k1');
ecdh.setPrivateKey(Buffer.from((0, address_1.trimLeading0x)(privateKey), 'hex'));

@@ -13,3 +13,3 @@ return ecdh.computeSecret(Buffer.from(ensureCompressed(publicKey), 'hex'));

function isCompressed(publicKey) {
var noLeading0x = (0, address_1.trimLeading0x)(publicKey);
const noLeading0x = (0, address_1.trimLeading0x)(publicKey);
if (noLeading0x.length === 64) {

@@ -25,4 +25,4 @@ return true;

// tslint:disable-next-line:import-blacklist
var EC = require('elliptic').ec;
var ec = new EC('secp256k1');
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
return ec.keyFromPublic(ensureUncompressedPrefix(publicKey), 'hex').getPublic(true, 'hex');

@@ -32,9 +32,9 @@ }

function ensureUncompressed(publicKey) {
var noLeading0x = (0, address_1.trimLeading0x)(publicKey);
const noLeading0x = (0, address_1.trimLeading0x)(publicKey);
// NOTE: elliptic is disabled elsewhere in this library to prevent
// accidental signing of truncated messages.
// tslint:disable-next-line:import-blacklist
var EC = require('elliptic').ec;
var ec = new EC('secp256k1');
var uncompressed = ec
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const uncompressed = ec
.keyFromPublic(ensureUncompressedPrefix(noLeading0x), 'hex')

@@ -46,3 +46,3 @@ .getPublic(false, 'hex');

function trimUncompressedPrefix(publicKey) {
var noLeading0x = (0, address_1.trimLeading0x)(publicKey);
const noLeading0x = (0, address_1.trimLeading0x)(publicKey);
if (noLeading0x.length === 130 && noLeading0x.startsWith('04')) {

@@ -55,5 +55,5 @@ return noLeading0x.slice(2);

function ensureUncompressedPrefix(publicKey) {
var noLeading0x = (0, address_1.trimLeading0x)(publicKey);
const noLeading0x = (0, address_1.trimLeading0x)(publicKey);
if (noLeading0x.length === 128) {
return "04".concat(noLeading0x);
return `04${noLeading0x}`;
}

@@ -60,0 +60,0 @@ return noLeading0x;

@@ -10,3 +10,3 @@ /**

exports.ECIES = exports.Decrypt = exports.Encrypt = exports.AES128DecryptAndHMAC = exports.AES128Decrypt = exports.AES128EncryptAndHMAC = exports.AES128Encrypt = exports.IV_LENGTH = void 0;
var crypto_1 = require("crypto");
const crypto_1 = require("crypto");
exports.IV_LENGTH = 16;

@@ -19,4 +19,4 @@ /**

*/
var IncCounter = function (ctr) {
for (var i = ctr.length - 1; i >= 0; i--) {
const IncCounter = (ctr) => {
for (let i = ctr.length - 1; i >= 0; i--) {
ctr[i]++;

@@ -41,9 +41,9 @@ if (ctr[i] !== 0) {

*/
var ConcatKDF = function (px, kdLen) {
var blockSize = 32;
var reps = ((kdLen + 7) * 8) / (blockSize * 8);
var counter = Buffer.from('00000001', 'hex');
var k = Buffer.from('00', 'hex');
for (var i = 0; i <= reps; i++) {
var hash = (0, crypto_1.createHash)('sha256');
const ConcatKDF = (px, kdLen) => {
const blockSize = 32;
const reps = ((kdLen + 7) * 8) / (blockSize * 8);
let counter = Buffer.from('00000001', 'hex');
let k = Buffer.from('00', 'hex');
for (let i = 0; i <= reps; i++) {
const hash = (0, crypto_1.createHash)('sha256');
hash.update(counter);

@@ -64,5 +64,5 @@ hash.update(px);

function AES128Encrypt(encryptionKey, iv, plaintext) {
var cipher = (0, crypto_1.createCipheriv)('aes-128-ctr', encryptionKey, iv);
var firstChunk = cipher.update(plaintext);
var secondChunk = cipher.final();
const cipher = (0, crypto_1.createCipheriv)('aes-128-ctr', encryptionKey, iv);
const firstChunk = cipher.update(plaintext);
const secondChunk = cipher.final();
return Buffer.concat([iv, firstChunk, secondChunk]);

@@ -79,5 +79,5 @@ }

function AES128EncryptAndHMAC(encryptionKey, macKey, plaintext) {
var iv = (0, crypto_1.randomBytes)(exports.IV_LENGTH);
var dataToMac = AES128Encrypt(encryptionKey, iv, plaintext);
var mac = (0, crypto_1.createHmac)('sha256', macKey).update(dataToMac).digest();
const iv = (0, crypto_1.randomBytes)(exports.IV_LENGTH);
const dataToMac = AES128Encrypt(encryptionKey, iv, plaintext);
const mac = (0, crypto_1.createHmac)('sha256', macKey).update(dataToMac).digest();
return Buffer.concat([dataToMac, mac]);

@@ -94,5 +94,5 @@ }

function AES128Decrypt(encryptionKey, iv, ciphertext) {
var cipher = (0, crypto_1.createDecipheriv)('aes-128-ctr', encryptionKey, iv);
var firstChunk = cipher.update(ciphertext);
var secondChunk = cipher.final();
const cipher = (0, crypto_1.createDecipheriv)('aes-128-ctr', encryptionKey, iv);
const firstChunk = cipher.update(ciphertext);
const secondChunk = cipher.final();
return Buffer.concat([firstChunk, secondChunk]);

@@ -109,7 +109,7 @@ }

function AES128DecryptAndHMAC(encryptionKey, macKey, ciphertext) {
var iv = ciphertext.slice(0, exports.IV_LENGTH);
var message = ciphertext.slice(exports.IV_LENGTH, ciphertext.length - 32);
var mac = ciphertext.slice(ciphertext.length - 32, ciphertext.length);
var dataToMac = Buffer.concat([iv, message]);
var computedMac = (0, crypto_1.createHmac)('sha256', macKey).update(dataToMac).digest();
const iv = ciphertext.slice(0, exports.IV_LENGTH);
const message = ciphertext.slice(exports.IV_LENGTH, ciphertext.length - 32);
const mac = ciphertext.slice(ciphertext.length - 32, ciphertext.length);
const dataToMac = Buffer.concat([iv, message]);
const computedMac = (0, crypto_1.createHmac)('sha256', macKey).update(dataToMac).digest();
if (!mac.equals(computedMac)) {

@@ -131,14 +131,14 @@ throw new Error('MAC mismatch');

// tslint:disable-next-line:import-blacklist
var EC = require('elliptic').ec;
var ec = new EC('secp256k1');
var ephemPrivKey = ec.keyFromPrivate((0, crypto_1.randomBytes)(32));
var ephemPubKey = ephemPrivKey.getPublic(false, 'hex');
var ephemPubKeyEncoded = Buffer.from(ephemPubKey, 'hex');
var px = ephemPrivKey.derive(ec.keyFromPublic(Buffer.concat([Buffer.from([0x04]), pubKeyTo])).getPublic());
var hash = ConcatKDF(px.toArrayLike(Buffer), 32);
var encryptionKey = hash.slice(0, 16);
var macKey = (0, crypto_1.createHash)('sha256').update(hash.slice(16)).digest();
var message = AES128EncryptAndHMAC(encryptionKey, macKey, plaintext);
var serializedCiphertext = Buffer.concat([
ephemPubKeyEncoded,
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const ephemPrivKey = ec.keyFromPrivate((0, crypto_1.randomBytes)(32));
const ephemPubKey = ephemPrivKey.getPublic(false, 'hex');
const ephemPubKeyEncoded = Buffer.from(ephemPubKey, 'hex');
const px = ephemPrivKey.derive(ec.keyFromPublic(Buffer.concat([Buffer.from([0x04]), pubKeyTo])).getPublic());
const hash = ConcatKDF(px.toArrayLike(Buffer), 32);
const encryptionKey = hash.slice(0, 16);
const macKey = (0, crypto_1.createHash)('sha256').update(hash.slice(16)).digest();
const message = AES128EncryptAndHMAC(encryptionKey, macKey, plaintext);
const serializedCiphertext = Buffer.concat([
ephemPubKeyEncoded, // 65 bytes
message, // iv + ciphertext + mac (min 48 bytes)

@@ -157,15 +157,15 @@ ]);

// Read iv, ephemPubKey, mac, ciphertext from encrypted message
var ephemPubKeyEncoded = encrypted.slice(0, 65);
var symmetricEncrypted = encrypted.slice(65);
const ephemPubKeyEncoded = encrypted.slice(0, 65);
const symmetricEncrypted = encrypted.slice(65);
// NOTE: elliptic is disabled elsewhere in this library to prevent
// accidental signing of truncated messages.
// tslint:disable-next-line:import-blacklist
var EC = require('elliptic').ec;
var ec = new EC('secp256k1');
var ephemPubKey = ec.keyFromPublic(ephemPubKeyEncoded).getPublic();
var px = ec.keyFromPrivate(privKey).derive(ephemPubKey);
var hash = ConcatKDF(px.toBuffer(), 32);
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const ephemPubKey = ec.keyFromPublic(ephemPubKeyEncoded).getPublic();
const px = ec.keyFromPrivate(privKey).derive(ephemPubKey);
const hash = ConcatKDF(px.toBuffer(), 32);
// km, ke
var encryptionKey = hash.slice(0, 16);
var macKey = (0, crypto_1.createHash)('sha256').update(hash.slice(16)).digest();
const encryptionKey = hash.slice(0, 16);
const macKey = (0, crypto_1.createHash)('sha256').update(hash.slice(16)).digest();
return AES128DecryptAndHMAC(encryptionKey, macKey, symmetricEncrypted);

@@ -175,7 +175,7 @@ }

exports.ECIES = {
Encrypt: Encrypt,
Decrypt: Decrypt,
AES128EncryptAndHMAC: AES128EncryptAndHMAC,
AES128DecryptAndHMAC: AES128DecryptAndHMAC,
Encrypt,
Decrypt,
AES128EncryptAndHMAC,
AES128DecryptAndHMAC,
};
//# sourceMappingURL=ecies.js.map

@@ -7,6 +7,6 @@ "use strict";

exports.reciprocal = exports.divide = exports.multiply = exports.fixedToInt = exports.fromFixed = exports.toFixed = exports.fixed1 = exports.digits = void 0;
var bignumber_js_1 = __importDefault(require("bignumber.js"));
const bignumber_js_1 = __importDefault(require("bignumber.js"));
exports.digits = new bignumber_js_1.default('24');
exports.fixed1 = new bignumber_js_1.default('1000000000000000000000000');
var toFixed = function (n) {
const toFixed = (n) => {
return exports.fixed1.times(n).integerValue(bignumber_js_1.default.ROUND_FLOOR);

@@ -16,3 +16,3 @@ };

// Keeps the decimal portion
var fromFixed = function (f) {
const fromFixed = (f) => {
return f.div(exports.fixed1);

@@ -22,15 +22,15 @@ };

// Returns an integer
var fixedToInt = function (f) {
const fixedToInt = (f) => {
return f.idiv(exports.fixed1);
};
exports.fixedToInt = fixedToInt;
var multiply = function (a, b) {
const multiply = (a, b) => {
return a.times(b).idiv(exports.fixed1);
};
exports.multiply = multiply;
var divide = function (a, b) {
const divide = (a, b) => {
return a.times(exports.fixed1).idiv(b);
};
exports.divide = divide;
var reciprocal = function (f) {
const reciprocal = (f) => {
return (0, exports.divide)(exports.fixed1, f);

@@ -37,0 +37,0 @@ };

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

exports.AddressUtils = exports.StringUtils = exports.SignatureUtils = exports.IstanbulUtils = exports.ECIES = void 0;
var AddressUtils = __importStar(require("./address"));
const AddressUtils = __importStar(require("./address"));
exports.AddressUtils = AddressUtils;

@@ -33,0 +33,0 @@ __exportStar(require("./contacts"), exports);

@@ -9,3 +9,3 @@ import * as t from 'io-ts';

export declare const SaltType: t.StringC;
export declare type Signature = t.TypeOf<typeof SignatureType>;
export declare type Address = t.TypeOf<typeof AddressType>;
export type Signature = t.TypeOf<typeof SignatureType>;
export type Address = t.TypeOf<typeof AddressType>;

@@ -27,7 +27,7 @@ "use strict";

exports.SaltType = exports.SignatureType = exports.PublicKeyType = exports.AddressType = exports.JSONStringType = exports.UrlType = exports.URL_REGEX = exports.isValidUrl = void 0;
var io_1 = require("@celo/base/lib/io");
var util_1 = require("@ethereumjs/util");
var Either_1 = require("fp-ts/lib/Either");
var t = __importStar(require("io-ts"));
var address_1 = require("./address");
const io_1 = require("@celo/base/lib/io");
const util_1 = require("@ethereumjs/util");
const Either_1 = require("fp-ts/lib/Either");
const t = __importStar(require("io-ts"));
const address_1 = require("./address");
// Exports moved to @celo/base, forwarding them

@@ -38,36 +38,22 @@ // here for backwards compatibility

Object.defineProperty(exports, "URL_REGEX", { enumerable: true, get: function () { return io_2.URL_REGEX; } });
exports.UrlType = new t.Type('Url', t.string.is, function (input, context) {
return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {
return io_1.URL_REGEX.test(stringValue)
? t.success(stringValue)
: t.failure(stringValue, context, 'is not a valid url');
});
}, String);
exports.JSONStringType = new t.Type('JSONString', t.string.is, function (input, context) {
return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {
try {
JSON.parse(stringValue);
return t.success(stringValue);
}
catch (error) {
return t.failure(stringValue, context, 'can not be parsed as JSON');
}
});
}, String);
exports.AddressType = new t.Type('Address', t.string.is, function (input, context) {
return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {
return (0, address_1.isValidAddress)(stringValue)
? t.success((0, util_1.toChecksumAddress)(stringValue))
: t.failure(stringValue, context, 'is not a valid address');
});
}, String);
exports.PublicKeyType = new t.Type('Public Key', t.string.is, function (input, context) {
return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {
return stringValue.startsWith('0x') && (0, util_1.isValidPublic)(Buffer.from(stringValue.slice(2), 'hex'), true)
? t.success((0, util_1.toChecksumAddress)(stringValue))
: t.failure(stringValue, context, 'is not a valid public key');
});
}, String);
exports.UrlType = new t.Type('Url', t.string.is, (input, context) => Either_1.either.chain(t.string.validate(input, context), (stringValue) => io_1.URL_REGEX.test(stringValue)
? t.success(stringValue)
: t.failure(stringValue, context, 'is not a valid url')), String);
exports.JSONStringType = new t.Type('JSONString', t.string.is, (input, context) => Either_1.either.chain(t.string.validate(input, context), (stringValue) => {
try {
JSON.parse(stringValue);
return t.success(stringValue);
}
catch (error) {
return t.failure(stringValue, context, 'can not be parsed as JSON');
}
}), String);
exports.AddressType = new t.Type('Address', t.string.is, (input, context) => Either_1.either.chain(t.string.validate(input, context), (stringValue) => (0, address_1.isValidAddress)(stringValue)
? t.success((0, util_1.toChecksumAddress)(stringValue))
: t.failure(stringValue, context, 'is not a valid address')), String);
exports.PublicKeyType = new t.Type('Public Key', t.string.is, (input, context) => Either_1.either.chain(t.string.validate(input, context), (stringValue) => stringValue.startsWith('0x') && (0, util_1.isValidPublic)(Buffer.from(stringValue.slice(2), 'hex'), true)
? t.success((0, util_1.toChecksumAddress)(stringValue))
: t.failure(stringValue, context, 'is not a valid public key')), String);
exports.SignatureType = t.string;
exports.SaltType = t.string;
//# sourceMappingURL=io.js.map
import BigNumber from 'bignumber.js';
import { Address } from './address';
export declare type Bitmap = BigNumber;
export type Bitmap = BigNumber;
export interface Seal {

@@ -5,0 +5,0 @@ bitmap: Bitmap;

@@ -30,8 +30,8 @@ "use strict";

exports.IstanbulUtils = exports.bitIsSet = exports.parseBlockExtraData = void 0;
var util_1 = require("@ethereumjs/util");
var bignumber_js_1 = __importDefault(require("bignumber.js"));
var rlp = __importStar(require("rlp"));
const util_1 = require("@ethereumjs/util");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const rlp = __importStar(require("rlp"));
// This file contains utilities that help with istanbul-specific block information.
// See https://github.com/celo-org/celo-blockchain/blob/master/core/types/istanbul.go
var ISTANBUL_EXTRA_VANITY_BYTES = 32;
const ISTANBUL_EXTRA_VANITY_BYTES = 32;
function bigNumberFromBuffer(data) {

@@ -49,7 +49,7 @@ return new bignumber_js_1.default('0x' + (data.toString('hex') || '0'), 16);

function parseBlockExtraData(data) {
var buffer = Buffer.from(data.replace(/^0x/, ''), 'hex');
var decode = rlp.decode('0x' + buffer.slice(ISTANBUL_EXTRA_VANITY_BYTES).toString('hex'));
const buffer = Buffer.from(data.replace(/^0x/, ''), 'hex');
const decode = rlp.decode('0x' + buffer.slice(ISTANBUL_EXTRA_VANITY_BYTES).toString('hex'));
return {
addedValidators: decode[0].map(function (addr) { return (0, util_1.toChecksumAddress)((0, util_1.bufferToHex)(addr)); }),
addedValidatorsPublicKeys: decode[1].map(function (key) { return '0x' + key.toString('hex'); }),
addedValidators: decode[0].map((addr) => (0, util_1.toChecksumAddress)((0, util_1.bufferToHex)(addr))),
addedValidatorsPublicKeys: decode[1].map((key) => '0x' + key.toString('hex')),
removedValidators: bigNumberFromBuffer(decode[2]),

@@ -64,3 +64,3 @@ seal: '0x' + decode[3].toString('hex'),

if (index < 0) {
throw new Error("bit index must be greater than zero: got ".concat(index));
throw new Error(`bit index must be greater than zero: got ${index}`);
}

@@ -74,5 +74,5 @@ return bitmap

exports.IstanbulUtils = {
parseBlockExtraData: parseBlockExtraData,
bitIsSet: bitIsSet,
parseBlockExtraData,
bitIsSet,
};
//# sourceMappingURL=istanbul.js.map

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

exports.levenshteinDistance = void 0;
var _min = function (d0, d1, d2, bx, ay) {
const _min = (d0, d1, d2, bx, ay) => {
return d0 < d1 || d2 < d1 ? (d0 > d2 ? d2 + 1 : d0 + 1) : bx === ay ? d1 : d1 + 1;

@@ -16,8 +16,8 @@ };

if (a.length > b.length) {
var tmp = a;
const tmp = a;
a = b;
b = tmp;
}
var la = a.length;
var lb = b.length;
let la = a.length;
let lb = b.length;
while (la > 0 && a.charCodeAt(la - 1) === b.charCodeAt(lb - 1)) {

@@ -27,3 +27,3 @@ la--;

}
var offset = 0;
let offset = 0;
while (offset < la && a.charCodeAt(offset) === b.charCodeAt(offset)) {

@@ -37,16 +37,16 @@ offset++;

}
var x = 0;
var y;
var d0;
var d1;
var d2;
var d3;
var dd;
var dy;
var ay;
var bx0;
var bx1;
var bx2;
var bx3;
var vector = [];
let x = 0;
let y;
let d0;
let d1;
let d2;
let d3;
let dd;
let dy;
let ay;
let bx0;
let bx1;
let bx2;
let bx3;
const vector = [];
for (y = 0; y < la; y++) {

@@ -56,3 +56,3 @@ vector.push(y + 1);

}
var len = vector.length - 1;
const len = vector.length - 1;
for (; x < lb - 3;) {

@@ -59,0 +59,0 @@ bx0 = b.charCodeAt(offset + (d0 = x));

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

exports.parseInputAmount = exports.stringToBoolean = exports.parseSolidityStringArray = void 0;
var bignumber_js_1 = __importDefault(require("bignumber.js"));
const bignumber_js_1 = __importDefault(require("bignumber.js"));
// Exports moved to @celo/base, forwarding them

@@ -14,4 +14,3 @@ // here for backwards compatibility

Object.defineProperty(exports, "stringToBoolean", { enumerable: true, get: function () { return parsing_1.stringToBoolean; } });
var parseInputAmount = function (inputString, decimalSeparator) {
if (decimalSeparator === void 0) { decimalSeparator = '.'; }
const parseInputAmount = (inputString, decimalSeparator = '.') => {
if (decimalSeparator !== '.') {

@@ -18,0 +17,0 @@ inputString = inputString.replace(decimalSeparator, '.');

@@ -15,3 +15,3 @@ /// <reference types="node" />

}
export declare type EIP712ObjectValue = string | number | BigNumber | boolean | Buffer | EIP712Object | EIP712ObjectValue[];
export type EIP712ObjectValue = string | number | BigNumber | boolean | Buffer | EIP712Object | EIP712ObjectValue[];
export interface EIP712Object {

@@ -38,3 +38,3 @@ [key: string]: EIP712ObjectValue;

*/
export declare type EIP712Optional<T extends EIP712ObjectValue> = {
export type EIP712Optional<T extends EIP712ObjectValue> = {
defined: boolean;

@@ -41,0 +41,0 @@ value: T;

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -36,38 +25,2 @@ if (k2 === undefined) k2 = k;

};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -78,32 +31,35 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.zeroValue = exports.structHash = exports.encodeData = exports.typeHash = exports.encodeType = exports.generateTypedDataHash = exports.noString = exports.noNumber = exports.noBool = exports.defined = exports.eip712OptionalSchema = exports.eip712OptionalType = exports.EIP712_BUILTIN_TYPES = exports.EIP712_DYNAMIC_TYPES = exports.EIP712_ATOMIC_TYPES = void 0;
var address_1 = require("@celo/base/lib/address");
var util_1 = require("@ethereumjs/util");
var bignumber_js_1 = require("bignumber.js");
var keccak_1 = require("ethereum-cryptography/keccak");
var utils_1 = require("ethereum-cryptography/utils");
var t = __importStar(require("io-ts"));
var web3_eth_abi_1 = __importDefault(require("web3-eth-abi"));
const address_1 = require("@celo/base/lib/address");
const util_1 = require("@ethereumjs/util");
const bignumber_js_1 = require("bignumber.js");
const keccak_1 = require("ethereum-cryptography/keccak");
const utils_1 = require("ethereum-cryptography/utils");
const t = __importStar(require("io-ts"));
const web3_eth_abi_1 = __importDefault(require("web3-eth-abi"));
/** Array of all EIP-712 atomic type names. */
exports.EIP712_ATOMIC_TYPES = __spreadArray([
exports.EIP712_ATOMIC_TYPES = [
'bool',
'address'
], __read((function () {
var result = [];
// Putting "bigger" types first, assuming they are more likely to be used.
// So `EIP712_ATOMIC_TYPES.includes(...)` calls are faster. (likely useless micro-optimization :D)
for (var i = 32; i >= 1; i--) {
result.push('bytes' + i);
result.push('uint' + i * 8);
result.push('int' + i * 8);
}
return result;
})()), false);
'address',
// bytes types from 1 to 32 bytes
// and uint/int types from 8 to 256 bits
...(() => {
const result = [];
// Putting "bigger" types first, assuming they are more likely to be used.
// So `EIP712_ATOMIC_TYPES.includes(...)` calls are faster. (likely useless micro-optimization :D)
for (let i = 32; i >= 1; i--) {
result.push('bytes' + i);
result.push('uint' + i * 8);
result.push('int' + i * 8);
}
return result;
})(),
];
exports.EIP712_DYNAMIC_TYPES = ['bytes', 'string'];
exports.EIP712_BUILTIN_TYPES = exports.EIP712_DYNAMIC_TYPES.concat(exports.EIP712_ATOMIC_TYPES);
// Regular expression used to identify and parse EIP-712 array type strings.
var EIP712_ARRAY_REGEXP = /^(?<memberType>[\w<>\[\]_\-]+)(\[(?<fixedLength>\d+)?\])$/;
const EIP712_ARRAY_REGEXP = /^(?<memberType>[\w<>\[\]_\-]+)(\[(?<fixedLength>\d+)?\])$/;
// Regular expression used to identify EIP-712 integer types (e.g. int256, uint256, uint8).
var EIP712_INT_REGEXP = /^u?int\d*$/;
const EIP712_INT_REGEXP = /^u?int\d*$/;
// Regular expression used to identify EIP-712 bytes types (e.g. bytes, bytes1, up to bytes32).
var EIP712_BYTES_REGEXP = /^bytes\d*$/;
const EIP712_BYTES_REGEXP = /^bytes\d*$/;
/**

@@ -114,11 +70,8 @@ * Utility to build EIP712Optional<T> types to insert in EIP-712 type arrays.

*/
var eip712OptionalType = function (typeName) {
var _a;
return (_a = {},
_a["Optional<".concat(typeName, ">")] = [
{ name: 'defined', type: 'bool' },
{ name: 'value', type: typeName },
],
_a);
};
const eip712OptionalType = (typeName) => ({
[`Optional<${typeName}>`]: [
{ name: 'defined', type: 'bool' },
{ name: 'value', type: typeName },
],
});
exports.eip712OptionalType = eip712OptionalType;

@@ -129,14 +82,12 @@ /**

*/
var eip712OptionalSchema = function (schema) {
return t.type({
defined: t.boolean,
value: schema,
});
};
const eip712OptionalSchema = (schema) => t.type({
defined: t.boolean,
value: schema,
});
exports.eip712OptionalSchema = eip712OptionalSchema;
/** Utility to construct an defined EIP712Optional value with inferred type. */
var defined = function (value) { return ({
const defined = (value) => ({
defined: true,
value: value,
}); };
value,
});
exports.defined = defined;

@@ -176,6 +127,4 @@ /** Undefined EIP712Optional type with value type boolean. */

*/
function findDependencies(primaryType, types, found) {
var e_1, _a;
var _b;
if (found === void 0) { found = []; }
function findDependencies(primaryType, types, found = []) {
var _a;
// If we have aready found the dependencies of this type, or it is a builtin, return early.

@@ -187,4 +136,4 @@ if (found.includes(primaryType) || exports.EIP712_BUILTIN_TYPES.includes(primaryType)) {

if (EIP712_ARRAY_REGEXP.test(primaryType)) {
var match = EIP712_ARRAY_REGEXP.exec(primaryType);
var memberType = (_b = match === null || match === void 0 ? void 0 : match.groups) === null || _b === void 0 ? void 0 : _b.memberType;
const match = EIP712_ARRAY_REGEXP.exec(primaryType);
const memberType = (_a = match === null || match === void 0 ? void 0 : match.groups) === null || _a === void 0 ? void 0 : _a.memberType;
return findDependencies(memberType, types, found);

@@ -194,20 +143,10 @@ }

if (types[primaryType] === undefined) {
throw new Error("Unrecognized type ".concat(primaryType, " is not included in the EIP-712 type list"));
throw new Error(`Unrecognized type ${primaryType} is not included in the EIP-712 type list`);
}
// Execute a depth-first search to populate the (inclusive) dependencies list.
// By the first invarient of this function, the resulting list should not contain duplicates.
var dependencies = [primaryType];
try {
for (var _c = __values(types[primaryType]), _d = _c.next(); !_d.done; _d = _c.next()) {
var field = _d.value;
dependencies.push.apply(dependencies, __spreadArray([], __read(findDependencies(field.type, types, found.concat(dependencies))), false));
}
const dependencies = [primaryType];
for (const field of types[primaryType]) {
dependencies.push(...findDependencies(field.type, types, found.concat(dependencies)));
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
return dependencies;

@@ -220,23 +159,9 @@ }

function encodeType(primaryType, types) {
var e_2, _a;
var deps = findDependencies(primaryType, types);
deps = deps.filter(function (d) { return d !== primaryType; });
let deps = findDependencies(primaryType, types);
deps = deps.filter((d) => d !== primaryType);
deps = [primaryType].concat(deps.sort());
var result = '';
try {
for (var deps_1 = __values(deps), deps_1_1 = deps_1.next(); !deps_1_1.done; deps_1_1 = deps_1.next()) {
var dep = deps_1_1.value;
result += "".concat(dep, "(").concat(types[dep].map(function (_a) {
var name = _a.name, type = _a.type;
return "".concat(type, " ").concat(name);
}).join(','), ")");
}
let result = '';
for (const dep of deps) {
result += `${dep}(${types[dep].map(({ name, type }) => `${type} ${name}`).join(',')})`;
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (deps_1_1 && !deps_1_1.done && (_a = deps_1.return)) _a.call(deps_1);
}
finally { if (e_2) throw e_2.error; }
}
return result;

@@ -254,4 +179,3 @@ }

if (exports.EIP712_ATOMIC_TYPES.includes(valueType)) {
// @ts-ignore TypeScript does not believe encodeParameter exists.
var hexEncoded = web3_eth_abi_1.default.encodeParameter(valueType, normalizeValue(valueType, value));
const hexEncoded = web3_eth_abi_1.default.encodeParameter(valueType, normalizeValue(valueType, value));
return Buffer.from((0, address_1.trimLeading0x)(hexEncoded), 'hex');

@@ -273,3 +197,2 @@ }

if (types[valueType] !== undefined) {
// tslint:disable-next-line:no-unnecessary-type-assertion.
return structHash(valueType, value, types);

@@ -280,10 +203,10 @@ }

// Note: If a fixed length is provided in the type, it is not checked.
var match = EIP712_ARRAY_REGEXP.exec(valueType);
var memberType_1 = (_a = match === null || match === void 0 ? void 0 : match.groups) === null || _a === void 0 ? void 0 : _a.memberType;
return (0, keccak_1.keccak256)(Buffer.concat(value.map(function (member) { return encodeValue(memberType_1, member, types); })));
const match = EIP712_ARRAY_REGEXP.exec(valueType);
const memberType = (_a = match === null || match === void 0 ? void 0 : match.groups) === null || _a === void 0 ? void 0 : _a.memberType;
return (0, keccak_1.keccak256)(Buffer.concat(value.map((member) => encodeValue(memberType, member, types))));
}
throw new Error("Unrecognized or unsupported type in EIP-712 encoding: ".concat(valueType));
throw new Error(`Unrecognized or unsupported type in EIP-712 encoding: ${valueType}`);
}
function normalizeValue(type, value) {
var normalizedValue = EIP712_INT_REGEXP.test(type) && bignumber_js_1.BigNumber.isBigNumber(value) ? value.toString() : value;
const normalizedValue = EIP712_INT_REGEXP.test(type) && bignumber_js_1.BigNumber.isBigNumber(value) ? value.toString() : value;
return normalizedValue;

@@ -295,7 +218,7 @@ }

function encodeData(primaryType, data, types) {
var fields = types[primaryType];
const fields = types[primaryType];
if (fields === undefined) {
throw new Error("Unrecognized primary type in EIP-712 encoding: ".concat(primaryType));
throw new Error(`Unrecognized primary type in EIP-712 encoding: ${primaryType}`);
}
return Buffer.concat(fields.map(function (field) { return encodeValue(field.type, data[field.name], types); }));
return Buffer.concat(fields.map((field) => encodeValue(field.type, data[field.name], types)));
}

@@ -317,5 +240,4 @@ exports.encodeData = encodeData;

*/
function zeroValue(primaryType, types) {
function zeroValue(primaryType, types = {}) {
var _a, _b;
if (types === void 0) { types = {}; }
// If the type is a built-in, return a pre-defined zero value.

@@ -341,19 +263,16 @@ if (exports.EIP712_BUILTIN_TYPES.includes(primaryType)) {

if (EIP712_ARRAY_REGEXP.test(primaryType)) {
var match = EIP712_ARRAY_REGEXP.exec(primaryType);
var memberType_2 = (_a = match === null || match === void 0 ? void 0 : match.groups) === null || _a === void 0 ? void 0 : _a.memberType;
var fixedLengthStr = (_b = match === null || match === void 0 ? void 0 : match.groups) === null || _b === void 0 ? void 0 : _b.fixedLength;
var fixedLength = fixedLengthStr === undefined ? 0 : parseInt(fixedLengthStr, 10);
return __spreadArray([], __read(Array(fixedLength).keys()), false).map(function () { return zeroValue(memberType_2, types); });
const match = EIP712_ARRAY_REGEXP.exec(primaryType);
const memberType = (_a = match === null || match === void 0 ? void 0 : match.groups) === null || _a === void 0 ? void 0 : _a.memberType;
const fixedLengthStr = (_b = match === null || match === void 0 ? void 0 : match.groups) === null || _b === void 0 ? void 0 : _b.fixedLength;
const fixedLength = fixedLengthStr === undefined ? 0 : parseInt(fixedLengthStr, 10);
return [...Array(fixedLength).keys()].map(() => zeroValue(memberType, types));
}
// Must be user-defined type. Return an object with all fields set to their zero value.
var fields = types[primaryType];
const fields = types[primaryType];
if (fields === undefined) {
throw new Error("Unrecognized primary type for EIP-712 zero value: ".concat(primaryType));
throw new Error(`Unrecognized primary type for EIP-712 zero value: ${primaryType}`);
}
return fields.reduce(function (obj, field) {
var _a;
return (__assign(__assign({}, obj), (_a = {}, _a[field.name] = zeroValue(field.type, types), _a)));
}, {});
return fields.reduce((obj, field) => (Object.assign(Object.assign({}, obj), { [field.name]: zeroValue(field.type, types) })), {});
}
exports.zeroValue = zeroValue;
//# sourceMappingURL=sign-typed-data-utils.js.map

@@ -11,47 +11,9 @@ "use strict";

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SignatureUtils = exports.guessSigner = exports.verifyEIP712TypedDataSigner = exports.recoverEIP712TypedDataSignerVrs = exports.recoverEIP712TypedDataSignerRsv = exports.parseSignatureWithoutPrefix = exports.parseSignature = exports.verifySignature = exports.signMessageWithoutPrefix = exports.signMessage = exports.signedMessageToPublicKey = exports.LocalSigner = exports.addressToPublicKey = exports.hashMessage = exports.hashMessageWithPrefix = exports.serializeSignature = exports.POP_SIZE = exports.NativeSigner = void 0;
var signatureUtils_1 = require("@celo/base/lib/signatureUtils");
var util_1 = require("@ethereumjs/util");
var web3_utils_1 = require("web3-utils");
var address_1 = require("./address");
var sign_typed_data_utils_1 = require("./sign-typed-data-utils");
const signatureUtils_1 = require("@celo/base/lib/signatureUtils");
const util_1 = require("@ethereumjs/util");
const web3_utils_1 = require("web3-utils");
const address_1 = require("./address");
const sign_typed_data_utils_1 = require("./sign-typed-data-utils");
// Exports moved to @celo/base, forwarding them

@@ -73,3 +35,3 @@ // here for backwards compatibility

function hashMessageWithPrefix(message) {
var prefix = '\x19Ethereum Signed Message:\n' + messageLength(message);
const prefix = '\x19Ethereum Signed Message:\n' + messageLength(message);
return (0, web3_utils_1.soliditySha3)(prefix, message);

@@ -83,22 +45,15 @@ }

function addressToPublicKey(signer, signFn) {
return __awaiter(this, void 0, void 0, function () {
var msg, data, sig, rawsig, prefixedMsg, pubKey, computedAddr;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
msg = Buffer.from('dummy_msg_data');
data = '0x' + msg.toString('hex');
return [4 /*yield*/, signFn(data, signer)];
case 1:
sig = _a.sent();
rawsig = (0, util_1.fromRpcSig)(sig);
prefixedMsg = hashMessageWithPrefix(data);
pubKey = (0, util_1.ecrecover)(Buffer.from(prefixedMsg.slice(2), 'hex'), rawsig.v, rawsig.r, rawsig.s);
computedAddr = (0, util_1.pubToAddress)(pubKey).toString('hex');
if (!(0, address_1.eqAddress)(computedAddr, signer)) {
throw new Error('computed address !== signer');
}
return [2 /*return*/, '0x' + pubKey.toString('hex')];
}
});
return __awaiter(this, void 0, void 0, function* () {
const msg = Buffer.from('dummy_msg_data');
const data = '0x' + msg.toString('hex');
// Note: Eth.sign typing displays incorrect parameter order
const sig = yield signFn(data, signer);
const rawsig = (0, util_1.fromRpcSig)(sig);
const prefixedMsg = hashMessageWithPrefix(data);
const pubKey = (0, util_1.ecrecover)(Buffer.from(prefixedMsg.slice(2), 'hex'), rawsig.v, rawsig.r, rawsig.s);
const computedAddr = (0, util_1.pubToAddress)(pubKey).toString('hex');
if (!(0, address_1.eqAddress)(computedAddr, signer)) {
throw new Error('computed address !== signer');
}
return '0x' + pubKey.toString('hex');
});

@@ -108,9 +63,6 @@ }

function LocalSigner(privateKey) {
var _this = this;
return {
sign: function (message) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, Promise.resolve((0, signatureUtils_1.serializeSignature)(signMessage(message, privateKey, (0, address_1.privateKeyToAddress)(privateKey))))];
});
}); },
sign: (message) => __awaiter(this, void 0, void 0, function* () {
return Promise.resolve((0, signatureUtils_1.serializeSignature)(signMessage(message, privateKey, (0, address_1.privateKeyToAddress)(privateKey))));
}),
};

@@ -120,3 +72,3 @@ }

function signedMessageToPublicKey(message, v, r, s) {
var pubKeyBuf = (0, util_1.ecrecover)(Buffer.from(message.slice(2), 'hex'), BigInt(v), Buffer.from(r.slice(2), 'hex'), Buffer.from(s.slice(2), 'hex'));
const pubKeyBuf = (0, util_1.ecrecover)(Buffer.from(message.slice(2), 'hex'), BigInt(v), Buffer.from(r.slice(2), 'hex'), Buffer.from(s.slice(2), 'hex'));
return '0x' + pubKeyBuf.toString('hex');

@@ -130,8 +82,8 @@ }

function signMessageWithoutPrefix(messageHash, privateKey, address) {
var publicKey = (0, util_1.privateToPublic)((0, util_1.toBuffer)(privateKey));
var derivedAddress = (0, util_1.bufferToHex)((0, util_1.pubToAddress)(publicKey));
const publicKey = (0, util_1.privateToPublic)((0, util_1.toBuffer)(privateKey));
const derivedAddress = (0, util_1.bufferToHex)((0, util_1.pubToAddress)(publicKey));
if (derivedAddress.toLowerCase() !== address.toLowerCase()) {
throw new Error('Provided private key does not match address of intended signer');
}
var _a = (0, util_1.ecsign)((0, util_1.toBuffer)(messageHash), (0, util_1.toBuffer)(privateKey)), r = _a.r, s = _a.s, v = _a.v;
const { r, s, v } = (0, util_1.ecsign)((0, util_1.toBuffer)(messageHash), (0, util_1.toBuffer)(privateKey));
if (!isValidSignature(address, messageHash, Number(v), (0, util_1.bufferToHex)(r), (0, util_1.bufferToHex)(s))) {

@@ -158,19 +110,18 @@ throw new Error('Unable to validate signature');

function parseSignatureWithoutPrefix(messageHash, signature, signer) {
var _a;
var _b = parseSignatureAsRsv(signature.slice(2)), r = _b.r, s = _b.s, v = _b.v;
let { r, s, v } = parseSignatureAsRsv(signature.slice(2));
if (isValidSignature(signer, messageHash, v, r, s)) {
return { v: v, r: r, s: s };
return { v, r, s };
}
;
(_a = parseSignatureAsVrs(signature.slice(2)), r = _a.r, s = _a.s, v = _a.v);
({ r, s, v } = parseSignatureAsVrs(signature.slice(2)));
if (isValidSignature(signer, messageHash, v, r, s)) {
return { v: v, r: r, s: s };
return { v, r, s };
}
throw new Error("Unable to parse signature (expected signer ".concat(signer, ")"));
throw new Error(`Unable to parse signature (expected signer ${signer})`);
}
exports.parseSignatureWithoutPrefix = parseSignatureWithoutPrefix;
function recoverEIP712TypedDataSigner(typedData, signature, parseFunction) {
var dataBuff = (0, sign_typed_data_utils_1.generateTypedDataHash)(typedData);
var _a = parseFunction((0, address_1.trimLeading0x)(signature)), r = _a.r, s = _a.s, v = _a.v;
var publicKey = (0, util_1.ecrecover)((0, util_1.toBuffer)(dataBuff), BigInt(v), (0, util_1.toBuffer)(r), (0, util_1.toBuffer)(s));
const dataBuff = (0, sign_typed_data_utils_1.generateTypedDataHash)(typedData);
const { r, s, v } = parseFunction((0, address_1.trimLeading0x)(signature));
const publicKey = (0, util_1.ecrecover)((0, util_1.toBuffer)(dataBuff), BigInt(v), (0, util_1.toBuffer)(r), (0, util_1.toBuffer)(s));
// TODO test error handling on this

@@ -206,22 +157,11 @@ return (0, util_1.bufferToHex)((0, util_1.pubToAddress)(publicKey));

function verifyEIP712TypedDataSigner(typedData, signature, signer) {
var e_1, _a;
try {
for (var _b = __values([recoverEIP712TypedDataSignerVrs, recoverEIP712TypedDataSignerRsv]), _c = _b.next(); !_c.done; _c = _b.next()) {
var recover = _c.value;
try {
if ((0, address_1.eqAddress)(recover(typedData, signature), signer)) {
return true;
}
for (const recover of [recoverEIP712TypedDataSignerVrs, recoverEIP712TypedDataSignerRsv]) {
try {
if ((0, address_1.eqAddress)(recover(typedData, signature), signer)) {
return true;
}
catch (e) {
// try both serialization formats before failing to verify
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
catch (e) {
// try both serialization formats before failing to verify
}
finally { if (e_1) throw e_1.error; }
}

@@ -232,5 +172,5 @@ return false;

function guessSigner(message, signature) {
var messageHash = hashMessageWithPrefix(message);
var _a = parseSignatureAsRsv(signature.slice(2)), r = _a.r, s = _a.s, v = _a.v;
var publicKey = (0, util_1.ecrecover)((0, util_1.toBuffer)(messageHash), BigInt(v), (0, util_1.toBuffer)(r), (0, util_1.toBuffer)(s));
const messageHash = hashMessageWithPrefix(message);
const { r, s, v } = parseSignatureAsRsv(signature.slice(2));
const publicKey = (0, util_1.ecrecover)((0, util_1.toBuffer)(messageHash), BigInt(v), (0, util_1.toBuffer)(r), (0, util_1.toBuffer)(s));
return (0, util_1.bufferToHex)((0, util_1.pubToAddress)(publicKey));

@@ -240,23 +180,23 @@ }

function parseSignatureAsVrs(signature) {
var v = parseInt(signature.slice(0, 2), 16);
var r = "0x".concat(signature.slice(2, 66));
var s = "0x".concat(signature.slice(66, 130));
let v = parseInt(signature.slice(0, 2), 16);
const r = `0x${signature.slice(2, 66)}`;
const s = `0x${signature.slice(66, 130)}`;
if (v < 27) {
v += 27;
}
return { v: v, r: r, s: s };
return { v, r, s };
}
function parseSignatureAsRsv(signature) {
var r = "0x".concat(signature.slice(0, 64));
var s = "0x".concat(signature.slice(64, 128));
var v = parseInt(signature.slice(128, 130), 16);
const r = `0x${signature.slice(0, 64)}`;
const s = `0x${signature.slice(64, 128)}`;
let v = parseInt(signature.slice(128, 130), 16);
if (v < 27) {
v += 27;
}
return { r: r, s: s, v: v };
return { r, s, v };
}
function isValidSignature(signer, message, v, r, s) {
try {
var publicKey = (0, util_1.ecrecover)((0, util_1.toBuffer)(message), BigInt(v), (0, util_1.toBuffer)(r), (0, util_1.toBuffer)(s));
var retrievedAddress = (0, util_1.bufferToHex)((0, util_1.pubToAddress)(publicKey));
const publicKey = (0, util_1.ecrecover)((0, util_1.toBuffer)(message), BigInt(v), (0, util_1.toBuffer)(r), (0, util_1.toBuffer)(s));
const retrievedAddress = (0, util_1.bufferToHex)((0, util_1.pubToAddress)(publicKey));
return (0, address_1.eqAddress)(retrievedAddress, signer);

@@ -270,12 +210,12 @@ }

NativeSigner: signatureUtils_1.NativeSigner,
LocalSigner: LocalSigner,
signMessage: signMessage,
signMessageWithoutPrefix: signMessageWithoutPrefix,
parseSignature: parseSignature,
parseSignatureWithoutPrefix: parseSignatureWithoutPrefix,
LocalSigner,
signMessage,
signMessageWithoutPrefix,
parseSignature,
parseSignatureWithoutPrefix,
serializeSignature: signatureUtils_1.serializeSignature,
recoverEIP712TypedDataSignerRsv: recoverEIP712TypedDataSignerRsv,
recoverEIP712TypedDataSignerVrs: recoverEIP712TypedDataSignerVrs,
verifyEIP712TypedDataSigner: verifyEIP712TypedDataSigner,
recoverEIP712TypedDataSignerRsv,
recoverEIP712TypedDataSignerVrs,
verifyEIP712TypedDataSigner,
};
//# sourceMappingURL=signatureUtils.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringUtils = exports.normalizeAccents = exports.appendPath = void 0;
var string_1 = require("@celo/base/lib/string");
const string_1 = require("@celo/base/lib/string");
// Exports moved to @celo/base, forwarding them

@@ -6,0 +6,0 @@ // here for backwards compatibility

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerAttestation = exports.authorizeSigner = void 0;
var authorizeSigner = function (_a) {
var account = _a.account, signer = _a.signer, chainId = _a.chainId, role = _a.role, accountsContractAddress = _a.accountsContractAddress;
return ({
types: {
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' },
],
AuthorizeSigner: [
{ name: 'account', type: 'address' },
{ name: 'signer', type: 'address' },
{ name: 'role', type: 'bytes32' },
],
},
primaryType: 'AuthorizeSigner',
domain: {
name: 'Celo Core Contracts',
version: '1.0',
chainId: chainId,
verifyingContract: accountsContractAddress,
},
message: {
account: account,
signer: signer,
role: role,
},
});
};
const authorizeSigner = ({ account, signer, chainId, role, accountsContractAddress, }) => ({
types: {
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' },
],
AuthorizeSigner: [
{ name: 'account', type: 'address' },
{ name: 'signer', type: 'address' },
{ name: 'role', type: 'bytes32' },
],
},
primaryType: 'AuthorizeSigner',
domain: {
name: 'Celo Core Contracts',
version: '1.0',
chainId,
verifyingContract: accountsContractAddress,
},
message: {
account,
signer,
role,
},
});
exports.authorizeSigner = authorizeSigner;
var registerAttestation = function (chainId, contractAddress, message) {
const registerAttestation = (chainId, contractAddress, message) => {
return {

@@ -56,3 +53,3 @@ types: {

version: '1.0',
chainId: chainId,
chainId,
verifyingContract: contractAddress,

@@ -59,0 +56,0 @@ },

{
"name": "@celo/utils",
"version": "5.0.6",
"version": "6.0.0-beta.0",
"description": "Celo common utils",

@@ -11,3 +11,3 @@ "author": "Celo",

"homepage": "https://celo-sdk-docs.readthedocs.io/en/latest/utils",
"repository": "https://github.com/celo-org/celo-monorepo/tree/master/packages/sdk/utils",
"repository": "https://github.com/celo-org/developer-tooling/tree/master/packages/sdk/utils",
"scripts": {

@@ -17,6 +17,6 @@ "prepublishOnly": "yarn build",

"clean": "tsc -b . --clean",
"docs": "typedoc",
"test": "jest --runInBand --ci",
"test:verbose": "jest --verbose",
"lint": "tslint -c tslint.json --project ."
"docs": "yarn run --top-level typedoc",
"test": "yarn run --top-level jest --runInBand --ci",
"test:verbose": "yarn run --top-level jest --verbose",
"lint": "yarn run --top-level eslint -c .eslintrc.js "
},

@@ -29,4 +29,2 @@ "files": [

"@ethereumjs/util": "8.0.5",
"rlp": "^2.2.4",
"@types/bn.js": "^5.1.0",
"@types/elliptic": "^6.4.9",

@@ -37,5 +35,5 @@ "@types/node": "^18.7.16",

"ethereum-cryptography": "1.2.0",
"bn.js": "4.11.9",
"fp-ts": "2.1.1",
"io-ts": "2.0.1",
"fp-ts": "2.1.1",
"rlp": "^2.2.4",
"web3-eth-abi": "1.10.0",

@@ -46,10 +44,3 @@ "web3-utils": "1.10.0"

"@celo/typescript": "0.0.1"
},
"resolutions": {
"@types/bn.js": "4.11.6",
"bn.js": "4.11.9",
"elliptic/bn.js": "bn.js@4.11.9",
"web3-utils/bn.js": "bn.js@4.11.9",
"@ethereumjs/bn.js": "bn.js@4.11.9"
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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